Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(chat): preserve browser login and identity for embedded videos

Chris50ce9ceb6c7d
diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index 922d520d66..8c01e3d91d 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -1,5 +1,3 @@
-import { authorizeVideoEmbed, hardenVideoEmbedSession, installVideoEmbedGuestHandlers } from '../webview-security';
-import { VIDEO_EMBED_PARTITION } from '../../shared/webviewPartition';
/**
* webview-security 单测 —— 模拟恶意 will-attach-webview 输入,断言 hardener 把
* 危险开关全部锁死、partition 强制覆盖。
@@ -40,6 +38,7 @@ import {
LOGIN_CAPTCHA_PARTITION,
} from '../../shared/webviewPartition';
import { getEffectiveAppShortcuts, type AppShortcutId } from '../../shared/appShortcuts';
+import { CURRENT_APP_ID } from '../../shared/brandRegion';
import * as appSessionState from '../appSessionState';
import { resolveGhostMediaHandoverTarget } from '../cindy-brain/ghostMediaHandoverTargetTracker';
import {
@@ -58,6 +57,7 @@ import {
installGhostGuestNavigationHandlers,
installGhostMediaHandoverSource,
installBrowserGuestHandlers,
+ installBrowserVideoReferrer,
installDeferredPopupRouter,
installLoginCaptchaGuestHandlers,
isAllowedLoginCaptchaUrl,
@@ -67,6 +67,26 @@ import {
setRsbPopupOpenerResolver,
} from '../webview-security';
+// Unit: login return/reload sent YouTube's own URL as Referer and the real
+// embedded player returned 152-4. Exercise the request callback, not source text.
+it('retains app identity on player return without replacing website embed origins', () => {
+ const onBeforeSendHeaders = vi.fn();
+ const browserSession = { webRequest: { onBeforeSendHeaders } } as unknown as Session;
+ installBrowserVideoReferrer(browserSession);
+ installBrowserVideoReferrer(browserSession);
+ expect(onBeforeSendHeaders).toHaveBeenCalledTimes(1);
+ const [filter, request] = onBeforeSendHeaders.mock.calls[0];
+ expect(filter.urls).toEqual(['https://www.youtube.com/embed/*']);
+ for (const referrer of [undefined, 'https://www.youtube.com/embed/E5wWVwe7-6E', 'https://www.youtube.com/']) {
+ const callback = vi.fn();
+ request({ requestHeaders: { ...(referrer ? { referer: referrer } : {}), Accept: 'text/html' } }, callback);
+ expect(callback).toHaveBeenCalledWith({ requestHeaders: { Referer: `https://${CURRENT_APP_ID}/`, Accept: 'text/html' } });
+ }
+ const callback = vi.fn();
+ request({ requestHeaders: { Referer: 'https://example.org/article' } }, callback);
+ expect(callback).toHaveBeenCalledWith({ requestHeaders: { Referer: 'https://example.org/article' } });
+});
+
describe('applyWebviewHardening', () => {
it('locks down all webPreferences fields per Codex tY', () => {
const webPreferences: Record<string, unknown> = {
@@ -128,8 +148,10 @@ describe('applyWebviewHardening', () => {
expect(webPreferences.preload).toBe('/app/.vite/build/browserCommentPreload.js');
});
- it('forces partition to BROWSER_PARTITION (overrides any renderer-set value)', () => {
- const webPreferences: Record<string, unknown> = {};
+ // Unit: Chromium selects the actual cookie store from WebPreferences, not
+ // only tag params. The old video partition must not survive browser routing.
+ it('forces the actual guest cookie store to the browser partition', () => {
+ const webPreferences: Record<string, unknown> = { partition: 'cindy-video-embed' };
const params: Record<string, string> = {
partition: 'persist:evil-other-session',
};
@@ -137,6 +159,7 @@ describe('applyWebviewHardening', () => {
applyWebviewHardening(webPreferences, params);
expect(params.partition).toBe(BROWSER_PARTITION);
+ expect(webPreferences.partition).toBe(BROWSER_PARTITION);
});
it('fills BROWSER_PARTITION when renderer did not set partition at all', () => {
@@ -1322,62 +1345,3 @@ describe('resolveGuestShortcutAction', () => {
expect(resolveGuestShortcutAction(key('KeyT', { meta: true }), getCombos)).toBeNull();
});
});
-
-// Unit: reported video-page playback needs a new guest branch; existing browser
-// tests do not cover this zero-bridge session, app identity or its navigation gate.
-describe('YouTube embedded player isolation', () => {
- const url = 'https://www.youtube-nocookie.com/embed/glW1pXWebnY?playsinline=1&autoplay=0';
- it('accepts canonical player URLs and removes all privileged guest settings', () => {
- const prefs: Record<string, unknown> = { preload: '/evil', nodeIntegration: true, webSecurity: false };
- const params = { src: url, partition: VIDEO_EMBED_PARTITION, allowpopups: 'true' };
- expect(authorizeVideoEmbed(prefs, params)).toBe(true);
- expect(prefs).toMatchObject({ partition: VIDEO_EMBED_PARTITION, sandbox: true, contextIsolation: true, webSecurity: true, nodeIntegration: false });
- expect(prefs.preload).toBeUndefined();
- expect(params.allowpopups).toBe('true');
- expect(prefs.disablePopups).toBe(false);
- expect(authorizeVideoEmbed({}, { ...params, src: 'https://example.com' })).toBe(false);
- });
- it('provides the app referer only for player requests and denies devices, downloads and navigation', () => {
- const session = Object.assign(new EventEmitter(), {
- setPermissionRequestHandler: vi.fn(), setPermissionCheckHandler: vi.fn(),
- webRequest: { onBeforeSendHeaders: vi.fn() },
- });
- hardenVideoEmbedSession(session as unknown as Session);
- hardenVideoEmbedSession(session as unknown as Session);
- expect(session.webRequest.onBeforeSendHeaders).toHaveBeenCalledTimes(1);
- const reply = vi.fn();
- session.webRequest.onBeforeSendHeaders.mock.calls[0][1]({ url, requestHeaders: {} }, reply);
- expect(reply.mock.calls[0][0].requestHeaders.Referer).toMatch(/^https:\/\/[^/]+\/$/);
- const permission = session.setPermissionRequestHandler.mock.calls[0][0];
- permission({ getURL: () => url }, 'camera', reply);
- expect(reply).toHaveBeenLastCalledWith(false);
- const deny = { preventDefault: vi.fn() };
- session.emit('will-download', deny);
- expect(deny.preventDefault).toHaveBeenCalledTimes(1);
- const guest = Object.assign(new EventEmitter(), { getURL: () => url, setWindowOpenHandler: vi.fn() });
- const openExternal = vi.fn().mockResolvedValue(undefined);
- installVideoEmbedGuestHandlers(guest as unknown as WebContents, openExternal);
- guest.emit('will-navigate', deny, 'file:///private');
- guest.emit('will-redirect', deny, 'https://example.com');
- expect(deny.preventDefault).toHaveBeenCalledTimes(3);
- expect(guest.setWindowOpenHandler.mock.calls[0][0]({ url: 'javascript:alert(1)' })).toEqual({ action: 'deny' });
- expect(openExternal).not.toHaveBeenCalled();
- });
- // Unit: login/help buttons were silently swallowed. Existing isolation coverage
- // did not exercise valid player links; no account page may enter the guest.
- it('opens player login and help links in the browser while denying native popups and redirects', () => {
- const guest = Object.assign(new EventEmitter(), { getURL: () => url, setWindowOpenHandler: vi.fn() });
- const openExternal = vi.fn().mockResolvedValue(undefined);
- installVideoEmbedGuestHandlers(guest as unknown as WebContents, openExternal);
- const popup = guest.setWindowOpenHandler.mock.calls[0][0];
- expect(popup({ url: 'https://accounts.google.com/ServiceLogin?continue=https://evil.test' })).toEqual({ action: 'deny' });
- expect(openExternal).toHaveBeenLastCalledWith('https://www.youtube.com/watch?v=glW1pXWebnY');
- const deny = { preventDefault: vi.fn() };
- guest.emit('will-navigate', deny, 'https://support.google.com/youtube/answer/3037019');
- expect(openExternal).toHaveBeenLastCalledWith('https://support.google.com/youtube/answer/3037019');
- guest.emit('will-redirect', deny, 'https://accounts.google.com/ServiceLogin');
- popup({ url: 'https://youtube.com.evil.test/watch?v=glW1pXWebnY' });
- expect(openExternal).toHaveBeenCalledTimes(2);
- expect(deny.preventDefault).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index 5e29facc5d..6cc5d3b192 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -1,6 +1,3 @@
-import { isYoutubeEmbedUrl, youtubePlayerExternalUrl } from '@cindy/maker-shared/rich-answer';
-import { CURRENT_APP_ID } from '../shared/brandRegion';
-import { VIDEO_EMBED_PARTITION } from '../shared/webviewPartition';
/**
* webview-security — RSB 内置浏览器 (web-browser plugin) 用的 `<webview>` 加固。
*
@@ -27,8 +24,8 @@ import { VIDEO_EMBED_PARTITION } from '../shared/webviewPartition';
import path from 'node:path';
-import { app, session, shell, type BrowserWindow, type Session, type WebContents } from 'electron';
-import { createLogger } from './logger';
+import { app, session, type BrowserWindow, type Session, type WebContents } from 'electron';
+import { CURRENT_APP_ID } from '../shared/brandRegion';
import {
BROWSER_PARTITION,
@@ -111,6 +108,7 @@ export function applyWebviewHardening(
// 也跑在我们指定的隔离 session 里(cookies / IDB / cache 单一来源)。Codex
// 用 Tb('app') 映射拿 partition 字符串,我们用单一常量,实质等价。
params.partition = BROWSER_PARTITION;
+ webPreferences.partition = BROWSER_PARTITION;
// ── webPreferences:guest 页面的渲染环境 ────────────────────────────────────
// 全部对齐 Codex tY(line 49849-49859):
@@ -939,55 +937,24 @@ export function installGhostMediaHandoverSource(
hostContents.once('destroyed', revoke);
}
-/** Reuse the zero-bridge guest hardening; only the canonical player URL may attach. */
-export function authorizeVideoEmbed(webPreferences: Record<string, unknown>, params: Record<string, string>): boolean {
- if (params.partition !== VIDEO_EMBED_PARTITION || !isYoutubeEmbedUrl(params.src)) return false;
- applyLoginCaptchaWebviewHardening(webPreferences, params);
- webPreferences.partition = VIDEO_EMBED_PARTITION;
- // Main denies native popups and routes validated player links to the browser.
- params.allowpopups = 'true';
- webPreferences.disablePopups = false;
- return true;
-}
-const hardenedVideoSessions = new WeakSet<object>();
-const videoEmbedLog = createLogger('video-embed');
-export function hardenVideoEmbedSession(videoSession: Session): void {
- if (hardenedVideoSessions.has(videoSession)) return;
- videoSession.setPermissionRequestHandler((contents, permission, callback) => {
- callback(permission === 'fullscreen' && isYoutubeEmbedUrl(contents.getURL()));
- });
- videoSession.setPermissionCheckHandler((contents, permission) =>
- permission === 'fullscreen' && !!contents && isYoutubeEmbedUrl(contents.getURL()));
- videoSession.on('will-download', event => event.preventDefault());
- // This is an isolated session, so it cannot replace the app/MCP header listener.
- videoSession.webRequest.onBeforeSendHeaders({ urls: ['https://www.youtube-nocookie.com/embed/*'] }, (details, callback) => {
+const browserVideoReferrers = new WeakSet<Session>();
+
+/** Login redirects/reloads can replace the app Referer with the player's own URL. */
+export function installBrowserVideoReferrer(browserSession: Session): void {
+ if (browserVideoReferrers.has(browserSession)) return;
+ // Single owner for this browser session's header listener; default-session MCP
+ // hooks are separate. Preserve a website's real embedding origin when present.
+ browserSession.webRequest.onBeforeSendHeaders({ urls: ['https://www.youtube.com/embed/*'] }, (details, callback) => {
const headers = { ...details.requestHeaders };
- if (isYoutubeEmbedUrl(details.url)) {
- for (const key of Object.keys(headers)) if (key.toLowerCase() === 'referer') delete headers[key];
+ const key = Object.keys(headers).find(name => name.toLowerCase() === 'referer');
+ const referrer = key ? headers[key] : undefined;
+ if (!referrer || /^https:\/\/www\.youtube\.com(?:\/|$)/i.test(referrer)) {
+ if (key) delete headers[key];
headers.Referer = `https://${CURRENT_APP_ID}/`;
}
callback({ requestHeaders: headers });
});
- hardenedVideoSessions.add(videoSession);
-}
-export function installVideoEmbedGuestHandlers(
- guest: WebContents,
- openExternal: (url: string) => Promise<void> = url => shell.openExternal(url),
-): void {
- const openPlayerLink = (url: string) => {
- const target = youtubePlayerExternalUrl(guest.getURL(), url);
- if (target) void openExternal(target).catch(() => videoEmbedLog.warn('Could not open source in browser'));
- };
- guest.setWindowOpenHandler(details => {
- openPlayerLink(details.url);
- return { action: 'deny' };
- });
- guest.on('will-navigate', (event, url) => {
- if (isYoutubeEmbedUrl(url)) return;
- event.preventDefault();
- openPlayerLink(url);
- });
- guest.on('will-redirect', (event, url) => { if (!isYoutubeEmbedUrl(url)) event.preventDefault(); });
+ browserVideoReferrers.add(browserSession);
}
export function installWebviewHardener(): void {
@@ -997,21 +964,9 @@ export function installWebviewHardener(): void {
// 不装浏览器的 popup 路由与快捷键转发)。
let pendingGhostAttach: ReturnType<typeof authorizeGhostWebviewAttach> = null;
let pendingCaptchaAttach = false;
- let pendingVideoAttach = false;
contents.on('will-attach-webview', (e, webPreferences, params) => {
- pendingVideoAttach = false;
pendingCaptchaAttach = false;
pendingGhostAttach = null;
- if (params.partition === VIDEO_EMBED_PARTITION) {
- if (!authorizeVideoEmbed(webPreferences as unknown as Record<string, unknown>, params)) {
- e.preventDefault();
- return;
- }
- try { hardenVideoEmbedSession(session.fromPartition(VIDEO_EMBED_PARTITION)); }
- catch { e.preventDefault(); return; }
- pendingVideoAttach = true;
- return;
- }
// 意识面板分支:声明了意识分区的 webview 必须验明正身——
// 分区/地址/已装清单三对齐才放行并保留专属分区;验证失败直接拒附加
// (绝不回落到浏览器分区,那会让 cindy-ghost:// 内容跑进错误 session)。
@@ -1052,6 +1007,7 @@ export function installWebviewHardener(): void {
pendingCaptchaAttach = true;
return;
}
+ installBrowserVideoReferrer(session.fromPartition(BROWSER_PARTITION));
applyWebviewHardening(
webPreferences as unknown as Record<string, unknown>,
params,
@@ -1061,11 +1017,6 @@ export function installWebviewHardener(): void {
);
});
contents.on('did-attach-webview', (_e, guestContents) => {
- if (pendingVideoAttach) {
- pendingVideoAttach = false;
- installVideoEmbedGuestHandlers(guestContents);
- return;
- }
if (pendingCaptchaAttach) {
pendingCaptchaAttach = false;
// 挑战页零弹窗;顶层导航只允许停留在托管挑战页白名单内(Turnstile 的
diff --git a/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx b/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx
index ee11e931f2..0e40da5c03 100644
--- a/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx
+++ b/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx
@@ -1,9 +1,10 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { youtubeVideo } from '@cindy/maker-shared/rich-answer';
-import { VIDEO_EMBED_PARTITION } from '@/../shared/webviewPartition';
+import { BROWSER_PARTITION } from '@/../shared/webviewPartition';
+import { CURRENT_APP_ID } from '@/../shared/brandRegion';
-/** Click-to-load, isolated site player. The original link remains available on every failure. */
+/** Click-to-load site player using the built-in browser’s persistent login session. */
export function VideoSitePreview({ src, title }: { src: string; title: string }) {
const video = youtubeVideo(src);
return video ? <YoutubePreview key={video.embed} video={video} title={title} /> : null;
@@ -16,10 +17,10 @@ function YoutubePreview({ video, title }: { video: NonNullable<ReturnType<typeof
if (!active || !host.current) return;
const target = host.current;
const guest = document.createElement('webview');
- guest.setAttribute('partition', VIDEO_EMBED_PARTITION);
- // Let popup requests reach Main's handler; it denies native windows and
- // opens only validated player links in the system browser.
+ guest.setAttribute('partition', BROWSER_PARTITION);
+ // Reuse the browser's session and popup flow so login can return to this player.
guest.setAttribute('allowpopups', '');
+ guest.setAttribute('httpreferrer', `https://${CURRENT_APP_ID}/`);
guest.setAttribute('src', video.embed);
guest.setAttribute('title', title);
guest.setAttribute('style', 'display:flex;width:100%;height:100%');
@@ -31,15 +32,7 @@ function YoutubePreview({ video, title }: { video: NonNullable<ReturnType<typeof
};
guest.addEventListener('did-fail-load', failed);
guest.addEventListener('render-process-gone', stop);
- const visibility = () => { if (document.hidden) stop(); };
- document.addEventListener('visibilitychange', visibility);
- const observer = new IntersectionObserver(entries => {
- if (entries.some(entry => !entry.isIntersecting)) stop();
- });
- observer.observe(target);
return () => {
- observer.disconnect();
- document.removeEventListener('visibilitychange', visibility);
guest.removeEventListener('did-fail-load', failed);
guest.removeEventListener('render-process-gone', stop);
guest.remove();
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx
index ac41a44889..5c15dd92fa 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx
@@ -275,14 +275,18 @@ it('preserves line-height units and keeps dense chart dates on the plot axis', (
// Unit: the user saw a failed <video> for a YouTube page. Mount the production
// site preview; click-to-load, URL replacement and unmount must own the guest.
it('loads a site player on demand, retains its source link and disposes it on replacement', () => {
- vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} });
const view = render(<VideoSitePreview src="https://youtube.com/watch?v=glW1pXWebnY" title="Tutorial" />);
expect(view.container.querySelector('webview')).toBeNull();
expect(screen.getByRole('link').getAttribute('href')).toBe('https://www.youtube.com/watch?v=glW1pXWebnY');
fireEvent.click(screen.getByRole('button'));
const guest = view.container.querySelector('webview')!;
- expect(guest.getAttribute('src')).toContain('youtube-nocookie.com/embed/glW1pXWebnY');
+ expect(guest.getAttribute('src')).toContain('youtube.com/embed/glW1pXWebnY');
expect(view.container.querySelector('video')).toBeNull();
+ // Opening a login page must not discard its player/opener when focus changes.
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(true);
+ fireEvent(document, new Event('visibilitychange'));
+ expect(guest.isConnected).toBe(true);
+ vi.restoreAllMocks();
view.rerender(<VideoSitePreview src="https://youtu.be/6b9FKpTeV28" title="Next" />);
expect(guest.isConnected).toBe(false);
expect(view.container.querySelector('webview')).toBeNull();
diff --git a/apps/desktop/src/shared/webviewPartition.ts b/apps/desktop/src/shared/webviewPartition.ts
index 4c051241aa..78d031bd5b 100644
--- a/apps/desktop/src/shared/webviewPartition.ts
+++ b/apps/desktop/src/shared/webviewPartition.ts
@@ -17,9 +17,6 @@
*/
export const BROWSER_PARTITION = 'persist:xdmaker-browser-app';
-/** Video-site players have no application/browser cookies or preload bridge. */
-export const VIDEO_EMBED_PARTITION = 'cindy-video-embed';
-
/**
* LOGIN_CAPTCHA_PARTITION — 登录页人机验证(Turnstile 托管挑战页)webview 的专用
* 分区。不带 `persist:` 前缀 = 纯内存 session,关闭 overlay 即弃,不与 RSB 浏览器
diff --git a/apps/mobile/src/__tests__/richContentViews.test.tsx b/apps/mobile/src/__tests__/richContentViews.test.tsx
index bcc5956faa..b6b5235b01 100644
--- a/apps/mobile/src/__tests__/richContentViews.test.tsx
+++ b/apps/mobile/src/__tests__/richContentViews.test.tsx
@@ -79,24 +79,24 @@ beforeEach(() => {
});
afterEach(() => { act(() => root.unmount()); runtime.clear(); vi.useRealTimers(); });
-// Unit: the real video component used to swallow login/help taps. The diagram
-// lifecycle tests do not cover navigation; a login popup is the minimal failure.
-it('opens video login/help in the system browser without navigating its isolated WebView', () => {
+// Unit: login was blocked by the actual video component's navigation callback.
+// Existing diagram tests do not exercise site navigation or native cookie policy.
+it('keeps video login and return navigation inside the persistent native WebView', () => {
act(() => root.render(createElement(VideoSitePreview, { src: 'https://youtu.be/E5wWVwe7-6E', title: 'Sound Burger' })));
expect(state.live).toBe(0);
act(() => state.play());
expect(state.live).toBe(1);
const player = state.props;
- player.onOpenWindow({ nativeEvent: { targetUrl: 'https://accounts.google.com/ServiceLogin' } });
- expect(state.openURL).toHaveBeenLastCalledWith('https://www.youtube.com/watch?v=E5wWVwe7-6E');
- expect(player.onShouldStartLoadWithRequest({ url: 'https://support.google.com/youtube/answer/3037019', navigationType: 'click', isTopFrame: true })).toBe(false);
- expect(state.openURL).toHaveBeenLastCalledWith('https://support.google.com/youtube/answer/3037019');
- expect(player.onShouldStartLoadWithRequest({ url: 'https://accounts.google.com/ServiceLogin', navigationType: 'other', isTopFrame: true })).toBe(false);
- for (const targetUrl of ['file:///private', 'javascript:alert(1)', 'https://youtube.com.evil.test/watch?v=E5wWVwe7-6E', 'https://[email protected]/watch?v=E5wWVwe7-6E']) {
- player.onOpenWindow({ nativeEvent: { targetUrl } });
+ expect(player.incognito).not.toBe(true);
+ expect(player.thirdPartyCookiesEnabled).not.toBe(false);
+ expect(player.setSupportMultipleWindows).toBe(false);
+ for (const url of ['https://accounts.google.com/ServiceLogin', player.source.uri, 'https://www.youtube.com/watch?v=E5wWVwe7-6E']) {
+ expect(player.onShouldStartLoadWithRequest({ url, isTopFrame: true })).toBe(true);
}
- expect(state.openURL).toHaveBeenCalledTimes(2);
- expect(player.onShouldStartLoadWithRequest({ url: player.source.uri, isTopFrame: true })).toBe(true);
+ for (const url of ['file:///private', 'javascript:alert(1)', 'https://[email protected]/watch?v=E5wWVwe7-6E']) {
+ expect(player.onShouldStartLoadWithRequest({ url, isTopFrame: true })).toBe(false);
+ }
+ expect(state.openURL).not.toHaveBeenCalled();
});
it('cancels unseen work, keeps visible content during a drag and reuses a snapshot on revisit', () => {
diff --git a/apps/mobile/src/session/VideoSitePreview.tsx b/apps/mobile/src/session/VideoSitePreview.tsx
index 22b5c306a5..7c5a0858b5 100644
--- a/apps/mobile/src/session/VideoSitePreview.tsx
+++ b/apps/mobile/src/session/VideoSitePreview.tsx
@@ -1,13 +1,14 @@
import { useIsFocused } from 'expo-router';
import { typeScale, lineHeight } from '@/theme/tokens';
import { useEffect, useState } from 'react';
-import { AppState, Image, Linking, Pressable, View } from 'react-native';
+import { Image, Linking, Pressable, View } from 'react-native';
import { WebView } from 'react-native-webview';
import * as Application from 'expo-application';
import { useTranslation } from 'react-i18next';
-import { youtubeVideo, isYoutubeEmbedUrl, youtubePlayerExternalUrl } from '@cindy/maker-shared/rich-answer';
+import { youtubeVideo } from '@cindy/maker-shared/rich-answer';
import { Text } from '@/components/AppText';
import { useTheme } from '@/theme';
+import { allowWebsiteNavigation } from './browserAddress';
import { registerMobileMessageWebView } from './mobileMessageWebViewMetrics';
export function VideoSitePreview({ src, title }: { src: string; title: string }) {
@@ -20,14 +21,6 @@ function YoutubePreview({ video, title }: { video: NonNullable<ReturnType<typeof
const focused = useIsFocused();
const [active, setActive] = useState(false);
const [width, setWidth] = useState(0);
- const openPlayerLink = (url: string) => {
- const target = youtubePlayerExternalUrl(video.embed, url);
- if (target) void Linking.openURL(target).catch(() => undefined);
- };
- useEffect(() => {
- const subscription = AppState.addEventListener('change', state => { if (state !== 'active') setActive(false); });
- return () => subscription.remove();
- }, []);
useEffect(() => active ? registerMobileMessageWebView('media') : undefined, [active]);
useEffect(() => { if (!focused) setActive(false); }, [focused]);
const textStyle = { color: colors.textPrimary, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall };
@@ -36,9 +29,6 @@ function YoutubePreview({ video, title }: { video: NonNullable<ReturnType<typeof
key={video.embed}
source={{ uri: video.embed, headers: { Referer: `https://${Application.applicationId ?? 'com.xd.cindy'}/` } }}
style={{ width: '100%', height: Math.max(200, width * 9 / 16), backgroundColor: colors.surface }}
- incognito
- sharedCookiesEnabled={false}
- thirdPartyCookiesEnabled={false}
allowsInlineMediaPlayback
allowsFullscreenVideo
javaScriptEnabled
@@ -50,14 +40,8 @@ function YoutubePreview({ video, title }: { video: NonNullable<ReturnType<typeof
allowUniversalAccessFromFileURLs={false}
mixedContentMode="never"
originWhitelist={['*']}
- scrollEnabled={false}
- setSupportMultipleWindows
- onOpenWindow={event => openPlayerLink(event.nativeEvent.targetUrl)}
- onShouldStartLoadWithRequest={request => {
- if (request.isTopFrame === false || isYoutubeEmbedUrl(request.url)) return true;
- if (request.navigationType === 'click') openPlayerLink(request.url);
- return false;
- }}
+ setSupportMultipleWindows={false}
+ onShouldStartLoadWithRequest={request => allowWebsiteNavigation(request.url)}
onError={() => setActive(false)}
onContentProcessDidTerminate={() => setActive(false)}
/> : <Pressable accessibilityRole="button" accessibilityLabel={t('message.richAnswer.playVideo')} onPress={() => setActive(true)}>
diff --git a/docs/dev-rules/electron-security-and-process-boundaries.md b/docs/dev-rules/electron-security-and-process-boundaries.md
index bd2f8c12d9..827bbdc365 100644
--- a/docs/dev-rules/electron-security-and-process-boundaries.md
+++ b/docs/dev-rules/electron-security-and-process-boundaries.md
@@ -187,16 +187,18 @@ auth-server)+ origin 命中 `setLoginCaptchaOriginResolver` 注入的 auth 端
### 正文视频网站播放器
-YouTube 视频组件使用 `cindy-video-embed` 非持久独立 WebView;不共用浏览器或应用
-Cookie,不注入 preload/IPC,不放宽主窗 CSP。Main 仅接受共享解析器生成的
-`https://www.youtube-nocookie.com/embed/<video-id>` 规范地址,禁止创建原生弹窗、下载、其它
-顶层导航与重定向;设备权限默认拒绝,仅已核验播放器可请求全屏。
-播放器的弹窗请求须到达 Main handler:经过共享解析器核验的 HTTPS YouTube/Google
-登录链接转为系统浏览器打开原视频,YouTube 帮助链接打开帮助页,其余目标拒绝。
-不把登录页装进播放器、不转发登录 continuation、不复制浏览器 Cookie;重定向不触发外部打开。
-专属 session 的请求钩子只向规范播放器请求提供当前安装 App ID 的 HTTPS Referer,
-遵守 YouTube 嵌入身份要求,不覆盖默认 session 的 MCP 请求钩子。点击后才装载,
-不可见/卸载时销毁 guest,原视频外链始终保留。普通视频文件继续走原媒体播放器。
+YouTube 视频组件复用内置浏览器的 `BROWSER_PARTITION` 持久会话、标准 WebView
+加固与原生弹窗路由。用户从播放器登录时,在 Cindy 浏览器完成授权,登录状态保留在同一
+会话中;不得另造无痕视频分区、阻断登录跳转或复制外部浏览器 Cookie。
+共享解析器从核验的视频 ID 生成 `https://www.youtube.com/embed/<video-id>`,
+不执行模型提供的任意 iframe/HTML。点击封面后装载,卸载时销毁 guest;切换焦点或打开
+登录页不会销毁播放器。主窗口 CSP、沙箱、上下文隔离和无 Node 的浏览器基线保持不变。
+
+播放器首次加载通过 WebView `httpreferrer` 提供当前 App ID。浏览器会话的单一请求头
+listener 仅匹配 YouTube `/embed/*`:来源缺失或登录返回变成 YouTube 自身时补上 App ID,
+已有网站嵌入来源原样保留。不注册第二个同会话 listener,也不触及 default session 的
+MCP 请求钩子。此身份要求来自 YouTube 官方文档,不伪装成第三方网站或改写 User-Agent。
+普通视频文件继续走原媒体播放器,原视频外链始终保留。
## 7.CSP、协议与 Electron Fuses
diff --git a/docs/rich-answers.md b/docs/rich-answers.md
index e3878234a3..c93c430a12 100644
--- a/docs/rich-answers.md
+++ b/docs/rich-answers.md
@@ -89,28 +89,25 @@ iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到
## 网站视频(2026-10-18)
-`video.src` 同时识别 YouTube 的 watch、youtu.be、shorts、live 与 embed 链接,
-由客户端从已核验的视频 ID 生成官方嵌入地址;保留起播时间,不传递任意查询参数。
-点击封面后装载播放器,始终显示原视频链接。桌面使用独立无 preload 的 WebView;
-手机复用已有 react-native-webview,无新增原生依赖或指纹变更,退后台/离开页面停止。
-播放器按 YouTube 的应用身份要求提供 Referer。外部媒体文件仍走原播放器,图片链路不变。
-其它网站页面目前只作为链接;不把任意网页误当视频文件,也不执行模型给出的 iframe/HTML。
-视频所有者限制嵌入、网络限制、YouTube 要求登录等仍由官方播放器决定,原链接可供打开。
-播放器内的登录/帮助按钮不能被静默吞掉:桌面和手机校验目标后交给系统浏览器,
-登录入口转到原视频页,帮助入口转到 YouTube 帮助页。不会把浏览器登录态复制回播放器,
-因此浏览器打开与答案内播放是两个独立验收项。
-
-本轮验证:共享 10 项、Desktop 66 项、Mobile 15 项定向回归及两端 typecheck 通过。
-隔离 Desktop 原历史答案的四个真实 YouTube 链接已显示封面和原链接,点击加载官方播放器;
-实际播放被 YouTube 的登录/机器人验证阻止,因此不声明播放验收通过。
-iPhone 18 Pro 模拟器通过本机 fixture 进入生产组件,实际加载同一视频的官方标题、封面与
-播放按钮,浅深色及中文原链接已目检;未完成原生触摸播放、Android 与跨设备端到端验收。
-本次未改图片或媒体文件播放器,不能据此宣称所有外链图片、所有视频网站均已验证。
-
-补充验证(登录按钮):原代码的桌面 Main handler 和手机组件在登录弹窗输入下均复现
-“没有打开任何目标”,回归修复后通过。桌面实测另发现 WebView 标签缺少 allowpopups,
-弹窗在到达 Main 前即被丢弃;补齐标签和 Main 设置后,从用户原历史答案的 Sound Burger
-播放器点击登录,已实际打开系统 Chrome 的同一原视频并播放。未读取或复制登录 Cookie。
-独立匿名 Chrome 的官方 YT.Player 对照(该视频与官方示例 M7lc1UVf-VE)均在 ready 后
-返回 error=150,播放器响应 LOGIN_REQUIRED,时间为 0;因此本轮仍未通过答案内播放,
-不将系统浏览器成功播放等同于答案内成功。手机本轮仅完成组件导航回归,未重跑原生触摸跳转。
+`video.src` 识别 YouTube watch、youtu.be、shorts、live 与 embed 链接,从核验的视频 ID
+生成官方 `youtube.com/embed` 地址;保留起播时间,不传任意查询参数。旧 nocookie 输入仍
+可解析。点击封面后装载,原视频链接始终可用。外部媒体文件、图片与其它网站链接行为不变。
+
+桌面复用 Cindy 内置浏览器的持久会话和登录弹窗路由;不再使用视频专属无痕分区、强制
+外部浏览器登录或离焦销毁播放器。手机复用已有 react-native-webview 的普通持久存储和
+同窗口导航,允许 HTTP(S) 登录与返回,保留对本地文件及非网页协议的拒绝和离开页面清理。
+没有新增原生依赖或指纹变更,也不读取、搬运外部浏览器凭证。
+
+播放器按官方要求提供 App ID Referer。桌面登录返回曾把 Referer 改成 YouTube 自身,
+在已登录状态仍报 152-4;浏览器请求回调补齐缺失/自身来源,保留普通网站的真实嵌入来源。
+它不修改 User-Agent、不关闭 Web Security,也不改变用户账号、IP 或视频所有者的限制。
+
+本轮定向回归:shared 10 项、Desktop 主进程 57 项、正文组件 8 项、Mobile 11 项;两端类型检查。
+旧实现对实际 cookie 分区与手机无痕状态的回归均失败,修复后通过。
+隔离 Desktop 使用原历史答案和用户自行完成的 Google 登录:确认播放器 loggedIn=true;
+错误来源时复现 152-4,恢复 App ID 来源后同一视频返回 OK,视频时间推进且 paused=false。重启测试版后登录态保留,首次装载、刷新和模拟登录返回
+三条路径均返回 OK;连续观察播放时间推进至 3.93 秒,再暂停供用户继续试用。
+iPhone 18 Pro 模拟器从生产组件装载同一官方播放器和原链接;手机登录后的播放、Android
+与跨设备端到端尚未验收,不能据此声明所有外联媒体和环境已通过。
+
+官方接入要求:[YouTube embedded player](https://developers.google.com/youtube/terms/required-minimum-functionality#embedded-youtube-player)。
diff --git a/packages/maker-shared/src/__tests__/richAnswer.test.ts b/packages/maker-shared/src/__tests__/richAnswer.test.ts
index 29f0f2780d..5fe1f5d71e 100644
--- a/packages/maker-shared/src/__tests__/richAnswer.test.ts
+++ b/packages/maker-shared/src/__tests__/richAnswer.test.ts
@@ -1,4 +1,4 @@
-import { youtubeVideo, isYoutubeEmbedUrl } from '../richAnswer';
+import { youtubeVideo } from '../richAnswer';
import { describe, expect, it } from 'vitest';
import { RichAnswerStream, RichInteractionMemory, hasRichAnswer, splitRichAnswer, richDefaults, richEvaluate, richLabel, richResolvedValues, richChart, richCalculationUnavailable, richVisualStyle, richVector, richLinePlot } from '../richAnswer';
// Tier 1: actual stream reducer. Regression targets are partial transport, edits,
@@ -206,10 +206,9 @@ it('routes YouTube pages to canonical players without turning arbitrary URLs int
for (const src of ['https://www.youtube.com/watch?v=glW1pXWebnY', 'https://youtu.be/glW1pXWebnY', 'https://m.youtube.com/shorts/glW1pXWebnY']) {
const video = youtubeVideo(src)!;
expect(video.id).toBe('glW1pXWebnY');
- expect(isYoutubeEmbedUrl(video.embed)).toBe(true);
- expect(isYoutubeEmbedUrl(src)).toBe(false);
+ expect(video.embed).toBe('https://www.youtube.com/embed/glW1pXWebnY?playsinline=1&autoplay=0');
}
expect(youtubeVideo('https://youtu.be/glW1pXWebnY?t=1m2s')?.embed).toContain('start=62');
for (const src of ['https://youtube.com.evil.test/watch?v=glW1pXWebnY', 'https://[email protected]/watch?v=glW1pXWebnY', 'file:///watch?v=glW1pXWebnY', 'https://example.org/movie.mp4', 'https://youtube.com/watch?v=bad']) expect(youtubeVideo(src)).toBeNull();
- expect(isYoutubeEmbedUrl('https://www.youtube-nocookie.com/embed/glW1pXWebnY?autoplay=1')).toBe(false);
+ expect(youtubeVideo('https://www.youtube-nocookie.com/embed/glW1pXWebnY?autoplay=1')?.embed).toBe('https://www.youtube.com/embed/glW1pXWebnY?playsinline=1&autoplay=0');
});
diff --git a/packages/maker-shared/src/richAnswer.ts b/packages/maker-shared/src/richAnswer.ts
index 0f843f4617..0d37e5db30 100644
--- a/packages/maker-shared/src/richAnswer.ts
+++ b/packages/maker-shared/src/richAnswer.ts
@@ -1,5 +1,5 @@
export { richColor, richVisualStyle, richVector } from "./richAnswerVisual";
-export { youtubeVideo, isYoutubeEmbedUrl, youtubePlayerExternalUrl } from "./youtubeVideo";
+export { youtubeVideo } from "./youtubeVideo";
/** Model-neutral, declarative answer components. No code evaluation or I/O. */
export const RICH_ANSWER_LANGUAGE = "cindy-ui";
export const RICH_ANSWER_KINDS = [
diff --git a/packages/maker-shared/src/youtubeVideo.ts b/packages/maker-shared/src/youtubeVideo.ts
index bf7635b50b..786ea47d1a 100644
--- a/packages/maker-shared/src/youtubeVideo.ts
+++ b/packages/maker-shared/src/youtubeVideo.ts
@@ -17,31 +17,9 @@ export function youtubeVideo(source: string): { id: string; embed: string; watch
const start = Number.isSafeInteger(seconds) && seconds > 0 ? seconds : 0;
return {
id,
- embed: `https://www.youtube-nocookie.com/embed/${id}?playsinline=1&autoplay=0${start ? `&start=${start}` : ''}`,
+ embed: `https://www.youtube.com/embed/${id}?playsinline=1&autoplay=0${start ? `&start=${start}` : ''}`,
watch: `https://www.youtube.com/watch?v=${id}${start ? `&t=${start}` : ''}`,
poster: `https://i.ytimg.com/vi/${id}/hqdefault.jpg`,
};
} catch { return null; }
}
-
-/** Host navigation gate: no arbitrary query parameters or non-player pages. */
-export function isYoutubeEmbedUrl(source: string): boolean {
- return youtubeVideo(source)?.embed === source;
-}
-
-/** Player login/help links leave the sandbox; account pages never enter it. */
-export function youtubePlayerExternalUrl(source: string, target: string): string | null {
- if (!isYoutubeEmbedUrl(source)) return null;
- try {
- const url = new URL(target);
- if (url.protocol !== 'https:' || url.username || url.password || url.port) return null;
- if (url.hostname === 'support.google.com' && url.pathname.startsWith('/youtube/')) return url.href;
- if (url.hostname === 'accounts.google.com'
- || ['youtube.com', 'www.youtube.com', 'm.youtube.com', 'www.youtube-nocookie.com', 'youtu.be'].includes(url.hostname)) {
- // Use the browser's own login context, without forwarding sandbox login
- // continuations or copying credentials back into the embedded player.
- return youtubeVideo(target)?.watch ?? youtubeVideo(source)!.watch;
- }
- } catch { /* Invalid or non-web targets remain blocked. */ }
- return null;
-}