Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): securely inject Node worker secrets (#327)
Kmny3af494a24da0
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 60fa61cfa7..615367eeec 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -344,10 +344,13 @@ describe('FORGE_GUIDE', () => {'setup 就绪声明','anyOf','secret:brave_api_key',+ 'Node 凭证同样可参与 setup.requires',// 2026-07-23 通用能力四件套:会话上下文 / node 多入口 / 目录选择 / 面板预览。'会话上下文(session-context 槽)','workdir_is_local','node.entries',+ 'node.secretBindings',+ 'request.cindy.secrets','目录选择(pick 槽)','cindy.pick','面板预览(preview 槽)',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.tsindex 5b2f1d52a6..cf2a8795fe 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts@@ -101,6 +101,34 @@ describe('evaluateGhostSetup · 启发式回落(无 setup 声明)', () => {expect(status.reauth).toEqual([]);});+ it('Node 持久凭证绑定:保险库未保存时拦截,保存后就绪', () => {+ const m = manifest({+ slots: ['tool', 'node'],+ tools: [{ name: 'mail', description: '收发邮件' }],+ settingsHtml: 'settings.html',+ node: {+ entry: 'worker.cjs',+ protocol: 'json-rpc-stdio',+ secretBindings: [+ {+ key: 'mail_authorization_code',+ label: '邮箱授权码',+ methods: ['mail/action'],+ },+ ],+ },+ });+ expect(evaluateGhostSetup(m, probes()).missingGroups).toEqual([+ [{ ref: 'secret:mail_authorization_code', label: '邮箱授权码', kind: 'key' }],+ ]);+ expect(+ evaluateGhostSetup(+ m,+ probes({ secretSaved: (key) => key === 'mail_authorization_code' }),+ ),+ ).toEqual({ ready: true, missingGroups: [], reauth: [] });+ });+it('连接声明:零连接未就绪,≥1 条就绪(GitLab 形态)', () => {const m = manifest({slots: ['tool', 'network'],diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.tsindex 401f0e1bba..4a2a68341d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts@@ -277,6 +277,120 @@ describe('nodeRuntimeBroker · 权限与协议', () => {expect(spawnProcess).not.toHaveBeenCalled();});+ it('只在清单绑定的方法中把 safeStorage 凭证注入 Worker 保留字段', async () => {+ const ghost = fakeGhost();+ ghost.manifest.node!.secretBindings = [+ {+ key: 'mail_code',+ label: '邮箱授权码',+ methods: ['mail/action'],+ },+ ];+ const child = makeAutoReplyProcess();+ const readSecret = vi.fn(() => 'fake-secret-value');+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ readSecret,+ spawnProcess: () => child as unknown as NodeWorkerProcess,+ });++ const result = await broker.handleRequest('node-ghost', {+ type: 'node-request',+ method: 'mail/action',+ params: { action: 'search' },+ // main.js 自报的同名字段不可信;broker 必须忽略并重铸。+ cindy: { secrets: { mail_code: 'attacker-value' } },+ });+ expect(result).toMatchObject({ ok: true });+ expect(readSecret).toHaveBeenCalledWith('node-ghost', 'mail_code');+ expect(child.received[0]).toMatchObject({+ method: 'mail/action',+ params: { action: 'search' },+ cindy: { secrets: { mail_code: 'fake-secret-value' } },+ });++ await broker.handleRequest('node-ghost', rpcRequest('account/status', {}));+ expect(readSecret).toHaveBeenCalledTimes(1);+ expect(child.received[1]).not.toHaveProperty('cindy');+ broker.destroyAll();+ });++ it('绑定凭证未保存时不向 Worker 发送业务请求,也不在日志中泄露值', async () => {+ const ghost = fakeGhost();+ ghost.manifest.node!.secretBindings = [+ {+ key: 'mail_code',+ label: '邮箱授权码',+ methods: ['mail/action'],+ },+ ];+ const child = makeAutoReplyProcess();+ const log = { info: vi.fn(), warn: vi.fn() };+ const spawnProcess = vi.fn(() => child as unknown as NodeWorkerProcess);+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ readSecret: () => null,+ spawnProcess,+ log,+ });++ expect(await broker.handleRequest('node-ghost', rpcRequest('mail/action', {}))).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ message: expect.stringContaining('邮箱授权码'),+ });+ expect(spawnProcess).not.toHaveBeenCalled();+ expect(child.received).toHaveLength(0);+ expect(JSON.stringify(log)).not.toContain('fake-secret-value');+ broker.destroyAll();+ });++ it('保险库读取异常时返回固定错误,不发送请求或泄露异常细节', async () => {+ const ghost = fakeGhost();+ ghost.manifest.node!.secretBindings = [+ {+ key: 'mail_code',+ label: '邮箱授权码',+ methods: ['mail/action'],+ },+ ];+ const child = makeAutoReplyProcess();+ const spawnProcess = vi.fn(() => child as unknown as NodeWorkerProcess);+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ readSecret: () => {+ throw new Error('vault failed with sensitive context');+ },+ spawnProcess,+ });++ const result = await broker.handleRequest('node-ghost', rpcRequest('mail/action', {}));+ expect(result).toMatchObject({+ ok: false,+ errorCode: 'INTERNAL',+ message: '读取 Node 请求所需凭证失败',+ });+ expect(JSON.stringify(result)).not.toContain('sensitive context');+ expect(spawnProcess).not.toHaveBeenCalled();+ expect(child.received).toHaveLength(0);+ broker.destroyAll();+ });++ it('mcp-stdio 保留初始化方法在启动 Worker 前拒绝', async () => {+ const ghost = fakeGhost({ protocol: 'mcp-stdio' });+ const spawnProcess = vi.fn();+ const broker = new GhostNodeRuntimeBroker({ getGhost: () => ghost, spawnProcess });++ for (const method of ['initialize', 'notifications/initialized']) {+ expect(await broker.handleRequest('node-ghost', rpcRequest(method, {}))).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ message: expect.stringContaining('MCP 初始化'),+ });+ }+ expect(spawnProcess).not.toHaveBeenCalled();+ });+it('mcp-stdio 由主机先 initialize,再发送 initialized 通知和业务方法', async () => {const methods: string[] = [];const ghost = fakeGhost({ protocol: 'mcp-stdio' });diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 554d588f98..4e2a1a3b13 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -711,7 +711,15 @@ Node 工作进程或 stdio MCP,见 §4.12)、\`session-context\`(派活时主机"lifecycle": "on-demand", // 可选:on-demand(缺省)/resident(常驻,单列高风险权限)"idleTimeoutSeconds": 120, // 可选:按需档空闲关闭时间,30–3600;resident 禁写"entries": ["node/build.cjs"], // 可选 ≤4 条:额外工作进程入口(每入口一个独立进程,调用时用 entry 指名,见 §4.12.1;不能与 entry / 浏览器沙箱 entry / 彼此重复)- "childSpawn": true // 可选:worker 可请宿主代启申报入口的原样 stdio 子进程(见 §4.12.4;装入确认框单列一行)+ "childSpawn": true, // 可选:worker 可请宿主代启申报入口的原样 stdio 子进程(见 §4.12.4;装入确认框单列一行)+ "secretBindings": [{ // 可选 1–4 条:safeStorage 持久化凭证按方法临时注入 Worker+ "key": "mail_code", // 插件内唯一,小写字母开头,1–32 位小写/数字/下划线+ "label": "邮箱授权码", // 安装确认与设置页展示名+ "methods": ["mail/action"], // 只在这些 JSON-RPC 方法中注入,每条 1–128 位+ "entry": "node/worker.cjs", // 可选:逐字命中 node.entry/entries;缺省仅主入口+ "hint": "请填写服务商授权码", // 可选 ≤200 字+ "url": "https://mail.example.com/settings" // 可选 https 申请页+ }]}\`\`\`@@ -798,10 +806,11 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它}\`\`\`-- 条目三种引用:\`secret:<key>\`(network.secrets 声明的凭证:user 源查已保存、oauth 源- 查已连接账号;账号全过期时主机弹「重新连接」话术)、\`connection:<key>\`(该连接声明- 下至少添加一条)、\`{ "kv": "<键名>", "label": "..." }\`(你 /kv 参数里的顶层键非空;- 键名主机无先验,label 必填)。+- 条目三种引用:\`secret:<key>\`(\`network.secrets\` 或 \`node.secretBindings\` 声明的+ 凭证:Node 绑定与 user 源查已保存、oauth 源查已连接账号;账号全过期时主机弹「重新连接」+ 话术)、\`connection:<key>\`(该连接声明下至少添加一条)、+ \`{ "kv": "<键名>", "label": "..." }\`(你 /kv 参数里的顶层键非空;键名主机无先验,+ label 必填)。Node 凭证同样可参与 setup.requires。- 引用必须逐字指向已声明的 key,悬空引用**打包期就拒**;\`login-email\` 源凭证恒就绪,引用它同样拒(没有配置动作可引导)。kv 引用要求已声明 settingsHtml(没有设置页没人填)。- **绝大多数意识不需要写本字段**:不声明时主机走启发式——声明过凭证/连接的意识,@@ -1350,6 +1359,9 @@ const r = await cindy.fetch({**凭证语义(必读)**:你在详单里只声明"需要一条叫什么的凭证、注入到哪个请求头";值由主机加密保管、只在代发请求时注入。**保险库里的明文你的代码永远读不回**——不要试图让用户把 key 发进聊天,更不要把 key 硬编码在源码里。+这里说的是 \`network.secrets\` 的浏览器沙箱/HTTP 代发语义;确需本地协议时,+\`node.secretBindings\` 是唯一允许把对应凭证交给 Node Worker 的显式例外,+并会在安装权限清单单独披露(见 §4.12.1)。**收单一律由你的 settingsHtml 负责**(宿主不渲染凭证输入框,声明 user 凭证必须同时声明 settingsHtml,校验强制):你在 settingsHtml 里画输入框收单,值经@@ -1851,6 +1863,51 @@ if (!response.ok) throw new Error(response.message);const result = response.result;\`\`\`+#### Node Worker 的持久化凭证绑定++本地 IMAP/SMTP 等协议确实需要 Worker 使用凭证明文时,在+\`node.secretBindings\` 声明凭证键与允许注入的方法。设置页仍只负责收单:++\`\`\`js+// settings.js:输入框里的值立即交给主机 safeStorage,不要进 /kv / 日志 / BroadcastChannel+await fetch('/secrets/mail_code', {+ method: 'PUT',+ body: JSON.stringify({ value: authorizationCode })+});+// GET /secrets 只能看到 { key:'mail_code', saved:true, tail? },永远没有明文+\`\`\`++浏览器 \`main.js\` 发给 Node 的业务参数里不要放凭证:++\`\`\`js+await cindy.node.request({+ method: 'mail/action',+ params: { action: 'search', query: '账单' }+});+\`\`\`++宿主现查清单,只有 method 与目标 entry 同时命中绑定时,才从 safeStorage+读取本插件自己的键,并在发往 Worker 的 JSON-RPC 保留字段中临时注入:++\`\`\`js+// worker 收到的 request;cindy 字段由宿主铸造,main.js 自报同名字段会被忽略+const authorizationCode = request.cindy.secrets.mail_code;+\`\`\`++规则与红线:++- \`secretBindings\` 最多 4 条,每条 \`methods\` 1–16 个;省略 \`entry\`+ 只绑定主入口,不能借同名方法把凭证送去其它入口;+- 未保存凭证时宿主在请求进入 Worker 前返回 \`PERMISSION_DENIED\`,设置页可用+ \`GET /secrets\` 的 saved 状态引导用户;+- 宿主不会直接把明文交给 \`main.js\`、Agent 参数或写入宿主日志;但 Worker+ 收到明文后可以主动回传、落盘或写日志,浏览器侧代码和 Agent 也可能因此间接+ 获得它。安装/更新权限清单会逐条披露此风险,只安装可信来源插件;+- Worker 用完不要缓存、落盘、回传或写日志;每次请求都以+ \`request.cindy.secrets\` 的当次值为准;+- \`node.secretBindings\` 与 \`network.secrets\` / \`network.connections\`+ 共用插件内凭证键命名空间,撞名拒装;声明它必须同时提供 \`settingsHtml\`。+长任务(构建/打包这类几分钟量级的活)加 \`maxTotalMs\` 开启**有动静就续期**:\`timeoutMs\` 变成"沉默窗口"——worker 只要还在输出(stdout 协议消息或 stderr日志)就不断续期,绝对上限 \`maxTotalMs\`(最长 15 分钟):diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.tsindex b3d4a35111..0a6d77ab25 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts@@ -78,6 +78,9 @@ function deriveRequirementGroups(manifest: GhostManifest): GhostSetupRequirementif (s.source === 'login-email') continue; // 登录派生恒就绪,不构成配置需求implicit.push({ kind: 'secret', key: s.key });}+ for (const s of manifest.node?.secretBindings ?? []) {+ implicit.push({ kind: 'secret', key: s.key });+ }for (const c of manifest.network?.connections ?? []) {implicit.push({ kind: 'connection', key: c.key });}@@ -94,9 +97,10 @@ function toStatusItem(manifest: GhostManifest, req: GhostSetupRequirement): Ghosreturn { ref: `connection:${req.key}`, label: decl?.label ?? req.key, kind: 'connection' };}const decl = manifest.network?.secrets?.find((s) => s.key === req.key);+ const nodeDecl = manifest.node?.secretBindings?.find((s) => s.key === req.key);return {ref: `secret:${req.key}`,- label: decl?.label ?? req.key,+ label: decl?.label ?? nodeDecl?.label ?? req.key,kind: decl?.source === 'oauth' ? 'oauth' : 'key',};}@@ -109,8 +113,11 @@ function verdictOf(manifest: GhostManifest, req: GhostSetupRequirement, probes:return probes.connectionCount(req.key) > 0 ? 'satisfied' : 'missing';}const decl = manifest.network?.secrets?.find((s) => s.key === req.key);+ const nodeDecl = manifest.node?.secretBindings?.find((s) => s.key === req.key);// 清单漂移防御(setup 引用在校验期保证存在,这里只可能是运行期清单被// 换过):查无声明按已就绪放行,交给运行期 networkSlot 兜底,不误拦。+ if (!decl && !nodeDecl) return 'satisfied';+ if (nodeDecl) return probes.secretSaved(req.key) ? 'satisfied' : 'missing';if (!decl) return 'satisfied';if (decl.source === 'login-email') return 'satisfied';if (decl.source === 'oauth') {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 780c045248..e7ef595737 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -585,6 +585,7 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {if (!nodeRuntimeBrokerSingleton) {nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,+ readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),sendToGhost: (ghostId, payload) => {sendToGhostLogic(ghostId, payload);},@@ -1837,24 +1838,27 @@ export function registerGhostIpc(): void {ghostKv.write(ghostId, value);},});- // /secrets 只写通道(user 凭证一律由意识 settingsHtml 收单入库——宿主- // 凭证渲染 2026-07-13 整体退役):现查在装清单拿收单键集(意识更新后立即- // 以新清单为准,不吃分区 handler 闭包里的旧快照);login-email 派生凭证- // 没有收单动作,不在键集内。保险库真身 = providerSecretStore(safeStorage- // 键名与官方别名同一套)。卸下后的残留请求查无此意识,统一 404。+ // /secrets 只写通道(network user 与 node.secretBindings 凭证一律由意识+ // settingsHtml 收单入库——宿主凭证渲染 2026-07-13 整体退役):现查在装+ // 清单拿收单键集(意识更新后立即以新清单为准,不吃分区 handler 闭包里的+ // 旧快照);login-email 派生凭证没有收单动作,不在键集内。保险库真身 =+ // providerSecretStore(safeStorage 键名与官方别名同一套)。卸下后的残留+ // 请求查无此意识,统一 404。setGhostSecretsHandler(async ({ ghostId, method, pathname, readBodyText }) => {const ghost = findAvailableGhost(ghostId);if (!ghost) return { status: 404 };- const secretDecls = ghost.manifest.network?.secrets ?? [];- const userSecretKeys = secretDecls+ const networkSecretDecls = ghost.manifest.network?.secrets ?? [];+ const nodeSecretDecls = ghost.manifest.node?.secretBindings ?? [];+ const userSecretKeys = networkSecretDecls// login-email(派生)与 oauth(主机托管授权)都没有"用户填值"这回事,// 不进 /secrets 收单键集(oauth 的 client 凭证走 /oauth 端点)。.filter((s) => s.source !== 'login-email' && s.source !== 'oauth')- .map((s) => s.key);+ .map((s) => s.key)+ .concat(nodeSecretDecls.map((s) => s.key));// login-email 派生身份:GET 状态回查附 identity(= 当前登录邮箱,设置页// 只读展示"用的是哪个身份")。回给意识不算新增泄露面——装入确认框已// 披露"将使用你的登录邮箱",且注入时它自己的服务端本就可见。写/删 405。- const identitySecretKeys = secretDecls+ const identitySecretKeys = networkSecretDecls.filter((s) => s.source === 'login-email').map((s) => s.key);return handleGhostSecretsRequest({@@ -1874,7 +1878,10 @@ export function registerGhostIpc(): void {// 入库成功 → 主机代言 tips("凭证「xxx」已保存",带意识身份头);// 文案里的名字用清单声明的 label(给用户看的名称),兜底裸 key。onStored: (secretKey) => {- const label = secretDecls.find((s) => s.key === secretKey)?.label ?? secretKey;+ const label =+ networkSecretDecls.find((s) => s.key === secretKey)?.label ??+ nodeSecretDecls.find((s) => s.key === secretKey)?.label ??+ secretKey;broadcastGhostHostNotice(ghostId, { textKey: 'secretSaved', textArgs: { name: label } });},log,diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex 5ac706407d..28f7e8e972 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -34,6 +34,7 @@ import {GHOST_NODE_CHILD_MODE_FLAG,GHOST_NODE_MAX_CHILDREN_PER_GHOST,GHOST_NODE_REQUEST_MAX_TOTAL_MS,+ isGhostNodeMcpReservedMethod,parseGhostNodeChildToHostMessage,} from '../../shared/ghost.js';@@ -76,6 +77,11 @@ export interface NodeWorkerProcess {export interface GhostNodeRuntimeBrokerDeps {getGhost(id: string): InstalledGhost | null;+ /**+ * 读取当前插件自己声明的 Node 凭证。生产接 safeStorage;返回 null =+ * 未保存或保险库不可用。调用方不得记录返回值。+ */+ readSecret?: (ghostId: string, secretKey: string) => string | null;spawnProcess?: (entryPath: string, cwd: string, ghostId: string) => NodeWorkerProcess;/** 代启原样 stdio 子进程(childSpawn;缺省用 utilityProcess 适配器)。 */spawnChildProcess?: (@@ -307,6 +313,11 @@ function errorResult(return { ok: false, errorCode, message, ...(data !== undefined ? { data } : {}) };}+function clearHostSecrets(secrets: Record<string, string> | undefined): void {+ if (!secrets) return;+ for (const key of Object.keys(secrets)) secrets[key] = '';+}+/*** 每意识的本地 Node 工作进程生命周期与 JSON-RPC stdio 中继。* 多进程窄版(2026-07-23):主入口之外,manifest.node.entries 申报的每个额外@@ -407,37 +418,77 @@ export class GhostNodeRuntimeBroker {}entryRel = request.entry;}+ const secretBindings = (ghost.manifest.node.secretBindings ?? []).filter(+ (binding) =>+ binding.methods.includes(request.method as string) &&+ (binding.entry ?? ghost.manifest.node!.entry) === entryRel,+ );++ if (+ ghost.manifest.node.protocol === 'mcp-stdio' &&+ isGhostNodeMcpReservedMethod(request.method as string)+ ) {+ return errorResult('INVALID_REQUEST', 'MCP 初始化由 Cindy 主机统一管理');+ }++ let hostSecrets: Record<string, string> | undefined;+ if (secretBindings.length > 0) {+ hostSecrets = Object.create(null) as Record<string, string>;+ try {+ for (const binding of secretBindings) {+ const value = this.deps.readSecret?.(ghostId, binding.key) ?? null;+ if (value === null) {+ clearHostSecrets(hostSecrets);+ return errorResult(+ 'PERMISSION_DENIED',+ `Node 请求需要先配置凭证「${binding.label}」`,+ );+ }+ hostSecrets[binding.key] = value;+ }+ } catch {+ clearHostSecrets(hostSecrets);+ return errorResult('INTERNAL', '读取 Node 请求所需凭证失败');+ }+ }let entry: WorkerEntry;try {entry = await this.ensureWorker(ghost, entryRel);} catch (error) {+ clearHostSecrets(hostSecrets);return errorResult('PROCESS_START_FAILED',error instanceof Error ? error.message : 'Node 工作进程启动失败',);}if (entry.pending.size >= MAX_PENDING_REQUESTS) {+ clearHostSecrets(hostSecrets);return errorResult('RATE_LIMITED', '这个插件同时等待的 Node 请求太多');}try {if (ghost.manifest.node.protocol === 'mcp-stdio') {- if (request.method === 'initialize' || request.method === 'notifications/initialized') {- return errorResult('INVALID_REQUEST', 'MCP 初始化由 Cindy 主机统一管理');- }await this.ensureMcpInitialized(entry);if (entry.pending.size >= MAX_PENDING_REQUESTS) {return errorResult('RATE_LIMITED', '这个插件同时等待的 Node 请求太多');}}- const result = await this.sendRpc(+ const pendingResult = this.sendRpc(entry,request.method,request.params ?? null,effectiveTimeoutMs,request.maxTotalMs as number | undefined,+ hostSecrets,);+ // writeLine/JSON.stringify 在 sendRpc 内同步完成;随即抹掉本次临时对象,+ // 不让凭证明文跟随 Promise 生命周期常驻在 broker 闭包里。+ if (hostSecrets) {+ clearHostSecrets(hostSecrets);+ hostSecrets = undefined;+ }+ const result = await pendingResult;return { ok: true, result };} catch (error) {if (error instanceof NodeRpcError) {@@ -447,6 +498,7 @@ export class GhostNodeRuntimeBroker {}return errorResult('INTERNAL', error instanceof Error ? error.message : String(error));} finally {+ clearHostSecrets(hostSecrets);this.scheduleIdleStop(entry);}}@@ -848,6 +900,7 @@ export class GhostNodeRuntimeBroker {params: unknown,timeoutMs: number,maxTotalMs?: number,+ hostSecrets?: Readonly<Record<string, string>>,): Promise<unknown> {this.clearIdleTimer(entry);const id = String(entry.nextId++);@@ -868,7 +921,15 @@ export class GhostNodeRuntimeBroker {entry.pending.set(id, pending);this.armPendingTimer(pending);try {- this.writeLine(entry, { jsonrpc: '2.0', id, method, params });+ this.writeLine(entry, {+ jsonrpc: '2.0',+ id,+ method,+ params,+ ...(hostSecrets && Object.keys(hostSecrets).length > 0+ ? { cindy: { secrets: hostSecrets } }+ : {}),+ });} catch (error) {entry.pending.delete(id);this.clearTimer(pending.timer);diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.tsindex a291fc720e..5bb220b0bd 100644--- a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts@@ -1,7 +1,8 @@/**- * /secrets 协议端点的纯函数分派层(user 凭证的只写入库通道,FORGE_GUIDE- * §4.7「意识收单」——宿主凭证渲染 2026-07-13 整体退役,用户填的凭证一律- * 经此通道)。与 ghostKvEndpoint 同拓扑:与 Electron 解耦、单测直接覆盖+ * /secrets 协议端点的纯函数分派层(用户凭证的只写入库通道,FORGE_GUIDE+ * §4.7「意识收单」——宿主凭证渲染 2026-07-13 整体退役,network.secrets+ * 与 node.secretBindings 声明的用户凭证一律经此通道)。与+ * ghostKvEndpoint 同拓扑:与 Electron 解耦、单测直接覆盖* (规范 14),唯一调用方是 electronSandboxAdapter 的 cindy-ghost:// 协议* handler(经 index.ts 注入的闭包供清单与保险库)。*@@ -24,8 +25,10 @@* 明文的动作,GET 只回"存没存"布尔 + 尾 4 位指纹(2026-07-13 Lizi 拍板的* 有意识降级:指纹在入库那一刻由主机截取、分键保管;老键的懒回填发生在* main 保险库层——与注入同权限的进程,本就每次代发都读明文——本端点及- * 沙箱可见面始终只有预截的 4 个字符)。保管(safeStorage)与注入- * (主机代发请求时)完全不变;login-email 派生凭证没有收单动作,404 同未声明。+ * 沙箱可见面始终只有预截的 4 个字符)。network 凭证仅在主机代发请求时+ * 注入;node.secretBindings 凭证仅由 broker 在清单限定的方法/入口请求中+ * 临时交给对应 Worker。两者都不经浏览器 main.js、Agent 参数或日志。+ * login-email 派生凭证没有收单动作,404 同未声明。*/import { GhostKvError } from '../ghostKvStore.js';@@ -55,7 +58,10 @@ export async function handleGhostSecretsRequest(args: {pathname: string;/** 惰性读 body(调用方给有界读取器;只在 PUT 消费)。 */readBodyText: () => Promise<string>;- /** 当前清单里 user 来源的凭证键(index.ts 现查在装清单,不吃缓存)。 */+ /**+ * 当前清单里可由用户写入的凭证键(network user + node.secretBindings;+ * index.ts 现查在装清单,不吃缓存)。+ */userSecretKeys: string[];/** 清单里 source:'login-email' 的凭证键(只读身份:GET 回 identity,写/删 405)。 */identitySecretKeys?: string[];diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex 30226ce35e..275b9198c6 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -61,7 +61,12 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {function itemIcon(item: GhostPermissionItem): LucideIcon {if (item.labelKey === 'panelLeft') return PanelLeft;// network 槽的凭证条目换钥匙图标(与域名条目区分:一个是"去哪",一个是"带什么")。- if (item.labelKey === 'networkSecret' || item.labelKey === 'networkSecretOauth') return KeyRound;+ if (+ item.labelKey === 'networkSecret' ||+ item.labelKey === 'networkSecretOauth' ||+ item.labelKey === 'nodeSecret'+ )+ return KeyRound;return KIND_ICON[item.kind];}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsxindex aa9610ce90..abef7a302e 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx@@ -117,6 +117,29 @@ describe('GhostPermissionList(装入全量清单)', () => {expect(screen.getByText('settings.ghosts.perm.codeDetailNetwork')).toBeTruthy();expect(screen.queryByText('settings.ghosts.perm.codeDetail')).toBeNull();});++ it('Node 持久凭证单独披露明文注入范围', () => {+ const node: GhostManifest = {+ ...chip(),+ slots: [...chip().slots, 'node'],+ settingsHtml: 'settings.html',+ node: {+ entry: 'worker.cjs',+ protocol: 'json-rpc-stdio',+ secretBindings: [+ {+ key: 'mail_authorization_code',+ label: '邮箱授权码',+ methods: ['account/connect', 'mail/action'],+ },+ ],+ },+ };+ render(<GhostPermissionList items={ghostPermissionItems(node)} />);+ expect(screen.getByText(/perm\.nodeSecret:.*邮箱授权码/)).toBeTruthy();+ expect(screen.getByText('settings.ghosts.perm.nodeSecretDetail')).toBeTruthy();+ expect(screen.getByText(/account\/connect\s+mail\/action/)).toBeTruthy();+ });});describe('GhostPermissionDiffView(更新权限 diff)', () => {diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex da4d44a6e8..d31591cdca 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2293,6 +2293,8 @@"nodeRuntime": "Can run a bundled Node program on this computer","nodeMcp": "Can run a bundled stdio MCP on this computer","nodeRuntimeDetail": "High risk: it has the same local access as your user account, including files, network, and starting other programs. Cindy cannot contain it in the browser sandbox.",+ "nodeSecret": "Can provide the stored credential “{{name}}” to the local Node program",+ "nodeSecretDetail": "Cindy stores it encrypted and injects it only while the declared Worker methods below run. The Node program receives the plaintext and can return, log, save, or otherwise expose it to browser-side plugin code or Agent parameters. Only install plugins you trust.","nodeResident": "The Node program can stay running in the background","nodeResidentDetail": "Runs while the plugin is enabled and stops when disabled, updated, uninstalled, or when Cindy exits.","tool": "Tool \"{{name}}\"",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 0e2774f652..c259c9e0df 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2292,6 +2292,8 @@"nodeRuntime": "同梱された Node プログラムをこのコンピューターで実行できます","nodeMcp": "同梱された stdio MCP をこのコンピューターで実行できます","nodeRuntimeDetail": "高リスク:あなたのユーザーアカウントと同じ権限で、ローカルファイルの読み書き、ネットワークアクセス、他のプログラムの起動ができます。Cindy のブラウザーサンドボックスでは隔離できません。",+ "nodeSecret": "保存済みの認証情報「{{name}}」をローカル Node プログラムに渡せます",+ "nodeSecretDetail": "Cindy は暗号化して保管し、以下で宣言された Worker メソッドの実行時だけ一時的に注入します。Node プログラムは平文を受け取り、ブラウザー側のプラグインコードや Agent パラメーターへ返したり、ログやファイルに保存したりできるため、信頼できるプラグインだけをインストールしてください。","nodeResident": "Node プログラムをバックグラウンドで常駐実行できます","nodeResidentDetail": "プラグインが有効な間は実行を続け、無効化、更新、アンインストール、または Cindy 終了時に停止します。","tool": "ツール「{{name}}」",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex d808ad516a..1a8697a754 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2292,6 +2292,8 @@"nodeRuntime": "함께 제공된 Node 프로그램을 이 컴퓨터에서 실행할 수 있음","nodeMcp": "함께 제공된 stdio MCP를 이 컴퓨터에서 실행할 수 있음","nodeRuntimeDetail": "고위험:사용자 계정과 같은 권한으로 로컬 파일을 읽거나 수정하고, 네트워크에 접근하며, 다른 프로그램을 시작할 수 있습니다. Cindy의 브라우저 샌드박스로 격리할 수 없습니다.",+ "nodeSecret": "저장된 자격 증명 ‘{{name}}’을(를) 로컬 Node 프로그램에 제공할 수 있음",+ "nodeSecretDetail": "Cindy가 암호화해 보관하고 아래에 선언된 Worker 메서드가 실행될 때만 임시로 주입합니다. Node 프로그램은 평문을 받으며 브라우저 측 플러그인 코드나 Agent 매개변수로 반환하거나 로그 또는 파일에 저장할 수 있으므로 신뢰할 수 있는 플러그인만 설치하세요.","nodeResident": "Node 프로그램을 백그라운드에서 계속 실행할 수 있음","nodeResidentDetail": "플러그인이 활성화된 동안 실행되며 비활성화, 업데이트, 제거 또는 Cindy 종료 시 중지됩니다.","tool": "도구 \"{{name}}\"",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 194384a46c..d9fc498e10 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2292,6 +2292,8 @@"nodeRuntime": "可在本机运行随插件附带的 Node 程序","nodeMcp": "可在本机运行随插件附带的 stdio MCP","nodeRuntimeDetail": "高风险:它和你本人一样,可以读取或修改你账号能访问的本机文件、访问网络并启动其它程序。Cindy 不能用浏览器沙箱限制它。",+ "nodeSecret": "可将已保存凭证「{{name}}」提供给本机 Node 程序",+ "nodeSecretDetail": "Cindy 加密保管,仅在下列已声明 Worker 方法执行时临时注入。Node 程序会收到明文,也可以将其回传、记录、保存或暴露给浏览器侧插件代码及 Agent 参数;请只安装可信插件。","nodeResident": "Node 程序可常驻后台","nodeResidentDetail": "插件启用期间会一直运行;停用、更新、卸载或退出 Cindy 时关闭。","tool": "工具「{{name}}」",diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 54c7b15989..2bc18e8688 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -5,6 +5,7 @@ import {deriveGhostSessionContext,diffGhostPermissionItems,ghostContentKeys,+ ghostExternalLinkUrls,ghostNetworkHostMatches,ghostPanelKind,ghostPreviewUrlAllowed,@@ -368,6 +369,154 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'node'] }).ok).toBe(false);});+ it('node.secretBindings 逐方法声明保险库凭证并生成单独权限项', () => {+ const result = validateGhostManifest({+ ...goodChipManifest(),+ settingsHtml: 'settings.html',+ slots: ['panel', 'node'],+ node: {+ entry: 'node/worker.cjs',+ protocol: 'json-rpc-stdio',+ secretBindings: [+ {+ key: 'mail_code',+ label: '邮箱授权码',+ methods: ['account/connect', 'mail/action'],+ url: 'https://mail.example.com/settings',+ },+ ],+ },+ });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.manifest.node?.secretBindings).toEqual([+ {+ key: 'mail_code',+ label: '邮箱授权码',+ methods: ['account/connect', 'mail/action'],+ url: 'https://mail.example.com/settings',+ },+ ]);+ expect(ghostPermissionItems(result.manifest)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ key: expect.stringContaining('node:secret:mail_code'),+ kind: 'node',+ labelKey: 'nodeSecret',+ labelArgs: { name: '邮箱授权码' },+ }),+ ]),+ );++ const reordered = validateGhostManifest({+ ...goodChipManifest(),+ settingsHtml: 'settings.html',+ slots: ['panel', 'node'],+ node: {+ entry: 'node/worker.cjs',+ protocol: 'json-rpc-stdio',+ secretBindings: [+ {+ key: 'mail_code',+ label: '邮箱授权码',+ methods: ['mail/action', 'account/connect'],+ url: 'https://mail.example.com/settings',+ },+ ],+ },+ });+ expect(reordered.ok).toBe(true);+ if (!reordered.ok) return;+ const permission = ghostPermissionItems(result.manifest).find((item) =>+ item.key.startsWith('node:secret:mail_code:'),+ );+ const reorderedPermission = ghostPermissionItems(reordered.manifest).find((item) =>+ item.key.startsWith('node:secret:mail_code:'),+ );+ expect(reorderedPermission?.key).toBe(permission?.key);+ expect(reorderedPermission?.detail).toBe('mail/action\naccount/connect');++ expect(ghostExternalLinkUrls(result.manifest)).toContain('https://mail.example.com/settings');+ });++ it('node.secretBindings 缺设置页、坏方法/入口、重复键或与 network 凭证撞名均拒', () => {+ const base = {+ ...goodChipManifest(),+ settingsHtml: 'settings.html',+ slots: ['panel', 'node'],+ node: {+ entry: 'node/worker.cjs',+ entries: ['node/secondary.cjs'],+ protocol: 'json-rpc-stdio',+ },+ };+ const binding = { key: 'mail_code', label: '邮箱授权码', methods: ['mail/action'] };+ expect(+ validateGhostManifest({+ ...base,+ settingsHtml: undefined,+ node: { ...base.node, secretBindings: [binding] },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...base,+ node: { ...base.node, secretBindings: [{ ...binding, methods: ['bad method'] }] },+ }).ok,+ ).toBe(false);+ for (const method of ['initialize', 'notifications/initialized']) {+ expect(+ validateGhostManifest({+ ...base,+ node: {+ ...base.node,+ protocol: 'mcp-stdio',+ secretBindings: [{ ...binding, methods: [method] }],+ },+ }).ok,+ ).toBe(false);+ }+ expect(+ validateGhostManifest({+ ...base,+ node: {+ ...base.node,+ protocol: 'json-rpc-stdio',+ secretBindings: [{ ...binding, methods: ['initialize'] }],+ },+ }).ok,+ ).toBe(true);+ expect(+ validateGhostManifest({+ ...base,+ node: { ...base.node, secretBindings: [{ ...binding, entry: 'node/other.cjs' }] },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...base,+ node: { ...base.node, secretBindings: [binding, binding] },+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...base,+ slots: ['panel', 'node', 'network'],+ node: { ...base.node, secretBindings: [binding] },+ network: {+ hosts: ['api.example.com'],+ secrets: [+ {+ key: 'mail_code',+ label: '重复',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ },+ ],+ },+ }).ok,+ ).toBe(false);+ });+it('工具声明(卡槽②)与 tool 槽成对;名/描述/条数校验', () => {const withTools = (slots: string[], tools: unknown) =>validateGhostManifest({ ...goodChipManifest(), slots, tools });diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex e2d718c03b..ddb4aef346 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -127,6 +127,40 @@ export type GhostNodeProtocol = (typeof GHOST_NODE_PROTOCOLS)[number];export const GHOST_NODE_LIFECYCLES = ['on-demand', 'resident'] as const;export type GhostNodeLifecycle = (typeof GHOST_NODE_LIFECYCLES)[number];+/** 单插件最多可声明的 Node 凭证绑定数。 */+export const GHOST_NODE_MAX_SECRET_BINDINGS = 4;+/** 单条 Node 凭证最多可绑定的 JSON-RPC 方法数。 */+export const GHOST_NODE_MAX_SECRET_METHODS = 16;+const GHOST_NODE_MCP_RESERVED_METHODS = new Set(['initialize', 'notifications/initialized']);++/** MCP 握手由宿主发起,插件业务请求与凭证绑定均不得占用这些方法。 */+export function isGhostNodeMcpReservedMethod(method: string): boolean {+ return GHOST_NODE_MCP_RESERVED_METHODS.has(method);+}++/**+ * 主机保险库 → 随包 Node Worker 的按请求凭证绑定。+ *+ * 值由 settingsHtml 经 `/secrets` 一次性写入 safeStorage;浏览器沙箱+ * main.js 不能直接从保险库读取明文。宿主仅在 method 与 entry 同时命中+ * 本声明时,把值放进发往 Worker 的保留字段 `cindy.secrets[key]`;+ * Worker 获得明文后仍可能主动回传或泄露。未声明 entry 时只允许主入口。+ */+export interface GhostNodeSecretBinding {+ /** 凭证键(插件内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */+ key: string;+ /** 给用户看的名称(安装确认与设置状态使用)。 */+ label: string;+ /** 允许注入的 JSON-RPC 方法白名单(1–16 条)。 */+ methods: string[];+ /** 可选目标入口;缺省只绑定 node.entry 主入口。 */+ entry?: string;+ /** 可选输入提示。 */+ hint?: string;+ /** 可选凭证申请页(仅 https;设置页外链须逐字命中)。 */+ url?: string;+}+/*** 随插件安装的本地 Node 工作进程声明。*@@ -155,6 +189,11 @@ export interface GhostNodeNeeds {* 权限本质不变:仍只能跑包内申报过的 JS,node 槽本就是用户级执行权。*/childSpawn?: boolean;+ /**+ * 由主机 safeStorage 持久化、按声明的方法临时注入 Worker 的凭证。+ * 这是 Node 高风险能力的一部分,安装权限清单会逐条披露。+ */+ secretBindings?: GhostNodeSecretBinding[];}/** node 额外入口条数上限(1 主 + 4 额外 = 每插件至多 5 个工作进程)。 */@@ -727,12 +766,13 @@ export function ghostPreviewUrlAllowed(manifest: GhostManifest, rawUrl: string):}/**- * 身份卡里声明过的全部外链地址(当前来源 = network.secrets[].url,装包时+ * 身份卡里声明过的全部外链地址(来源 = network.secrets[].url 与+ * node.secretBindings[].url,装包时* 已校验仅 https):意识 webview 外链闸(GhostExternalLinkGate)的白名单,* settingsHtml/面板里的 <a href> 逐字命中才转系统浏览器打开。*/export function ghostExternalLinkUrls(manifest: GhostManifest): string[] {- return (manifest.network?.secrets ?? [])+ return [...(manifest.network?.secrets ?? []), ...(manifest.node?.secretBindings ?? [])].map((s) => s.url).filter((url): url is string => typeof url === 'string' && url.length > 0);}@@ -1122,6 +1162,18 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItlabelKey: manifest.node.protocol === 'mcp-stdio' ? 'nodeMcp' : 'nodeRuntime',detailKey: 'nodeRuntimeDetail',});+ for (const binding of manifest.node.secretBindings ?? []) {+ const targetEntry = binding.entry ?? manifest.node.entry;+ const stableMethods = [...binding.methods].sort();+ items.unshift({+ key: `node:secret:${binding.key}:${targetEntry}:${stableMethods.join(',')}`,+ kind: 'node',+ labelKey: 'nodeSecret',+ labelArgs: { name: binding.label },+ detailKey: 'nodeSecretDetail',+ detail: binding.methods.join('\n'),+ });+ }if (manifest.node.lifecycle === 'resident') {items.unshift({key: 'node:resident',@@ -1735,7 +1787,15 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: '声明了 node 能力详单但 slots 未包含 "node"' };}const nodeRaw = raw.node as Record<string, unknown>;- const allowedNodeFields = new Set(['entry', 'protocol', 'lifecycle', 'idleTimeoutSeconds', 'entries', 'childSpawn']);+ const allowedNodeFields = new Set([+ 'entry',+ 'protocol',+ 'lifecycle',+ 'idleTimeoutSeconds',+ 'entries',+ 'childSpawn',+ 'secretBindings',+ ]);const unknownNodeField = Object.keys(nodeRaw).find((key) => !allowedNodeFields.has(key));if (unknownNodeField) {return {@@ -1811,6 +1871,153 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (nodeRaw.childSpawn !== undefined && typeof nodeRaw.childSpawn !== 'boolean') {return { ok: false, reason: 'node.childSpawn 必须是布尔值' };}+ let nodeSecretBindings: GhostNodeSecretBinding[] | undefined;+ if (nodeRaw.secretBindings !== undefined) {+ if (+ !Array.isArray(nodeRaw.secretBindings) ||+ nodeRaw.secretBindings.length === 0 ||+ nodeRaw.secretBindings.length > GHOST_NODE_MAX_SECRET_BINDINGS+ ) {+ return {+ ok: false,+ reason: `node.secretBindings 必须是 1–${GHOST_NODE_MAX_SECRET_BINDINGS} 条的数组`,+ };+ }+ if (raw.settingsHtml === undefined) {+ return {+ ok: false,+ reason: 'node.secretBindings 需要 settingsHtml 收集凭证',+ };+ }+ nodeSecretBindings = [];+ const seenSecretKeys = new Set<string>();+ for (const bindingRaw of nodeRaw.secretBindings) {+ if (!isPlainObject(bindingRaw)) {+ return { ok: false, reason: 'node.secretBindings 每项必须是对象' };+ }+ const binding = bindingRaw as Record<string, unknown>;+ const unknownBindingField = Object.keys(binding).find(+ (key) => !['key', 'label', 'methods', 'entry', 'hint', 'url'].includes(key),+ );+ if (unknownBindingField) {+ return {+ ok: false,+ reason: `node.secretBindings[] 含不允许的字段 ${JSON.stringify(unknownBindingField)}`,+ };+ }+ if (typeof binding.key !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(binding.key)) {+ return {+ ok: false,+ reason: 'node.secretBindings[].key 必须是小写字母开头的 1–32 位小写/数字/下划线',+ };+ }+ if (seenSecretKeys.has(binding.key)) {+ return {+ ok: false,+ reason: `node.secretBindings 含重复 key ${JSON.stringify(binding.key)}`,+ };+ }+ seenSecretKeys.add(binding.key);+ if (+ typeof binding.label !== 'string' ||+ binding.label.trim().length === 0 ||+ binding.label.length > 64+ ) {+ return {+ ok: false,+ reason: 'node.secretBindings[].label 必须是 1–64 字符的非空字符串',+ };+ }+ if (+ !Array.isArray(binding.methods) ||+ binding.methods.length === 0 ||+ binding.methods.length > GHOST_NODE_MAX_SECRET_METHODS+ ) {+ return {+ ok: false,+ reason: `node.secretBindings[].methods 必须是 1–${GHOST_NODE_MAX_SECRET_METHODS} 条的数组`,+ };+ }+ const methods: string[] = [];+ for (const method of binding.methods) {+ if (typeof method !== 'string' || !/^[A-Za-z0-9_./:-]{1,128}$/.test(method)) {+ return {+ ok: false,+ reason: 'node.secretBindings[].methods 每项必须是 1–128 位安全方法名',+ };+ }+ if (nodeRaw.protocol === 'mcp-stdio' && isGhostNodeMcpReservedMethod(method)) {+ return {+ ok: false,+ reason: `node.secretBindings[].methods 不能绑定宿主保留的 MCP 方法 ${JSON.stringify(method)}`,+ };+ }+ if (methods.includes(method)) {+ return {+ ok: false,+ reason: `node.secretBindings[].methods 含重复方法 ${JSON.stringify(method)}`,+ };+ }+ methods.push(method);+ }+ let bindingEntry: string | undefined;+ if (binding.entry !== undefined) {+ if (+ typeof binding.entry !== 'string' ||+ (binding.entry !== nodeRaw.entry && !(nodeEntries ?? []).includes(binding.entry))+ ) {+ return {+ ok: false,+ reason: 'node.secretBindings[].entry 必须逐字命中 node.entry 或 node.entries',+ };+ }+ bindingEntry = binding.entry;+ }+ if (+ binding.hint !== undefined &&+ (typeof binding.hint !== 'string' ||+ binding.hint.trim().length === 0 ||+ binding.hint.length > 200)+ ) {+ return {+ ok: false,+ reason: 'node.secretBindings[].hint 必须是 1–200 字符的非空字符串',+ };+ }+ if (binding.url !== undefined) {+ if (+ typeof binding.url !== 'string' ||+ binding.url.length === 0 ||+ binding.url.length > 200+ ) {+ return {+ ok: false,+ reason: 'node.secretBindings[].url 必须是 1–200 字符的字符串',+ };+ }+ let parsed: URL;+ try {+ parsed = new URL(binding.url);+ } catch {+ return { ok: false, reason: 'node.secretBindings[].url 不是合法的绝对地址' };+ }+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {+ return {+ ok: false,+ reason: 'node.secretBindings[].url 仅支持 https 且不允许内嵌用户名/密码',+ };+ }+ }+ nodeSecretBindings.push({+ key: binding.key,+ label: binding.label,+ methods,+ ...(bindingEntry !== undefined ? { entry: bindingEntry } : {}),+ ...(binding.hint !== undefined ? { hint: binding.hint as string } : {}),+ ...(binding.url !== undefined ? { url: binding.url as string } : {}),+ });+ }+ }node = {entry: nodeRaw.entry,protocol: nodeRaw.protocol as GhostNodeProtocol,@@ -1822,6 +2029,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {: {}),...(nodeEntries !== undefined ? { entries: nodeEntries } : {}),...(nodeRaw.childSpawn !== undefined ? { childSpawn: nodeRaw.childSpawn } : {}),+ ...(nodeSecretBindings !== undefined ? { secretBindings: nodeSecretBindings } : {}),};}if (slots.includes('node') && node === undefined) {@@ -1973,6 +2181,12 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (seenKeys.has(s.key)) {return { ok: false, reason: `network.secrets 含重复 key ${JSON.stringify(s.key)}` };}+ if (node?.secretBindings?.some((binding) => binding.key === s.key)) {+ return {+ ok: false,+ reason: `network.secrets 的 key ${JSON.stringify(s.key)} 与 node.secretBindings 撞名`,+ };+ }seenKeys.add(s.key);if (typeof s.label !== 'string' || s.label.trim().length === 0 || s.label.length > 64) {return { ok: false, reason: 'network.secrets[].label 必须是 1–64 字符的非空字符串' };@@ -2513,6 +2727,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {connections = [];const seenConnKeys = new Set<string>();const secretKeySet = new Set((secrets ?? []).map((s) => s.key));+ const nodeSecretKeySet = new Set((node?.secretBindings ?? []).map((s) => s.key));for (const c of n.connections) {if (!isPlainObject(c)) return { ok: false, reason: 'network.connections 每项必须是对象' };if (typeof c.key !== 'string' || !/^[a-z][a-z0-9_]{0,31}$/.test(c.key)) {@@ -2525,6 +2740,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (secretKeySet.has(c.key)) {return { ok: false, reason: `network.connections[].key ${JSON.stringify(c.key)} 与 network.secrets 的 key 撞名(两者共用命名空间)` };}+ if (nodeSecretKeySet.has(c.key)) {+ return { ok: false, reason: `network.connections[].key ${JSON.stringify(c.key)} 与 node.secretBindings 的 key 撞名(两者共用命名空间)` };+ }seenConnKeys.add(c.key);if (typeof c.label !== 'string' || c.label.trim().length === 0 || c.label.length > 64) {return { ok: false, reason: 'network.connections[].label 必须是 1–64 字符的非空字符串' };@@ -2598,7 +2816,14 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (!Array.isArray(su.requires) || su.requires.length > GHOST_SETUP_MAX_GROUPS) {return { ok: false, reason: `setup.requires 必须是 0–${GHOST_SETUP_MAX_GROUPS} 组的数组(空数组 = 显式声明无使用前置需求)` };}- const secretByKey = new Map((network?.secrets ?? []).map((s) => [s.key, s] as const));+ const secretByKey = new Map<string, { loginDerived: boolean }>([+ ...(network?.secrets ?? []).map(+ (s) => [s.key, { loginDerived: s.source === 'login-email' }] as const,+ ),+ ...(node?.secretBindings ?? []).map(+ (s) => [s.key, { loginDerived: false }] as const,+ ),+ ]);const connectionKeys = new Set((network?.connections ?? []).map((c) => c.key));const groups: GhostSetupGroup[] = [];for (const g of su.requires) {@@ -2618,9 +2843,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (refKind === 'secret') {const decl = secretByKey.get(refKey);if (!decl) {- return { ok: false, reason: `setup 引用了未声明的凭证 ${JSON.stringify(refKey)}(必须逐字取自 network.secrets[].key)` };+ return { ok: false, reason: `setup 引用了未声明的凭证 ${JSON.stringify(refKey)}(必须逐字取自 network.secrets[].key 或 node.secretBindings[].key)` };}- if (decl.source === 'login-email') {+ if (decl.loginDerived) {return { ok: false, reason: `setup 不允许引用 login-email 源凭证 ${JSON.stringify(refKey)}(登录派生身份恒就绪,无配置动作可引导)` };}item = { kind: 'secret', key: refKey };