Skip to content

The agent that grows with you

fix(desktop): play YouTube embeds through a loopback player host

Brooklyn Nicholson7817bf522af3
diff --git a/apps/desktop/electron/embed-host.test.ts b/apps/desktop/electron/embed-host.test.ts
new file mode 100644
index 00000000000..7d4a3b0006a
--- /dev/null
+++ b/apps/desktop/electron/embed-host.test.ts
@@ -0,0 +1,65 @@
+import assert from 'node:assert/strict'
+import http from 'node:http'
+
+import { test } from 'vitest'
+
+import { startEmbedHost, youtubeWrapperFor } from './embed-host'
+
+const ORIGIN = 'http://127.0.0.1:5555'
+
+function get(origin: string, path: string, host = new URL(origin).host) {
+ return new Promise<{ body: string; headers: http.IncomingHttpHeaders; status: number }>((resolve, reject) => {
+ const request = http.get(`${origin}${path}`, { headers: { host } }, response => {
+ let body = ''
+ response.on('data', chunk => (body += chunk))
+ response.on('end', () => resolve({ body, headers: response.headers, status: response.statusCode ?? 0 }))
+ })
+
+ request.on('error', reject)
+ })
+}
+
+test('wraps the player with an origin YouTube can match', () => {
+ const html = youtubeWrapperFor('/youtube/M7lc1UVf-VE?start=42&rel=0&modestbranding=1', ORIGIN)!
+ const src = new URL(/src="([^"]+)"/.exec(html)![1].replaceAll('&amp;', '&'))
+
+ assert.equal(src.origin, 'https://www.youtube-nocookie.com')
+ assert.equal(src.pathname, '/embed/M7lc1UVf-VE')
+ assert.equal(src.searchParams.get('origin'), ORIGIN)
+ assert.equal(src.searchParams.get('start'), '42')
+ assert.equal(src.searchParams.get('rel'), '0')
+ assert.match(html, /allowfullscreen/)
+})
+
+test('serves nothing but a well-formed video id', () => {
+ for (const path of ['/', '/youtube/', '/youtube/short', '/youtube/M7lc1UVf-VE/x', '/youtube/"><script>x', '/other']) {
+ assert.equal(youtubeWrapperFor(path, ORIGIN), null, path)
+ }
+})
+
+test('drops unknown and non-numeric params instead of forwarding them', () => {
+ const html = youtubeWrapperFor('/youtube/M7lc1UVf-VE?start=1"x&autoplay=1&origin=https://evil.test', ORIGIN)!
+ const src = new URL(/src="([^"]+)"/.exec(html)![1].replaceAll('&amp;', '&'))
+
+ assert.equal(src.searchParams.get('start'), null)
+ assert.equal(src.searchParams.get('autoplay'), null)
+ assert.equal(src.searchParams.get('origin'), ORIGIN)
+})
+
+test('the live host serves the wrapper locked down, and only to its own Host', async t => {
+ const host = await startEmbedHost()
+ t.onTestFinished(() => host.close())
+
+ assert.match(host.origin, /^http:\/\/127\.0\.0\.1:\d+$/)
+
+ const ok = await get(host.origin, '/youtube/M7lc1UVf-VE')
+ assert.equal(ok.status, 200)
+ assert.match(
+ String(ok.headers['content-security-policy']),
+ /default-src 'none'; frame-src https:\/\/www\.youtube-nocookie\.com/
+ )
+ assert.match(ok.body, new RegExp(`origin=${encodeURIComponent(host.origin)}`))
+
+ assert.equal((await get(host.origin, '/youtube/nope')).status, 404)
+ assert.equal((await get(host.origin, '/youtube/M7lc1UVf-VE', 'evil.test')).status, 404)
+})
diff --git a/apps/desktop/electron/embed-host.ts b/apps/desktop/electron/embed-host.ts
new file mode 100644
index 00000000000..012a61b29ed
--- /dev/null
+++ b/apps/desktop/electron/embed-host.ts
@@ -0,0 +1,107 @@
+import http from 'node:http'
+import type { AddressInfo } from 'node:net'
+
+// YouTube refuses to play (error 153) unless the embedding page has an http(s)
+// origin it can match against the player's `origin` param, and on modern
+// Electron a stamped Referer header is dropped. The packaged renderer is a
+// file:// page, so it can't host the player itself. This loopback host serves
+// one tiny wrapper page per video; the renderer iframes the wrapper and the
+// wrapper iframes the player. Only the wrapper gets an http origin — the
+// renderer, its storage and its backend connections stay on file://.
+
+const YOUTUBE_ID_RE = /^[A-Za-z0-9_-]{11}$/
+const PLAYER_ORIGIN = 'https://www.youtube-nocookie.com'
+const PASSTHROUGH_PARAMS = ['modestbranding', 'rel', 'start'] as const
+
+const ALLOW =
+ 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen'
+
+interface EmbedHost {
+ close: () => Promise<void>
+ origin: string
+}
+
+function wrapperHtml(playerUrl: string): string {
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="referrer" content="strict-origin-when-cross-origin"><style>html,body,iframe{margin:0;width:100%;height:100%;border:0;background:transparent;overflow:hidden}</style></head><body><iframe src="${playerUrl}" allow="${ALLOW}" allowfullscreen referrerpolicy="strict-origin-when-cross-origin" title="YouTube embed"></iframe></body></html>`
+}
+
+/** The wrapper document for a request path, or null for anything we don't serve. */
+function youtubeWrapperFor(requestUrl: string, origin: string): null | string {
+ const url = new URL(requestUrl, origin)
+ const match = /^\/youtube\/([^/]+)$/.exec(url.pathname)
+
+ if (!match || !YOUTUBE_ID_RE.test(match[1])) {
+ return null
+ }
+
+ const player = new URL(`/embed/${match[1]}`, PLAYER_ORIGIN)
+
+ for (const key of PASSTHROUGH_PARAMS) {
+ const value = url.searchParams.get(key)
+
+ if (value && /^\d+$/.test(value)) {
+ player.searchParams.set(key, value)
+ }
+ }
+
+ player.searchParams.set('origin', origin)
+
+ return wrapperHtml(player.toString().replaceAll('&', '&amp;'))
+}
+
+async function startEmbedHost(): Promise<EmbedHost> {
+ let origin = ''
+
+ const server = http.createServer((request, response) => {
+ // Loopback only, and only our own Host: a page that DNS-rebinds onto this
+ // port gets nothing.
+ if (request.method !== 'GET' || request.headers.host !== new URL(origin).host) {
+ response.writeHead(404).end()
+
+ return
+ }
+
+ const html = youtubeWrapperFor(request.url || '/', origin)
+
+ if (!html) {
+ response.writeHead(404).end()
+
+ return
+ }
+
+ response.writeHead(200, {
+ 'Cache-Control': 'no-store',
+ 'Content-Security-Policy': `default-src 'none'; frame-src ${PLAYER_ORIGIN}; style-src 'unsafe-inline'`,
+ 'Content-Type': 'text/html; charset=utf-8',
+ 'X-Content-Type-Options': 'nosniff'
+ })
+ response.end(html)
+ })
+
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen({ host: '127.0.0.1', port: 0 }, () => resolve())
+ })
+
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+
+ return {
+ close: () => new Promise<void>(done => server.close(() => done())),
+ origin
+ }
+}
+
+let shared: null | Promise<EmbedHost> = null
+
+/** Start the host on first use; later callers share it. A failed start retries next time. */
+function embedHostOrigin(): Promise<string> {
+ shared ??= startEmbedHost().catch(error => {
+ shared = null
+
+ throw error
+ })
+
+ return shared.then(host => host.origin)
+}
+
+export { embedHostOrigin, startEmbedHost, youtubeWrapperFor }
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 84fa362271c..5f45ee34de7 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -240,6 +240,7 @@ import {
} from './desktop-uninstall'
import { describeDevCdpDecision, resolveDevCdpPort } from './dev-cdp'
import { preReadyDockLaunchSteps } from './dock-launch-order'
+import { embedHostOrigin } from './embed-host'
import { installEmbedReferer } from './embed-referer'
import { createAmbientClaimArbiter } from './event-dedupe'
import { openExternalUrl as externalOpen, type ExternalOpenDeps, reportPreOpenStatFailure } from './external-open'
@@ -1175,6 +1176,7 @@ if (IS_WINDOWS || process.platform === 'linux') {
}
ipcMain.handle('hermes:get-remote-display-reason', () => REMOTE_DISPLAY_REASON)
+ipcMain.handle('hermes:embed-host:origin', () => embedHostOrigin())
// Keep the renderer's PROCESS priority normal while its windows are hidden —
// a deprioritized renderer streams a live answer visibly slower once the
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 23948840b2f..7efa03a9de7 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -37,6 +37,8 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
guestOnboardingEnabled: launchFlags?.guestOnboarding === true,
localSkin: localSkin && typeof localSkin === 'object' ? localSkin : null,
getConnection: (profile, opts) => ipcRenderer.invoke('hermes:connection', profile, opts),
+ // Loopback origin that hosts YouTube's player for the file:// renderer.
+ getEmbedHostOrigin: () => ipcRenderer.invoke('hermes:embed-host:origin'),
// Registry-scoped backend resolution: { connectionId, profile } → descriptor.
getConnectionFor: payload => ipcRenderer.invoke('hermes:connection:for', payload),
getProfileRoutes: profiles => ipcRenderer.invoke('hermes:plugin-profile-routes', profiles),
diff --git a/apps/desktop/src/components/assistant-ui/embeds/youtube-embed.test.tsx b/apps/desktop/src/components/assistant-ui/embeds/youtube-embed.test.tsx
new file mode 100644
index 00000000000..d84407c5977
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/embeds/youtube-embed.test.tsx
@@ -0,0 +1,33 @@
+import { cleanup, render } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { detectEmbed } from './providers'
+import type { FrameEmbed } from './providers/types'
+import YouTubeEmbedRenderer, { wrappedYoutubeSrc } from './youtube-embed'
+
+afterEach(cleanup)
+
+const descriptor = detectEmbed('https://www.youtube.com/watch?v=M7lc1UVf-VE&t=42') as FrameEmbed
+
+describe('YouTubeEmbedRenderer', () => {
+ it('embeds directly with its own origin on an http renderer, never asking for the host', () => {
+ const getEmbedHostOrigin = vi.fn()
+ window.hermesDesktop = { ...window.hermesDesktop, getEmbedHostOrigin }
+
+ const { container } = render(<YouTubeEmbedRenderer descriptor={descriptor} />)
+ const src = new URL(container.querySelector('iframe')!.src)
+
+ expect(src.origin).toBe('https://www.youtube-nocookie.com')
+ expect(src.searchParams.get('origin')).toBe(window.location.origin)
+ expect(getEmbedHostOrigin).not.toHaveBeenCalled()
+ })
+
+ it('maps the player URL onto the loopback wrapper with the same video and params', () => {
+ const src = new URL(wrappedYoutubeSrc(descriptor.embedUrl, 'http://127.0.0.1:5555'))
+
+ expect(src.origin).toBe('http://127.0.0.1:5555')
+ expect(src.pathname).toBe('/youtube/M7lc1UVf-VE')
+ expect(src.searchParams.get('start')).toBe('42')
+ expect(src.searchParams.get('rel')).toBe('0')
+ })
+})
diff --git a/apps/desktop/src/components/assistant-ui/embeds/youtube-embed.tsx b/apps/desktop/src/components/assistant-ui/embeds/youtube-embed.tsx
index 72eef2e1014..d1c7a80ab52 100644
--- a/apps/desktop/src/components/assistant-ui/embeds/youtube-embed.tsx
+++ b/apps/desktop/src/components/assistant-ui/embeds/youtube-embed.tsx
@@ -1,6 +1,6 @@
'use client'
-import { useMemo } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import type { FrameEmbed } from './providers/types'
import { useIsDark } from './use-is-dark'
@@ -8,27 +8,67 @@ import { useIsDark } from './use-is-dark'
const YOUTUBE_ALLOW =
'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen'
+const hasHttpOrigin = () =>
+ typeof window !== 'undefined' &&
+ (window.location.protocol === 'http:' || window.location.protocol === 'https:') &&
+ Boolean(window.location.origin) &&
+ window.location.origin !== 'null'
+
function youtubeSrc(embedUrl: string): string {
const url = new URL(embedUrl)
// Only pass origin when it is an HTTP(S) origin; custom schemes (app://,
// file://) can make the player reject otherwise embeddable videos.
- if (
- typeof window !== 'undefined' &&
- (window.location.protocol === 'http:' || window.location.protocol === 'https:') &&
- window.location.origin &&
- window.location.origin !== 'null'
- ) {
+ if (hasHttpOrigin()) {
url.searchParams.set('origin', window.location.origin)
}
return url.toString()
}
+/** The same video and params, served through the Desktop loopback wrapper. */
+export function wrappedYoutubeSrc(embedUrl: string, hostOrigin: string): string {
+ const url = new URL(embedUrl)
+ const id = url.pathname.split('/').pop() ?? ''
+
+ return `${hostOrigin}/youtube/${encodeURIComponent(id)}${url.search}`
+}
+
+// The packaged renderer is a file:// page, which YouTube rejects (error 153), so
+// there the player is hosted by a loopback wrapper page (electron/embed-host.ts).
+// Dev and web renderers already have an http origin and embed directly.
+function usePlayerSrc(embedUrl: string): null | string {
+ const direct = useMemo(() => youtubeSrc(embedUrl), [embedUrl])
+ const getHostOrigin = hasHttpOrigin() ? undefined : window.hermesDesktop?.getEmbedHostOrigin
+ const [wrapped, setWrapped] = useState<null | string>(null)
+
+ useEffect(() => {
+ if (!getHostOrigin) {
+ return
+ }
+
+ let live = true
+
+ getHostOrigin()
+ .then(origin => live && setWrapped(wrappedYoutubeSrc(embedUrl, origin)))
+ .catch(() => live && setWrapped(direct))
+
+ return () => {
+ live = false
+ }
+ }, [direct, embedUrl, getHostOrigin])
+
+ return getHostOrigin ? wrapped : direct
+}
+
// Keep this as a plain iframe and let YouTube render its native player/error UI.
export default function YouTubeEmbedRenderer({ descriptor }: { descriptor: FrameEmbed }) {
const isDark = useIsDark()
- const src = useMemo(() => youtubeSrc(descriptor.embedUrl), [descriptor.embedUrl])
+ const src = usePlayerSrc(descriptor.embedUrl)
+
+ if (!src) {
+ return <div className="block aspect-video w-full" />
+ }
// Width is capped to the ratio by UrlEmbed, so aspect-video sizes height ≤ cap.
return (
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index e278bcbef99..79c7244ff35 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -56,6 +56,8 @@ declare global {
// optional profile list is used only by the single-local v1 fallback;
// endpoint and auth material never crosses the IPC boundary.
getProfileRoutes: (profiles: string[]) => Promise<DesktopPluginProfileRoute[]>
+ // Loopback origin serving the YouTube player wrapper (packaged file:// renderer).
+ getEmbedHostOrigin?: () => Promise<string>
// Reconnect-after-wake recovery: liveness-probe the cached PRIMARY backend
// and drop it if a remote one has gone unreachable, so the next
// getConnection() rebuilds a reachable descriptor instead of the renderer