fix(desktop): stream remote media without renderer credentials
This commit is contained in:
@@ -179,6 +179,7 @@ import { buildHudWindowUrl } from './hud-url'
|
||||
import { imageContextMenuItems } from './image-context-menu'
|
||||
import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'
|
||||
import { ensureMainWindow } from './main-window-lifecycle'
|
||||
import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'
|
||||
import {
|
||||
oauthGuardMayHardFail,
|
||||
oauthSessionIsLive,
|
||||
@@ -1067,30 +1068,10 @@ app.setAboutPanelOptions({
|
||||
copyright: 'Copyright © 2026 Nous Research'
|
||||
})
|
||||
|
||||
// Custom scheme for streaming local media (video/audio) into the renderer.
|
||||
// Reading large media through `readFileDataUrl` failed: it base64-loads the
|
||||
// whole file into memory and is hard-capped (default 16 MB, Settings → Chat),
|
||||
// so any non-trivial video silently refused to load. Streaming via a protocol
|
||||
// handler removes the size cap and gives the <video> element seekable,
|
||||
// range-aware playback. Must be registered before the app is ready.
|
||||
const MEDIA_PROTOCOL = 'hermes-media'
|
||||
|
||||
// Only audio/video may be streamed. Without this the handler would read any
|
||||
// non-blocklisted local file (no size cap) for any `fetch(hermes-media://…)`.
|
||||
const STREAMABLE_MEDIA_EXTS = new Set([
|
||||
'.avi',
|
||||
'.flac',
|
||||
'.m4a',
|
||||
'.mkv',
|
||||
'.mov',
|
||||
'.mp3',
|
||||
'.mp4',
|
||||
'.ogg',
|
||||
'.opus',
|
||||
'.wav',
|
||||
'.webm'
|
||||
])
|
||||
|
||||
// Custom scheme for streaming audio/video into the renderer. Local paths read
|
||||
// from this machine; remote paths are proxied through the configured gateway
|
||||
// with main-process authentication. This avoids whole-file data URLs and keeps
|
||||
// playback seekable and Range-aware. Must be registered before app readiness.
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: MEDIA_PROTOCOL,
|
||||
@@ -1104,31 +1085,45 @@ protocol.registerSchemesAsPrivileged([
|
||||
])
|
||||
|
||||
function registerMediaProtocol() {
|
||||
protocol.handle(MEDIA_PROTOCOL, async request => {
|
||||
let resolvedPath
|
||||
const handler = createMediaProtocolHandler({
|
||||
ensureRemoteBearer: baseUrl => ensureNativeAccessToken(baseUrl).catch(() => null),
|
||||
fetchLocal: (resolvedPath, headers, method) =>
|
||||
electronNet.fetch(pathToFileURL(resolvedPath).toString(), {
|
||||
bypassCustomProtocolHandlers: true,
|
||||
credentials: 'omit',
|
||||
headers,
|
||||
method
|
||||
}),
|
||||
fetchRemote: (url, headers, method) =>
|
||||
electronNet.fetch(url, {
|
||||
bypassCustomProtocolHandlers: true,
|
||||
credentials: 'omit',
|
||||
headers,
|
||||
method
|
||||
}),
|
||||
fetchRemoteWithCookies: (url, headers, method) => {
|
||||
const oauthSession = getOauthSession()
|
||||
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
if (!oauthSession) {
|
||||
throw new Error('OAuth session partition is unavailable.')
|
||||
}
|
||||
|
||||
const filePath = decodeURIComponent(url.pathname.replace(/^\/+/, ''))
|
||||
return oauthSession.fetch(url, {
|
||||
bypassCustomProtocolHandlers: true,
|
||||
credentials: 'include',
|
||||
headers,
|
||||
method
|
||||
})
|
||||
},
|
||||
resolveLocalFile: async filePath => {
|
||||
const { resolvedPath } = await resolveReadableFileForIpc(filePath, { purpose: 'Media stream' })
|
||||
|
||||
;({ resolvedPath } = await resolveReadableFileForIpc(filePath, { purpose: 'Media stream' }))
|
||||
} catch {
|
||||
return new Response('Media not found', { status: 404 })
|
||||
}
|
||||
|
||||
if (!STREAMABLE_MEDIA_EXTS.has(path.extname(resolvedPath).toLowerCase())) {
|
||||
return new Response('Unsupported media type', { status: 415 })
|
||||
}
|
||||
|
||||
// Delegate to Electron's net stack on a file:// URL — it resolves the
|
||||
// content-type and honors Range requests so seeking works. Forward the
|
||||
// renderer's headers (notably Range) and skip custom-protocol re-entry.
|
||||
return electronNet.fetch(pathToFileURL(resolvedPath).toString(), {
|
||||
bypassCustomProtocolHandlers: true,
|
||||
headers: request.headers
|
||||
})
|
||||
return resolvedPath
|
||||
},
|
||||
resolveRemoteConnection: profile => ensureBackend(profile)
|
||||
})
|
||||
|
||||
protocol.handle(MEDIA_PROTOCOL, handler)
|
||||
}
|
||||
|
||||
let mainWindow = null
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
createMediaProtocolHandler,
|
||||
isStreamableMediaPath,
|
||||
type MediaProtocolDependencies,
|
||||
mediaRequestHeaders,
|
||||
remoteMediaEndpoint
|
||||
} from './media-protocol'
|
||||
|
||||
function dependencies(overrides: Partial<MediaProtocolDependencies> = {}) {
|
||||
return {
|
||||
ensureRemoteBearer: vi.fn(async (_baseUrl: string) => null),
|
||||
fetchLocal: vi.fn(async (_resolvedPath: string, _headers: Headers) => new Response('local', { status: 206 })),
|
||||
fetchRemote: vi.fn(async (_url: string, _headers: Headers) => new Response('remote', { status: 206 })),
|
||||
fetchRemoteWithCookies: vi.fn(async (_url: string, _headers: Headers) =>
|
||||
new Response('cookie', { status: 206 })
|
||||
),
|
||||
resolveLocalFile: vi.fn(async (filePath: string) => filePath),
|
||||
resolveRemoteConnection: vi.fn(async (_profile?: string) => ({
|
||||
authMode: 'token' as const,
|
||||
baseUrl: 'https://gateway.test',
|
||||
mode: 'remote' as const,
|
||||
token: 'secret'
|
||||
})),
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function request(url: string, headers: Record<string, string> = {}, method = 'GET') {
|
||||
return { headers: new Headers(headers), method, url }
|
||||
}
|
||||
|
||||
describe('media protocol helpers', () => {
|
||||
it('recognises only supported audio/video extensions case-insensitively', () => {
|
||||
expect(isStreamableMediaPath('/tmp/render.MP4')).toBe(true)
|
||||
expect(isStreamableMediaPath('/tmp/voice.flac')).toBe(true)
|
||||
expect(isStreamableMediaPath('/tmp/secrets.txt')).toBe(false)
|
||||
})
|
||||
|
||||
it('forwards range/cache negotiation headers but strips renderer credentials', () => {
|
||||
const headers = mediaRequestHeaders(
|
||||
new Headers({
|
||||
Accept: 'video/mp4',
|
||||
Authorization: 'Bearer renderer-secret',
|
||||
Cookie: 'session=renderer-secret',
|
||||
Host: 'attacker.test',
|
||||
Range: 'bytes=10-20'
|
||||
})
|
||||
)
|
||||
|
||||
expect(Object.fromEntries(headers)).toEqual({ accept: 'video/mp4', range: 'bytes=10-20' })
|
||||
})
|
||||
|
||||
it('preserves a configured gateway path prefix', () => {
|
||||
const endpoint = new URL(remoteMediaEndpoint('https://gateway.test/hermes/', '/tmp/a b.mp4'))
|
||||
|
||||
expect(endpoint.pathname).toBe('/hermes/api/files/stream')
|
||||
expect(endpoint.searchParams.get('path')).toBe('/tmp/a b.mp4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createMediaProtocolHandler', () => {
|
||||
it('streams local media through the resolved local-file dependency', async () => {
|
||||
const deps = dependencies()
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://stream/%2Ftmp%2Fclip.mp4', {
|
||||
Authorization: 'Bearer renderer-secret',
|
||||
Range: 'bytes=1-3'
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(206)
|
||||
expect(deps.resolveLocalFile).toHaveBeenCalledWith('/tmp/clip.mp4')
|
||||
expect(deps.fetchLocal).toHaveBeenCalledOnce()
|
||||
const [, headers] = vi.mocked(deps.fetchLocal).mock.calls[0]
|
||||
expect(headers.get('range')).toBe('bytes=1-3')
|
||||
expect(headers.get('authorization')).toBeNull()
|
||||
})
|
||||
|
||||
it('preserves explicit HEAD requests through the local stream fetch', async () => {
|
||||
const fetchLocal = vi.fn(async (..._args: unknown[]) => new Response(null, { status: 200 }))
|
||||
|
||||
const deps = dependencies({
|
||||
fetchLocal: fetchLocal as MediaProtocolDependencies['fetchLocal']
|
||||
})
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://stream/%2Ftmp%2Fclip.mp4', {}, 'HEAD')
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(fetchLocal).toHaveBeenCalledOnce()
|
||||
expect(fetchLocal.mock.calls[0]?.[2]).toBe('HEAD')
|
||||
expect(deps.resolveRemoteConnection).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('proxies token-auth remote media without placing the token in the URL', async () => {
|
||||
const deps = dependencies({
|
||||
resolveRemoteConnection: vi.fn(async () => ({
|
||||
authMode: 'token' as const,
|
||||
baseUrl: 'https://gateway.test/hermes',
|
||||
mode: 'remote' as const,
|
||||
token: 's e/cret'
|
||||
}))
|
||||
})
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://remote/%2Froot%2Foutputs%2Frender.mp4?profile=reviewer', {
|
||||
Range: 'bytes=0-1023'
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(206)
|
||||
expect(deps.resolveRemoteConnection).toHaveBeenCalledWith('reviewer')
|
||||
expect(deps.fetchRemote).toHaveBeenCalledOnce()
|
||||
const [rawUrl, headers] = vi.mocked(deps.fetchRemote).mock.calls[0]
|
||||
const url = new URL(rawUrl)
|
||||
expect(url.pathname).toBe('/hermes/api/files/stream')
|
||||
expect(url.searchParams.get('path')).toBe('/root/outputs/render.mp4')
|
||||
expect(url.searchParams.has('token')).toBe(false)
|
||||
expect(headers.get('x-hermes-session-token')).toBe('s e/cret')
|
||||
expect(headers.get('range')).toBe('bytes=0-1023')
|
||||
})
|
||||
|
||||
it('preserves explicit HEAD requests through the token-auth remote proxy', async () => {
|
||||
const fetchRemote = vi.fn(async (..._args: unknown[]) => new Response(null, { status: 200 }))
|
||||
|
||||
const deps = dependencies({
|
||||
fetchRemote: fetchRemote as MediaProtocolDependencies['fetchRemote']
|
||||
})
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://remote/%2Froot%2Foutputs%2Frender.mp4', {}, 'HEAD')
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(fetchRemote).toHaveBeenCalledOnce()
|
||||
expect(fetchRemote.mock.calls[0]?.[2]).toBe('HEAD')
|
||||
})
|
||||
|
||||
it('rejects protocol methods other than GET and HEAD', async () => {
|
||||
const deps = dependencies()
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://remote/%2Froot%2Foutputs%2Frender.mp4', {}, 'POST')
|
||||
)
|
||||
|
||||
expect(response.status).toBe(405)
|
||||
expect(response.headers.get('allow')).toBe('GET, HEAD')
|
||||
expect(deps.resolveRemoteConnection).not.toHaveBeenCalled()
|
||||
expect(deps.fetchRemote).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses a refreshed native bearer for OAuth remote media when available', async () => {
|
||||
const deps = dependencies({
|
||||
ensureRemoteBearer: vi.fn(async () => 'native-access-token'),
|
||||
resolveRemoteConnection: vi.fn(async () => ({
|
||||
authMode: 'oauth' as const,
|
||||
baseUrl: 'https://gateway.test',
|
||||
mode: 'remote' as const,
|
||||
token: null
|
||||
}))
|
||||
})
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://remote/%2Ftmp%2Fclip.mp4')
|
||||
)
|
||||
|
||||
expect(response.status).toBe(206)
|
||||
expect(deps.fetchRemote).toHaveBeenCalledOnce()
|
||||
expect(deps.fetchRemoteWithCookies).not.toHaveBeenCalled()
|
||||
const [, headers] = vi.mocked(deps.fetchRemote).mock.calls[0]
|
||||
expect(headers.get('authorization')).toBe('Bearer native-access-token')
|
||||
})
|
||||
|
||||
it('preserves explicit HEAD requests through the native-bearer remote fetch', async () => {
|
||||
const fetchRemote = vi.fn(async (..._args: unknown[]) => new Response(null, { status: 200 }))
|
||||
|
||||
const deps = dependencies({
|
||||
ensureRemoteBearer: vi.fn(async () => 'native-access-token'),
|
||||
fetchRemote: fetchRemote as MediaProtocolDependencies['fetchRemote'],
|
||||
resolveRemoteConnection: vi.fn(async () => ({
|
||||
authMode: 'oauth' as const,
|
||||
baseUrl: 'https://gateway.test',
|
||||
mode: 'remote' as const,
|
||||
token: null
|
||||
}))
|
||||
})
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://remote/%2Ftmp%2Fclip.mp4', {}, 'HEAD')
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(fetchRemote).toHaveBeenCalledOnce()
|
||||
expect((fetchRemote.mock.calls[0]?.[1] as Headers).get('authorization')).toBe('Bearer native-access-token')
|
||||
expect(fetchRemote.mock.calls[0]?.[2]).toBe('HEAD')
|
||||
expect(deps.fetchRemoteWithCookies).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses the isolated OAuth cookie session when no native bearer exists', async () => {
|
||||
const deps = dependencies({
|
||||
resolveRemoteConnection: vi.fn(async () => ({
|
||||
authMode: 'oauth' as const,
|
||||
baseUrl: 'https://gateway.test',
|
||||
mode: 'remote' as const,
|
||||
token: null
|
||||
}))
|
||||
})
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://remote/%2Ftmp%2Fclip.mp4')
|
||||
)
|
||||
|
||||
expect(response.status).toBe(206)
|
||||
expect(deps.fetchRemote).not.toHaveBeenCalled()
|
||||
expect(deps.fetchRemoteWithCookies).toHaveBeenCalledOnce()
|
||||
const [, headers] = vi.mocked(deps.fetchRemoteWithCookies).mock.calls[0]
|
||||
expect(headers.get('authorization')).toBeNull()
|
||||
})
|
||||
|
||||
it('preserves explicit HEAD requests through the isolated-cookie remote fetch', async () => {
|
||||
const fetchRemoteWithCookies = vi.fn(async (..._args: unknown[]) => new Response(null, { status: 200 }))
|
||||
|
||||
const deps = dependencies({
|
||||
fetchRemoteWithCookies: fetchRemoteWithCookies as MediaProtocolDependencies['fetchRemoteWithCookies'],
|
||||
resolveRemoteConnection: vi.fn(async () => ({
|
||||
authMode: 'oauth' as const,
|
||||
baseUrl: 'https://gateway.test',
|
||||
mode: 'remote' as const,
|
||||
token: null
|
||||
}))
|
||||
})
|
||||
|
||||
const response = await createMediaProtocolHandler(deps)(
|
||||
request('hermes-media://remote/%2Ftmp%2Fclip.mp4', {}, 'HEAD')
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(fetchRemoteWithCookies).toHaveBeenCalledOnce()
|
||||
expect((fetchRemoteWithCookies.mock.calls[0]?.[1] as Headers).get('authorization')).toBeNull()
|
||||
expect(fetchRemoteWithCookies.mock.calls[0]?.[2]).toBe('HEAD')
|
||||
expect(deps.fetchRemote).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails closed for unsupported extensions and missing remote auth', async () => {
|
||||
const deps = dependencies({
|
||||
resolveRemoteConnection: vi.fn(async () => ({
|
||||
authMode: 'token' as const,
|
||||
baseUrl: 'https://gateway.test',
|
||||
mode: 'remote' as const,
|
||||
token: null
|
||||
}))
|
||||
})
|
||||
|
||||
const handler = createMediaProtocolHandler(deps)
|
||||
|
||||
expect((await handler(request('hermes-media://remote/%2Ftmp%2Fsecret.txt'))).status).toBe(415)
|
||||
expect((await handler(request('hermes-media://remote/%2Ftmp%2Fclip.mp4'))).status).toBe(401)
|
||||
expect(deps.fetchRemote).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
const STREAMABLE_MEDIA_EXTENSIONS = [
|
||||
'.avi',
|
||||
'.flac',
|
||||
'.m4a',
|
||||
'.mkv',
|
||||
'.mov',
|
||||
'.mp3',
|
||||
'.mp4',
|
||||
'.ogg',
|
||||
'.opus',
|
||||
'.wav',
|
||||
'.webm'
|
||||
] as const
|
||||
|
||||
const FORWARDED_MEDIA_REQUEST_HEADERS = ['accept', 'if-modified-since', 'if-none-match', 'if-range', 'range'] as const
|
||||
|
||||
export const MEDIA_PROTOCOL = 'hermes-media'
|
||||
|
||||
type MediaProtocolMode = 'remote' | 'stream'
|
||||
|
||||
interface MediaProtocolTarget {
|
||||
filePath: string
|
||||
mode: MediaProtocolMode
|
||||
profile?: string
|
||||
}
|
||||
|
||||
export interface MediaRemoteConnection {
|
||||
authMode?: 'oauth' | 'token'
|
||||
baseUrl: string
|
||||
mode?: 'local' | 'remote'
|
||||
token?: null | string
|
||||
}
|
||||
|
||||
type MediaRequestMethod = 'GET' | 'HEAD'
|
||||
|
||||
export interface MediaProtocolDependencies {
|
||||
ensureRemoteBearer: (baseUrl: string) => Promise<null | string>
|
||||
fetchLocal: (resolvedPath: string, headers: Headers, method: MediaRequestMethod) => Promise<Response>
|
||||
fetchRemote: (url: string, headers: Headers, method: MediaRequestMethod) => Promise<Response>
|
||||
fetchRemoteWithCookies: (url: string, headers: Headers, method: MediaRequestMethod) => Promise<Response>
|
||||
resolveLocalFile: (filePath: string) => Promise<string>
|
||||
resolveRemoteConnection: (profile?: string) => Promise<MediaRemoteConnection>
|
||||
}
|
||||
|
||||
function parseMediaProtocolTarget(rawUrl: string): MediaProtocolTarget {
|
||||
const url = new URL(rawUrl)
|
||||
const mode = url.hostname as MediaProtocolMode
|
||||
|
||||
if (mode !== 'remote' && mode !== 'stream') {
|
||||
throw new Error('Unsupported media protocol target')
|
||||
}
|
||||
|
||||
const filePath = decodeURIComponent(url.pathname.replace(/^\/+/, ''))
|
||||
|
||||
if (!filePath) {
|
||||
throw new Error('Missing media path')
|
||||
}
|
||||
|
||||
const profile = url.searchParams.get('profile')?.trim() || undefined
|
||||
|
||||
return { filePath, mode, profile }
|
||||
}
|
||||
|
||||
export function isStreamableMediaPath(filePath: string): boolean {
|
||||
const lower = filePath.toLowerCase()
|
||||
|
||||
return STREAMABLE_MEDIA_EXTENSIONS.some(extension => lower.endsWith(extension))
|
||||
}
|
||||
|
||||
export function mediaRequestHeaders(source: Headers): Headers {
|
||||
const forwarded = new Headers()
|
||||
|
||||
for (const name of FORWARDED_MEDIA_REQUEST_HEADERS) {
|
||||
const value = source.get(name)
|
||||
|
||||
if (value) {
|
||||
forwarded.set(name, value)
|
||||
}
|
||||
}
|
||||
|
||||
return forwarded
|
||||
}
|
||||
|
||||
export function remoteMediaEndpoint(baseUrl: string, filePath: string): string {
|
||||
const normalizedBase = baseUrl.replace(/\/+$/, '')
|
||||
const url = new URL(`${normalizedBase}/api/files/stream`)
|
||||
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
throw new Error(`Unsupported Hermes backend URL protocol: ${url.protocol}`)
|
||||
}
|
||||
|
||||
url.searchParams.set('path', filePath)
|
||||
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
export function createMediaProtocolHandler(dependencies: MediaProtocolDependencies) {
|
||||
return async (request: Pick<Request, 'headers' | 'method' | 'url'>): Promise<Response> => {
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
||||
return new Response('Method not allowed', {
|
||||
headers: { allow: 'GET, HEAD' },
|
||||
status: 405
|
||||
})
|
||||
}
|
||||
|
||||
const method: MediaRequestMethod = request.method
|
||||
let target: MediaProtocolTarget
|
||||
|
||||
try {
|
||||
target = parseMediaProtocolTarget(request.url)
|
||||
} catch {
|
||||
return new Response('Media not found', { status: 404 })
|
||||
}
|
||||
|
||||
if (!isStreamableMediaPath(target.filePath)) {
|
||||
return new Response('Unsupported media type', { status: 415 })
|
||||
}
|
||||
|
||||
const headers = mediaRequestHeaders(request.headers)
|
||||
|
||||
if (target.mode === 'stream') {
|
||||
try {
|
||||
const resolvedPath = await dependencies.resolveLocalFile(target.filePath)
|
||||
|
||||
if (!isStreamableMediaPath(resolvedPath)) {
|
||||
return new Response('Unsupported media type', { status: 415 })
|
||||
}
|
||||
|
||||
return await dependencies.fetchLocal(resolvedPath, headers, method)
|
||||
} catch {
|
||||
return new Response('Media not found', { status: 404 })
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const connection = await dependencies.resolveRemoteConnection(target.profile)
|
||||
|
||||
if (connection.mode !== 'remote') {
|
||||
return new Response('Remote media backend unavailable', { status: 404 })
|
||||
}
|
||||
|
||||
const endpoint = remoteMediaEndpoint(connection.baseUrl, target.filePath)
|
||||
|
||||
if (connection.authMode === 'oauth') {
|
||||
const bearer = await dependencies.ensureRemoteBearer(connection.baseUrl)
|
||||
|
||||
if (bearer) {
|
||||
headers.set('authorization', `Bearer ${bearer}`)
|
||||
|
||||
return await dependencies.fetchRemote(endpoint, headers, method)
|
||||
}
|
||||
|
||||
return await dependencies.fetchRemoteWithCookies(endpoint, headers, method)
|
||||
}
|
||||
|
||||
if (!connection.token) {
|
||||
return new Response('Remote media authentication unavailable', { status: 401 })
|
||||
}
|
||||
|
||||
headers.set('x-hermes-session-token', connection.token)
|
||||
|
||||
return await dependencies.fetchRemote(endpoint, headers, method)
|
||||
} catch {
|
||||
return new Response('Remote media unavailable', { status: 502 })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
isInlineMediaSrc,
|
||||
isRemoteGateway,
|
||||
mediaExternalUrl,
|
||||
mediaGatewayStreamUrl,
|
||||
resolveMediaDisplaySrc,
|
||||
resolveMediaPlaybackSrc
|
||||
} from './media'
|
||||
@@ -76,6 +77,24 @@ describe('mediaExternalUrl', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('mediaGatewayStreamUrl', () => {
|
||||
afterEach(() => {
|
||||
$connection.set(null)
|
||||
})
|
||||
|
||||
it('rewrites gateway-local media to the main-process remote stream proxy', () => {
|
||||
$connection.set({ mode: 'remote', baseUrl: 'https://gw', token: 's e/cret' } as never)
|
||||
expect(mediaGatewayStreamUrl('file:///tmp/a b.mp4')).toBe('hermes-media://remote/%2Ftmp%2Fa%20b.mp4')
|
||||
})
|
||||
|
||||
it('supports OAuth remotes with no renderer-visible token and scopes pool profiles', () => {
|
||||
$connection.set({ authMode: 'oauth', mode: 'remote', profile: 'voice reviewer', token: null } as never)
|
||||
expect(mediaGatewayStreamUrl('/tmp/a.mp4')).toBe(
|
||||
'hermes-media://remote/%2Ftmp%2Fa.mp4?profile=voice%20reviewer'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveMediaDisplaySrc', () => {
|
||||
const api = vi.fn(async ({ path }: { path: string }) => {
|
||||
if (path.startsWith('/api/fs/read-data-url?')) {
|
||||
@@ -153,12 +172,12 @@ describe('resolveMediaPlaybackSrc', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('routes gateway-local video through the authenticated download endpoint', async () => {
|
||||
it('routes OAuth gateway-local video through the authenticated main-process proxy', async () => {
|
||||
vi.stubGlobal('window', { hermesDesktop: { api: vi.fn() } })
|
||||
$connection.set({ mode: 'remote', baseUrl: 'https://gateway.test', token: 's e/cret' } as never)
|
||||
$connection.set({ authMode: 'oauth', mode: 'remote', profile: 'default', token: null } as never)
|
||||
|
||||
await expect(resolveMediaPlaybackSrc('/root/outputs/render.mp4')).resolves.toBe(
|
||||
'https://gateway.test/api/files/download?path=%2Froot%2Foutputs%2Frender.mp4&token=s%20e%2Fcret'
|
||||
'hermes-media://remote/%2Froot%2Foutputs%2Frender.mp4?profile=default'
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -83,16 +83,16 @@ export async function resolveMediaDisplaySrc(path: string): Promise<string> {
|
||||
}
|
||||
|
||||
// Audio/video need a seekable source instead of a whole-file data URL. Keep
|
||||
// remote URLs untouched, route gateway-local files through the authenticated
|
||||
// download endpoint, and reserve the Electron protocol for files on this
|
||||
// desktop machine.
|
||||
// remote URLs untouched and route filesystem paths through the Electron media
|
||||
// protocol. Its main-process handler reads local files directly or proxies a
|
||||
// remote gateway with the connection's bearer/cookie/token authentication.
|
||||
export async function resolveMediaPlaybackSrc(path: string): Promise<string> {
|
||||
if (isInlineMediaSrc(path)) {
|
||||
return path
|
||||
}
|
||||
|
||||
if (window.hermesDesktop && ['audio', 'video'].includes(mediaKind(path))) {
|
||||
return isRemoteGateway() ? mediaExternalUrl(path) : mediaStreamUrl(path)
|
||||
return isRemoteGateway() ? mediaGatewayStreamUrl(path) : mediaStreamUrl(path)
|
||||
}
|
||||
|
||||
return resolveMediaDisplaySrc(path)
|
||||
@@ -119,6 +119,23 @@ export function mediaExternalUrl(path: string): string {
|
||||
return /^file:/i.test(path) ? path : `file://${path}`
|
||||
}
|
||||
|
||||
// Remote gateway audio/video is proxied by the Electron main process. OAuth
|
||||
// connections intentionally expose no static token to the renderer, so a bare
|
||||
// HTTPS source cannot authenticate reliably. The custom protocol keeps secrets
|
||||
// out of renderer URLs while forwarding Range requests to /api/files/stream.
|
||||
export function mediaGatewayStreamUrl(path: string): string {
|
||||
const conn = $connection.get()
|
||||
|
||||
if (isRemoteGateway()) {
|
||||
const file = encodeURIComponent(filePathFromMediaPath(path))
|
||||
const profile = conn?.profile ? `?profile=${encodeURIComponent(conn.profile)}` : ''
|
||||
|
||||
return `hermes-media://remote/${file}${profile}`
|
||||
}
|
||||
|
||||
return mediaExternalUrl(path)
|
||||
}
|
||||
|
||||
// Custom Electron scheme (registered in electron/main.ts) that streams a local
|
||||
// file with Range support. Used for audio/video so playback bypasses the data
|
||||
// URL size cap and supports seeking. `path` may be a plain path or `file://…`.
|
||||
|
||||
+71
-12
@@ -1886,6 +1886,21 @@ _MEDIA_CONTENT_TYPES = {
|
||||
_MEDIA_MAX_BYTES = 25 * 1024 * 1024
|
||||
_MANAGED_FILES_ROOT_ENV = "HERMES_DASHBOARD_FILES_ROOT"
|
||||
_MANAGED_FILE_MAX_BYTES = 100 * 1024 * 1024
|
||||
_STREAMABLE_MEDIA_EXTENSIONS = frozenset(
|
||||
{
|
||||
".avi",
|
||||
".flac",
|
||||
".m4a",
|
||||
".mkv",
|
||||
".mov",
|
||||
".mp3",
|
||||
".mp4",
|
||||
".ogg",
|
||||
".opus",
|
||||
".wav",
|
||||
".webm",
|
||||
}
|
||||
)
|
||||
_HOSTED_MANAGED_FILES_ROOT = Path("/opt/data")
|
||||
|
||||
|
||||
@@ -2576,17 +2591,14 @@ async def read_managed_file(request: Request, path: str):
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/files/download")
|
||||
async def download_managed_file(request: Request, path: str):
|
||||
"""Stream a managed file as an attachment download.
|
||||
|
||||
Remote clients (desktop app, browser dashboard) open agent-written files
|
||||
that live on *this* gateway's disk, not theirs. Auth-gated like every other
|
||||
managed-files route — ``auth_middleware`` additionally accepts the session
|
||||
token as a ``?token=`` query param here so a shell/browser-opened download
|
||||
(which can't set the session header) still authenticates. See ``/api/pty``
|
||||
for the same query-token precedent.
|
||||
"""
|
||||
def _managed_file_response(
|
||||
request: Request,
|
||||
path: str,
|
||||
*,
|
||||
content_disposition_type: str,
|
||||
media_only: bool = False,
|
||||
) -> FileResponse:
|
||||
"""Build a range-aware response after applying managed-file policy."""
|
||||
policy, target, _display_path = _resolve_managed_path(path, request)
|
||||
if not target.exists():
|
||||
raise HTTPException(status_code=404, detail="File not found")
|
||||
@@ -2594,6 +2606,8 @@ async def download_managed_file(request: Request, path: str):
|
||||
raise HTTPException(status_code=400, detail="Path is not a file")
|
||||
if _is_sensitive_path(target):
|
||||
raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed")
|
||||
if media_only and target.suffix.lower() not in _STREAMABLE_MEDIA_EXTENSIONS:
|
||||
raise HTTPException(status_code=415, detail="Unsupported media type")
|
||||
|
||||
try:
|
||||
size = target.stat().st_size
|
||||
@@ -2608,7 +2622,52 @@ async def download_managed_file(request: Request, path: str):
|
||||
path=str(target),
|
||||
media_type=mime_type,
|
||||
filename=target.name,
|
||||
content_disposition_type="attachment",
|
||||
content_disposition_type=content_disposition_type,
|
||||
headers={"X-Content-Type-Options": "nosniff"} if media_only else None,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/files/download")
|
||||
async def download_managed_file(request: Request, path: str):
|
||||
"""Stream a managed file as an attachment download.
|
||||
|
||||
Remote clients (desktop app, browser dashboard) open agent-written files
|
||||
that live on *this* gateway's disk, not theirs. Auth-gated like every other
|
||||
managed-files route — ``auth_middleware`` additionally accepts the session
|
||||
token as a ``?token=`` query param here so a shell/browser-opened download
|
||||
(which can't set the session header) still authenticates. See ``/api/pty``
|
||||
for the same query-token precedent. Chromium identifies ``<audio>`` and
|
||||
``<video>`` subresource requests through ``Sec-Fetch-Dest``; serve those
|
||||
inline for compatibility with Desktop builds that still use this route as
|
||||
their player source, while preserving attachment semantics for ordinary
|
||||
link/document requests.
|
||||
"""
|
||||
fetch_destination = request.headers.get("sec-fetch-dest", "").lower()
|
||||
is_media_subresource = fetch_destination in {"audio", "video"}
|
||||
return _managed_file_response(
|
||||
request,
|
||||
path,
|
||||
content_disposition_type="inline" if is_media_subresource else "attachment",
|
||||
media_only=is_media_subresource,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/files/stream")
|
||||
@app.head("/api/files/stream")
|
||||
async def stream_managed_file(request: Request, path: str):
|
||||
"""Stream managed audio/video inline with HTTP Range support.
|
||||
|
||||
Electron's Chromium media pipeline may reject an attachment response used
|
||||
as an ``<audio>`` or ``<video>`` source. This route shares the download
|
||||
endpoint's authentication, size cap, sensitive-file guard, MIME detection,
|
||||
and Starlette ``FileResponse`` range handling, but explicitly marks the
|
||||
response inline so metadata loading, playback, and seeking work remotely.
|
||||
"""
|
||||
return _managed_file_response(
|
||||
request,
|
||||
path,
|
||||
content_disposition_type="inline",
|
||||
media_only=True,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -92,7 +92,8 @@ def _seed_file(client, root, name="out/hello.txt"):
|
||||
|
||||
def test_download_authenticates_via_query_token(forced_files_client):
|
||||
client, root = forced_files_client
|
||||
file_path = _seed_file(client, root)
|
||||
file_path = _seed_file(client, root, name="out/demo.mp4")
|
||||
active_content = _seed_file(client, root, name="out/page.html")
|
||||
|
||||
# Drop the session header so only the ?token= query param authenticates —
|
||||
# mirrors a browser/shell-opened download that can't set the session header.
|
||||
@@ -104,6 +105,24 @@ def test_download_authenticates_via_query_token(forced_files_client):
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
assert ok.content == b"hello"
|
||||
assert ok.headers["content-disposition"].startswith("attachment;")
|
||||
|
||||
playback = client.get(
|
||||
"/api/files/download",
|
||||
params={"path": str(file_path), "token": web_server._SESSION_TOKEN},
|
||||
headers={"Sec-Fetch-Dest": "video", "Range": "bytes=1-3"},
|
||||
)
|
||||
assert playback.status_code == 206
|
||||
assert playback.content == b"ell"
|
||||
assert playback.headers["content-disposition"].startswith("inline;")
|
||||
assert playback.headers["x-content-type-options"] == "nosniff"
|
||||
|
||||
rejected = client.get(
|
||||
"/api/files/download",
|
||||
params={"path": str(active_content), "token": web_server._SESSION_TOKEN},
|
||||
headers={"Sec-Fetch-Dest": "video"},
|
||||
)
|
||||
assert rejected.status_code == 415
|
||||
|
||||
assert client.get(
|
||||
"/api/files/download", params={"path": str(file_path), "token": "nope"}
|
||||
@@ -113,14 +132,66 @@ def test_download_authenticates_via_query_token(forced_files_client):
|
||||
).status_code == 401
|
||||
|
||||
|
||||
def test_stream_requires_header_auth_and_supports_ranges(forced_files_client):
|
||||
client, root = forced_files_client
|
||||
file_path = _seed_file(client, root, name="out/demo.mp4")
|
||||
|
||||
# Electron's main-process proxy supplies the connection credential as a
|
||||
# header. Unlike browser-visible download links, the stream endpoint must
|
||||
# not accept credentials in its URL.
|
||||
params = {"path": str(file_path)}
|
||||
|
||||
full = client.get("/api/files/stream", params=params)
|
||||
assert full.status_code == 200
|
||||
assert full.content == b"hello"
|
||||
assert full.headers["content-type"] == "video/mp4"
|
||||
assert full.headers["content-disposition"].startswith("inline;")
|
||||
assert full.headers["accept-ranges"] == "bytes"
|
||||
assert full.headers["x-content-type-options"] == "nosniff"
|
||||
|
||||
partial = client.get(
|
||||
"/api/files/stream",
|
||||
params=params,
|
||||
headers={"Range": "bytes=1-3"},
|
||||
)
|
||||
assert partial.status_code == 206
|
||||
assert partial.content == b"ell"
|
||||
assert partial.headers["content-range"] == "bytes 1-3/5"
|
||||
assert partial.headers["content-disposition"].startswith("inline;")
|
||||
assert partial.headers["x-content-type-options"] == "nosniff"
|
||||
|
||||
head = client.head("/api/files/stream", params=params)
|
||||
assert head.status_code == 200
|
||||
assert head.content == b""
|
||||
assert head.headers["content-length"] == "5"
|
||||
assert head.headers["x-content-type-options"] == "nosniff"
|
||||
|
||||
del client.headers[web_server._SESSION_HEADER_NAME]
|
||||
assert client.get(
|
||||
"/api/files/stream",
|
||||
params={"path": str(file_path), "token": web_server._SESSION_TOKEN},
|
||||
).status_code == 401
|
||||
assert client.get("/api/files/stream", params=params).status_code == 401
|
||||
|
||||
|
||||
def test_stream_rejects_non_media_active_content(forced_files_client):
|
||||
client, root = forced_files_client
|
||||
|
||||
for name in ("out/page.html", "out/image.svg"):
|
||||
file_path = _seed_file(client, root, name=name)
|
||||
response = client.get("/api/files/stream", params={"path": str(file_path)})
|
||||
assert response.status_code == 415
|
||||
assert response.json()["detail"] == "Unsupported media type"
|
||||
|
||||
|
||||
def test_query_token_does_not_authenticate_other_endpoints(forced_files_client):
|
||||
client, root = forced_files_client
|
||||
file_path = _seed_file(client, root)
|
||||
|
||||
del client.headers[web_server._SESSION_HEADER_NAME]
|
||||
|
||||
# The query-token escape hatch is scoped to /api/files/download only; it must
|
||||
# not unlock the rest of the API surface.
|
||||
# The query-token escape hatch is scoped to downloads only; it must not
|
||||
# unlock the rest of the API surface.
|
||||
leaked = client.get(
|
||||
"/api/files/read",
|
||||
params={"path": str(file_path), "token": web_server._SESSION_TOKEN},
|
||||
@@ -253,6 +324,7 @@ def test_other_credential_store_basenames_blocked(forced_files_client):
|
||||
p.write_text("SECRET=abc123")
|
||||
assert client.get("/api/files/read", params={"path": str(p)}).status_code == 403, name
|
||||
assert client.get("/api/files/download", params={"path": str(p)}).status_code == 403, name
|
||||
assert client.get("/api/files/stream", params={"path": str(p)}).status_code == 403, name
|
||||
|
||||
listing = client.get("/api/files", params={"path": str(root)})
|
||||
names = [e["name"] for e in listing.json()["entries"]]
|
||||
@@ -295,6 +367,7 @@ def test_credential_dir_trees_blocked_on_subdir_descent(forced_files_client):
|
||||
for p in (mcp_file, pairing_file):
|
||||
assert client.get("/api/files/read", params={"path": str(p)}).status_code == 403, str(p)
|
||||
assert client.get("/api/files/download", params={"path": str(p)}).status_code == 403, str(p)
|
||||
assert client.get("/api/files/stream", params={"path": str(p)}).status_code == 403, str(p)
|
||||
|
||||
# Listing the credential dir itself yields nothing exploitable: every child
|
||||
# is filtered because the parent component is a credential dir.
|
||||
|
||||
Reference in New Issue
Block a user