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(plugins): 允许声明本机预览的插件页面嵌入回环页面(取回另存实现)

Dash4a0b9b62e642
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
index 5d28699203..f6ca1793b5 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
@@ -612,6 +612,80 @@ describe('electronSandboxAdapter owner partition', () => {
}
});
+ it('回环嵌入插件:面板子帧及其同端口请求放行,面板自身与其它端口仍拒绝', async () => {
+ const embed = ghost('loopback-embed');
+ embed.manifest.preview = { hosts: ['127.0.0.1'] };
+ embed.manifest.node = { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' };
+ ensureGhostProtocolRegistered(embed);
+ const registered = harness.sessions.get(
+ approvedPartition('cindy-ghost-owner:cloud:opaque-owner-a:loopback-embed'),
+ );
+ const handler = registered?.beforeRequest.mock.calls[0]?.[0] as
+ | ((details: Record<string, unknown>, callback: (result: { cancel: boolean }) => void) => void)
+ | undefined;
+ expect(handler).toBeTypeOf('function');
+ const cancelled = (details: Record<string, unknown>): boolean => {
+ const callback = vi.fn();
+ handler?.(details, callback);
+ return callback.mock.calls[0]?.[0].cancel as boolean;
+ };
+ const panelUrl = 'cindy-ghost://loopback-embed/panel.html';
+ const page = 'http://127.0.0.1:50365/control?udid=x';
+ // 面板把本机页面装进 <iframe>
+ expect(cancelled({ url: page, resourceType: 'subFrame', frame: { url: 'about:blank', parent: { url: panelUrl } } })).toBe(false);
+ expect(cancelled({ url: page, resourceType: 'subFrame', referrer: panelUrl })).toBe(false);
+ // 子帧内回到同一主机:端口的资源与 WebSocket
+ for (const [url, resourceType] of [
+ ['http://127.0.0.1:50365/control.js', 'script'],
+ ['http://127.0.0.1:50365/control.css', 'stylesheet'],
+ ['http://127.0.0.1:50365/control-api', 'xhr'],
+ ['ws://127.0.0.1:50365/simulators/x/stream', 'webSocket'],
+ ['http://127.0.0.1:50365/shot.jpg', 'image'],
+ ] as const) {
+ expect(cancelled({ url, resourceType, frame: { url: page } }), `${resourceType} ${url}`).toBe(false);
+ }
+ // 拒绝:顶层导航、面板页自己直连回环、换端口、换主机、非回环父帧、HTTPS 伪装
+ for (const details of [
+ { url: page, resourceType: 'mainFrame', frame: { url: panelUrl } },
+ { url: 'http://127.0.0.1:50365/control-api', resourceType: 'xhr', frame: { url: panelUrl } },
+ { url: 'http://127.0.0.1:50365/control-api', resourceType: 'xhr', referrer: panelUrl },
+ { url: 'http://127.0.0.1:1/other', resourceType: 'xhr', frame: { url: page } },
+ { url: 'ws://127.0.0.1:1/socket', resourceType: 'webSocket', frame: { url: page } },
+ { url: 'http://10.0.0.5:50365/x', resourceType: 'xhr', frame: { url: page } },
+ { url: page, resourceType: 'subFrame', frame: { url: 'about:blank', parent: { url: 'cindy-ghost://other-ghost/panel.html' } } },
+ { url: page, resourceType: 'subFrame', frame: { url: 'about:blank', parent: { url: 'https://evil.example/' } } },
+ { url: page, resourceType: 'subFrame' },
+ { url: 'http://user:[email protected]:50365/x', resourceType: 'xhr', frame: { url: page } },
+ { url: 'https://127.0.0.1:50365/x', resourceType: 'xhr', frame: { url: page } },
+ ]) {
+ expect(cancelled(details), JSON.stringify(details)).toBe(true);
+ }
+ const response = await registered?.protocolHandler?.(new Request('cindy-ghost://loopback-embed/panel.html'));
+ expect(response?.headers.get('content-security-policy')).toContain("frame-src 'self' http://127.0.0.1:* http://localhost:*");
+ });
+
+ it('未同时声明 panel、node 与回环 preview 的插件不放行任何回环请求,CSP 不含 frame-src', async () => {
+ const cases: Array<[string, (m: Record<string, unknown>) => void]> = [
+ ['loopback-no-node', (m) => { m.preview = { hosts: ['127.0.0.1'] }; }],
+ ['loopback-no-preview', (m) => { m.node = { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' }; }],
+ ['loopback-remote-preview', (m) => { m.preview = { hosts: ['demo.example.dev'] }; m.node = { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' }; }],
+ ];
+ for (const [id, mutate] of cases) {
+ const installed = ghost(id);
+ mutate(installed.manifest as unknown as Record<string, unknown>);
+ ensureGhostProtocolRegistered(installed);
+ const registered = harness.sessions.get(approvedPartition(`cindy-ghost-owner:cloud:opaque-owner-a:${id}`));
+ const handler = registered?.beforeRequest.mock.calls[0]?.[0] as
+ | ((details: Record<string, unknown>, callback: (result: { cancel: boolean }) => void) => void)
+ | undefined;
+ const callback = vi.fn();
+ handler?.({ url: 'http://127.0.0.1:50365/control', resourceType: 'subFrame', frame: { url: 'about:blank', parent: { url: `cindy-ghost://${id}/panel.html` } } }, callback);
+ expect(callback.mock.calls[0]?.[0].cancel, id).toBe(true);
+ const response = await registered?.protocolHandler?.(new Request(`cindy-ghost://${id}/panel.html`));
+ expect(response?.headers.get('content-security-policy'), id).not.toContain('frame-src');
+ }
+ });
+
it('重复确保同一分区不会累积网络或协议 listener', () => {
const installed = ghost('https-image-listener-once');
ensureGhostProtocolRegistered(installed);
diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
index d79b4e59b0..03c5e383d0 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
@@ -14,6 +14,8 @@ import {
type GhostMediaModelsResult,
type GhostMediaModelType,
type InstalledGhost,
+ ghostLoopbackOrigin,
+ ghostPanelLoopbackEmbedAllowed,
} from '../../../shared/ghost.js';
import { getActiveAppSession, type ActiveAppSession } from '../../appSessionState.js';
import { ownerScopedGhostPartition, ownerScopedGhostPartitionForInstalledGhost } from '../ghostWebviewPartition.js';
@@ -405,6 +407,35 @@ export function revokeLegacyGhostProtocolPartition(ghostId: string): void {
*/
export const GHOST_HTML_CSP =
"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; media-src 'self' data: blob:";
+/** 回环嵌入插件(见 ghostPanelLoopbackEmbedAllowed)额外允许的子帧来源;其余 CSP 不变。 */
+const GHOST_LOOPBACK_FRAME_CSP = "frame-src 'self' http://127.0.0.1:* http://localhost:*";
+
+/** 分区网络闸看到的请求形状(只取判定所需字段,便于单测构造)。 */
+interface LoopbackEmbedRequestDetails {
+ url: string;
+ resourceType: string;
+ referrer?: string;
+ frame?: { url: string; parent?: { url: string } | null } | null;
+}
+
+/**
+ * 回环嵌入请求是否放行:
+ * - 子帧导航(subFrame)到回环地址:父帧必须是本插件自己的页面;
+ * - 子帧内的其它请求(脚本/样式/XHR/WebSocket/媒体…):发起帧与目标必须是
+ * 同一回环主机:端口;
+ * - 顶层导航(mainFrame)与来自 cindy-ghost 页面自身的回环请求一律拒绝。
+ */
+function loopbackEmbedRequestAllowed(details: LoopbackEmbedRequestDetails, selfPrefix: string): boolean {
+ const target = ghostLoopbackOrigin(details.url);
+ if (!target) return false;
+ if (details.resourceType === 'mainFrame') return false;
+ if (details.resourceType === 'subFrame') {
+ const parent = details.frame?.parent?.url ?? details.referrer ?? '';
+ return parent.startsWith(selfPrefix);
+ }
+ const from = details.frame?.url ?? details.referrer;
+ return ghostLoopbackOrigin(from) === target;
+}
function createGhostProtocolTargetGuard(
ghostId: string,
@@ -460,6 +491,11 @@ function registerGhostProtocol(
// 任意插件页面发出的 HTTPS image 请求(<img> 与 CSS 图片共用该资源类型)。
// HTTP 图片、XHR/fetch、脚本、样式、字体、媒体、WebSocket 与其它协议继续拒绝。
const selfPrefix = `${SCHEME}://${ghostId}/`;
+ // 回环嵌入(ghostPanelLoopbackEmbedAllowed):面板页可以把随包 Node 进程在本机
+ // 提供的页面装进 <iframe>;该子帧内的请求只许回到同一主机:端口(含 WebSocket)。
+ // 面板页自身发出的回环 fetch/XHR 仍被拒;顶层导航到回环地址仍被拒。
+ const loopbackEmbed = ghostPanelLoopbackEmbedAllowed(ghost.manifest);
+ const htmlCsp = loopbackEmbed ? `${GHOST_HTML_CSP}; ${GHOST_LOOPBACK_FRAME_CSP}` : GHOST_HTML_CSP;
ses.webRequest.onBeforeRequest((details, callback) => {
let allowed = details.url.startsWith(selfPrefix);
if (!allowed && isGhostProtocolOwnerActive(owner) && details.resourceType === 'image') {
@@ -469,6 +505,9 @@ function registerGhostProtocol(
allowed = false;
}
}
+ if (!allowed && loopbackEmbed && isGhostProtocolOwnerActive(owner)) {
+ allowed = loopbackEmbedRequestAllowed(details, selfPrefix);
+ }
callback({ cancel: !allowed });
});
const handleRequest = async (request: Request): Promise<Response> => {
@@ -676,7 +715,7 @@ function registerGhostProtocol(
status: 200,
headers: {
'Content-Type': 'text/html; charset=utf-8',
- 'Content-Security-Policy': GHOST_HTML_CSP,
+ 'Content-Security-Policy': htmlCsp,
'Cache-Control': 'no-cache',
},
});
@@ -691,7 +730,7 @@ function registerGhostProtocol(
status: 200,
headers: {
'Content-Type': mime,
- ...(mime.startsWith('text/html') ? { 'Content-Security-Policy': GHOST_HTML_CSP } : {}),
+ ...(mime.startsWith('text/html') ? { 'Content-Security-Policy': htmlCsp } : {}),
'Cache-Control': 'no-cache',
},
});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 059e2c5a30..5be9470341 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1160,6 +1160,38 @@ export function ghostPreviewUrlAllowed(manifest: GhostManifest, rawUrl: string):
return hosts.some((pattern) => ghostNetworkHostMatches(pattern, hostname));
}
+const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);
+
+/**
+ * 回环地址的「主机:端口」身份(http / ws,无凭证);非回环或其它协议返回 null。
+ * 面板嵌入回环预览时,嵌入帧内的请求只许回到同一主机:端口。
+ */
+export function ghostLoopbackOrigin(rawUrl: unknown): string | null {
+ if (typeof rawUrl !== 'string' || rawUrl.length === 0 || rawUrl.length > GHOST_PREVIEW_URL_MAX_CHARS) return null;
+ let url: URL;
+ try {
+ url = new URL(rawUrl);
+ } catch {
+ return null;
+ }
+ if (url.username !== '' || url.password !== '') return null;
+ if (url.protocol !== 'http:' && url.protocol !== 'ws:') return null;
+ const hostname = url.hostname.toLowerCase();
+ if (!LOOPBACK_HOSTNAMES.has(hostname)) return null;
+ return `${hostname}:${url.port || '80'}`;
+}
+
+/**
+ * 停靠面板能否嵌入本机回环预览页:身份卡必须同时声明 panel、node 工作进程
+ * (页面由随包进程在本机提供)以及 preview.hosts 中的 localhost / 127.0.0.1。
+ * 满足时主机放行面板内指向回环地址的子帧,以及该子帧回到同一主机:端口的请求;
+ * 面板页自身仍不能联网。
+ */
+export function ghostPanelLoopbackEmbedAllowed(manifest: GhostManifest): boolean {
+ if (!manifest.panel || !manifest.node) return false;
+ return (manifest.preview?.hosts ?? []).some((host) => host === 'localhost' || host === '127.0.0.1');
+}
+
/**
* 身份卡里声明过的全部外链地址(来源 = network.secrets[].url 与
* node.secretBindings[].url,装包时
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index a4e019bb33..180adf3ed8 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -555,6 +555,14 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
`ghost_call.attachments` 显式交接;Host 复用已有的通用授权链,将授权后的指纹注入
`args.attachments`,绝不把本地绝对路径暴露给插件。插件自行保存业务状态和更新 UI。
Host 不自动回调插件,也不得新增画廊等插件业务语义。
+- 回环嵌入是第二个、也是更窄的页面网络例外:插件同时声明 `panel`、`node` 工作进程和
+ `preview.hosts` 中的 `localhost` / `127.0.0.1` 时(`ghostPanelLoopbackEmbedAllowed`),
+ 其页面 CSP 追加 `frame-src 'self' http://127.0.0.1:* http://localhost:*`,分区请求闸放行
+ 两类请求:面板页作为父帧发起的回环子帧导航;该子帧内回到**同一主机:端口**的资源、
+ XHR 与 WebSocket。面板页自身发出的回环 fetch/XHR、顶层导航到回环地址、换端口或换主机
+ 的请求、带凭证的 URL 与 HTTPS 伪装一律继续拒绝。嵌入页由插件自己的随包 Node 进程在
+ 本机提供,因此不扩大插件可达的网络范围;权限请求处理器不变(嵌入页不能申请摄像头、
+ 定位等权限)。首个消费者是官方 `baguette-simulator`(iOS 模拟器停靠面板)。
- 所有插件 HTML 页面(`settingsHtml`、panel、mainView 与逻辑页)都可以通过 `<img>` 或
CSS 图片直接加载任意 HTTPS 地址,这是唯一的页面网络直连例外。Host 统一生成包含
`img-src https:` 的 CSP,并由 owner × plugin session 请求闸把外部请求严格限定为