Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix after #665: harden the read-file-bytes byte source (inode fail-closed + sensitive-media policy)
Lizi3d390f0b69f4
diff --git a/apps/desktop/src/main/__tests__/fileReadBytes.test.ts b/apps/desktop/src/main/__tests__/fileReadBytes.test.tsindex 4a437d5af5..30716caac0 100644--- a/apps/desktop/src/main/__tests__/fileReadBytes.test.ts+++ b/apps/desktop/src/main/__tests__/fileReadBytes.test.ts@@ -3,19 +3,20 @@* trustedAppRenderer.test; here we exercise every validation / policy /* symlink / size-cap / sanitized-error path of the injectable core. */-import type { Stats } from 'node:fs';-import { describe, expect, it, vi } from 'vitest';import {readFileBytesForPreview,READ_FILE_BYTES_CAP,type FileHandleLike,+ type FileIdentityStat,type ReadFileBytesDeps,} from '../fileReadBytes';-function statStub(size: number, isFile = true, ino = 1, dev = 1): Stats {- return { size, isFile: () => isFile, ino, dev } as unknown as Stats;+/** dev/ino/size are bigint, matching the `{ bigint: true }` stats production+ * injects — a 0 inode means "identity unavailable" and must fail closed. */+function statStub(size: number, isFile = true, ino = 1, dev = 1): FileIdentityStat {+ return { size: BigInt(size), isFile: () => isFile, ino: BigInt(ino), dev: BigInt(dev) };}/** Fake FileHandle whose fstat size can differ from the readable bytes, so we@@ -127,6 +128,24 @@ describe('readFileBytesForPreview', () => {).toBe('PRECONDITION_FAILED');});+ it('fails closed when the inode identity is unavailable (ino reported as 0)', async () => {+ // Some Windows / network filesystems report ino 0. Both sides then read 0,+ // so an equality check would pass and the swap guard would silently be a+ // no-op exactly where it is needed. Must reject instead.+ expect(+ await codeOf(+ readFileBytesForPreview(+ { filePath: ABS },+ deps({+ stat: async () => statStub(4, true, 0, 1),+ open: async () =>+ fakeHandle({ statSize: 4, data: Buffer.from([1, 2, 3, 4]), ino: 0 }),+ }),+ ),+ ),+ ).toBe('PRECONDITION_FAILED');+ });+it('rejects a non-regular file (FIFO/socket/device) with INVALID_PARAMS', async () => {expect(await codeOf(diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 89c0e1ba96..43d90a9640 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -213,7 +213,11 @@ import {} from './device-link/remoteMediaProtocol';import { localFileSchemePrivilege, registerLocalFileProtocolHandler } from './localFileProtocol';import { audioFileSchemePrivilege, registerAudioFileProtocolHandler } from './audioFileProtocol';-import { buildSystemPathBlocklist, isPathAllowedAgainst } from './filePathPolicy';+import {+ buildSystemPathBlocklist,+ getSensitiveMediaBlocklist,+ isPathAllowedAgainst,+} from './filePathPolicy';import { readFileThumbnail } from './fileThumbnail';import { resolveShellOpenPathTarget } from './shellOpenPath';import { cindyGhostSchemePrivilege } from './cindy-brain/runtime/electronSandboxAdapter';@@ -4299,12 +4303,20 @@ const registerIpcHandlers = () => {);// Read a local file's raw bytes for in-app rendering (currently PDF preview).- // Same path policy + size cap as read-file-for-attachment, but returns a- // Uint8Array over structured clone instead of base64: pdf.js getDocument({- // data }) wants bytes, and skipping base64 avoids a large transient string- // plus a main-thread atob/charCodeAt decode loop in the renderer. No new- // access surface — read-file-for-attachment already exposes these same bytes- // (as base64) under the identical isPathAllowed policy.+ // Returns a Uint8Array over structured clone instead of base64: pdf.js+ // getDocument({ data }) wants bytes, and skipping base64 avoids a large+ // transient string plus a main-thread atob/charCodeAt decode loop in the+ // renderer. Same 30MB cap as read-file-for-attachment.+ //+ // Path policy is the SENSITIVE-MEDIA blocklist, not the system one used by the+ // attachment IPCs: this channel replaces the xdt-file:// protocol as the byte+ // source for PDF preview, and that protocol denies credential / browser-profile+ // dirs (localFileProtocol.ts). Previewing files out of an agent-writable+ // workdir means the click authorizes "show this PDF", not "read wherever this+ // symlink points", so the stricter list is the right one — a workdir+ // `leak.pdf -> ~/.ssh/id_rsa` must not reach the renderer here when the+ // protocol it replaced would have refused it. Sibling ImagePreview still goes+ // through xdt-file://, so this keeps one policy across the file browser.ipcMain.handle('read-file-bytes',async (@@ -4327,10 +4339,19 @@ const registerIpcHandlers = () => {const noFollow =typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;return readFileBytesForPreview(params, {- isPathAllowed,+ isPathAllowed: (p) => isPathAllowedAgainst(p, getSensitiveMediaBlocklist()),realpath: (p) => fs.promises.realpath(p),- stat: (p) => fs.promises.stat(p),- open: (p) => fs.promises.open(p, fs.constants.O_RDONLY | noFollow),+ // bigint stats: dev/ino identity must not be rounded (see FileIdentityStat).+ stat: (p) => fs.promises.stat(p, { bigint: true }),+ open: async (p) => {+ const handle = await fs.promises.open(p, fs.constants.O_RDONLY | noFollow);+ return {+ stat: () => handle.stat({ bigint: true }),+ read: (buffer, offset, length, position) =>+ handle.read(buffer, offset, length, position),+ close: () => handle.close(),+ };+ },});},);diff --git a/apps/desktop/src/main/fileReadBytes.ts b/apps/desktop/src/main/fileReadBytes.tsindex 6a3a47f566..dce26c2b53 100644--- a/apps/desktop/src/main/fileReadBytes.ts+++ b/apps/desktop/src/main/fileReadBytes.ts@@ -26,7 +26,6 @@* - success returns an exact-copy Uint8Array (no pooled-slab spillover).*/-import type { Stats } from 'node:fs';import * as nodePath from 'node:path';import { throwIpcError } from './utils/ipcValidate.js';@@ -34,9 +33,23 @@ import { throwIpcError } from './utils/ipcValidate.js';/** Hard ceiling regardless of the caller-requested maxSize. */export const READ_FILE_BYTES_CAP = 30 * 1024 * 1024;+/**+ * The stat fields this module needs. `dev`/`ino`/`size` are bigint because the+ * identity check below is only sound on bigint stats: the default numeric+ * `Stats` rounds 64-bit file ids past 2^53 (large NTFS volumes), which would let+ * two different files on one device compare equal. Callers therefore inject+ * `stat(p, { bigint: true })` / `handle.stat({ bigint: true })`.+ */+export interface FileIdentityStat {+ dev: bigint;+ ino: bigint;+ size: bigint;+ isFile(): boolean;+}+/** The subset of fs.promises.FileHandle this module uses (injectable for tests). */export interface FileHandleLike {- stat: () => Promise<Stats>;+ stat: () => Promise<FileIdentityStat>;read: (buffer: Buffer,offset: number,@@ -50,10 +63,22 @@ export interface ReadFileBytesDeps {isPathAllowed: (filePath: string) => boolean;realpath: (filePath: string) => Promise<string>;/** stat of the (symlink-free) realpath, for the expected dev/ino identity. */- stat: (filePath: string) => Promise<Stats>;+ stat: (filePath: string) => Promise<FileIdentityStat>;open: (filePath: string) => Promise<FileHandleLike>;}+/**+ * `dev + ino` is the stable identity between the policy-checked path and the+ * opened descriptor. A 0 inode means the platform / filesystem does not report+ * one (some Windows and network filesystems), i.e. the identity is UNAVAILABLE+ * — fail closed rather than let `0 === 0` silently satisfy the swap guard in+ * exactly the cases it exists to catch. Same rule as `isSameFileObject` in+ * chatAttachmentSave.ts.+ */+function isSameFileObject(expected: FileIdentityStat, actual: FileIdentityStat): boolean {+ return expected.ino !== 0n && expected.dev === actual.dev && expected.ino === actual.ino;+}+export async function readFileBytesForPreview(params: unknown,deps: ReadFileBytesDeps,@@ -120,21 +145,25 @@ export async function readFileBytesForPreview(}// Descriptor-identity revalidation: the opened fd must be the very inode the// policy-checked realpath resolved to (guards the ancestor-symlink swap).- if (st.dev !== expected.dev || st.ino !== expected.ino) {+ // Fails closed when the identity is unavailable — see isSameFileObject.+ if (!isSameFileObject(expected, st)) {throwIpcError('PRECONDITION_FAILED', 'file changed during read');}- if (st.size > maxSize) {+ // Down to Number only after the identity check: the size ceiling is a plain+ // number and a 30MB cap is far below Number.MAX_SAFE_INTEGER.+ const size = Number(st.size);+ if (size > maxSize) {throwIpcError('PRECONDITION_FAILED', 'file exceeds the preview size limit');}// Bound the buffer to the fstat'd size of THIS descriptor (≤ maxSize): even// if the file grows or is replaced after the check, we never read more than// this into main-process memory. Loop over short reads; stop early on EOF// (file shrank) and return exactly what was read.- const buffer = Buffer.alloc(st.size);+ const buffer = Buffer.alloc(size);let offset = 0;- while (offset < st.size) {+ while (offset < size) {const { bytesRead } = await handle- .read(buffer, offset, st.size - offset, offset)+ .read(buffer, offset, size - offset, offset).catch(() => throwIpcError('INTERNAL', 'failed to read file'));if (bytesRead === 0) break;offset += bytesRead;