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。

feat(desktop): confirm ghost external links (#2969)

xutianqi689cbbf38624
diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index 4b525acac7..0c02a3cff1 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -44,6 +44,7 @@ import {
RSB_BROWSER_POPUP_CHANNEL,
applyGhostWebviewHardening,
applyWebviewHardening,
+ installGhostGuestNavigationHandlers,
installBrowserGuestHandlers,
installDeferredPopupRouter,
isGuestShortcutKeyDownType,
@@ -308,6 +309,74 @@ describe('applyGhostWebviewHardening(意识面板 webview)', () => {
});
});
+describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用导航链)', () => {
+ function makeHarness() {
+ let openHandler: (() => { action: 'deny' }) | null = null;
+ const guest = new EventEmitter() as EventEmitter & {
+ setWindowOpenHandler: ReturnType<typeof vi.fn>;
+ };
+ guest.setWindowOpenHandler = vi.fn((handler) => {
+ openHandler = handler;
+ });
+ const host = { id: 10 } as unknown as WebContents;
+ const preview = vi.fn();
+ const external = vi.fn();
+ installGhostGuestNavigationHandlers(host, guest as unknown as WebContents, 'xd-sites', {
+ preview,
+ external,
+ });
+ return { guest, host, preview, external, getOpenHandler: () => openHandler };
+ }
+
+ it('普通 HTTPS <a> 的 will-navigate 被拦下并带真实 host/guest 交给外链处理', () => {
+ const harness = makeHarness();
+ const event = { preventDefault: vi.fn() };
+
+ harness.guest.emit('will-navigate', event, 'https://workers.xd.team/workspace/published');
+
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(harness.external).toHaveBeenCalledWith(
+ 'xd-sites',
+ 'https://workers.xd.team/workspace/published',
+ harness.host,
+ harness.guest,
+ );
+ expect(harness.preview).not.toHaveBeenCalled();
+ });
+
+ it('预览仍走既有处理,同 Ghost 协议普通页面仍允许原位导航', () => {
+ const harness = makeHarness();
+ const previewEvent = { preventDefault: vi.fn() };
+ const allowEvent = { preventDefault: vi.fn() };
+ const hash = 'a'.repeat(64);
+
+ harness.guest.emit('will-navigate', previewEvent, `cindy-ghost://xd-sites/preview/${hash}.png`);
+ harness.guest.emit('will-navigate', allowEvent, 'cindy-ghost://xd-sites/panel.html');
+
+ expect(previewEvent.preventDefault).toHaveBeenCalledOnce();
+ expect(harness.preview).toHaveBeenCalledOnce();
+ expect(allowEvent.preventDefault).not.toHaveBeenCalled();
+ });
+
+ it('HTTP/自定义协议被静默拦下,不进入外链处理', () => {
+ const harness = makeHarness();
+ for (const url of ['http://workers.xd.team/', 'custom://workers.xd.team/']) {
+ const event = { preventDefault: vi.fn() };
+ harness.guest.emit('will-navigate', event, url);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ }
+ expect(harness.external).not.toHaveBeenCalled();
+ });
+
+ it('target=_blank / window.open 继续由 setWindowOpenHandler 一律 deny', () => {
+ const harness = makeHarness();
+
+ expect(harness.guest.setWindowOpenHandler).toHaveBeenCalledOnce();
+ expect(harness.getOpenHandler()?.()).toEqual({ action: 'deny' });
+ expect(harness.external).not.toHaveBeenCalled();
+ });
+});
+
describe('installDeferredPopupRouter', () => {
afterEach(() => {
vi.useRealTimers();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index eedec3ea69..bd09c70c0c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1458,6 +1458,31 @@ describe('FORGE_GUIDE', () => {
expect(FORGE_GUIDE).toContain('会在插件边界固定映射为 `en`');
});
+ it('settingsHtml / panel 普通 HTTPS 外链契约与宿主安全闸一致', () => {
+ const settingsSection = FORGE_GUIDE.slice(
+ FORGE_GUIDE.indexOf('## 4.8 设置自绘(settingsHtml)+ 自定义参数存取(/kv)'),
+ FORGE_GUIDE.indexOf('## 4.9'),
+ );
+ for (const marker of [
+ '<a href="https://…">',
+ 'network.secrets[].url',
+ 'node.secretBindings[].url',
+ '逐字一致',
+ 'xd.com',
+ 'xd.cn',
+ 'workers.xd.team',
+ '二次确认',
+ '非 HTTPS',
+ '用户名/密码',
+ 'target="_blank"',
+ 'window.open()',
+ '不支持',
+ ]) {
+ expect(settingsSection).toContain(marker);
+ }
+ expect(settingsSection).not.toContain('声明之外的任何外链点了没反应');
+ });
+
it('分章体量守卫:每个 ## 章节须留在单次工具结果安全体量内(#890 分章投递的不变量)', () => {
// 手册"随主机版本演进"持续增长;任一章越过单次 MCP 结果上限会静默复现 #890 于该章。
// 上限取 32KB:当前最大章 ~22KB,余量 ~45%,越线即该拆小节。
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.i18n.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.i18n.test.ts
new file mode 100644
index 0000000000..aeaab26ae0
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.i18n.test.ts
@@ -0,0 +1,53 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const LOCALES = ['zh-CN', 'zh-TW', 'en', 'ja', 'ko'] as const;
+const OPEN_WEBSITE_COPY = {
+ 'zh-CN': '打开网站',
+ 'zh-TW': '開啟網站',
+ en: 'Open Website',
+ ja: 'ウェブサイトを開く',
+ ko: '웹사이트 열기',
+} as const;
+
+function readCopy(locale: (typeof LOCALES)[number]) {
+ const path = resolve(__dirname, `../../../renderer/i18n/locales/${locale}/common.json`);
+ return JSON.parse(readFileSync(path, 'utf8')) as {
+ ghostPanel?: {
+ externalLinkConfirm?: {
+ title?: string;
+ message?: string;
+ open?: string;
+ cancel?: string;
+ };
+ };
+ };
+}
+
+describe('Ghost 外链原生确认框 i18n', () => {
+ it.each(LOCALES)('%s 补齐 main t() 消费的四个 key', (locale) => {
+ expect(readCopy(locale).ghostPanel?.externalLinkConfirm).toEqual({
+ title: expect.any(String),
+ message: expect.any(String),
+ open: expect.any(String),
+ cancel: expect.any(String),
+ });
+ });
+
+ it.each(LOCALES)('%s 主操作使用“动词 + 对象”文案', (locale) => {
+ expect(readCopy(locale).ghostPanel?.externalLinkConfirm?.open).toBe(
+ OPEN_WEBSITE_COPY[locale],
+ );
+ });
+
+ it('zh-CN 使用已确认的精确文案', () => {
+ expect(readCopy('zh-CN').ghostPanel?.externalLinkConfirm).toEqual({
+ title: '是否要 Cindy 打开外部网站',
+ message: '是否要 Cindy 打开外部网站',
+ open: '打开网站',
+ cancel: '取消',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.test.ts
new file mode 100644
index 0000000000..2a3e27e9e5
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.test.ts
@@ -0,0 +1,488 @@
+import type { BrowserWindow, MessageBoxOptions, WebContents } from 'electron';
+import { describe, expect, it, vi } from 'vitest';
+
+import { GhostExternalLinkGate, GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS } from '../previewGate';
+import { runGhostExternalLinkNavigation } from '../ghostExternalLinkNavigation';
+
+function makeContents() {
+ let guestDestroyed = false;
+ let hostDestroyed = false;
+ let focused = true;
+ const host = {
+ isDestroyed: vi.fn(() => hostDestroyed),
+ } as unknown as WebContents;
+ const guest = {
+ isDestroyed: vi.fn(() => guestDestroyed),
+ isFocused: vi.fn(() => focused),
+ hostWebContents: host,
+ } as unknown as WebContents;
+ return {
+ guest,
+ host,
+ destroyGuest: () => {
+ guestDestroyed = true;
+ },
+ destroyHost: () => {
+ hostDestroyed = true;
+ },
+ detachGuest: () => {
+ (guest as unknown as { hostWebContents: WebContents | null }).hostWebContents = null;
+ },
+ blurGuest: () => {
+ focused = false;
+ },
+ };
+}
+
+function makeHarness(options: {
+ declared?: string[] | null;
+ declaredExternalUrls?: () => string[] | null;
+ now?: () => number;
+ dialogResponse?: number;
+}) {
+ const gate = new GhostExternalLinkGate({
+ declaredExternalUrls:
+ options.declaredExternalUrls ??
+ (() => ('declared' in options ? (options.declared ?? null) : [])),
+ now: options.now,
+ });
+ let ownerDestroyed = false;
+ const owner = {
+ isDestroyed: vi.fn(() => ownerDestroyed),
+ } as unknown as BrowserWindow;
+ const resolveOwner = vi.fn<(hostContents: WebContents) => BrowserWindow | null>(() => owner);
+ const showMessageBox = vi.fn<
+ (owner: BrowserWindow, options: MessageBoxOptions) => Promise<{ response: number }>
+ >(async () => ({ response: options.dialogResponse ?? 1 }));
+ const openExternal = vi.fn<(url: string) => Promise<void>>(async () => undefined);
+ const debug = vi.fn();
+ const warn = vi.fn();
+ const translate = vi.fn((key: string) => {
+ const labels: Record<string, string> = {
+ 'ghostPanel.externalLinkConfirm.title': '是否要 Cindy 打开外部网站',
+ 'ghostPanel.externalLinkConfirm.message': '是否要 Cindy 打开外部网站',
+ 'ghostPanel.externalLinkConfirm.open': '打开网站',
+ 'ghostPanel.externalLinkConfirm.cancel': '取消',
+ };
+ return labels[key] ?? key;
+ });
+ return {
+ gate,
+ owner,
+ resolveOwner,
+ showMessageBox,
+ openExternal,
+ debug,
+ warn,
+ translate,
+ destroyOwner: () => {
+ ownerDestroyed = true;
+ },
+ deps: {
+ gate,
+ resolveOwner,
+ showMessageBox,
+ openExternal,
+ translate,
+ logger: { debug, warn },
+ },
+ };
+}
+
+describe('runGhostExternalLinkNavigation', () => {
+ it.each([
+ [
+ '现有 Manifest 声明',
+ 'https://example.com/settings/keys',
+ ['https://example.com/settings/keys'],
+ ],
+ ['固定授信主机', 'https://workers.xd.team/workspace/published', []],
+ ])('%s 直接调用系统浏览器,不弹确认框', async (_label, url, declared) => {
+ const contents = makeContents();
+ const harness = makeHarness({ declared });
+
+ await runGhostExternalLinkNavigation(
+ { ghostId: 'xd-sites', url, hostContents: contents.host, guestContents: contents.guest },
+ harness.deps,
+ );
+
+ expect(harness.openExternal).toHaveBeenCalledWith(url);
+ expect(harness.showMessageBox).not.toHaveBeenCalled();
+ expect(harness.resolveOwner).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['固定授信主机', 'https://workers.xd.team/workspace/published'],
+ ['普通 HTTPS', 'https://example.com/workspace'],
+ ])('插件已不可用时拒绝%s,不打开也不弹窗', async (_label, url) => {
+ const contents = makeContents();
+ const harness = makeHarness({ declared: null });
+
+ await runGhostExternalLinkNavigation(
+ { ghostId: 'xd-sites', url, hostContents: contents.host, guestContents: contents.guest },
+ harness.deps,
+ );
+
+ expect(harness.openExternal).not.toHaveBeenCalled();
+ expect(harness.showMessageBox).not.toHaveBeenCalled();
+ expect(harness.resolveOwner).not.toHaveBeenCalled();
+ });
+
+ it('普通 HTTPS 把准确配置挂到发起 webview 的实际宿主窗口', async () => {
+ const contents = makeContents();
+ const harness = makeHarness({ dialogResponse: 1 });
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://EXAMPLE.com:443/a/../workspace',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.resolveOwner).toHaveBeenCalledWith(contents.host);
+ expect(harness.showMessageBox).toHaveBeenCalledWith(harness.owner, {
+ type: 'question',
+ title: '是否要 Cindy 打开外部网站',
+ message: '是否要 Cindy 打开外部网站',
+ detail: 'https://example.com/workspace',
+ buttons: ['打开网站', '取消'],
+ defaultId: 0,
+ cancelId: 1,
+ noLink: true,
+ } satisfies MessageBoxOptions);
+ expect(harness.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('主窗口、侧栏独立窗口与 detached panel 都按各自 hostContents 解析 owner', async () => {
+ const surfaces = ['main', 'sidebar', 'detached'] as const;
+ const entries = surfaces.map((surface) => {
+ const contents = makeContents();
+ const owner = {
+ surface,
+ isDestroyed: vi.fn(() => false),
+ } as unknown as BrowserWindow;
+ return { surface, contents, owner };
+ });
+ const ownerByHost = new Map(entries.map(({ contents, owner }) => [contents.host, owner]));
+ const gate = new GhostExternalLinkGate({ declaredExternalUrls: () => [] });
+ const resolveOwner = vi.fn(
+ (hostContents: WebContents) => ownerByHost.get(hostContents) ?? null,
+ );
+ const showMessageBox = vi.fn(async () => ({ response: 1 }));
+ const openExternal = vi.fn(async () => undefined);
+ const deps = {
+ gate,
+ resolveOwner,
+ showMessageBox,
+ openExternal,
+ translate: (key: string) => key,
+ logger: { debug: vi.fn(), warn: vi.fn() },
+ };
+
+ for (const { surface, contents, owner } of entries) {
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: `xd-sites-${surface}`,
+ url: `https://${surface}.example.com/workspace`,
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ deps,
+ );
+ expect(resolveOwner).toHaveBeenLastCalledWith(contents.host);
+ expect(showMessageBox).toHaveBeenLastCalledWith(owner, expect.any(Object));
+ }
+
+ expect(showMessageBox).toHaveBeenCalledTimes(entries.length);
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['打开', 0, 1],
+ ['取消', 1, 0],
+ ['关闭弹窗', -1, 0],
+ ])('%s 后只按选择决定是否打开弹窗展示的不可变 URL', async (_label, response, opens) => {
+ const contents = makeContents();
+ const harness = makeHarness({ dialogResponse: response });
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://EXAMPLE.com:443/a/../workspace',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.openExternal).toHaveBeenCalledTimes(opens);
+ if (opens === 1)
+ expect(harness.openExternal).toHaveBeenCalledWith('https://example.com/workspace');
+ });
+
+ it.each(['guest', 'host', 'owner'] as const)('%s 在确认期间销毁后不打开', async (target) => {
+ const contents = makeContents();
+ const harness = makeHarness({ dialogResponse: 0 });
+ harness.showMessageBox.mockImplementationOnce(async () => {
+ if (target === 'guest') contents.destroyGuest();
+ if (target === 'host') contents.destroyHost();
+ if (target === 'owner') harness.destroyOwner();
+ return { response: 0 };
+ });
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/workspace',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('确认期间插件撤权后不打开,并释放确认防重入状态', async () => {
+ let now = 1_000;
+ let available = true;
+ const contents = makeContents();
+ const harness = makeHarness({
+ now: () => now,
+ dialogResponse: 0,
+ declaredExternalUrls: () => (available ? [] : null),
+ });
+ harness.showMessageBox.mockImplementationOnce(async () => {
+ available = false;
+ return { response: 0 };
+ });
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/first',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.openExternal).not.toHaveBeenCalled();
+
+ available = true;
+ now += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/second',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.showMessageBox).toHaveBeenCalledTimes(2);
+ });
+
+ it('guest 已脱离原宿主时不弹窗也不打开', async () => {
+ const contents = makeContents();
+ contents.detachGuest();
+ const harness = makeHarness({ dialogResponse: 0 });
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/workspace',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.showMessageBox).not.toHaveBeenCalled();
+ expect(harness.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('无法解析实际宿主 BrowserWindow 时 fail closed 并释放确认状态', async () => {
+ let now = 1_000;
+ const contents = makeContents();
+ const harness = makeHarness({ now: () => now });
+ harness.resolveOwner.mockReturnValue(null);
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/first',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+ now += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/second',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.resolveOwner).toHaveBeenCalledTimes(2);
+ expect(harness.showMessageBox).not.toHaveBeenCalled();
+ });
+
+ it('dialog 异常仍释放同一 ghost 的确认防重入状态', async () => {
+ let now = 1_000;
+ const contents = makeContents();
+ const harness = makeHarness({ now: () => now });
+ harness.showMessageBox.mockRejectedValueOnce(new Error('dialog failed'));
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/first',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+ now += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/second',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.showMessageBox).toHaveBeenCalledTimes(2);
+ expect(harness.warn).toHaveBeenCalledWith(
+ 'ghost external link confirmation failed',
+ expect.objectContaining({ ghostId: 'xd-sites', error: 'dialog failed' }),
+ );
+ });
+
+ it('同一 ghost 确认进行中拒绝重入,不显示第二个 dialog', async () => {
+ let now = 1_000;
+ const contents = makeContents();
+ const harness = makeHarness({ now: () => now });
+ let finishDialog!: (value: { response: number }) => void;
+ harness.showMessageBox.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishDialog = resolve;
+ }),
+ );
+
+ const first = runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/first',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+ await vi.waitFor(() => expect(harness.showMessageBox).toHaveBeenCalledOnce());
+ now += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/second',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.showMessageBox).toHaveBeenCalledOnce();
+ finishDialog({ response: 1 });
+ await first;
+ });
+
+ it('确认框结束后立即释放防重入,不等待 shell.openExternal 完成', async () => {
+ let now = 1_000;
+ const contents = makeContents();
+ const harness = makeHarness({ now: () => now, dialogResponse: 0 });
+ let finishOpen!: () => void;
+ harness.openExternal.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishOpen = resolve;
+ }),
+ );
+
+ const first = runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/first',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+ await vi.waitFor(() => expect(harness.openExternal).toHaveBeenCalledOnce());
+ now += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/second',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.showMessageBox).toHaveBeenCalledTimes(2);
+ finishOpen();
+ await first;
+ });
+
+ it('失焦页面不会直接打开或弹窗', async () => {
+ const contents = makeContents();
+ contents.blurGuest();
+ const harness = makeHarness({ declared: ['https://example.com/settings'] });
+
+ await runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/settings',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+
+ expect(harness.showMessageBox).not.toHaveBeenCalled();
+ expect(harness.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('shell.openExternal 失败只记录 warn,不向调用方抛错', async () => {
+ const contents = makeContents();
+ const harness = makeHarness({});
+ harness.openExternal.mockRejectedValueOnce(new Error('shell failed'));
+
+ await expect(
+ runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://workers.xd.team/workspace/published',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ ),
+ ).resolves.toBeUndefined();
+ expect(harness.warn).toHaveBeenCalledWith(
+ 'ghost external link open failed',
+ expect.objectContaining({ ghostId: 'xd-sites', error: 'shell failed' }),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts
index 365e9dc0c8..66cceccb95 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/previewGate.test.ts
@@ -40,38 +40,129 @@ describe('classifyGhostPanelNavigation', () => {
describe('GhostExternalLinkGate(设置区/面板「前往控制台」外链闸)', () => {
const DECLARED = 'https://example.com/settings/keys';
- const makeGate = (opts?: { urls?: string[]; now?: () => number }) =>
+ const makeGate = (opts?: { urls?: string[] | null; now?: () => number }) =>
new GhostExternalLinkGate({
- declaredExternalUrls: (ghostId) => (ghostId === 'art' ? (opts?.urls ?? [DECLARED]) : []),
+ declaredExternalUrls: (ghostId) => {
+ if (ghostId !== 'art') return null;
+ return opts && 'urls' in opts ? (opts.urls ?? null) : [DECLARED];
+ },
now: opts?.now,
});
const focused = () => true;
- it('身份卡声明过的地址 + 持焦点 → 放行原样 URL', () => {
+ it('身份卡声明过的地址 + 持焦点 → 直接打开原样 URL', () => {
expect(makeGate().request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused })).toEqual({
- ok: true,
+ action: 'direct-open',
url: DECLARED,
});
});
- it('声明之外的地址拒(逐字比对,不做归一化:尾斜杠/大小写都不认)', () => {
+ it.each([
+ 'https://xd.com/',
+ 'https://www.xd.com/path',
+ 'https://deep.console.xd.com/path',
+ 'https://xd.cn/',
+ 'https://www.xd.cn/path',
+ 'https://deep.console.xd.cn/path',
+ 'https://workers.xd.team/workspace/published',
+ ])('固定授信主机直接打开:%s', (url) => {
+ expect(
+ makeGate({ urls: [] }).request({ ghostId: 'art', url, isPanelFocused: focused }),
+ ).toEqual({
+ action: 'direct-open',
+ url,
+ });
+ });
+
+ it.each([
+ 'https://evilxd.com/',
+ 'https://xd.com.evil.com/',
+ 'https://notxd.cn/',
+ 'https://xd.cn.evil.com/',
+ 'https://sub.workers.xd.team/',
+ 'https://workers-xd.team/',
+ 'https://example.com/path',
+ ])('近似主机或普通 HTTPS 不自动授信,而是请求确认:%s', (url) => {
+ expect(
+ makeGate({ urls: [] }).request({ ghostId: 'art', url, isPanelFocused: focused }),
+ ).toEqual({
+ action: 'confirm',
+ url,
+ });
+ });
+
+ it('合法 HTTPS 在判定前规范化,并仅以规范化后的 hostname 判断授信', () => {
+ expect(
+ makeGate({ urls: [] }).request({
+ ghostId: 'art',
+ url: 'https://XD.COM:443/workspace/./published',
+ isPanelFocused: focused,
+ }),
+ ).toEqual({ action: 'direct-open', url: 'https://xd.com/workspace/published' });
+ });
+
+ it('现有声明地址仍优先逐字命中;非逐字版本作为普通 HTTPS 进入确认', () => {
let t = 1000;
const gate = makeGate({ now: () => t });
- expect(gate.request({ ghostId: 'art', url: 'https://evil.example/', isPanelFocused: focused })).toEqual({
- ok: false,
- reason: 'not-declared',
+ expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused })).toEqual({
+ action: 'direct-open',
+ url: DECLARED,
});
t += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
expect(gate.request({ ghostId: 'art', url: `${DECLARED}/`, isPanelFocused: focused })).toEqual({
- ok: false,
- reason: 'not-declared',
+ action: 'confirm',
+ url: `${DECLARED}/`,
+ });
+ });
+
+ it.each([
+ ['固定授信地址', 'https://workers.xd.team/workspace/published'],
+ ['普通 HTTPS', 'https://example.com/workspace'],
+ ])('查无此意识或已停用时拒绝%s,不保留旧 guest 的宿主能力', (_label, url) => {
+ expect(
+ makeGate().request({ ghostId: 'other', url, isPanelFocused: focused }),
+ ).toEqual({
+ action: 'reject',
+ reason: 'ghost-unavailable',
+ });
+ });
+
+ it('有效意识的空声明列表与不可用意识保持可区分', () => {
+ expect(
+ makeGate({ urls: [] }).request({
+ ghostId: 'art',
+ url: 'https://example.com/workspace',
+ isPanelFocused: focused,
+ }),
+ ).toEqual({
+ action: 'confirm',
+ url: 'https://example.com/workspace',
+ });
+ expect(
+ makeGate({ urls: null }).request({
+ ghostId: 'art',
+ url: 'https://example.com/workspace',
+ isPanelFocused: focused,
+ }),
+ ).toEqual({
+ action: 'reject',
+ reason: 'ghost-unavailable',
});
});
- it('查无此意识(已卸下/沉睡)= 空白名单 → not-declared', () => {
- expect(makeGate().request({ ghostId: 'other', url: DECLARED, isPanelFocused: focused })).toEqual({
- ok: false,
- reason: 'not-declared',
+ it.each([
+ 'http://xd.com/',
+ 'ftp://xd.com/',
+ 'file:///etc/passwd',
+ 'custom://xd.com/path',
+ 'https://[email protected]/',
+ 'https://user:[email protected]/',
+ 'not-a-url',
+ 'https://[invalid',
+ ])('非 HTTPS、带凭证或畸形 URL 拒绝:%s', (url) => {
+ expect(makeGate().request({ ghostId: 'art', url, isPanelFocused: focused })).toEqual({
+ action: 'reject',
+ reason: 'bad-url',
});
});
@@ -79,33 +170,39 @@ describe('GhostExternalLinkGate(设置区/面板「前往控制台」外链闸)'
let t = 1000;
const gate = makeGate({ now: () => t });
expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: () => false })).toEqual({
- ok: false,
+ action: 'reject',
reason: 'not-focused',
});
// 失焦拒绝不占限速窗口:随后用户真点击立即可放行。
t += 1;
- expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused }).ok).toBe(true);
+ expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused }).action).toBe(
+ 'direct-open',
+ );
});
it('限速按尝试记账:窗口内重试被拒且顺延窗口,连续 spam 闸整体关死', () => {
let t = 1000;
const gate = makeGate({ now: () => t });
- expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused }).ok).toBe(true);
+ expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused }).action).toBe(
+ 'direct-open',
+ );
// 999ms 后重试:拒,且这次尝试本身顺延了窗口。
t += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS - 1;
expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused })).toEqual({
- ok: false,
+ action: 'reject',
reason: 'rate-limited',
});
// 距首次放行已 1s,但距上次「尝试」只差 1ms:仍拒(spam 关死语义)。
t += 1;
expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused })).toEqual({
- ok: false,
+ action: 'reject',
reason: 'rate-limited',
});
// 距上次尝试满 1s:恢复。
t += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
- expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused }).ok).toBe(true);
+ expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused }).action).toBe(
+ 'direct-open',
+ );
});
it('限速罩住声明比对:窗口内的垃圾导航不触发白名单查询(不给刷磁盘 IO)', () => {
@@ -118,18 +215,72 @@ describe('GhostExternalLinkGate(设置区/面板「前往控制台」外链闸)'
},
now: () => t,
});
- expect(gate.request({ ghostId: 'art', url: 'https://evil.example/', isPanelFocused: focused }).ok).toBe(false);
+ expect(
+ gate.request({ ghostId: 'art', url: 'https://evil.example/', isPanelFocused: focused })
+ .action,
+ ).toBe('confirm');
expect(lookups).toBe(1);
// 窗口内连环垃圾导航:rate-limited 提前拦下,白名单查询一次都不该发生。
for (let i = 0; i < 10; i += 1) {
t += 10;
- expect(gate.request({ ghostId: 'art', url: 'https://evil.example/', isPanelFocused: focused })).toEqual({
- ok: false,
+ expect(
+ gate.request({ ghostId: 'art', url: 'https://evil.example/', isPanelFocused: focused }),
+ ).toEqual({
+ action: 'reject',
reason: 'rate-limited',
});
}
expect(lookups).toBe(1);
});
+
+ it('同一 ghost 确认进行中拒绝新的尝试,释放后可再次确认', () => {
+ let t = 1000;
+ const gate = makeGate({ urls: [], now: () => t });
+ const first = gate.request({
+ ghostId: 'art',
+ url: 'https://example.com/first',
+ isPanelFocused: focused,
+ });
+ expect(first).toEqual({ action: 'confirm', url: 'https://example.com/first' });
+ t += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ expect(
+ gate.request({ ghostId: 'art', url: 'https://example.com/second', isPanelFocused: focused }),
+ ).toEqual({
+ action: 'reject',
+ reason: 'confirmation-pending',
+ });
+
+ gate.releaseConfirmation('art');
+ t += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ expect(
+ gate.request({ ghostId: 'art', url: 'https://example.com/second', isPanelFocused: focused }),
+ ).toEqual({
+ action: 'confirm',
+ url: 'https://example.com/second',
+ });
+ });
+
+ it('direct-open 与 reject 不占确认状态', () => {
+ let t = 1000;
+ const gate = makeGate({ now: () => t });
+ expect(gate.request({ ghostId: 'art', url: DECLARED, isPanelFocused: focused }).action).toBe(
+ 'direct-open',
+ );
+ t += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ expect(
+ gate.request({ ghostId: 'art', url: 'http://example.com/', isPanelFocused: focused }),
+ ).toEqual({
+ action: 'reject',
+ reason: 'bad-url',
+ });
+ t += GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS;
+ expect(
+ gate.request({ ghostId: 'art', url: 'https://example.com/confirm', isPanelFocused: focused }),
+ ).toEqual({
+ action: 'confirm',
+ url: 'https://example.com/confirm',
+ });
+ });
});
describe('parseGhostPreviewUrl', () => {
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 57b7d9269e..82129d8d37 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3061,15 +3061,21 @@ tool-call 内轮询时记得定期发 tool-progress 心跳续命(见 §4"长任
settingsHeight(此时主机不注入上述响应式规则,超出部分由你的页面内部滚动)。
意识沉睡时设置区不渲染(显示沉睡提示),唤醒后可用。
-**外链(前往控制台)**:设置区/面板里可以放 \`<a href="https://…">\` 链接,但
-只有 **href 与身份卡 \`network.secrets[].url\` 声明逐字一致**的地址会被主机放行
-——点击时主机拦下导航、转系统浏览器打开(沙箱页自身永远不离开自己协议)。
-声明之外的任何外链点了没反应(主机静默拦下),脚本自动跳转也无效(须用户
-真点击且页面持有焦点,同一意识 1s 内至多放行一次)。href 直接从身份卡声明里
-**原样复制**——浏览器会把导航地址归一化(域名转小写、根路径补尾斜杠),声明
-写成非规范形态会导致比对永远失配、链接点了没反应,所以声明本身也用规范形态
-(小写域名、根路径带 \`/\`)。典型用法:输入行下方放一条
-\`<a class="console-link" href="…">前往控制台获取 ↗</a>\`,方便用户一键去申请 key。
+**外链(前往控制台)**:设置区/面板里可以放普通同页
+\`<a href="https://…">\`。主机会拦下导航并交给系统默认浏览器,沙箱页自身永远
+不离开 \`cindy-ghost://\`。合法地址按以下顺序处理:
+
+1. href 与身份卡既有 \`network.secrets[].url\` 或 \`node.secretBindings[].url\`
+ **逐字一致**时直接打开(保持存量插件兼容);href 最好从声明原样复制;
+2. URL 解析后的主机是 \`xd.com\` / \`xd.cn\` 根域或任意层级子域,或精确
+ \`workers.xd.team\`,直接打开;
+3. 其它合法 HTTPS 地址会显示完整规范化 URL,由用户二次确认后才打开。
+
+非 HTTPS、畸形 URL、内嵌用户名/密码的地址一律拒绝。只支持普通同页链接:
+\`target="_blank"\` 与 \`window.open()\` 不支持。页面必须持有焦点,同一意识
+1s 内至多处理一次外链尝试,且同一意识同时最多一个确认框。典型用法:输入行
+下方放一条 \`<a class="console-link" href="…">前往控制台获取 ↗</a>\`,方便用户
+一键去申请 key。
**自定义参数持久化(/kv)**:每段意识有一份主机代管的 JSON 参数(单意识一份,
互相隔离),设置页 / 面板 / 电子脑同源共用,读写都走 \`fetch('/kv')\`:
diff --git a/apps/desktop/src/main/cindy-brain/ghostExternalLinkNavigation.ts b/apps/desktop/src/main/cindy-brain/ghostExternalLinkNavigation.ts
new file mode 100644
index 0000000000..68682c1564
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostExternalLinkNavigation.ts
@@ -0,0 +1,122 @@
+import type { BrowserWindow, MessageBoxOptions, WebContents } from 'electron';
+
+import type { GhostExternalLinkGate } from './previewGate.js';
+
+export interface GhostExternalLinkNavigationLogger {
+ debug(message: string, meta: Record<string, unknown>): void;
+ warn(message: string, meta: Record<string, unknown>): void;
+}
+
+export interface GhostExternalLinkNavigationDeps {
+ gate: GhostExternalLinkGate;
+ resolveOwner(hostContents: WebContents): BrowserWindow | null;
+ showMessageBox(owner: BrowserWindow, options: MessageBoxOptions): Promise<{ response: number }>;
+ openExternal(url: string): Promise<void>;
+ translate(key: string): string;
+ logger: GhostExternalLinkNavigationLogger;
+}
+
+export interface GhostExternalLinkNavigationParams {
+ ghostId: string;
+ url: string;
+ /** did-attach-webview 事件所属的宿主 renderer。 */
+ hostContents: WebContents;
+ /** 发起 will-navigate 的 Ghost guest。 */
+ guestContents: WebContents;
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+function guestStillBelongsToHost(guestContents: WebContents, hostContents: WebContents): boolean {
+ if (guestContents.isDestroyed() || hostContents.isDestroyed()) return false;
+ return guestContents.hostWebContents === hostContents;
+}
+
+async function openExternalBestEffort(
+ ghostId: string,
+ url: string,
+ deps: GhostExternalLinkNavigationDeps,
+): Promise<void> {
+ try {
+ await deps.openExternal(url);
+ } catch (error) {
+ deps.logger.warn('ghost external link open failed', {
+ ghostId,
+ error: errorMessage(error),
+ });
+ }
+}
+
+/**
+ * 执行一次 Ghost 主 frame 的 will-navigate 外链导航。
+ *
+ * 纯策略(URL、焦点、限速、授信域、确认防重入)由 GhostExternalLinkGate
+ * 决定;这里仅协调 Electron 的原生确认框与系统浏览器。确认分支始终绑定
+ * did-attach-webview 的真实宿主窗口,并在用户确认后重验 guest → host →
+ * owner 整条归属链,避免窗口切换或销毁后把旧确认应用到别处。
+ */
+export async function runGhostExternalLinkNavigation(
+ params: GhostExternalLinkNavigationParams,
+ deps: GhostExternalLinkNavigationDeps,
+): Promise<void> {
+ const outcome = deps.gate.request({
+ ghostId: params.ghostId,
+ url: params.url,
+ isPanelFocused: () => !params.guestContents.isDestroyed() && params.guestContents.isFocused(),
+ });
+ if (outcome.action === 'reject') {
+ deps.logger.debug('ghost external link rejected', {
+ ghostId: params.ghostId,
+ reason: outcome.reason,
+ });
+ return;
+ }
+ if (outcome.action === 'direct-open') {
+ await openExternalBestEffort(params.ghostId, outcome.url, deps);
+ return;
+ }
+
+ // outcome.url 是 Gate 在弹窗前固化的规范化 URL;后续只使用这一个值。
+ const confirmedUrl = outcome.url;
+ let shouldOpen = false;
+ try {
+ if (!guestStillBelongsToHost(params.guestContents, params.hostContents)) return;
+ const owner = deps.resolveOwner(params.hostContents);
+ if (!owner || owner.isDestroyed()) return;
+
+ let response: number;
+ try {
+ ({ response } = await deps.showMessageBox(owner, {
+ type: 'question',
+ title: deps.translate('ghostPanel.externalLinkConfirm.title'),
+ message: deps.translate('ghostPanel.externalLinkConfirm.message'),
+ detail: confirmedUrl,
+ buttons: [
+ deps.translate('ghostPanel.externalLinkConfirm.open'),
+ deps.translate('ghostPanel.externalLinkConfirm.cancel'),
+ ],
+ defaultId: 0,
+ cancelId: 1,
+ noLink: true,
+ }));
+ } catch (error) {
+ deps.logger.warn('ghost external link confirmation failed', {
+ ghostId: params.ghostId,
+ error: errorMessage(error),
+ });
+ return;
+ }
+ if (response !== 0) return;
+ if (!guestStillBelongsToHost(params.guestContents, params.hostContents)) return;
+ if (owner.isDestroyed()) return;
+ if (!deps.gate.isGhostAvailable(params.ghostId)) return;
+ shouldOpen = true;
+ } finally {
+ deps.gate.releaseConfirmation(params.ghostId);
+ }
+ if (shouldOpen) {
+ await openExternalBestEffort(params.ghostId, confirmedUrl, deps);
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 2e5ea563b0..98aa564879 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -303,6 +303,7 @@ import {
type MinimalAgentEvent,
} from './subscriptionGateway.js';
import { GhostExternalLinkGate, GhostPreviewGate, resolveGhostPanelMedia } from './previewGate.js';
+import { runGhostExternalLinkNavigation } from './ghostExternalLinkNavigation.js';
import {
ghostSecretSaved,
readGhostSecret,
@@ -6984,7 +6985,7 @@ function getGhostExternalLinkGate(): GhostExternalLinkGate {
externalLinkGateSingleton = new GhostExternalLinkGate({
declaredExternalUrls: (ghostId) => {
const ghost = findAvailableGhost(ghostId);
- return ghost && ghost.enabled ? ghostExternalLinkUrls(ghost.manifest) : [];
+ return ghost && ghost.enabled ? ghostExternalLinkUrls(ghost.manifest) : null;
},
});
}
@@ -6993,30 +6994,27 @@ function getGhostExternalLinkGate(): GhostExternalLinkGate {
/**
* 意识 webview 外链导航的主机侧处理(webview-security 拦下 https 导航后调用):
- * 过外链闸(身份卡声明白名单/焦点/限速,见 previewGate.ts 的
- * GhostExternalLinkGate)→ 转系统浏览器打开(shell.openExternal)。
+ * 过外链闸(合法 HTTPS / 焦点 / 限速 / 声明或授信直开 / 其余确认,见
+ * previewGate.ts 的 GhostExternalLinkGate)→ 转系统浏览器打开。
* 一切失败静默(仅 debug 日志),不给沙箱探测面。
*/
export function handleGhostExternalLinkNavigation(
ghostId: string,
url: string,
+ hostContents: WebContents,
guestContents: WebContents,
): void {
- const outcome = getGhostExternalLinkGate().request({
- ghostId,
- url,
- isPanelFocused: () => !guestContents.isDestroyed() && guestContents.isFocused(),
- });
- if (!outcome.ok) {
- log.debug('ghost external link rejected', { ghostId, reason: outcome.reason });
- return;
- }
- void shell.openExternal(outcome.url).catch((err) => {
- log.warn('ghost external link open failed', {
- ghostId,
- error: err instanceof Error ? err.message : String(err),
- });
- });
+ void runGhostExternalLinkNavigation(
+ { ghostId, url, hostContents, guestContents },
+ {
+ gate: getGhostExternalLinkGate(),
+ resolveOwner: (contents) => BrowserWindow.fromWebContents(contents),
+ showMessageBox: (owner, options) => dialog.showMessageBox(owner, options),
+ openExternal: (targetUrl) => shell.openExternal(targetUrl),
+ translate: t,
+ logger: log,
+ },
+ );
}
/**
diff --git a/apps/desktop/src/main/cindy-brain/previewGate.ts b/apps/desktop/src/main/cindy-brain/previewGate.ts
index 30c62cfcfa..2ce15da02e 100644
--- a/apps/desktop/src/main/cindy-brain/previewGate.ts
+++ b/apps/desktop/src/main/cindy-brain/previewGate.ts
@@ -44,7 +44,7 @@ const PREVIEW_MEDIA_EXTS = new Set([...IMAGE_EXTS, ...VIDEO_EXTS]);
* - 'allow' 自己协议同 id 下的普通页面,放行(现状行为);
* - 'preview' 预览链接,拦下导航并走预览闸;
* - 'external' https 外部地址,拦下导航并走外链闸(GhostExternalLinkGate:
- * 只有身份卡声明过的控制台地址才转系统浏览器打开,其余丢弃);
+ * 身份卡声明地址/基座授信主机直开,其它合法地址二次确认);
* - 'block' 其它一切(非 https 外部地址 / 别的意识 / 畸形 URL),拦下丢弃。
*/
export type GhostPanelNavigation = 'allow' | 'preview' | 'external' | 'block';
@@ -210,35 +210,64 @@ export const GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS = 1000;
export interface GhostExternalLinkGateDeps {
/**
* 该意识身份卡里声明过的全部外链地址(network.secrets[].url 等,装包时
- * 已校验仅 https)。查不到意识(已卸下/沉睡)返回空数组。
+ * 已校验仅 https)。有效但无声明返回空数组;查不到或已停用返回 null,
+ * 让旧 guest 在授权生命周期结束后 fail closed。
*/
- declaredExternalUrls(ghostId: string): readonly string[];
+ declaredExternalUrls(ghostId: string): readonly string[] | null;
/** 时钟注入(限速用;缺省 Date.now)。 */
now?(): number;
}
export type GhostExternalLinkOutcome =
- | { ok: true; url: string }
- | { ok: false; reason: 'not-declared' | 'not-focused' | 'rate-limited' };
+ | { action: 'direct-open'; url: string }
+ | { action: 'confirm'; url: string }
+ | {
+ action: 'reject';
+ reason:
+ | 'bad-url'
+ | 'not-focused'
+ | 'rate-limited'
+ | 'confirmation-pending'
+ | 'ghost-unavailable';
+ };
+
+/**
+ * 首版基座固定授信主机。根域与子域必须按 DNS label 边界匹配,不能用裸
+ * `endsWith('xd.com')`,否则 evilxd.com 会被误放行。workers.xd.team 只认
+ * 精确主机,不自动把其子域纳入信任。
+ */
+function isTrustedGhostExternalHostname(hostname: string): boolean {
+ if (hostname === 'workers.xd.team') return true;
+ return (
+ hostname === 'xd.com' ||
+ hostname.endsWith('.xd.com') ||
+ hostname === 'xd.cn' ||
+ hostname.endsWith('.xd.cn')
+ );
+}
/**
- * 外链闸(设置区/面板里的「前往控制台」链接):意识 webview 导航到 https
- * 地址时,主机拦下导航并在这里过闸——**逐字命中身份卡声明过的地址**
- * (network.secrets[].url,装包校验仅 https)才转系统浏览器打开。安全模型
- * 与预览闸同一纪律(廉价检查挡在贵检查前面):
- * - 焦点闸:webview 必须正持有焦点(用户真点了链接)才放行,后台脚本
- * location.href 刷不起浏览器;
+ * 外链闸(设置区/面板里的「前往控制台」链接):意识 webview 导航时,主机
+ * 拦下导航并在这里过闸。只接受无内嵌凭证的绝对 HTTPS 地址;逐字命中
+ * 身份卡既有声明或命中固定授信主机的直接转系统浏览器,其余合法地址交
+ * 宿主弹二次确认。安全模型与预览闸同一纪律(廉价检查挡在贵检查前面):
+ * - 焦点闸:webview 必须正持有焦点才放行,未聚焦页面不能触发。焦点只
+ * 是 activation 前置条件,不是“真实点击”证明;will-navigate 本身无法
+ * 区分普通 `<a>` 与聚焦页面里的脚本导航;
* - 限速:**按尝试记账**(不只按成功),同一意识两次尝试至少间隔 1s——
* 声明比对要经 GhostManager 实扫磁盘上的身份卡(目录即注册表,无缓存),
* 限速必须罩住它,持焦点的恶意页用导航垃圾也刷不动主进程 IO;
* 连续 spam 会不断顺延窗口(闸整体关死),对真实点击无感;
- * - 白名单是声明式的(身份卡装包时定死),沙箱页给的字符串没有机会变成
- * 任意跳转(防钓鱼是结构性的);
+ * - 现有声明地址维持逐字比对兼容语义;授信主机只按 URL 解析器规范化的
+ * hostname + DNS label 边界判断;确认分支只回规范化后的不可变 URL;
+ * - 同一意识最多一个确认在途,宿主无论打开、取消或异常都须 release;
* - 失败静默(调用方只记 debug 日志),不给沙箱可探测的差异面。
*/
export class GhostExternalLinkGate {
/** 意识 id → 上次尝试时刻(限速账本,按尝试记账;体量 = 已装意识数,无需清理)。 */
private lastAttemptAt = new Map<string, number>();
+ /** 正在等待宿主原生确认框的意识;确认结束时由调用方释放。 */
+ private confirmationPending = new Set<string>();
constructor(private readonly deps: GhostExternalLinkGateDeps) {}
@@ -248,18 +277,49 @@ export class GhostExternalLinkGate {
/** webview 当前是否持有焦点(guestContents.isFocused)。 */
isPanelFocused: () => boolean;
}): GhostExternalLinkOutcome {
- if (!params.isPanelFocused()) return { ok: false, reason: 'not-focused' };
+ if (!params.isPanelFocused()) return { action: 'reject', reason: 'not-focused' };
const now = this.deps.now?.() ?? Date.now();
const last = this.lastAttemptAt.get(params.ghostId);
this.lastAttemptAt.set(params.ghostId, now);
if (last !== undefined && now - last < GHOST_EXTERNAL_LINK_MIN_INTERVAL_MS) {
- return { ok: false, reason: 'rate-limited' };
+ return { action: 'reject', reason: 'rate-limited' };
}
- // 逐字比对(不做归一化):href 必须与身份卡声明完全一致,规则简单可预期。
- if (!this.deps.declaredExternalUrls(params.ghostId).includes(params.url)) {
- return { ok: false, reason: 'not-declared' };
+ if (this.confirmationPending.has(params.ghostId)) {
+ return { action: 'reject', reason: 'confirmation-pending' };
}
- return { ok: true, url: params.url };
+ let parsed: URL;
+ try {
+ parsed = new URL(params.url);
+ } catch {
+ return { action: 'reject', reason: 'bad-url' };
+ }
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
+ return { action: 'reject', reason: 'bad-url' };
+ }
+ const declaredExternalUrls = this.deps.declaredExternalUrls(params.ghostId);
+ if (declaredExternalUrls === null) {
+ return { action: 'reject', reason: 'ghost-unavailable' };
+ }
+ // 既有声明继续逐字比对,避免改变存量插件已经依赖的直开语义。
+ if (declaredExternalUrls.includes(params.url)) {
+ return { action: 'direct-open', url: params.url };
+ }
+ const normalizedUrl = parsed.href;
+ if (isTrustedGhostExternalHostname(parsed.hostname)) {
+ return { action: 'direct-open', url: normalizedUrl };
+ }
+ this.confirmationPending.add(params.ghostId);
+ return { action: 'confirm', url: normalizedUrl };
+ }
+
+ /** 宿主确认框结束后的 finally 钩;重复释放无副作用。 */
+ releaseConfirmation(ghostId: string): void {
+ this.confirmationPending.delete(ghostId);
+ }
+
+ /** 原生确认返回后复核授权生命周期,防止弹窗期间停用或卸载后仍打开。 */
+ isGhostAvailable(ghostId: string): boolean {
+ return this.deps.declaredExternalUrls(ghostId) !== null;
}
}
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index 3069e52163..dddc57c022 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -653,6 +653,38 @@ export function installBrowserGuestHandlers(
});
}
+interface GhostGuestNavigationHandlers {
+ preview: typeof handleGhostPreviewNavigation;
+ external: typeof handleGhostExternalLinkNavigation;
+}
+
+/**
+ * settingsHtml 与 panel 共用的 Ghost guest 导航接线。策略仍集中在
+ * previewGate / cindy-brain;这里仅保证普通 will-navigate 被主机接管,
+ * popup 路径继续一律拒绝,并把 did-attach 时的真实 hostContents 原样传入。
+ */
+export function installGhostGuestNavigationHandlers(
+ hostContents: WebContents,
+ guestContents: WebContents,
+ ghostId: string,
+ handlers: GhostGuestNavigationHandlers = {
+ preview: handleGhostPreviewNavigation,
+ external: handleGhostExternalLinkNavigation,
+ },
+): void {
+ guestContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ guestContents.on('will-navigate', (event, url) => {
+ const nav = classifyGhostPanelNavigation(url, ghostId);
+ if (nav === 'allow') return;
+ event.preventDefault();
+ if (nav === 'preview') {
+ handlers.preview(ghostId, url, hostContents, guestContents);
+ } else if (nav === 'external') {
+ handlers.external(ghostId, url, hostContents, guestContents);
+ }
+ });
+}
+
export function installWebviewHardener(): void {
app.on('web-contents-created', (_event, contents) => {
// will-attach → did-attach 对同一个 guest 同步成对触发;用闭包变量把
@@ -693,18 +725,8 @@ export function installWebviewHardener(): void {
// 意识面板零弹窗、零跳转:window.open 全拒,导航锁死在自己协议同源内。
// 两个声明式例外(都是拦下导航、主机代办,面板侧依旧零桥):
// - /preview/ 预览链接 → 主窗口弹 lightbox(cindy-brain/previewGate.ts);
- // - https 外链 → 外链闸(身份卡声明过的控制台地址才放行)转系统浏览器。
- guestContents.setWindowOpenHandler(() => ({ action: 'deny' }));
- guestContents.on('will-navigate', (event, url) => {
- const nav = classifyGhostPanelNavigation(url, ghostId);
- if (nav === 'allow') return;
- event.preventDefault();
- if (nav === 'preview') {
- handleGhostPreviewNavigation(ghostId, url, contents, guestContents);
- } else if (nav === 'external') {
- handleGhostExternalLinkNavigation(ghostId, url, guestContents);
- }
- });
+ // - https 外链 → 外链闸(声明/授信直开,其余二次确认)转系统浏览器。
+ installGhostGuestNavigationHandlers(contents, guestContents, ghostId);
return;
}
installBrowserGuestHandlers(contents, guestContents);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index c250d59644..88df410498 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4984,6 +4984,12 @@
"title": "Disable \"{{name}}\"?",
"body": "Closing this panel disables the plugin and pauses its capabilities. You can re-enable it anytime from Plugins in the sidebar.",
"confirm": "Disable"
+ },
+ "externalLinkConfirm": {
+ "title": "Allow Cindy to open an external website?",
+ "message": "Allow Cindy to open an external website?",
+ "open": "Open Website",
+ "cancel": "Cancel"
}
},
"ghostPanelWindow": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4770aaf779..3d57953d3f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5009,6 +5009,12 @@
"title": "「{{name}}」を無効にしますか?",
"body": "このパネルを閉じるとプラグインが無効になり、機能が停止します。サイドバーの「プラグイン」からいつでも再度有効にできます。",
"confirm": "無効にする"
+ },
+ "externalLinkConfirm": {
+ "title": "Cindy で外部ウェブサイトを開きますか?",
+ "message": "Cindy で外部ウェブサイトを開きますか?",
+ "open": "ウェブサイトを開く",
+ "cancel": "キャンセル"
}
},
"ghostPanelWindow": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index c4249cb790..f57ff67f59 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5009,6 +5009,12 @@
"title": "\"{{name}}\" 플러그인을 비활성화할까요?",
"body": "이 패널을 닫으면 플러그인이 비활성화되고 기능이 중지됩니다. 사이드바의 '플러그인'에서 언제든지 다시 활성화할 수 있습니다.",
"confirm": "비활성화"
+ },
+ "externalLinkConfirm": {
+ "title": "Cindy에서 외부 웹사이트를 열까요?",
+ "message": "Cindy에서 외부 웹사이트를 열까요?",
+ "open": "웹사이트 열기",
+ "cancel": "취소"
}
},
"ghostPanelWindow": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index deaca2118c..2bb7fc5ec0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4982,6 +4982,12 @@
"title": "停用「{{name}}」?",
"body": "关闭这个面板会停用插件并暂停其能力。你可以随时在侧边栏「插件」中重新启用。",
"confirm": "停用"
+ },
+ "externalLinkConfirm": {
+ "title": "是否要 Cindy 打开外部网站",
+ "message": "是否要 Cindy 打开外部网站",
+ "open": "打开网站",
+ "cancel": "取消"
}
},
"ghostPanelWindow": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index adcec26a31..eec7358b5c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5009,6 +5009,12 @@
"title": "停用「{{name}}」?",
"body": "關閉這個面板會停用插件並暫停其能力。你可以隨時在側邊欄「插件」中重新啟用。",
"confirm": "停用"
+ },
+ "externalLinkConfirm": {
+ "title": "是否要讓 Cindy 開啟外部網站",
+ "message": "是否要讓 Cindy 開啟外部網站",
+ "open": "開啟網站",
+ "cancel": "取消"
}
},
"ghostPanelWindow": {
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 0e05b2f279..9a719da87e 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -2780,6 +2780,42 @@ describe('ghost · network 详单校验', () => {
}
});
+ it('ghostExternalLinkUrls 同时聚合 network secret 与 node secret binding 地址', () => {
+ const parsed = validateGhostManifest({
+ ...goodChipManifest(),
+ settingsHtml: 'settings.html',
+ slots: ['panel', 'network', 'node'],
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ ...goodSecret(),
+ url: 'https://network.example.com/settings/keys',
+ },
+ ],
+ },
+ node: {
+ entry: 'node/worker.cjs',
+ protocol: 'json-rpc-stdio',
+ secretBindings: [
+ {
+ key: 'worker_token',
+ label: 'Worker Token',
+ methods: ['worker/run'],
+ url: 'https://node.example.com/settings/keys',
+ },
+ ],
+ },
+ });
+
+ expect(parsed.ok, JSON.stringify(parsed)).toBe(true);
+ if (!parsed.ok) return;
+ expect(ghostExternalLinkUrls(parsed.manifest)).toEqual([
+ 'https://network.example.com/settings/keys',
+ 'https://node.example.com/settings/keys',
+ ]);
+ });
+
it('secrets.source:login-email 收入清单;user 归一化省略;野值拒;login-email 带 url 拒', () => {
const withSource = (secret: Record<string, unknown>) =>
validateGhostManifest(withNet({ hosts: ['api.example.com'], secrets: [secret] }));