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): allow HTTPS images in plugin pages (#3928)

fmfsaisaic39f21e3dcbd
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 cdba7e2cfe..7f87090e02 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1689,6 +1689,51 @@ describe('FORGE_GUIDE', () => {
expect(settingsSection).not.toContain('声明之外的任何外链点了没反应');
});
+ it('所有插件页面只开放 HTTPS 图片直连,不扩大其它网络能力', () => {
+ const mainJsIntro = FORGE_GUIDE.slice(
+ FORGE_GUIDE.indexOf('## 4. main.js 电子脑(沙箱后台逻辑)'),
+ FORGE_GUIDE.indexOf('### 4.0.1'),
+ );
+ const settingsSection = FORGE_GUIDE.slice(
+ FORGE_GUIDE.indexOf('## 4.8 设置自绘(settingsHtml)+ 自定义参数存取(/kv)'),
+ FORGE_GUIDE.indexOf('## 4.9'),
+ );
+ const sandboxRedlines = FORGE_GUIDE.slice(
+ FORGE_GUIDE.indexOf('## 6. 沙箱红线(平台结构保证,写了也没用)'),
+ FORGE_GUIDE.indexOf('## 7. 打包与测试'),
+ );
+
+ for (const section of [mainJsIntro, settingsSection, sandboxRedlines]) {
+ expect(section).toContain('HTTPS 图片');
+ expect(section).toContain('无通用网络直连');
+ }
+ for (const marker of [
+ '所有插件 HTML 页面',
+ 'settingsHtml、panel、mainView 与逻辑页',
+ '**HTTPS 图片资源**',
+ '<img src="https://…">',
+ 'background-image: url("https://…")',
+ 'Electron 判定为 `image`',
+ '不会放行',
+ '`fetch()` / XHR',
+ '外部脚本',
+ '外部样式表',
+ '`http:` 图片',
+ '共用浏览器存储和',
+ '`BroadcastChannel`,脚本/样式',
+ "new BroadcastChannel('my-ghost').postMessage",
+ '完整图片 URL',
+ '`onload` / `onerror`',
+ ]) {
+ expect(settingsSection).toContain(marker);
+ }
+ for (const marker of ['fetch/XHR/', 'WebSocket', '除 HTTPS 图片外']) {
+ expect(sandboxRedlines).toContain(marker);
+ }
+ expect(FORGE_GUIDE).not.toContain('跑在无网络、无文件、无 Node');
+ expect(FORGE_GUIDE).not.toContain('默认无网络');
+ });
+
it('分章体量守卫:每个 ## 章节须留在单次工具结果安全体量内(#890 分章投递的不变量)', () => {
// 手册"随主机版本演进"持续增长;任一章越过单次 MCP 结果上限会静默复现 #890 于该章。
// 上限取 32KB:当前最大章 ~22KB,余量 ~45%,越线即该拆小节。
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 5cb7114f73..f1366202ea 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -2017,7 +2017,9 @@ Cindy 先发布,确认首个支持它的**正式版本号**后,再把 \`minC
## 4. main.js 电子脑(沙箱后台逻辑)
-跑在无网络、无文件、无 Node 的独立沙箱页里,只有一个全局 \`cindy\`:
+跑在无文件、无 Node、无通用网络直连的独立沙箱页里,只有一个全局 \`cindy\`。
+唯一外部直连例外是所有插件页面共有的 HTTPS 图片请求;\`fetch\` / XHR、脚本、样式、
+字体、音视频与 WebSocket 仍不能直连:
\`\`\`js
// 收活:AI 调你的工具时收到 tool-call
@@ -3230,8 +3232,16 @@ tool-call 内轮询时记得定期发 tool-progress 心跳续命(见 §4"长任
"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮),超 800 内部滚动
\`\`\`
-**渲染环境**:与面板同款沙箱页(零桥、零网络直连、CSP 只认同源)。主题变量与
-面板同一套(§5「主题」条的 \`var(--xxx, 回退值)\` 写法照用),主机注入并随换肤
+**渲染环境**:与面板同款沙箱页(零桥、无通用网络直连,与同插件面板/逻辑页共用浏览器存储和
+\`BroadcastChannel\`,脚本/样式/字体/媒体/数据请求仍只认同源)。所有插件 HTML 页面
+(settingsHtml、panel、mainView 与逻辑页)唯一的网络直连例外都是**HTTPS 图片资源**:
+\`<img src="https://…">\` 与 CSS \`background-image: url("https://…")\` 可以直接加载
+任意 HTTPS 地址。主机统一生成 CSP 并只放行 Electron 判定为 \`image\` 的 HTTPS 请求;
+它**不会放行** \`fetch()\` / XHR、外部脚本、外部样式表、字体、音视频、WebSocket、
+\`http:\` 图片或其它协议。加载远程图片会向第三方暴露网络地址及完整图片 URL,不要把密钥、
+token 或用户私密数据拼进 URL。CSP 仍阻止内联脚本和 \`onload\` / \`onerror\` 等内联事件;
+同包外挂 JS 的行为不变。主题变量与面板同一套(§5「主题」条的
+\`var(--xxx, 回退值)\` 写法照用),主机注入并随换肤
自动重灌;设置区基线背景 = 宿主设置卡片色(与相邻卡片无缝),别再自己铺整页
底色。高度缺省自适应:主机在页面就绪后量内容高度,内容动态增减(展开区、
追加列表)时会自动跟随重量(内部 ResizeObserver 通知宿主再量,你无需做
@@ -4324,12 +4334,13 @@ const opened = await cindy.iosSimulator.request({
## 6. 沙箱红线(平台结构保证,写了也没用)
-- **本节说的是 main.js 浏览器电子脑**:它无文件系统、无 Node API、默认无网络——
+- **本节说的是 main.js 浏览器电子脑**:它无文件系统、无 Node API、无通用网络直连
+ (所有插件页面共有的 HTTPS 图片请求是唯一例外)——
即使另声明 node,Node 也在独立进程里,只能经 §4.12 的 stdio 与 main.js 交换数据,
不会把 require/process 等能力注入 main.js。想用 AI/出图走 cindy-request 求主机代办,
随包代码与 CLI 走 §4.12 的 Node 工作进程,网络走 \`cindy.fetch\`,落盘走 \`cindy.fs\`;
是否需要 manifest 声明取决于是 Agent 在途调用还是插件自主调用,见 §4.2、
- §4.7 和 §4.10。沙箱内直连(fetch/XHR/
+ §4.7 和 §4.10。除 HTTPS 图片外,沙箱内直连(fetch/XHR/
WebSocket)与直接读写磁盘永远不存在,声明字段给的是"请主机代办"的资格,
不是能力本身;
- 保险库里的凭证明文永不进沙箱:network 的 key 由主机保管注入,你的代码
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 20d1ecb6bb..cbb5ee3fac 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
@@ -76,7 +76,7 @@ vi.mock('electron', () => ({
vi.mock('node:fs', () => ({ createReadStream: vi.fn() }));
vi.mock('node:fs/promises', () => ({
default: {
- readFile: vi.fn(),
+ readFile: vi.fn().mockResolvedValue(new Uint8Array([1])),
stat: vi.fn().mockResolvedValue({ isFile: () => true, size: 0 }),
},
}));
@@ -251,6 +251,83 @@ describe('electronSandboxAdapter owner partition', () => {
expect(appContextProvider).toHaveBeenCalledOnce();
});
+ it('boot 与任意插件 HTML 响应统一允许 HTTPS 图片,其他 CSP 能力不放宽', async () => {
+ const installed = ghost('https-image-csp');
+ installed.manifest.settingsHtml = 'settings.html';
+ installed.manifest.mainView = { html: 'main-view.html' };
+ ensureGhostProtocolRegistered(installed);
+ const registered = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:https-image-csp',
+ );
+
+ for (const pathname of ['/', '/panel.html', '/settings.html', '/main-view.html', '/other.html']) {
+ const response = await registered?.protocolHandler?.(
+ new Request(`cindy-ghost://https-image-csp${pathname}`),
+ );
+ const csp = response?.headers.get('content-security-policy');
+ expect(csp, pathname).toContain("img-src 'self' data: blob: https:");
+ expect(csp, pathname).toContain("default-src 'self'");
+ expect(csp, pathname).not.toContain('connect-src https:');
+ expect(csp, pathname).not.toContain('script-src https:');
+ expect(csp, pathname).not.toContain('style-src https:');
+ expect(csp, pathname).not.toContain('media-src https:');
+ }
+ });
+
+ it('插件 session 只额外放行 HTTPS image,同源资源保持放行', () => {
+ ensureGhostProtocolRegistered(ghost('https-image-network'));
+ const registered = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:https-image-network',
+ );
+ const handler = registered?.beforeRequest.mock.calls[0]?.[0] as
+ | ((
+ details: { url: string; resourceType: string },
+ callback: (result: { cancel: boolean }) => void,
+ ) => void)
+ | undefined;
+ expect(handler).toBeTypeOf('function');
+
+ const isCancelled = (url: string, resourceType: string): boolean => {
+ const callback = vi.fn();
+ handler?.({ url, resourceType }, callback);
+ expect(callback).toHaveBeenCalledOnce();
+ return callback.mock.calls[0]?.[0].cancel as boolean;
+ };
+
+ expect(isCancelled('https://images.example.com/logo.png', 'image')).toBe(false);
+ expect(isCancelled('cindy-ghost://https-image-network/panel.html', 'mainFrame')).toBe(false);
+ expect(isCancelled('cindy-ghost://https-image-network/icon.png', 'image')).toBe(false);
+
+ for (const [url, resourceType] of [
+ ['http://images.example.com/logo.png', 'image'],
+ ['https://example.com/data', 'xhr'],
+ ['https://example.com/data', 'fetch'],
+ ['https://example.com/app.js', 'script'],
+ ['https://example.com/app.css', 'stylesheet'],
+ ['https://example.com/font.woff2', 'font'],
+ ['https://example.com/video.mp4', 'media'],
+ ['wss://example.com/socket', 'webSocket'],
+ ['ftp://example.com/logo.png', 'image'],
+ ['not a valid URL', 'image'],
+ ['cindy-ghost://other-ghost/icon.png', 'image'],
+ ] as const) {
+ expect(isCancelled(url, resourceType), `${resourceType} ${url}`).toBe(true);
+ }
+ });
+
+ it('重复确保同一分区不会累积网络或协议 listener', () => {
+ const installed = ghost('https-image-listener-once');
+ ensureGhostProtocolRegistered(installed);
+ ensureGhostProtocolRegistered(installed);
+
+ const registered = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:https-image-listener-once',
+ );
+ expect(harness.fromPartition).toHaveBeenCalledOnce();
+ expect(registered?.beforeRequest).toHaveBeenCalledOnce();
+ expect(registered?.protocolHandle).toHaveBeenCalledOnce();
+ });
+
it('请求已进入 handler 后切换 owner 不取消或重新检查在途 provider', async () => {
let finishProvider!: (result: GhostMediaModelsResult) => void;
const provider = vi.fn(
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostFiles.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostFiles.test.ts
index 183ba284d4..c05db6eaa7 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostFiles.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostFiles.test.ts
@@ -37,5 +37,11 @@ describe('ghostFileMime / ghostBootHtml', () => {
const html = ghostBootHtml('main.js');
expect(html).toContain('<script src="/main.js">');
expect(html).toContain('Content-Security-Policy');
+ // boot 同时受 meta 与响应头 CSP 约束;meta 相对基线只增加 HTTPS 图片,
+ // 不能把响应头原有的 data/blob 图片或 media 能力带进有效交集。
+ expect(html).toContain("img-src 'self' https:");
+ expect(html).not.toContain("img-src 'self' data:");
+ expect(html).not.toContain('blob:');
+ expect(html).not.toContain('media-src');
});
});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
index 2f056f1940..bb546ffd20 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
@@ -259,11 +259,12 @@ export function ensureGhostProtocolRegistered(
/**
* 意识页面(html 响应)统一佩戴的 CSP:脚本/样式/资源只许同源(= 自己的
- * 安装目录),img/media 额外放行 data:/blob:(生成图等内存产物使用)。
+ * 安装目录),img 额外放行 data:/blob:/https:(远程图片),media 额外放行
+ * data:/blob:。
* 与分区级断网(onBeforeRequest)构成双保险。
*/
const GHOST_HTML_CSP =
- "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:";
+ "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; media-src 'self' data: blob:";
function registerGhostProtocol(
partition: string,
@@ -289,13 +290,20 @@ function registerGhostProtocol(
ses.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false));
ses.setPermissionCheckHandler(() => false);
ses.on('will-download', (event) => event.preventDefault());
- // 分区级断网(docs/dev-rules/plugin-security-and-authoring.md 的"网络永远不直连"):本分区发出的一切
- // 请求,只放行自己协议同 id 下的资源;http(s) / ws / 其它协议一律掐断。
- // 进程沙箱不管网络,这里才是"零网络"承诺的真正闸门;外部数据未来走
- // 主机代发(管子服务),不走这里。devtools 前端跑在自己的进程,不受影响。
+ // 分区级网络闸:默认只放行自己协议同 id 下的资源;唯一外部例外是
+ // 任意插件页面发出的 HTTPS image 请求(<img> 与 CSS 图片共用该资源类型)。
+ // HTTP 图片、XHR/fetch、脚本、样式、字体、媒体、WebSocket 与其它协议继续拒绝。
const selfPrefix = `${SCHEME}://${ghostId}/`;
ses.webRequest.onBeforeRequest((details, callback) => {
- callback({ cancel: !details.url.startsWith(selfPrefix) });
+ let allowed = details.url.startsWith(selfPrefix);
+ if (!allowed && isGhostProtocolOwnerActive(owner) && details.resourceType === 'image') {
+ try {
+ allowed = new URL(details.url).protocol === 'https:';
+ } catch {
+ allowed = false;
+ }
+ }
+ callback({ cancel: !allowed });
});
ses.protocol.handle(SCHEME, async (request) => {
try {
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.ts
index acd5fc89d2..ca82e03356 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.ts
@@ -68,9 +68,9 @@ export function ghostBootHtml(entry: string): string {
return [
'<!doctype html>',
'<html><head><meta charset="utf-8">',
- // 沙箱页自身的 CSP:只允许同源(即 cindy-ghost://<id>/ 自己的安装目录)
- // 脚本与资源,连 inline script 都不给——意识代码全部来自落盘文件。
- `<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'">`,
+ // meta 与响应头 CSP 会取交集:保留原 default/style 约束,只为图片加入
+ // HTTPS;不在这里继承响应头已有的 data:/blob:/media 放行。
+ `<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' https:">`,
'</head><body>',
`<script src="${src}"></script>`,
'</body></html>',
diff --git a/docs/dev-rules/electron-security-and-process-boundaries.md b/docs/dev-rules/electron-security-and-process-boundaries.md
index b6e7147b54..ad74422214 100644
--- a/docs/dev-rules/electron-security-and-process-boundaries.md
+++ b/docs/dev-rules/electron-security-and-process-boundaries.md
@@ -189,6 +189,11 @@ auth-server)+ origin 命中 `setLoginCaptchaOriginResolver` 注入的 auth 端
- 正式包不得新增远程脚本或 `'unsafe-inline'`。现有 `'unsafe-eval'` 仅为 vendored drawio
的已知例外;新增用途必须先做安全评估,不能顺手扩大 `script-src`、`connect-src` 或
`frame-src`。
+- 所有插件 HTML 页面统一允许 HTTPS 图片:Host 生成的 CSP 只给 `img-src` 增加 `https:`,
+ owner × plugin session 的请求闸只额外放行
+ `protocol === "https:" && resourceType === "image"`。HTTP 图片、XHR/fetch、脚本、
+ 样式表、字体、媒体、WebSocket 与其它协议保持拒绝,同 ghost 的 `cindy-ghost://` 资源照常
+ 放行。不得把这项图片能力扩成通用网络口子;listener 继续按 partition 幂等注册。
- 新的本地资源通道优先使用范围受控的自定义协议,不新增 `file://` 读取路径。主 Renderer
仍使用 `file://` 是存量架构,迁移需要单独设计和验证,不能在普通功能 PR 中顺带改动。
- 打包必须保留现有 Fuses:关闭 RunAsNode、Node options 和 CLI inspect,开启 cookie 加密、
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 1de805db97..4702520e36 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -84,8 +84,10 @@
## 2. 运行时沙箱与进程隔离
-- 每个运行中的插件使用独立 Electron 沙箱进程与专属 session partition。沙箱禁止直接访问
- Node、宿主文件系统和网络。
+- 每个运行中的插件使用独立 Electron 沙箱进程与按 owner × plugin 隔离的内存 session
+ partition。同插件的 `settingsHtml`、panel 与逻辑页继续共享该 partition,保留 browser
+ storage 与 `BroadcastChannel` 契约;沙箱禁止直接访问 Node、宿主文件系统和通用网络,
+ 唯一例外是第 4 节明确限定的 HTTPS 图片资源。
- 插件只允许读取自身安装目录内、经安全相对路径校验的静态资源,不得越权读取其它目录。
- 逻辑页只能经最小 `contextBridge` 管子申请主机能力;面板 webview 保持零特权桥。
- 主机按 `webContents` 绑定反查真实 ghostId,**不信任 sender 自报身份**。
@@ -316,6 +318,16 @@
`ghost_call.attachments` 显式交接;Host 复用已有的通用授权链,将授权后的指纹注入
`args.attachments`,绝不把本地绝对路径暴露给插件。插件自行保存业务状态和更新 UI。
Host 不自动回调插件,也不得新增画廊等插件业务语义。
+- 所有插件 HTML 页面(`settingsHtml`、panel、mainView 与逻辑页)都可以通过 `<img>` 或
+ CSS 图片直接加载任意 HTTPS 地址,这是唯一的页面网络直连例外。Host 统一生成包含
+ `img-src https:` 的 CSP,并由 owner × plugin session 请求闸把外部请求严格限定为
+ `protocol === "https:" && resourceType === "image"`。HTTP 图片、`fetch` / XHR、脚本、
+ 样式表、字体、音视频、WebSocket 与其它协议一律不因此放行;同 ghost 的
+ `cindy-ghost://` 资源继续放行。该能力不新增 HTML sanitizer 或图片属性白名单;既有 CSP
+ 继续阻止内联脚本和内联事件处理器,同包脚本行为不变。远程图片请求会向第三方暴露用户的
+ 网络地址及完整 URL,作者不得把密钥、令牌或用户私密数据拼进图片 URL。session listener
+ 按 owner × plugin 幂等注册;设置页与同插件其它页面继续共享 browser storage、IndexedDB
+ 与 `BroadcastChannel`。
- 面板供片与注入的主题 token 只用 `ghostPanelTheme.ts` 白名单内的值,不扩大暴露面。
- `iosSimulator` 能力只允许读取 Host 当前台前任务的公开模拟器状态,并请求打开既有
Host viewer。请求协议不得出现插件自报 `sessionId`,可选 `instanceId` 必须重新匹配
@@ -493,8 +505,9 @@ topic 路由;产品层多端语义见
## Review 清单
-1. 沙箱是否保持进程隔离、专属 partition、无 Node/宿主 FS/网络直连?身份是否由主机
- 反查而非信任 sender 自报?
+1. 沙箱是否保持进程隔离、专属 partition、无 Node/宿主 FS/通用网络直连?HTTPS 图片
+ 例外是否仍严格限定为 `protocol === "https:" && resourceType === "image"`?身份是否由
+ 主机反查而非信任 sender 自报?
2. 是否先按执行者分清边界:当前 Agent 在途的通用操作是否严格绑定同插件、同会话、
未交卷的 `callId` 并复用 Agent 授权;插件自主 Host 能力是否以 manifest 直接字段声明、
在详情如实展示并由 Host 守门?是否误把安装弹窗或前端展示当成授权事实?