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): allow guests to read referenced files outside workdir

david7771ed02a789
diff --git a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
index 707b33f3c4..a1fc0c736b 100644
--- a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
@@ -122,6 +122,18 @@ describe('fetchLocalMediaToOss — scheme 路由', () => {
expect(uploadLocalFile).not.toHaveBeenCalled();
});
+ // Regression: the outside-file exception must survive materialization, while
+ // still pinning a single canonical file rather than opening its whole directory.
+ it('materializes exactly the referenced outside file and rejects a changed target', async () => {
+ const file = path.resolve('deliveries/report.pdf');
+ const arg = { url: 'xdt-file://local?path=' + encodeURIComponent(file) };
+ assertSharedTaskMedia.mockResolvedValue({ file });
+ await expect(shared(() => resolveAuthorizedMedia(arg))).resolves.toMatchObject({ absPath: file });
+ realpathMock.mockResolvedValue(path.resolve('deliveries/private.pdf'));
+ await expect(shared(() => fetchLocalMediaToOss(arg))).rejects.toThrow('PERMISSION_DENIED');
+ expect(uploadLocalFile).not.toHaveBeenCalled();
+ });
+
it('preserves upload size limits and isolates shared-task upload cache', async () => {
const url = 'xdt-file://local?path=' + encodeURIComponent(path.resolve('work/a.png')) + '&maxBytes=100';
let scope: string | undefined;
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 b0a4ae9aad..af84c50c09 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskMediaAccess.test.ts
@@ -1,4 +1,5 @@
import path from 'node:path';
+import { pathToFileURL } from 'node:url';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const deps = vi.hoisted(() => ({ read: vi.fn(), session: vi.fn(), realpath: vi.fn(), query: vi.fn() }));
vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ query: deps.query }) }));
@@ -9,6 +10,8 @@ vi.mock('../../localDb/ipc/sessions.js', () => ({ getSessionFsSnapshot: deps.ses
import { assertSharedTaskMedia } from '../sharedTaskMediaAccess.js';
import type { SharedTaskPeerCapture } from '../sharedTaskDispatch.js';
let current = true;
+// Markdown destinations use forward separators; native path assertions do not.
+const markdownPath = (file: string) => file.split(path.sep).join('/');
const capture: SharedTaskPeerCapture = {
author: { sharedTaskId: 'shared', sessionId: 'task', memberId: 'm', accountId: 'u', displayName: 'Guest' },
isCurrent: () => current, authorize: () => current,
@@ -20,6 +23,79 @@ beforeEach(() => {
deps.query.mockResolvedValue([]);
});
describe('shared task media access', () => {
+ // Regression: a delivered file outside the workdir must be readable, without
+ // granting its directory or trusting a guest's pasted path (unit tier).
+ it.each(['assistant', 'user'])('reads an outside file linked by the %s in this task', async (role) => {
+ const file = path.resolve('deliveries/report final.pdf');
+ deps.query.mockResolvedValue([{ rowid: 1, role, content: JSON.stringify({ text: `[report](<${markdownPath(file)}>)` }), agentMeta: null }]);
+ await expect(assertSharedTaskMedia('xdt-file://local?path=' + encodeURIComponent(file), capture))
+ .resolves.toEqual({ file });
+ });
+ it('reads owner attachments outside the workdir without authorizing their siblings', async () => {
+ const file = path.resolve('uploads/report.pdf');
+ deps.query.mockResolvedValue([{ rowid: 1, role: 'user', content: JSON.stringify({ files: [{ path: file }] }), agentMeta: null }]);
+ await expect(assertSharedTaskMedia('xdt-file://local?path=' + encodeURIComponent(file), capture)).resolves.toEqual({ file });
+ await expect(assertSharedTaskMedia('xdt-file://local?path=' + encodeURIComponent(file + '.secret'), capture)).rejects.toThrow('PERMISSION_DENIED');
+ });
+ it('does not treat a guest message as authority for outside files', async () => {
+ const file = path.resolve('other/private.pdf');
+ deps.query.mockResolvedValue([{ rowid: 1, role: 'user', content: JSON.stringify({ text: `[file](<${markdownPath(file)}>)` }), agentMeta: JSON.stringify({ sharedTaskAuthor: { memberId: 'm' } }) }]);
+ await expect(assertSharedTaskMedia('xdt-file://local?path=' + encodeURIComponent(file), capture)).rejects.toThrow('PERMISSION_DENIED');
+ });
+ it('reads host-materialized guest attachments but not a JSON-looking guest message', async () => {
+ const file = path.resolve('uploads/report%20final.pdf');
+ const content = { files: [{ path: file }] };
+ const row = { rowid: 1, role: 'user', agentMeta: JSON.stringify({ sharedTaskAuthor: { memberId: 'm' } }) };
+ const url = 'xdt-file://local?path=' + encodeURIComponent(file);
+ deps.query.mockResolvedValueOnce([{ ...row, content: JSON.stringify(content) }]);
+ await expect(assertSharedTaskMedia(url, capture)).resolves.toEqual({ file });
+ deps.query.mockResolvedValue([{ ...row, content: JSON.stringify(JSON.stringify(content)) }]);
+ await expect(assertSharedTaskMedia(url, capture)).rejects.toThrow('PERMISSION_DENIED');
+ });
+ it('rechecks membership after reading outside-file provenance', async () => {
+ const file = path.resolve('deliveries/report.pdf');
+ deps.query.mockImplementation(async () => { current = false; return [{ rowid: 1, role: 'assistant', content: JSON.stringify(`[report](<${markdownPath(file)}>)`) }]; });
+ await expect(assertSharedTaskMedia('xdt-file://local?path=' + encodeURIComponent(file), capture)).rejects.toThrow('PERMISSION_DENIED');
+ });
+ it.each(['inline', 'reference', 'encoded', 'audio', 'tool-result'])('recognizes an exact outside-file reference in %s form', async (kind) => {
+ const file = path.resolve('deliveries/report (final).pdf');
+ const url = 'xdt-file://local?path=' + encodeURIComponent(file).replace(/\(/g, '%28').replace(/\)/g, '%29');
+ const content = kind === 'inline' ? '`' + file + '`'
+ : kind === 'reference' ? `[report][r]\n\n[r]: <${markdownPath(file)}>`
+ : kind === 'encoded' ? `[report](<${pathToFileURL(file).href}>)`
+ : url;
+ deps.query.mockResolvedValue([{ rowid: 1, role: kind === 'tool-result' ? 'tool_result' : 'assistant', content: JSON.stringify(content) }]);
+ await expect(assertSharedTaskMedia(kind === 'audio' ? url.replace('xdt-file:', 'xdt-audio:') : url, capture)).resolves.toEqual({ file });
+ });
+ it.each(['fenced', 'unused-definition', 'prefix', 'remote-host'])('rejects %s text that does not deliver this local file', async (kind) => {
+ const file = path.resolve('deliveries/report.pdf');
+ const content = kind === 'fenced' ? '```md\n[report](<' + markdownPath(file) + '>)\n```'
+ : kind === 'unused-definition' ? `[r]: <${markdownPath(file)}>`
+ : kind === 'remote-host' ? `[report](xdt-file://local?path=${encodeURIComponent(file)}&remoteHostId=ssh)`
+ : `[report](<${markdownPath(file)}.secret>)`;
+ deps.query.mockResolvedValue([{ rowid: 1, role: 'assistant', content: JSON.stringify(content) }]);
+ await expect(assertSharedTaskMedia('xdt-file://local?path=' + encodeURIComponent(file), capture)).rejects.toThrow('PERMISSION_DENIED');
+ });
+ it('reads a generated file only after its matching tool completes successfully', async () => {
+ const file = path.resolve('deliveries/report.pdf');
+ const row = { rowid: 1, role: 'tool_use', toolUseId: 'write-1', content: JSON.stringify({ toolName: 'Write', input: { file_path: file, content: 'report' } }) };
+ const url = 'xdt-file://local?path=' + encodeURIComponent(file);
+ for (const result of [null, '<tool_use_error>Permission denied</tool_use_error>', { ok: false }, 'File written']) {
+ deps.query.mockResolvedValueOnce([row]).mockResolvedValueOnce(result === null ? [] : [{ content: JSON.stringify(result) }]);
+ if (result === 'File written') await expect(assertSharedTaskMedia(url, capture)).resolves.toEqual({ file });
+ else await expect(assertSharedTaskMedia(url, capture)).rejects.toThrow('PERMISSION_DENIED');
+ }
+ });
+ it('does not cache file grants and scopes the history query to live messages in the current task', async () => {
+ const file = path.resolve('deliveries/report.pdf');
+ const url = 'xdt-file://local?path=' + encodeURIComponent(file);
+ deps.query.mockResolvedValueOnce([{ rowid: 1, role: 'assistant', content: JSON.stringify(`[report](<${markdownPath(file)}>)`) }]).mockResolvedValueOnce([]);
+ await expect(assertSharedTaskMedia(url, capture)).resolves.toEqual({ file });
+ await expect(assertSharedTaskMedia(url, capture)).rejects.toThrow('PERMISSION_DENIED');
+ // These query predicates are the cross-task/rewind authorization boundary.
+ expect(deps.query.mock.calls[0][0]).toContain('session_id = ? AND rewind_at IS NULL');
+ expect(deps.query.mock.calls[0][1][0]).toBe('task');
+ });
it('allows legacy generated media only when its complete URL occurs in host-authored task history', async () => {
const url = 'xdt-video://art/clip.mp4';
deps.query.mockResolvedValue([{ content: JSON.stringify({ text: '[video](' + url + ')' }) }]);
diff --git a/apps/desktop/src/main/device-link/mediaFetch.ts b/apps/desktop/src/main/device-link/mediaFetch.ts
index 464507ce58..ebac87b62b 100644
--- a/apps/desktop/src/main/device-link/mediaFetch.ts
+++ b/apps/desktop/src/main/device-link/mediaFetch.ts
@@ -320,7 +320,7 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: number
const url = record.url;
if (typeof url !== 'string' || !url) throw new Error('media:fetch 缺少 url');
const sharedTask = getDeviceLinkInvokeContext()?.sharedTask;
- let sharedRoot: string | undefined;
+ let sharedRoot: string | { file: string } | undefined;
if (sharedTask) {
sharedRoot = await assertSharedTaskMedia(url, sharedTask);
}
@@ -391,8 +391,10 @@ export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: number
throw new Error('媒体文件不存在或不可读');
}
// realpath 再查:挡字面形式看似无害的 symlink 逃逸。
- if (sharedRoot && !isInsideRealDir(real, sharedRoot)) {
- throw new Error('[PERMISSION_DENIED] Media left the shared task workdir');
+ if (sharedRoot && (typeof sharedRoot === 'string'
+ ? !isInsideRealDir(real, sharedRoot)
+ : path.relative(sharedRoot.file, real) !== '')) {
+ throw new Error('[PERMISSION_DENIED] Media left the shared task file scope');
}
if (!isPathAllowedAgainst(real, getSensitiveMediaBlocklist())) {
log.warn(`media:fetch blocked sensitive realpath ${url.slice(0, 60)}`);
diff --git a/apps/desktop/src/main/device-link/sharedTaskFileReferences.ts b/apps/desktop/src/main/device-link/sharedTaskFileReferences.ts
new file mode 100644
index 0000000000..1f76595577
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskFileReferences.ts
@@ -0,0 +1,141 @@
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { unified } from 'unified';
+import remarkParse from 'remark-parse';
+import { visit } from 'unist-util-visit';
+import { describeToolUse, createdPathsFromDescriptor } from '@cindy/maker-shared/tool-use-descriptor';
+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
+import { isToolResultFailureLike } from '@cindy/maker-shared/message-presentation';
+import { extractPayloadToolResultFiles } from '@cindy/maker-shared/payload-summary';
+import { extractCommandOutputPathCandidates } from '../../shared/commandOutputPaths.js';
+import { getDbClient } from '../localDb/client/current.js';
+import type { SharedTaskPeerCapture } from './sharedTaskDispatch.js';
+
+const markdown = unified().use(remarkParse);
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
+}
+function decode(value: string): unknown {
+ try { return JSON.parse(value); } catch { return value; }
+}
+
+/** Only explicit file references count; a substring in source, a patch or a log does not. */
+function references(content: unknown, role: string, includeText: boolean): string[] {
+ const body = record(content);
+ if (role === 'tool_use') {
+ const tool = parseMessageToolUse({ role, content });
+ const descriptor = describeToolUse(tool.toolName, tool.input);
+ if (descriptor.kind === 'command') return extractCommandOutputPathCandidates(descriptor.command);
+ return createdPathsFromDescriptor(descriptor);
+ }
+ if (role === 'tool_result') {
+ return extractPayloadToolResultFiles(typeof content === 'string' ? content : JSON.stringify(content)).map((file) => file.url);
+ }
+ const result: string[] = [];
+ // Persisted attachments have passed the host's input-reference admission and
+ // materialization. Never interpret a JSON-looking message string as attachments.
+ for (const key of ['files', 'images']) {
+ if (!Array.isArray(body?.[key])) continue;
+ for (const attachment of body[key]) {
+ const file = record(attachment);
+ if (typeof file?.path === 'string') result.push(file.path);
+ if (typeof file?.url === 'string') result.push(file.url);
+ }
+ }
+ if (!includeText) return result;
+ const text = typeof content === 'string' ? content : typeof body?.text === 'string' ? body.text : '';
+ // Match the rendered links/file chips, not examples inside fenced source or
+ // unused reference definitions. An AST also preserves spaces and parentheses.
+ result.push(text);
+ const tree = markdown.parse(text);
+ const definitions = new Map<string, string>();
+ visit(tree, 'definition', (node) => {
+ if (!definitions.has(node.identifier)) definitions.set(node.identifier, node.url);
+ });
+ visit(tree, (node) => {
+ if (node.type === 'link' || node.type === 'image') result.push(node.url);
+ else if (node.type === 'inlineCode') result.push(node.value);
+ else if (node.type === 'linkReference' || node.type === 'imageReference') {
+ const url = definitions.get(node.identifier);
+ if (url) result.push(url);
+ }
+ });
+ return result;
+}
+
+function referencePath(reference: string, workingDir: string): string | null {
+ let value = reference.trim();
+ try {
+ if (value.startsWith('xdt-file://') || value.startsWith('xdt-audio://')) {
+ const url = new URL(value);
+ // A remote file reference must never grant access to a coincident local path.
+ if (url.searchParams.has('remoteHostId')) return null;
+ value = url.searchParams.get('path') ?? (value.startsWith('xdt-file:///') ? decodeURIComponent(value.slice('xdt-file://'.length)) : '');
+ } else if (value.startsWith('file://')) {
+ value = fileURLToPath(value);
+ } else {
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return null;
+ // Markdown file links may carry a line locator. It is not part of the file.
+ value = value.replace(/(?::\d+(?::\d+)?|#L\d+(?:-L\d+)?)$/, '');
+ // Raw local Markdown destinations/attachment paths preserve literal '%',
+ // unlike file:// and query-based URLs, which were decoded above.
+ }
+ if (!value || value.includes('\0')) return null;
+ if (!path.isAbsolute(value) && !/^(?:\.\.?)[\\/]/.test(value)) return null;
+ return path.resolve(workingDir, value);
+ } catch { return null; }
+}
+
+/** Read current host history, never the guest's payload or a stale authorization cache. */
+export async function sharedTaskReferencesFile(
+ requested: string, workingDir: string, capture: SharedTaskPeerCapture,
+): Promise<boolean> {
+ const name = path.basename(requested);
+ const encodedName = encodeURIComponent(name);
+ 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
+ WHERE session_id = ? AND rewind_at IS NULL AND rowid > ?
+ AND role IN ('user', 'assistant', 'tool_use', 'tool_result')
+ AND (instr(lower(content), lower(?)) > 0 OR instr(lower(content), lower(?)) > 0 OR instr(lower(content), lower(?)) > 0 OR instr(lower(content), lower(?)) > 0)
+ ORDER BY rowid LIMIT 64`,
+ [capture.author.sessionId, after, ...needles],
+ );
+ if (!capture.isCurrent()) return false;
+ for (const row of rows) {
+ // Guest attribution is stamped by Main. Guest prose never grants access;
+ // only the separately validated, host-materialized attachments are usable.
+ const meta = row.agentMeta ? record(decode(row.agentMeta)) : null;
+ if (row.role === 'user' && row.agentMeta && !meta) continue;
+ const content = decode(row.content);
+ if (!references(content, row.role, row.role !== 'user' || !meta?.sharedTaskAuthor).some((reference) => {
+ const candidate = referencePath(reference, workingDir);
+ return candidate !== null && path.relative(requested, candidate) === '';
+ })) continue;
+ 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 });
+ if (!tool.toolUseId) continue;
+ const results = await getDbClient().query<{ content: string }>(
+ `SELECT content FROM messages WHERE session_id = ? AND role = 'tool_result'
+ AND rewind_at IS NULL AND tool_use_id = ? AND rowid > ? ORDER BY rowid LIMIT 1`,
+ [capture.author.sessionId, tool.toolUseId, row.rowid],
+ );
+ if (!capture.isCurrent()) return false;
+ if (!results.length) continue;
+ const result = decode(results[0].content);
+ if (isToolResultFailureLike(describeToolUse(tool.toolName, tool.input), typeof result === 'string' ? result : JSON.stringify(result))) continue;
+ }
+ return true;
+ }
+ if (rows.length < 64) return false;
+ const last = rows[rows.length - 1].rowid;
+ if (last <= after) return false;
+ after = last;
+ }
+ return false;
+}
diff --git a/apps/desktop/src/main/device-link/sharedTaskMediaAccess.ts b/apps/desktop/src/main/device-link/sharedTaskMediaAccess.ts
index dc1ba20128..105eb24dad 100644
--- a/apps/desktop/src/main/device-link/sharedTaskMediaAccess.ts
+++ b/apps/desktop/src/main/device-link/sharedTaskMediaAccess.ts
@@ -5,11 +5,12 @@ import { sessionCanRead } from '../cindy-media/ledger.js';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
import { getDbClient } from '../localDb/client/current.js';
import type { SharedTaskPeerCapture } from './sharedTaskDispatch.js';
+import { sharedTaskReferencesFile } from './sharedTaskFileReferences.js';
function deny(): never { throw new Error('[PERMISSION_DENIED] Media does not belong to this shared task'); }
/** Run before any local read/SSH transfer, and recheck membership after awaits. */
-export async function assertSharedTaskMedia(url: string, capture: SharedTaskPeerCapture): Promise<string | undefined> {
+export async function assertSharedTaskMedia(url: string, capture: SharedTaskPeerCapture): Promise<string | { file: string } | undefined> {
if (!capture.isCurrent() || !capture.authorize('attachment.read')) deny();
const sessionId = capture.author.sessionId;
const blob = parseBlobUrl(url);
@@ -48,6 +49,12 @@ export async function assertSharedTaskMedia(url: string, capture: SharedTaskPeer
if (!requested || !path.isAbsolute(requested)) deny();
const [file, root] = await Promise.all([realpath(requested), realpath(snapshot.workingDir)]);
const relative = path.relative(root, file);
- if (relative.startsWith('..') || path.isAbsolute(relative) || !capture.isCurrent()) deny();
+ if (!capture.isCurrent()) deny();
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
+ if (!await sharedTaskReferencesFile(requested, snapshot.workingDir, capture) || !capture.isCurrent()) deny();
+ // Grant exactly this canonical file, never its containing directory. The
+ // materializer checks it again after resolving the path before reading.
+ return { file };
+ }
return root;
}
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index 2d1c12c29b..900e3aa399 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -40,6 +40,7 @@
- 房主保留共享管理、归档/删除/导出/分支、权限模式、工作目录、插件/MCP 配置和后台/定时任务管理权限。
- 访客通过客户端接口只能直接访问共享任务及其资源,不能调用全局凭证、其他任务或任意主机文件接口。Agent 原生工具不承诺工作目录硬隔离。
- 文件浏览器(2026-10-10 用户裁决):访客可在文件浏览器中浏览和编辑本任务工作目录,读写权限与房主一致:列目录、读取、搜索、缩略图、保存、新建、重命名、删除,以及文件变化监听。主机只认本机记录的任务工作目录与执行端点(本地或任务所属 SSH 主机),访客传入的路径只用于比对;读写前复核成员资格。文件导出/文件夹下载这类导出任务仍只限同账号(它们走房主的同账号中转路径),工作目录本身的管理(更换目录)仍归房主。实现见 `sharedTaskDispatch.ts`(通道与操作)、`sharedTaskFileAccess.ts`(目录绑定)与 `file-browser/device-op.ts`。
+- 任务关联的本机文件即使位于工作目录外,访客也可经原有取件通道只读访问(2026-10-19 修复):归属由房主端当前未回退的消息记录确认,包括主机已校验并接收的结构化附件(含访客上传)、房主/Agent 明确交付的文件链接及已完成且未报错的工具产出。访客自行粘贴的路径、代码示例、其他任务记录或仅前缀相同的路径不构成授权;仅放行关联的具体文件,不开放其父目录浏览或写入。取件继续检查成员资格、敏感路径和解析后的文件身份,不缓存历史授权结论。Desktop 与 Mobile 共用房主校验,无新增 wire 字段;SSH 的工作目录限界保持原规则,不以本机路径例外绕过。实现与回归见 `sharedTaskFileReferences.ts`、`sharedTaskMediaAccess.ts` 及 `sharedTaskMediaAccess.test.ts`、`mediaFetch.test.ts`。
- 消息按主机现有输入队列顺序处理,保留 clientId 幂等。访客仅编辑/撤回自己未处理消息,房主可处理全部未处理消息;直接更新内容,不显示“已编辑”。
- 发言者身份来自经过验证的账号和成员关系,不能信任消息正文或客户端自报的身份。