Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复 ASAR 文件导致 worktree 回收反复失败 (#4669)
Chris Zhangb4ffa2a7a721
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex fe7ace53cd..e5bc8d3d71 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1773,6 +1773,12 @@ const config: ForgeConfig = {// 大通讯录 JSON/gzip/crypto 隔离在线程中,避免阻塞 Electron main。target: 'preload',},+ {+ entry: 'src/main/worktree/recoveryArchiveWorker.ts',+ config: 'vite.recovery-archive-worker.config.ts',+ // Physical ASAR bytes belong in recovery archives; isolate noAsar from main.+ target: 'preload',+ },{entry: 'src/main/process-monitor/windowsProcessScanWorker.ts',config: 'vite.process-scan-worker.config.ts',diff --git a/apps/desktop/scripts/fixtures/worktree-recovery-asar.cjs b/apps/desktop/scripts/fixtures/worktree-recovery-asar.cjsnew file mode 100644index 0000000000..7b205e14ca--- /dev/null+++ b/apps/desktop/scripts/fixtures/worktree-recovery-asar.cjs@@ -0,0 +1,51 @@+const assert = require('node:assert/strict');+const path = require('node:path');+const crypto = require('node:crypto');+const fs = require('node:fs/promises');+const physicalFs = require('original-fs').promises;+const { app } = require('electron');+const { runRecoveryArchiveTask: run } = require('./client.cjs');+const io = require('./io.cjs');+const root = process.env.CINDY_RECOVERY_TEST_ROOT;+app.setPath('userData', path.join(root, 'profile'));++(async () => {+ const source = path.join(root, 'source');+ const directory = path.join(root, 'archives');+ const staging = path.join(root, 'restored');+ const asar = path.join(source, 'app.asar');+ const bytes = await physicalFs.readFile(asar);+ const key = crypto.randomBytes(32);+ const iv = crypto.randomBytes(12);+ const originalNoAsar = process.noAsar;+ assert.equal((await fs.lstat(asar)).isDirectory(), true, 'fixture must reproduce Electron virtual ASAR');+ assert.equal((await io.inventoryWorktree(source))['app.asar'].kind, 'directory');+ if (process.platform !== 'win32') {+ await assert.rejects(io.createRecoveryArchive(source, 'abcd', directory, key, 'test-only', iv), /archive content does not match/);+ }+ const inventory = await run({ operation: 'inventory', root: source });+ assert.equal(inventory['app.asar'].kind, 'file');+ assert.equal(inventory['app.asar'].hash, crypto.createHash('sha256').update(bytes).digest('hex'));+ const archive = await run({ operation: 'create', root: source, resourceId: 'abcd', directory, key, encryptedKey: 'test-only', iv });+ // The existing verifier can read the new archive: no archive-format migration.+ await io.verifyRecoveryArchive(archive, directory, key);+ await run({ operation: 'verify', archive, directory, key });+ await fs.mkdir(staging);+ await run({ operation: 'extract', archive, staging, keep: false, directory, key });+ assert.deepEqual(await physicalFs.readFile(path.join(staging, 'app.asar')), bytes);+ assert.equal(await fs.readFile(path.join(staging, 'app.asar.unpacked', 'native.node'), 'utf8'), 'unpacked fixture');+ assert.equal(await fs.readFile(path.join(staging, '.env'), 'utf8'), 'synthetic ignored fixture');+ await fs.unlink(path.join(staging, '.env'));+ await run({ operation: 'extract', archive, staging, keep: true, directory, key });+ assert.deepEqual(await run({ operation: 'inventory', root: staging }), inventory);+ // Authentication failure must not emit restored plaintext.+ const corrupt = { ...archive, tag: Buffer.alloc(16).toString('base64') };+ const empty = path.join(root, 'empty');+ await fs.mkdir(empty);+ await assert.rejects(run({ operation: 'extract', archive: corrupt, staging: empty, keep: false, directory, key }));+ assert.deepEqual(await fs.readdir(empty), []);+ assert.equal(process.noAsar, originalNoAsar);+ assert.equal((await fs.lstat(asar)).isDirectory(), true, 'main must retain ASAR support');+ key.fill(0);+ process.stdout.write('PASS: old failure reproduced; packaged worker inventory/create/verify/restore/keep/authentication; main ASAR unchanged\n');+})().then(() => app.exit(0), (error) => { process.stderr.write(`${error.stack}\n`); app.exit(1); });diff --git a/apps/desktop/scripts/test-worktree-recovery-asar.mjs b/apps/desktop/scripts/test-worktree-recovery-asar.mjsnew file mode 100644index 0000000000..2b72c94126--- /dev/null+++ b/apps/desktop/scripts/test-worktree-recovery-asar.mjs@@ -0,0 +1,55 @@+// Explicit Electron regression: node apps/desktop/scripts/test-worktree-recovery-asar.mjs+// Uses only synthetic temp fixtures; never starts Cindy or reads its profile/keychain.+import assert from 'node:assert/strict';+import { execFile } from 'node:child_process';+import { createRequire, builtinModules } from 'node:module';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';+import { build } from 'vite';+import { createPackage } from '@electron/asar';++const require = createRequire(import.meta.url);+const desktop = fileURLToPath(new URL('..', import.meta.url));+const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-asar-recovery-'));+try {+ const bundle = path.join(root, 'bundle');+ const contents = path.join(root, 'contents');+ const source = path.join(root, 'source');+ await fs.mkdir(bundle);+ await fs.mkdir(contents);+ await fs.mkdir(source);+ await fs.writeFile(path.join(contents, 'inside.txt'), 'physical ASAR fixture');+ await createPackage(contents, path.join(source, 'app.asar'));+ await fs.chmod(path.join(source, 'app.asar'), 0o644);+ await fs.mkdir(path.join(source, 'app.asar.unpacked'));+ await fs.writeFile(path.join(source, 'app.asar.unpacked', 'native.node'), 'unpacked fixture');+ await fs.writeFile(path.join(source, '.env'), 'synthetic ignored fixture');+ await fs.writeFile(path.join(source, '.git'), 'excluded Git admin pointer');+ for (const [entry, name] of [+ ['recoveryArchiveWorker', 'recoveryArchiveWorker.js'],+ ['recoveryArchiveWorkerClient', 'client.cjs'],+ ['recoveryArchiveIO', 'io.cjs'],+ ]) {+ await build({+ configFile: path.join(desktop, 'vite.recovery-archive-worker.config.ts'),+ logLevel: 'error',+ build: {+ outDir: bundle, emptyOutDir: false, minify: false,+ lib: { entry: path.join(desktop, `src/main/worktree/${entry}.ts`), formats: ['cjs'], fileName: () => name },+ rollupOptions: { external: [...builtinModules, ...builtinModules.map((name) => `node:${name}`)] },+ },+ });+ }+ await fs.copyFile(path.join(desktop, 'scripts/fixtures/worktree-recovery-asar.cjs'), path.join(bundle, 'main.cjs'));+ await fs.writeFile(path.join(bundle, 'package.json'), JSON.stringify({ main: 'main.cjs' }));+ const packaged = path.join(root, 'app.asar');+ await createPackage(bundle, packaged);+ const env = { ...process.env, CINDY_RECOVERY_TEST_ROOT: root };+ delete env.ELECTRON_RUN_AS_NODE;+ const result = await promisify(execFile)(require('electron'), [packaged], { env, timeout: 60_000 });+ assert.match(result.stdout, /PASS:/);+ process.stdout.write(result.stdout);+} finally { await fs.rm(root, { recursive: true, force: true }); }diff --git a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.tsindex bdfbda6792..dc2dda0367 100644--- a/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts+++ b/apps/desktop/src/main/__tests__/managedWorktreeRecycle.test.ts@@ -1,3 +1,8 @@+// These suites exercise real archive I/O in Node; Electron worker isolation is covered separately.+vi.mock('../worktree/recoveryArchiveWorkerClient', async () => {+ const { executeRecoveryArchiveTask } = await import('../worktree/recoveryArchiveTask');+ return { runRecoveryArchiveTask: executeRecoveryArchiveTask };+});import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import fs from 'node:fs/promises';import os from 'node:os';diff --git a/apps/desktop/src/main/__tests__/recoveryArchiveWorkerClient.test.ts b/apps/desktop/src/main/__tests__/recoveryArchiveWorkerClient.test.tsnew file mode 100644index 0000000000..511ff37d40--- /dev/null+++ b/apps/desktop/src/main/__tests__/recoveryArchiveWorkerClient.test.ts@@ -0,0 +1,75 @@+import { EventEmitter } from 'node:events';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({+ worker: null as (EventEmitter & { terminate: ReturnType<typeof vi.fn>; unref: ReturnType<typeof vi.fn> }) | null,+ fail: false,+}));+vi.mock('node:worker_threads', () => ({+ Worker: vi.fn(function () {+ if (state.fail) throw new Error('cannot start worker');+ return state.worker;+ }),+}));+import { RECOVERY_ARCHIVE_TIMEOUT_MS, runRecoveryArchiveTask } from '../worktree/recoveryArchiveWorkerClient';++describe('recovery archive worker lifecycle', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ state.worker = Object.assign(new EventEmitter(), { terminate: vi.fn().mockResolvedValue(0), unref: vi.fn() });+ state.fail = false;+ });+ afterEach(() => { vi.useRealTimers(); });+ it('returns the worker evidence', async () => {+ const result = runRecoveryArchiveTask({ operation: 'inventory', root: '/fixture' });+ state.worker!.emit('message', { ok: true, result: { 'app.asar': { kind: 'file', hash: 'digest', mode: 420 } } });+ state.worker!.emit('exit', 0);+ await expect(result).resolves.toHaveProperty(['app.asar', 'kind'], 'file');+ expect(state.worker!.terminate).toHaveBeenCalledOnce();+ expect(state.worker!.unref).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ expect(state.worker!.eventNames()).toEqual([]);+ });+ it.each([0, 1])('rejects an exit without a reply even for exit code %s', async (code) => {+ const result = runRecoveryArchiveTask({ operation: 'inventory', root: '/fixture' });+ state.worker!.emit('exit', code);+ await expect(result).rejects.toThrow('exited before replying');+ });+ it('propagates archive verification failures', async () => {+ const result = runRecoveryArchiveTask({ operation: 'inventory', root: '/fixture' });+ state.worker!.emit('message', { ok: false, error: 'archive content does not match worktree inventory' });+ await expect(result).rejects.toThrow('archive content does not match');+ });+ it('terminates a nonresponsive worker before releasing its caller', async () => {+ let terminated!: (code: number) => void;+ state.worker!.terminate.mockReturnValue(new Promise<number>((resolve) => { terminated = resolve; }));+ const result = runRecoveryArchiveTask({ operation: 'inventory', root: '/fixture' });+ let settled = false;+ const checked = expect(result).rejects.toThrow('inventory timed out');+ void result.catch(() => { settled = true; });+ await vi.advanceTimersByTimeAsync(RECOVERY_ARCHIVE_TIMEOUT_MS);+ expect(state.worker!.terminate).toHaveBeenCalledOnce();+ expect(settled).toBe(false);+ // A late result or error must not overtake timeout/termination.+ state.worker!.emit('message', { ok: true, result: {} });+ state.worker!.emit('error', new Error('racing error'));+ terminated(1);+ await checked;+ expect(state.worker!.terminate).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });+ it('surfaces termination failures instead of reporting success', async () => {+ state.worker!.terminate.mockRejectedValue(new Error('termination failed'));+ const result = runRecoveryArchiveTask({ operation: 'inventory', root: '/fixture' });+ state.worker!.emit('message', { ok: true, result: {} });+ await expect(result).rejects.toThrow('termination failed');+ });+ it('rejects worker startup and runtime errors', async () => {+ state.fail = true;+ await expect(runRecoveryArchiveTask({ operation: 'inventory', root: '/fixture' })).rejects.toThrow('cannot start');+ state.fail = false;+ const result = runRecoveryArchiveTask({ operation: 'inventory', root: '/fixture' });+ state.worker!.emit('error', new Error('worker crashed'));+ await expect(result).rejects.toThrow('worker crashed');+ });+});diff --git a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.tsindex 3b19aba3ac..c7f69cff0c 100644--- a/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRecovery.git-integration.test.ts@@ -1,3 +1,8 @@+// These suites exercise real archive I/O in Node; Electron worker isolation is covered separately.+vi.mock('../worktree/recoveryArchiveWorkerClient', async () => {+ const { executeRecoveryArchiveTask } = await import('../worktree/recoveryArchiveTask');+ return { runRecoveryArchiveTask: executeRecoveryArchiveTask };+});import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';import { execFile } from 'node:child_process';import { promisify } from 'node:util';diff --git a/apps/desktop/src/main/worktree/recoveryArchive.ts b/apps/desktop/src/main/worktree/recoveryArchive.tsindex 9cb1e7bd6f..b7f2e7b8d2 100644--- a/apps/desktop/src/main/worktree/recoveryArchive.ts+++ b/apps/desktop/src/main/worktree/recoveryArchive.ts@@ -1,160 +1,41 @@-import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';-import { createReadStream, createWriteStream } from 'node:fs';-import fs from 'node:fs/promises';-import path from 'node:path';-import { pipeline } from 'node:stream/promises';+import { randomBytes } from 'node:crypto';import { safeStorage } from 'electron';-import * as tar from 'tar';import { recycleJournalRoot } from './recycleJournal';+import { runRecoveryArchiveTask } from './recoveryArchiveWorkerClient';+import type { FileEvidence, WorktreeRecoveryArchive } from './recoveryArchiveIO';-interface FileEvidence {- kind: 'file' | 'link' | 'directory';- hash: string;- mode: number;-}--/** Compressed, encrypted local recovery bytes; secrets never enter Git objects. */-export interface WorktreeRecoveryArchive {- file: string;- encryptedKey: string;- iv: string;- tag: string;- files: Record<string, FileEvidence>;-}--function restorableMode(mode: number): number {- // Windows exposes read/write attributes; tar adds synthetic directory execute bits.- return mode & (process.platform === 'win32' ? 0o666 : 0o777);-}--export async function inventoryWorktree(root: string): Promise<Record<string, FileEvidence>> {- const files: Record<string, FileEvidence> = Object.create(null);- const walk = async (directory: string): Promise<void> => {- for (const name of await fs.readdir(directory)) {- if (directory === root && name === '.git') continue;- const absolute = path.join(directory, name);- const stat = await fs.lstat(absolute);- const relative = path.relative(root, absolute);- const mode = restorableMode(stat.mode);- if (stat.isSymbolicLink()) {- files[relative] = { kind: 'link', hash: await fs.readlink(absolute), mode };- } else if (stat.isDirectory()) {- files[relative] = { kind: 'directory', hash: '', mode };- await walk(absolute);- } else if (stat.isFile()) {- const hash = createHash('sha256');- for await (const chunk of createReadStream(absolute)) hash.update(chunk);- files[relative] = { kind: 'file', hash: hash.digest('hex'), mode };- } else {- throw new Error('worktree contains an unsupported filesystem entry');- }- }- };- await walk(root);- return files;-}+export type { WorktreeRecoveryArchive } from './recoveryArchiveIO';+export { sameWorktreeFiles } from './recoveryArchiveIO';-export function sameWorktreeFiles(- actual: Record<string, FileEvidence>,- saved: Record<string, FileEvidence>,- allowMissing = false,-): boolean {- if (!allowMissing && Object.keys(actual).length !== Object.keys(saved).length) return false;- return Object.entries(actual).every(([name, file]) => {- const expected = saved[name];- return expected?.kind === file.kind && expected.hash === file.hash && expected.mode === file.mode;- });+export function inventoryWorktree(root: string): Promise<Record<string, FileEvidence>> {+ return runRecoveryArchiveTask({ operation: 'inventory', root });}-function archivePath(archive: Pick<WorktreeRecoveryArchive, 'file'>): string {- if (!/^[a-f0-9-]+\.tar\.gz\.enc$/.test(archive.file)) throw new Error('invalid recovery archive path');- return path.join(recycleJournalRoot(), archive.file);+export async function createRecoveryArchive(root: string, resourceId: string): Promise<WorktreeRecoveryArchive> {+ const key = randomBytes(32);+ try {+ const encryptedKey = safeStorage.encryptString(key.toString('base64')).toString('base64');+ return await runRecoveryArchiveTask({+ operation: 'create', root, resourceId, directory: recycleJournalRoot(),+ key, encryptedKey, iv: randomBytes(12),+ });+ } finally { key.fill(0); }}-function decryptArchive(archive: WorktreeRecoveryArchive) {+async function withArchiveKey<T>(archive: WorktreeRecoveryArchive, run: (key: Buffer) => Promise<T>): Promise<T> {const key = Buffer.from(safeStorage.decryptString(Buffer.from(archive.encryptedKey, 'base64')), 'base64');- const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(archive.iv, 'base64'));- key.fill(0);- decipher.setAuthTag(Buffer.from(archive.tag, 'base64'));- return decipher;-}--/** Fully authenticate before any restore is allowed to emit plaintext files. */-export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive): Promise<void> {- const files: Record<string, FileEvidence> = Object.create(null);- const entries: Promise<void>[] = [];- const parser = tar.t({- strict: true,- onReadEntry(entry) {- const name = path.normalize(entry.path).replace(/[\\/]+$/, '');- if (path.isAbsolute(name) || name === '..' || name.startsWith(`..${path.sep}`) || name === '.git') {- throw new Error('unsafe worktree archive entry');- }- const check = (async () => {- if (files[name]) throw new Error('duplicate worktree archive entry');- const hash = createHash('sha256');- for await (const chunk of entry) hash.update(chunk);- const mode = restorableMode(entry.mode ?? 0);- if (entry.type === 'Directory') files[name] = { kind: 'directory', hash: '', mode };- else if (entry.type === 'SymbolicLink') {- if (typeof entry.linkpath !== 'string') throw new Error('invalid archive symbolic link');- files[name] = { kind: 'link', hash: entry.linkpath, mode };- }- else if (entry.type === 'Link') {- if (typeof entry.linkpath !== 'string') throw new Error('invalid archive hard link');- const target = archive.files[path.normalize(entry.linkpath)];- if (target?.kind !== 'file') throw new Error('invalid archive hard link');- files[name] = { ...target, mode };- } else if (entry.type === 'File') files[name] = { kind: 'file', hash: hash.digest('hex'), mode };- else throw new Error('unsupported worktree archive entry');- })();- // Handle rejection immediately even while the remaining encrypted stream drains.- void check.catch(() => {});- entries.push(check);- },- });- await pipeline(createReadStream(archivePath(archive)), decryptArchive(archive), parser);- await Promise.all(entries);- if (!sameWorktreeFiles(files, archive.files)) throw new Error('archive content does not match worktree inventory');+ try { return await run(key); } finally { key.fill(0); }}-export async function createRecoveryArchive(root: string, resourceId: string): Promise<WorktreeRecoveryArchive> {- const files = await inventoryWorktree(root);- const key = randomBytes(32);- const iv = randomBytes(12);- const encryptedKey = safeStorage.encryptString(key.toString('base64')).toString('base64');- const cipher = createCipheriv('aes-256-gcm', key, iv);- key.fill(0);- const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;- await fs.mkdir(recycleJournalRoot(), { recursive: true });- const target = archivePath({ file });- try {- await pipeline(- tar.c({ cwd: root, gzip: true, follow: false, noDirRecurse: true, strict: true }, Object.keys(files)),- cipher,- createWriteStream(target, { flags: 'wx', mode: 0o600 }),- );- const handle = await fs.open(target, 'r+');- try { await handle.sync(); } finally { await handle.close(); }- const archive = { file, encryptedKey, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), files };- await verifyRecoveryArchive(archive);- if (!sameWorktreeFiles(await inventoryWorktree(root), files)) throw new Error('worktree changed during archive');- return archive;- } catch (error) {- await fs.rm(target, { force: true });- throw error;- }+export function verifyRecoveryArchive(archive: WorktreeRecoveryArchive): Promise<void> {+ return withArchiveKey(archive, (key) => runRecoveryArchiveTask({+ operation: 'verify', archive, directory: recycleJournalRoot(), key,+ }));}-/** Authenticate first; keep mode fills only missing bytes of a verified partial restore. */-export async function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep = false): Promise<void> {- await verifyRecoveryArchive(archive);- await pipeline(- createReadStream(archivePath(archive)), decryptArchive(archive),- tar.x({ cwd: staging, strict: true, preservePaths: false, unlink: !keep, keep }),- );- if (!sameWorktreeFiles(await inventoryWorktree(staging), archive.files)) {- throw new Error('restored worktree files do not match recovery archive');- }+export function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep = false): Promise<void> {+ return withArchiveKey(archive, (key) => runRecoveryArchiveTask({+ operation: 'extract', archive, staging, keep, directory: recycleJournalRoot(), key,+ }));}diff --git a/apps/desktop/src/main/worktree/recoveryArchiveIO.ts b/apps/desktop/src/main/worktree/recoveryArchiveIO.tsnew file mode 100644index 0000000000..a2a5acbedc--- /dev/null+++ b/apps/desktop/src/main/worktree/recoveryArchiveIO.ts@@ -0,0 +1,151 @@+import { createCipheriv, createDecipheriv, createHash, randomUUID } from 'node:crypto';+import { createReadStream, createWriteStream } from 'node:fs';+import fs from 'node:fs/promises';+import path from 'node:path';+import { pipeline } from 'node:stream/promises';+import * as tar from 'tar';++export interface FileEvidence {+ kind: 'file' | 'link' | 'directory';+ hash: string;+ mode: number;+}++/** Compressed, encrypted local recovery bytes; secrets never enter Git objects. */+export interface WorktreeRecoveryArchive {+ file: string;+ encryptedKey: string;+ iv: string;+ tag: string;+ files: Record<string, FileEvidence>;+}++function restorableMode(mode: number): number {+ // Windows exposes read/write attributes; tar adds synthetic directory execute bits.+ return mode & (process.platform === 'win32' ? 0o666 : 0o777);+}++export async function inventoryWorktree(root: string): Promise<Record<string, FileEvidence>> {+ const files: Record<string, FileEvidence> = Object.create(null);+ const walk = async (directory: string): Promise<void> => {+ for (const name of await fs.readdir(directory)) {+ if (directory === root && name === '.git') continue;+ const absolute = path.join(directory, name);+ const stat = await fs.lstat(absolute);+ const relative = path.relative(root, absolute);+ const mode = restorableMode(stat.mode);+ if (stat.isSymbolicLink()) {+ files[relative] = { kind: 'link', hash: await fs.readlink(absolute), mode };+ } else if (stat.isDirectory()) {+ files[relative] = { kind: 'directory', hash: '', mode };+ await walk(absolute);+ } else if (stat.isFile()) {+ const hash = createHash('sha256');+ for await (const chunk of createReadStream(absolute)) hash.update(chunk);+ files[relative] = { kind: 'file', hash: hash.digest('hex'), mode };+ } else {+ throw new Error('worktree contains an unsupported filesystem entry');+ }+ }+ };+ await walk(root);+ return files;+}++export function sameWorktreeFiles(+ actual: Record<string, FileEvidence>,+ saved: Record<string, FileEvidence>,+ allowMissing = false,+): boolean {+ if (!allowMissing && Object.keys(actual).length !== Object.keys(saved).length) return false;+ return Object.entries(actual).every(([name, file]) => {+ const expected = saved[name];+ return expected?.kind === file.kind && expected.hash === file.hash && expected.mode === file.mode;+ });+}++function archivePath(directory: string, archive: Pick<WorktreeRecoveryArchive, 'file'>): string {+ if (!/^[a-f0-9-]+\.tar\.gz\.enc$/.test(archive.file)) throw new Error('invalid recovery archive path');+ return path.join(directory, archive.file);+}++function decryptArchive(archive: WorktreeRecoveryArchive, key: Uint8Array) {+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(archive.iv, 'base64'));+ decipher.setAuthTag(Buffer.from(archive.tag, 'base64'));+ return decipher;+}++/** Fully authenticate before any restore is allowed to emit plaintext files. */+export async function verifyRecoveryArchive(archive: WorktreeRecoveryArchive, directory: string, key: Uint8Array): Promise<void> {+ const files: Record<string, FileEvidence> = Object.create(null);+ const entries: Promise<void>[] = [];+ const parser = tar.t({+ strict: true,+ onReadEntry(entry) {+ const name = path.normalize(entry.path).replace(/[\\/]+$/, '');+ if (path.isAbsolute(name) || name === '..' || name.startsWith(`..${path.sep}`) || name === '.git') {+ throw new Error('unsafe worktree archive entry');+ }+ const check = (async () => {+ if (files[name]) throw new Error('duplicate worktree archive entry');+ const hash = createHash('sha256');+ for await (const chunk of entry) hash.update(chunk);+ const mode = restorableMode(entry.mode ?? 0);+ if (entry.type === 'Directory') files[name] = { kind: 'directory', hash: '', mode };+ else if (entry.type === 'SymbolicLink') {+ if (typeof entry.linkpath !== 'string') throw new Error('invalid archive symbolic link');+ files[name] = { kind: 'link', hash: entry.linkpath, mode };+ }+ else if (entry.type === 'Link') {+ if (typeof entry.linkpath !== 'string') throw new Error('invalid archive hard link');+ const target = archive.files[path.normalize(entry.linkpath)];+ if (target?.kind !== 'file') throw new Error('invalid archive hard link');+ files[name] = { ...target, mode };+ } else if (entry.type === 'File') files[name] = { kind: 'file', hash: hash.digest('hex'), mode };+ else throw new Error('unsupported worktree archive entry');+ })();+ // Handle rejection immediately even while the remaining encrypted stream drains.+ void check.catch(() => {});+ entries.push(check);+ },+ });+ await pipeline(createReadStream(archivePath(directory, archive)), decryptArchive(archive, key), parser);+ await Promise.all(entries);+ if (!sameWorktreeFiles(files, archive.files)) throw new Error('archive content does not match worktree inventory');+}++export async function createRecoveryArchive(root: string, resourceId: string, directory: string, key: Uint8Array, encryptedKey: string, iv: Uint8Array): Promise<WorktreeRecoveryArchive> {+ const files = await inventoryWorktree(root);+ const cipher = createCipheriv('aes-256-gcm', key, iv);+ const file = `${resourceId}-${randomUUID()}.tar.gz.enc`;+ await fs.mkdir(directory, { recursive: true });+ const target = archivePath(directory, { file });+ try {+ await pipeline(+ tar.c({ cwd: root, gzip: true, follow: false, noDirRecurse: true, strict: true }, Object.keys(files)),+ cipher,+ createWriteStream(target, { flags: 'wx', mode: 0o600 }),+ );+ const handle = await fs.open(target, 'r+');+ try { await handle.sync(); } finally { await handle.close(); }+ const archive = { file, encryptedKey, iv: Buffer.from(iv).toString('base64'), tag: cipher.getAuthTag().toString('base64'), files };+ await verifyRecoveryArchive(archive, directory, key);+ if (!sameWorktreeFiles(await inventoryWorktree(root), files)) throw new Error('worktree changed during archive');+ return archive;+ } catch (error) {+ await fs.rm(target, { force: true });+ throw error;+ }+}++/** Authenticate first; keep mode fills only missing bytes of a verified partial restore. */+export async function extractRecoveryArchive(archive: WorktreeRecoveryArchive, staging: string, keep: boolean, directory: string, key: Uint8Array): Promise<void> {+ await verifyRecoveryArchive(archive, directory, key);+ await pipeline(+ createReadStream(archivePath(directory, archive)), decryptArchive(archive, key),+ tar.x({ cwd: staging, strict: true, preservePaths: false, unlink: !keep, keep }),+ );+ if (!sameWorktreeFiles(await inventoryWorktree(staging), archive.files)) {+ throw new Error('restored worktree files do not match recovery archive');+ }+}diff --git a/apps/desktop/src/main/worktree/recoveryArchiveTask.ts b/apps/desktop/src/main/worktree/recoveryArchiveTask.tsnew file mode 100644index 0000000000..9001da4f8e--- /dev/null+++ b/apps/desktop/src/main/worktree/recoveryArchiveTask.ts@@ -0,0 +1,26 @@+import * as io from './recoveryArchiveIO';+import type { FileEvidence, WorktreeRecoveryArchive } from './recoveryArchiveIO';++type ArchiveInput = { archive: WorktreeRecoveryArchive; directory: string; key: Uint8Array };+export type RecoveryArchiveTask =+ | { operation: 'inventory'; root: string }+ | { operation: 'create'; root: string; resourceId: string; directory: string; key: Uint8Array; encryptedKey: string; iv: Uint8Array }+ | ({ operation: 'verify' } & ArchiveInput)+ | ({ operation: 'extract'; staging: string; keep: boolean } & ArchiveInput);+export type RecoveryArchiveResult<T extends RecoveryArchiveTask> =+ T extends { operation: 'inventory' } ? Record<string, FileEvidence> :+ T extends { operation: 'create' } ? WorktreeRecoveryArchive : void;++/** Run only with physical filesystem semantics (Node, or the isolated Electron worker). */+export async function executeRecoveryArchiveTask(task: RecoveryArchiveTask) {+ try {+ switch (task.operation) {+ case 'inventory': return await io.inventoryWorktree(task.root);+ case 'create': return await io.createRecoveryArchive(task.root, task.resourceId, task.directory, task.key, task.encryptedKey, task.iv);+ case 'verify': return await io.verifyRecoveryArchive(task.archive, task.directory, task.key);+ case 'extract': return await io.extractRecoveryArchive(task.archive, task.staging, task.keep, task.directory, task.key);+ }+ } finally {+ if ('key' in task) task.key.fill(0);+ }+}diff --git a/apps/desktop/src/main/worktree/recoveryArchiveWorker.ts b/apps/desktop/src/main/worktree/recoveryArchiveWorker.tsnew file mode 100644index 0000000000..3bcafc8744--- /dev/null+++ b/apps/desktop/src/main/worktree/recoveryArchiveWorker.ts@@ -0,0 +1,12 @@+// eslint-disable-next-line no-restricted-imports -- Physical archive I/O must not change Electron main's ASAR semantics.+import { parentPort, workerData } from 'node:worker_threads';+import { executeRecoveryArchiveTask } from './recoveryArchiveTask';+import type { RecoveryArchiveTask } from './recoveryArchiveTask';++// Imports must finish while this worker can still load its own bundle from app.asar.+// process.noAsar is isolate-local: main and other workers retain virtual ASAR access.+process.noAsar = true;+void executeRecoveryArchiveTask(workerData as RecoveryArchiveTask).then(+ (result) => parentPort!.postMessage({ ok: true, result }),+ (error: unknown) => parentPort!.postMessage({ ok: false, error: error instanceof Error ? error.message : String(error) }),+);diff --git a/apps/desktop/src/main/worktree/recoveryArchiveWorkerClient.ts b/apps/desktop/src/main/worktree/recoveryArchiveWorkerClient.tsnew file mode 100644index 0000000000..fc720c4759--- /dev/null+++ b/apps/desktop/src/main/worktree/recoveryArchiveWorkerClient.ts@@ -0,0 +1,42 @@+import path from 'node:path';+// eslint-disable-next-line no-restricted-imports -- Keep physical filesystem semantics isolated from Electron main.+import { Worker } from 'node:worker_threads';+import type { RecoveryArchiveResult, RecoveryArchiveTask } from './recoveryArchiveTask';++// Recovery includes ignored build dependencies, so allow large local archives while+// still bounding an operation that never replies. This is not a retry budget.+export const RECOVERY_ARCHIVE_TIMEOUT_MS = 30 * 60_000;++export function runRecoveryArchiveTask<T extends RecoveryArchiveTask>(task: T): Promise<RecoveryArchiveResult<T>> {+ return new Promise((resolve, reject) => {+ const worker = new Worker(path.join(__dirname, 'recoveryArchiveWorker.js'), { workerData: task });+ let finishing = false;+ const finish = (error?: Error, result?: RecoveryArchiveResult<T>) => {+ if (finishing) return;+ finishing = true;+ clearTimeout(timer);+ // Do not release the caller's resource lock while the worker can still write.+ // Keep the error listener until termination to absorb a racing worker error.+ void worker.terminate().then(() => {+ worker.removeAllListeners();+ if (error) reject(error);+ else resolve(result as RecoveryArchiveResult<T>);+ }, (terminationError: unknown) => {+ reject(terminationError);+ });+ };+ const timer = setTimeout(() => {+ finish(new Error(`worktree recovery ${task.operation} timed out after ${RECOVERY_ARCHIVE_TIMEOUT_MS}ms`));+ }, RECOVERY_ARCHIVE_TIMEOUT_MS);+ worker.once('message', (message: { ok: boolean; result: RecoveryArchiveResult<T>; error?: string }) => {+ finish(message.ok ? undefined : new Error(message.error ?? 'worktree recovery worker failed'), message.result);+ });+ worker.on('error', (error: unknown) => finish(error instanceof Error ? error : new Error(String(error))));+ worker.once('exit', (code) => {+ finish(new Error(`worktree recovery worker exited before replying (${code})`));+ });+ // Attaching message listeners refs the port; unref only after installing them.+ worker.unref();+ timer.unref();+ });+}diff --git a/apps/desktop/vite.recovery-archive-worker.config.ts b/apps/desktop/vite.recovery-archive-worker.config.tsnew file mode 100644index 0000000000..1b6cccc9d6--- /dev/null+++ b/apps/desktop/vite.recovery-archive-worker.config.ts@@ -0,0 +1,15 @@+import { defineConfig } from 'vite';++export default defineConfig({+ resolve: {+ conditions: ['node'],+ mainFields: ['module', 'jsnext:main', 'jsnext'],+ },+ build: {+ rollupOptions: {+ output: {+ inlineDynamicImports: true,+ },+ },+ },+});