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): route embedded video login and help links to browser

Chris65f660e0df59
diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index e4172614f8..922d520d66 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -1333,7 +1333,8 @@ describe('YouTube embedded player isolation', () => {
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).not.toHaveProperty('allowpopups');
+ 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', () => {
@@ -1353,11 +1354,30 @@ describe('YouTube embedded player isolation', () => {
const deny = { preventDefault: vi.fn() };
session.emit('will-download', deny);
expect(deny.preventDefault).toHaveBeenCalledTimes(1);
- const guest = Object.assign(new EventEmitter(), { setWindowOpenHandler: vi.fn() });
- installVideoEmbedGuestHandlers(guest as unknown as WebContents);
+ 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]()).toEqual({ action: 'deny' });
+ 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 c54d6b9655..5e29facc5d 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -1,4 +1,4 @@
-import { isYoutubeEmbedUrl } from '@cindy/maker-shared/rich-answer';
+import { isYoutubeEmbedUrl, youtubePlayerExternalUrl } from '@cindy/maker-shared/rich-answer';
import { CURRENT_APP_ID } from '../shared/brandRegion';
import { VIDEO_EMBED_PARTITION } from '../shared/webviewPartition';
/**
@@ -27,7 +27,8 @@ import { VIDEO_EMBED_PARTITION } from '../shared/webviewPartition';
import path from 'node:path';
-import { app, session, type BrowserWindow, type Session, type WebContents } from 'electron';
+import { app, session, shell, type BrowserWindow, type Session, type WebContents } from 'electron';
+import { createLogger } from './logger';
import {
BROWSER_PARTITION,
@@ -943,9 +944,13 @@ export function authorizeVideoEmbed(webPreferences: Record<string, unknown>, par
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) => {
@@ -965,9 +970,23 @@ export function hardenVideoEmbedSession(videoSession: Session): void {
});
hardenedVideoSessions.add(videoSession);
}
-export function installVideoEmbedGuestHandlers(guest: WebContents): void {
- guest.setWindowOpenHandler(() => ({ action: 'deny' }));
- guest.on('will-navigate', (event, url) => { if (!isYoutubeEmbedUrl(url)) event.preventDefault(); });
+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(); });
}
diff --git a/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx b/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx
index 27bdccd711..ee11e931f2 100644
--- a/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx
+++ b/apps/desktop/src/renderer/components/chat/VideoSitePreview.tsx
@@ -17,6 +17,9 @@ function YoutubePreview({ video, title }: { video: NonNullable<ReturnType<typeof
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('allowpopups', '');
guest.setAttribute('src', video.embed);
guest.setAttribute('title', title);
guest.setAttribute('style', 'display:flex;width:100%;height:100%');
diff --git a/apps/mobile/src/__tests__/richContentViews.test.tsx b/apps/mobile/src/__tests__/richContentViews.test.tsx
index a5a3764ede..bcc5956faa 100644
--- a/apps/mobile/src/__tests__/richContentViews.test.tsx
+++ b/apps/mobile/src/__tests__/richContentViews.test.tsx
@@ -6,10 +6,11 @@ import { MermaidDiagramWebView, type MermaidDiagramWebViewHandle } from '@/sessi
import { MathFormulaWebView } from '@/session/mathWebView';
import { RichContentContext } from '@/session/richContentContext';
import { RichContentRuntime } from '@/session/richContentRuntime';
+import { VideoSitePreview } from '@/session/VideoSitePreview';
const state = vi.hoisted(() => ({
props: {} as any, image: null as any, layout: null as any, mounts: 0, live: 0, imageLive: 0, height: 0,
- dark: false, inject: vi.fn(),
+ dark: false, inject: vi.fn(), play: null as any, openURL: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('react-native', async () => {
const { useEffect } = await import('react');
@@ -19,6 +20,13 @@ vi.mock('react-native', async () => {
state.height = props.style?.find((style: any) => typeof style?.height === 'number')?.height;
return props.children;
},
+ Text: (props: any) => props.children,
+ Pressable: (props: any) => {
+ if (props.accessibilityRole === 'button') state.play = props.onPress;
+ return props.children;
+ },
+ AppState: { addEventListener: () => ({ remove: () => undefined }) },
+ Linking: { openURL: state.openURL },
Image: (props: any) => {
state.image = props;
useEffect(() => { state.imageLive++; return () => { state.imageLive--; }; }, []);
@@ -37,6 +45,12 @@ vi.mock('react-native-webview', async () => {
}) };
});
vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: {} }));
+vi.mock('expo-router', () => ({ useIsFocused: () => true }));
+vi.mock('react-i18next', async importOriginal => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('@/theme/ThemeProvider', () => ({ useTheme: () => ({ colors: {} }) }));
vi.mock('@/theme', () => ({
useThemedStyles: () => ({}),
useTheme: () => ({ mode: state.dark ? 'dark' : 'light', colors: {
@@ -60,10 +74,31 @@ function message(props: any, payload: unknown) { act(() => props.onMessage({ nat
beforeEach(() => {
vi.useFakeTimers(); runtime = new RichContentRuntime();
state.mounts = 0; state.live = 0; state.imageLive = 0; state.image = null; state.layout = null; state.dark = false;
+ state.openURL.mockClear(); state.play = null;
root = createRoot(document.createElement('div'));
});
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', () => {
+ 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(state.openURL).toHaveBeenCalledTimes(2);
+ expect(player.onShouldStartLoadWithRequest({ url: player.source.uri, isTopFrame: true })).toBe(true);
+});
+
it('cancels unseen work, keeps visible content during a drag and reuses a snapshot on revisit', () => {
runtime.onScroll(); render('mermaid', 'graph TD; A-->B'); tick(100);
expect(state.mounts).toBe(0);
diff --git a/apps/mobile/src/session/VideoSitePreview.tsx b/apps/mobile/src/session/VideoSitePreview.tsx
index 475acf54a8..22b5c306a5 100644
--- a/apps/mobile/src/session/VideoSitePreview.tsx
+++ b/apps/mobile/src/session/VideoSitePreview.tsx
@@ -5,7 +5,7 @@ import { AppState, 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 } from '@cindy/maker-shared/rich-answer';
+import { youtubeVideo, isYoutubeEmbedUrl, youtubePlayerExternalUrl } from '@cindy/maker-shared/rich-answer';
import { Text } from '@/components/AppText';
import { useTheme } from '@/theme';
import { registerMobileMessageWebView } from './mobileMessageWebViewMetrics';
@@ -20,6 +20,10 @@ 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();
@@ -48,8 +52,12 @@ function YoutubePreview({ video, title }: { video: NonNullable<ReturnType<typeof
originWhitelist={['*']}
scrollEnabled={false}
setSupportMultipleWindows
- onOpenWindow={() => undefined}
- onShouldStartLoadWithRequest={request => request.isTopFrame === false || isYoutubeEmbedUrl(request.url)}
+ 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;
+ }}
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 a4f461003a..bd2f8c12d9 100644
--- a/docs/dev-rules/electron-security-and-process-boundaries.md
+++ b/docs/dev-rules/electron-security-and-process-boundaries.md
@@ -189,8 +189,11 @@ auth-server)+ origin 命中 `setLoginCaptchaOriginResolver` 注入的 auth 端
YouTube 视频组件使用 `cindy-video-embed` 非持久独立 WebView;不共用浏览器或应用
Cookie,不注入 preload/IPC,不放宽主窗 CSP。Main 仅接受共享解析器生成的
-`https://www.youtube-nocookie.com/embed/<video-id>` 规范地址,禁止弹窗、下载、其它
+`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,原视频外链始终保留。普通视频文件继续走原媒体播放器。
diff --git a/docs/rich-answers.md b/docs/rich-answers.md
index c0c672d07a..e3878234a3 100644
--- a/docs/rich-answers.md
+++ b/docs/rich-answers.md
@@ -96,6 +96,9 @@ iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到
播放器按 YouTube 的应用身份要求提供 Referer。外部媒体文件仍走原播放器,图片链路不变。
其它网站页面目前只作为链接;不把任意网页误当视频文件,也不执行模型给出的 iframe/HTML。
视频所有者限制嵌入、网络限制、YouTube 要求登录等仍由官方播放器决定,原链接可供打开。
+播放器内的登录/帮助按钮不能被静默吞掉:桌面和手机校验目标后交给系统浏览器,
+登录入口转到原视频页,帮助入口转到 YouTube 帮助页。不会把浏览器登录态复制回播放器,
+因此浏览器打开与答案内播放是两个独立验收项。
本轮验证:共享 10 项、Desktop 66 项、Mobile 15 项定向回归及两端 typecheck 通过。
隔离 Desktop 原历史答案的四个真实 YouTube 链接已显示封面和原链接,点击加载官方播放器;
@@ -103,3 +106,11 @@ iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到
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;因此本轮仍未通过答案内播放,
+不将系统浏览器成功播放等同于答案内成功。手机本轮仅完成组件导航回归,未重跑原生触摸跳转。
diff --git a/packages/maker-shared/src/richAnswer.ts b/packages/maker-shared/src/richAnswer.ts
index 4c6f233ea9..0f843f4617 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 } from "./youtubeVideo";
+export { youtubeVideo, isYoutubeEmbedUrl, youtubePlayerExternalUrl } 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 9bc36aba32..bf7635b50b 100644
--- a/packages/maker-shared/src/youtubeVideo.ts
+++ b/packages/maker-shared/src/youtubeVideo.ts
@@ -28,3 +28,20 @@ export function youtubeVideo(source: string): { id: string; embed: string; watch
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;
+}