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(sharing): verify command output file timestamps

davida9c0c70f11cf
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts
index c43b06c9d7..4ec660ea7a 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts
@@ -2,9 +2,9 @@ import path from 'node:path';
import { pathToFileURL } from 'node:url';
import Database from 'better-sqlite3';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-const deps = vi.hoisted(() => ({ read: vi.fn(), session: vi.fn(), realpath: vi.fn(), query: vi.fn() }));
+const deps = vi.hoisted(() => ({ read: vi.fn(), session: vi.fn(), realpath: vi.fn(), stat: vi.fn(), query: vi.fn() }));
vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ query: deps.query }) }));
-vi.mock('node:fs/promises', () => ({ realpath: deps.realpath }));
+vi.mock('node:fs/promises', () => ({ realpath: deps.realpath, stat: deps.stat }));
vi.mock('../../cindy-media/blobStore.js', () => ({ parseBlobUrl: (url: string) => url === 'cindy-media://blobs/hash.png' ? { hash: 'hash' } : null }));
vi.mock('../../cindy-media/ledger.js', () => ({ sessionCanRead: deps.read }));
vi.mock('../../localDb/ipc/sessions.js', () => ({ getSessionFsSnapshot: deps.session }));
@@ -155,6 +155,24 @@ describe('shared task media access', () => {
else await expect(assertSharedTaskMedia(url, capture)).rejects.toThrow('PERMISSION_DENIED');
}
});
+ // A successful no-clobber command can leave a pre-existing target untouched.
+ // Lexical output paths need file/time evidence before granting outside access.
+ it.each(['written', 'unchanged', 'later-write', 'directory', 'stat-error', 'missing-time', 'revoked'])('checks command output file evidence: %s', async (kind) => {
+ // The extractor intentionally excludes temp directories; do not depend on
+ // whether this checkout itself happens to live under a temp directory.
+ const file = path.join(path.parse(process.cwd()).root, 'deliveries', 'private.pdf');
+ const row = { rowid: 1, role: 'tool_use', toolUseId: 'copy-1', createdAt: 100,
+ content: JSON.stringify({ toolName: 'Bash', input: { command: `cp -n /work/source.txt "${markdownPath(file)}"` } }) };
+ deps.query.mockResolvedValueOnce([row]).mockResolvedValueOnce([{ content: JSON.stringify(''), createdAt: kind === 'missing-time' ? null : 200 }]);
+ deps.stat.mockImplementation(async () => {
+ if (kind === 'stat-error') throw new Error('ENOENT');
+ if (kind === 'revoked') current = false;
+ return { isFile: () => kind !== 'directory', mtimeMs: kind === 'unchanged' ? 99 : kind === 'later-write' ? 201 : 150 };
+ });
+ const access = assertSharedTaskMedia('xdt-file://local?path=' + encodeURIComponent(file), capture);
+ if (kind === 'written') await expect(access).resolves.toEqual({ file });
+ else await expect(access).rejects.toThrow('PERMISSION_DENIED');
+ });
// Direct result links must pass the same completed/non-failed provenance gate
// as tool-use outputs; an error message mentioning a URL is not a delivery.
it.each(['ok', 'structured-error', 'text-error', 'missing-use', 'missing-id', 'revoked'])('checks direct tool-result provenance: %s', async (kind) => {
diff --git a/apps/desktop/src/main/device-link/sharedTaskFileReferences.ts b/apps/desktop/src/main/device-link/sharedTaskFileReferences.ts
index b8c8fbdb95..55fe8304ab 100644
--- a/apps/desktop/src/main/device-link/sharedTaskFileReferences.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskFileReferences.ts
@@ -1,4 +1,5 @@
import path from 'node:path';
+import { stat } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
@@ -124,8 +125,8 @@ export async function sharedTaskReferencesFile(
const needles = [name, encodedName, encodedName.replace(/[!'()*]/g, (char) => '%' + char.charCodeAt(0).toString(16)), JSON.stringify(name).slice(1, -1)];
let after = 0;
while (capture.isCurrent()) {
- const rows = await getDbClient().query<{ rowid: number; role: string; content: string; agentMeta: string | null; toolUseId: string | null }>(
- `SELECT rowid, role, content, agent_meta AS agentMeta, tool_use_id AS toolUseId FROM messages
+ const rows = await getDbClient().query<{ rowid: number; role: string; content: string; agentMeta: string | null; toolUseId: string | null; createdAt: number }>(
+ `SELECT rowid, role, content, agent_meta AS agentMeta, tool_use_id AS toolUseId, created_at AS createdAt FROM messages
WHERE session_id = ? AND rewind_at IS NULL AND rowid > ?
AND ${visibleHistory}
AND role IN ('user', 'assistant', 'tool_use', 'tool_result')
@@ -167,10 +168,10 @@ export async function sharedTaskReferencesFile(
if (row.role === 'tool_use') {
// A queued/denied tool invocation is not delivery. Only completed output
// records can expose generated file chips outside the workspace.
- const tool = parseMessageToolUse({ ...row, content });
+ const tool = parseMessageToolUse({ role: row.role, toolUseId: row.toolUseId, content });
if (!tool.toolUseId) continue;
- const results = await getDbClient().query<{ content: string }>(
- `SELECT content FROM messages WHERE session_id = ? AND role = 'tool_result'
+ const results = await getDbClient().query<{ content: string; createdAt: number }>(
+ `SELECT content, created_at AS createdAt FROM messages WHERE session_id = ? AND role = 'tool_result'
AND rewind_at IS NULL AND tool_use_id = ? AND rowid > ?
AND ${visibleHistory} ORDER BY rowid LIMIT 1`,
[capture.author.sessionId, tool.toolUseId, row.rowid],
@@ -178,7 +179,20 @@ export async function sharedTaskReferencesFile(
if (!capture.isCurrent()) return false;
if (!results.length) continue;
const result = decode(results[0].content);
- if (toolResultFailed(describeToolUse(tool.toolName, tool.input), result)) continue;
+ const descriptor = describeToolUse(tool.toolName, tool.input);
+ if (toolResultFailed(descriptor, result)) continue;
+ if (descriptor.kind === 'command') {
+ // Output-path extraction is lexical. A successful no-clobber command
+ // must not expose an untouched, pre-existing file at its destination.
+ const start = row.createdAt;
+ const end = results[0].createdAt;
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) continue;
+ const file = await stat(requested).catch(() => null);
+ if (!capture.isCurrent()) return false;
+ // Message timestamps have millisecond precision; include the result's
+ // final millisecond even when the filesystem reports fractional ms.
+ if (!file?.isFile() || !Number.isFinite(file.mtimeMs) || file.mtimeMs < start || file.mtimeMs >= end + 1) continue;
+ }
}
return true;
}
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index 99bc5f63d6..26af3153e2 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -43,6 +43,7 @@
- 任务关联的本机文件即使位于工作目录外,访客也可经原有取件通道只读访问(2026-10-19 修复):归属由房主端当前未回退且未被 `/clear` 隐藏的消息记录确认,包括主机已校验并接收的结构化附件(含访客上传)、房主/Agent 明确交付的文件链接及已完成且未报错的工具产出。文件引用及配对的工具调用、结果均须晚于任务的清空边界;清空前的记录即使仍在数据库中,也不再提供授权。访客自行粘贴的路径、代码示例、其他任务记录或仅前缀相同的路径不构成授权;仅放行关联的具体文件,不开放其父目录浏览或写入。取件继续检查成员资格、敏感路径和解析后的文件身份,不缓存历史授权结论。Desktop 与 Mobile 共用房主校验,无新增 wire 字段;SSH 的工作目录限界保持原规则,不以本机路径例外绕过。实现与回归见 `sharedTaskFileReferences.ts`、`sharedTaskMediaAccess.ts` 及 `sharedTaskMediaAccess.test.ts`、`mediaFetch.test.ts`。
- 工具结果中的普通文本链接不构成外部文件交付,包括读取、搜索、网页或 shell 返回的内容。原生工具产出沿用调用中明确声明的输出路径;MCP/动态工具的结果只认既有结构化交付字段 `xdt_media_produced`、`_xdt_model_files`,并继续核对调用配对、成功状态及当前历史边界。原生读取和 shell 输出即使形似这些字段,也不按交付解释。房主/Agent 在消息中明确交付的链接仍按上述规则处理。
- 工具结果外层 `ok: true` 仅代表调用包装成功,内层 `result` 的失败状态同样阻止文件授权,调用产出路径与结果交付字段使用相同判定。房主/Agent 消息中可解析为文件链接的正文路径和完整行内代码路径沿用界面已有的链接/文件卡片语义;代码块中的示例、普通代码表达式、链接标签中的路径不提供额外授权。正文路径分词由 Renderer 与房主共用 `shared/bareFilePathTokens.ts`,仍须完整匹配请求文件。
+- shell 命令中的输出路径只是词法候选,不能仅凭调用成功就授权工作目录外的旧文件。取件时还须确认目标为普通文件,修改时间落在该调用到配对结果的执行时段内;无法读取元数据、缺少有效时间、未修改的旧目标或执行时段外的修改均不能使用该命令作为授权依据。显式消息链接及结构化交付仍按各自规则处理。
- 消息按主机现有输入队列顺序处理,保留 clientId 幂等。访客仅编辑/撤回自己未处理消息,房主可处理全部未处理消息;直接更新内容,不显示“已编辑”。
- 发言者身份来自经过验证的账号和成员关系,不能信任消息正文或客户端自报的身份。