Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(plugins): 在 Node 日志落盘前脱敏注入令牌

liugaoweibeba8f6178b1
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
index 94aa54fa9d..0c24d3fb90 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
@@ -1766,7 +1766,63 @@ describe('nodeRuntimeBroker · 意外死亡诊断(2026-07-26)', () => {
const message = (result as { message?: string }).message ?? '';
expect(message).toContain('[REDACTED]');
expect(message).not.toContain('sk-secret-token-12345');
- });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('sk-secret-token-12345');
+ });
+
+ it.each(['whole', 'split', 'truncated-log', 'partial-at-exit', 'after-stop', 'after-drain'] as const)(
+ 'OAuth stderr %s 在主日志及退出诊断中都不泄露令牌', async (scenario) => {
+ const ghost = fakeGhost();
+ ghost.manifest.network = { hosts: ['example.test'], secrets: [{
+ key: 'mail_account', label: 'Mail', source: 'oauth',
+ inject: { header: 'Authorization', format: 'Bearer {value}' },
+ oauth: { authorizeUrl: 'https://example.test/auth', tokenUrl: 'https://example.test/token', scopes: ['mail'] },
+ }] };
+ ghost.manifest.node!.secretBindings = [{ key: 'token', label: 'Mail', methods: ['slow'], oauthSecret: 'mail_account' }];
+ const tokens = ['ya29.fake-access-token-account-A-abcdefgh', 'ya29.fake-access-token-account-B-ijklmnop'];
+ let child!: FakeNodeProcess;
+ const log = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
+ const sendToGhost = vi.fn();
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost, log, sendToGhost,
+ resolveOauthSecret: async (_ghost, _key, account) => ({ ok: true, accessToken: tokens[account === 'b' ? 1 : 0] }),
+ spawnProcess: () => (child = new FakeNodeProcess()),
+ });
+ try {
+ const first = broker.handleRequest('node-ghost', { ...rpcRequest('slow'), authAccount: 'a' });
+ const second = broker.handleRequest('node-ghost', { ...rpcRequest('slow'), authAccount: 'b' });
+ await vi.waitFor(() => expect(child?.received).toHaveLength(2));
+ const token = tokens[0];
+ if (scenario === 'whole' || scenario === 'truncated-log') {
+ child.stderr.write(`${scenario === 'truncated-log' ? 'x'.repeat(4050) : ''}Error: ${token} ${tokens[1]}\n`);
+ } else if (scenario === 'after-drain') {
+ child.emit('exit', 1, null);
+ // 不发 end,让生产的有界 drain 兜底先结算、清理令牌集合。
+ await Promise.all([first, second]);
+ child.stderr.write(`Error: ${token}\n`);
+ } else {
+ child.stderr.write(`Error: ${token.slice(0, 18)}`);
+ if (scenario === 'after-stop') broker.stop('node-ghost');
+ if (scenario !== 'partial-at-exit') child.stderr.write(`${token.slice(18)} ${tokens[1]}\n`);
+ }
+ if (scenario !== 'after-drain') child.emit('exit', 1, null);
+ child.stderr.end();
+ const results = await Promise.all([first, second]);
+ const allOutput = JSON.stringify([log.warn.mock.calls, log.info.mock.calls, log.debug.mock.calls, sendToGhost.mock.calls, results]);
+ // 同时检查 logger 真正收到的参数,不能只 stringify mock 函数本身。
+ const stderrText = log.warn.mock.calls
+ .filter(([message]) => message === 'ghost node stderr')
+ .map(([, meta]) => meta.text).join('');
+ for (const secret of tokens) {
+ expect(allOutput).not.toContain(secret);
+ expect(stderrText).not.toContain(secret);
+ }
+ expect(allOutput).not.toContain(token.slice(0, 18));
+ if (scenario !== 'after-stop' && scenario !== 'after-drain') expect(allOutput).toContain('[REDACTED]');
+ } finally {
+ broker.destroyAll();
+ }
+ },
+ );
});
describe('nodeRuntimeBroker · 权限与协议', () => {
diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
index 3b33c0a5c6..a4559ae1ea 100644
--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
@@ -317,6 +317,8 @@ interface WorkerEntry {
stderrTotalChars: number;
/** stderr 也可能把多字节字符切在两个 Buffer 之间,与 stdout 同理需流式解码。 */
stderrDecoder: StringDecoder;
+ /** 尚可能属于令牌前缀的末段;不写日志或诊断缓存,排空时也不原样释放。 */
+ stderrRedactionPending: string;
/** stdout 的 UTF-8 字节可能把一个汉字切在两个 chunk 之间,必须流式解码。 */
stdoutDecoder: StringDecoder;
stdoutBuffer: string;
@@ -328,7 +330,7 @@ interface WorkerEntry {
hardKillTimer: NodeJS.Timeout | null;
mcpInitPromise: Promise<void> | null;
stopping: boolean;
- /** 曾发给本 worker 的凭证明文(退出诊断脱敏用;settleExit 后立即清空)。 */
+ /** 曾发给本 worker 的凭证明文(stderr 及退出诊断脱敏用;settleExit 后立即清空)。 */
exposedSecretValues: Set<string>;
/** exit 后 stderr drain 用:非 null 表示进程已退出、正在等待管道排空。 */
exitDrain: {
@@ -1408,6 +1410,7 @@ export class GhostNodeRuntimeBroker {
}
entry.pending.clear();
entry.exposedSecretValues.clear();
+ entry.stderrRedactionPending = '';
// PID 是启动期已经捕获的只读 fact;停止关键路径前不再调用诊断 getter/logger。
const stopPid = entry.diagnosticPid;
let sigtermKillReturned = false;
@@ -1648,6 +1651,7 @@ export class GhostNodeRuntimeBroker {
stderrSegments: [],
stderrTotalChars: 0,
stderrDecoder: new StringDecoder('utf8'),
+ stderrRedactionPending: '',
stdoutDecoder: new StringDecoder('utf8'),
stdoutBuffer: '',
nextId: 1,
@@ -1712,12 +1716,15 @@ export class GhostNodeRuntimeBroker {
child.onControl?.((message) => this.handleWorkerControl(entry, message));
child.stdout.on('data', (chunk) => this.handleStdout(entry, chunk));
child.stderr.on('data', (chunk) => {
- const decoded = entry.stderrDecoder.write(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
+ // stop/排空结算已清掉令牌集合,不能把迟到输出当作无凭据的新进程日志。
+ if (entry.stopping || (this.workers.get(key) !== entry && !entry.exitDrain)) return;
+ const decoded = this.redactStderrChunk(entry,
+ entry.stderrDecoder.write(typeof chunk === 'string' ? Buffer.from(chunk) : chunk));
if (entry.startupPhase && entry.startupStderr.length < STARTUP_STDERR_CAP) {
entry.startupStderr = (entry.startupStderr + decoded).slice(0, STARTUP_STDERR_CAP);
}
// 按段带时间戳截存,退出时只取回看窗口内的段,不让老日志被新 chunk 携带。
- entry.stderrSegments.push({ text: decoded, at: this.now() });
+ if (decoded) entry.stderrSegments.push({ text: decoded, at: this.now() });
entry.stderrTotalChars += decoded.length;
// 总量控制:保留尾部 EXIT_STDERR_CAP 字符——部分裁剪最老段的头部。
if (entry.stderrTotalChars > EXIT_STDERR_CAP) {
@@ -2184,14 +2191,14 @@ export class GhostNodeRuntimeBroker {
this.clearTimer(entry.exitDrain.timer);
entry.exitDrain = null;
// flush stderrDecoder 残留字节(多字节字符被切在最后一个 chunk 边界时)
- const tail = entry.stderrDecoder.end();
+ const tail = this.redactStderrChunk(entry, entry.stderrDecoder.end(), true);
if (tail) {
entry.stderrSegments.push({ text: tail, at: this.now() });
entry.stderrTotalChars += tail.length;
}
const ghostId = entry.ghost.manifest.id;
const exitHint = this.exitStderrHint(entry, exitedAt);
- const detail = `${error?.message ?? `code=${code}, signal=${signal ?? 'none'}`}${
+ const detail = `${this.redactSecrets(entry, error?.message ?? `code=${code}, signal=${signal ?? 'none'}`)}${
exitHint ? `:${exitHint}` : ''
}`;
for (const pending of entry.pending.values()) {
@@ -2266,6 +2273,24 @@ export class GhostNodeRuntimeBroker {
return text;
}
+ private redactStderrChunk(entry: WorkerEntry, chunk: string, flush = false): string {
+ const text = this.redactSecrets(entry, entry.stderrRedactionPending + chunk);
+ // 完整令牌先替换;可能跨 chunk 的前缀只留在内存,不能先写出再补救。
+ // 留存长度严格小于该进程已接收的最长凭据,不积累整行日志。
+ let pendingLength = 0;
+ for (const secret of entry.exposedSecretValues) {
+ for (let length = Math.min(secret.length - 1, text.length); length > pendingLength; length--) {
+ if (text.endsWith(secret.slice(0, length))) {
+ pendingLength = length;
+ break;
+ }
+ }
+ }
+ const end = text.length - pendingLength;
+ entry.stderrRedactionPending = flush ? '' : text.slice(end);
+ return text.slice(0, end) + (flush && pendingLength > 0 ? '[REDACTED]' : '');
+ }
+
private scheduleIdleStop(entry: WorkerEntry): void {
const key = GhostNodeRuntimeBroker.keyOf(entry.ghost.manifest.id, entry.entryRel);
if (this.workers.get(key) !== entry) return;