Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: isolate desktop validation and reject invalid GFS targets
Alfredo Lopez93e566b1c34c
diff --git a/desktop-app/src/__tests__/tokenStore.devIsolation.test.ts b/desktop-app/src/__tests__/tokenStore.devIsolation.test.tsnew file mode 100644index 000000000..bd8e2fb81--- /dev/null+++ b/desktop-app/src/__tests__/tokenStore.devIsolation.test.ts@@ -0,0 +1,168 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { promises as fs } from 'node:fs'+import os from 'node:os'+import path from 'node:path'++const electronState = vi.hoisted(() => ({+ isReady: false,+ userDataDir: '',+ keychain: new Map<string, string>(),+}))++vi.mock('keytar', () => ({+ getPassword: vi.fn(+ async (service: string, account: string) =>+ electronState.keychain.get(`${service}::${account}`) ?? null+ ),+ setPassword: vi.fn(async (service: string, account: string, value: string) => {+ electronState.keychain.set(`${service}::${account}`, value)+ }),+ deletePassword: vi.fn(async (service: string, account: string) =>+ electronState.keychain.delete(`${service}::${account}`)+ ),+}))++vi.mock('electron', () => ({+ app: {+ isReady: vi.fn(() => electronState.isReady),+ getPath: vi.fn(() => electronState.userDataDir),+ },+ safeStorage: {+ isEncryptionAvailable: vi.fn(() => true),+ encryptString: vi.fn((value: string) => Buffer.from(`unit-enc:${value}`, 'utf8')),+ decryptString: vi.fn((value: Buffer) => value.toString('utf8').replace(/^unit-enc:/, '')),+ },+}))++const ENV = 'env_a-000000000000'+const SERVICE = 'Evenfire'+const LEGACY_ACCOUNT = 'session-token'+const SCOPED_ACCOUNT = `${LEGACY_ACCOUNT}::${ENV}`+const OFFICIAL_SCOPED_FILE = `session-token-${ENV}.json`+const OFFICIAL_LEGACY_FILE = 'session-token.json'++let officialHome = ''+let isolatedDir = ''+let TokenStore: typeof import('../tokenStore.js').TokenStore++beforeEach(async () => {+ electronState.isReady = false+ electronState.userDataDir = ''+ electronState.keychain.clear()+ officialHome = await fs.mkdtemp(path.join(os.tmpdir(), 'evenfire-official-home-'))+ isolatedDir = await fs.mkdtemp(path.join(os.tmpdir(), 'evenfire-isolated-user-data-'))+ vi.spyOn(os, 'homedir').mockReturnValue(officialHome)+ TokenStore = (await import('../tokenStore.js')).TokenStore+})++afterEach(async () => {+ vi.restoreAllMocks()+ await fs.rm(officialHome, { recursive: true, force: true })+ await fs.rm(isolatedDir, { recursive: true, force: true })+})++async function seedOfficialStorage(): Promise<{ scoped: string; legacy: string }> {+ const officialStorage = path.join(officialHome, '.evenfire')+ const scopedValue = ['unit', ENV, 'scoped'].join(':')+ const legacyValue = ['unit', 'legacy'].join(':')+ const scoped = JSON.stringify({ token: scopedValue })+ const legacy = JSON.stringify({ token: legacyValue })+ await fs.mkdir(officialStorage, { recursive: true })+ await fs.writeFile(path.join(officialStorage, OFFICIAL_SCOPED_FILE), scoped)+ await fs.writeFile(path.join(officialStorage, OFFICIAL_LEGACY_FILE), legacy)+ electronState.keychain.set(`${SERVICE}::${SCOPED_ACCOUNT}`, scopedValue)+ electronState.keychain.set(`${SERVICE}::${LEGACY_ACCOUNT}`, legacyValue)+ return { scoped, legacy }+}++async function keytarCalls(): Promise<number> {+ const keytar = await import('keytar')+ return (+ vi.mocked(keytar.getPassword).mock.calls.length ++ vi.mocked(keytar.setPassword).mock.calls.length ++ vi.mocked(keytar.deletePassword).mock.calls.length+ )+}++async function officialDocuments(): Promise<{ scoped: string; legacy: string }> {+ const officialStorage = path.join(officialHome, '.evenfire')+ return {+ scoped: await fs.readFile(path.join(officialStorage, OFFICIAL_SCOPED_FILE), 'utf8'),+ legacy: await fs.readFile(path.join(officialStorage, OFFICIAL_LEGACY_FILE), 'utf8'),+ }+}++describe('TokenStore dev isolation', () => {+ it('reads an empty isolated store without importing official storage', async () => {+ const official = await seedOfficialStorage()+ electronState.isReady = true+ electronState.userDataDir = isolatedDir+ const store = new TokenStore({ isolatedUserDataPath: isolatedDir })++ await expect(store.getSessionToken(ENV)).resolves.toBeNull()++ expect(await keytarCalls()).toBe(0)+ expect(electronState.keychain.get(`${SERVICE}::${SCOPED_ACCOUNT}`)).toBe(+ ['unit', ENV, 'scoped'].join(':')+ )+ expect(electronState.keychain.get(`${SERVICE}::${LEGACY_ACCOUNT}`)).toBe(+ ['unit', 'legacy'].join(':')+ )+ expect(await officialDocuments()).toEqual(official)+ })++ it('persists and clears an encrypted isolated file without keytar calls', async () => {+ const official = await seedOfficialStorage()+ const isolatedValue = ['unit', 'isolated'].join(':')+ electronState.isReady = true+ electronState.userDataDir = isolatedDir+ const store = new TokenStore({ isolatedUserDataPath: isolatedDir })+ const encryptedFile = path.join(isolatedDir, `session-token-${ENV}.enc`)++ await store.setSessionToken(isolatedValue, ENV)+ expect(await store.getSessionToken(ENV)).toBe(isolatedValue)+ expect((await fs.stat(encryptedFile)).mode & 0o777).toBe(0o600)+ expect(await fs.readdir(isolatedDir)).toEqual([path.basename(encryptedFile)])++ await store.clearSessionToken(ENV)+ await expect(store.getSessionToken(ENV)).resolves.toBeNull()+ await expect(fs.access(encryptedFile)).rejects.toMatchObject({ code: 'ENOENT' })++ expect(await keytarCalls()).toBe(0)+ expect(await officialDocuments()).toEqual(official)+ })++ it('rejects isolated operations before Electron is ready', async () => {+ const store = new TokenStore({ isolatedUserDataPath: isolatedDir })+ const isolatedValue = ['unit', 'isolated'].join(':')++ await expect(store.getSessionToken(ENV)).rejects.toThrow(/requires Electron readiness/)+ await expect(store.setSessionToken(isolatedValue, ENV)).rejects.toThrow(+ /requires Electron readiness/+ )+ await expect(store.clearSessionToken(ENV)).rejects.toThrow(/requires Electron readiness/)++ expect(await keytarCalls()).toBe(0)+ expect(await fs.readdir(isolatedDir)).toEqual([])+ })++ it('rejects isolated operations when declared and actual userData differ', async () => {+ const actualDir = await fs.mkdtemp(path.join(os.tmpdir(), 'evenfire-actual-user-data-'))+ try {+ const isolatedValue = ['unit', 'isolated'].join(':')+ electronState.isReady = true+ electronState.userDataDir = actualDir+ const store = new TokenStore({ isolatedUserDataPath: isolatedDir })++ await expect(store.getSessionToken(ENV)).rejects.toThrow(/directory mismatch/)+ await expect(store.setSessionToken(isolatedValue, ENV)).rejects.toThrow(/directory mismatch/)+ await expect(store.clearSessionToken(ENV)).rejects.toThrow(/directory mismatch/)++ expect(await keytarCalls()).toBe(0)+ expect(await fs.readdir(actualDir)).toEqual([])+ expect(await fs.readdir(isolatedDir)).toEqual([])+ } finally {+ await fs.rm(actualDir, { recursive: true, force: true })+ }+ })+})diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 7fc59f65c..3c6bd1c98 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -866,6 +866,10 @@ export function migrateDesktopGfsUploadState(value: unknown): {}}+export interface AppServiceOptions {+ tokenStore?: TokenStore+}+export class AppService {private readonly authClient = new AuthClient()private readonly memberRegistrationServiceClient = new MemberRegistrationServiceClient()@@ -878,7 +882,7 @@ export class AppService {requestJson,fetchBytes: (url, token, opts) => fetchBoundedBytes(url, token, opts),})- private readonly tokenStore = new TokenStore()+ private readonly tokenStore: TokenStoreprivate readonly rpcTokenManager = new RpcTokenManager(this.authClient)private sessionToken: string | null = nullprivate me: SessionMe | null = null@@ -974,6 +978,10 @@ export class AppService {{ ownerId: number; stop: (opts?: { silent?: boolean }) => void }>()+ constructor(options: AppServiceOptions = {}) {+ this.tokenStore = options.tokenStore ?? new TokenStore()+ }+private static dedupe(values: string[]): string[] {return Array.from(new Set(values.map(value => String(value || '').trim()).filter(Boolean)))}diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.tsindex 6e49c7527..170f0b462 100644--- a/desktop-app/src/main.ts+++ b/desktop-app/src/main.ts@@ -35,6 +35,7 @@ import {import { shouldAcceptSandboxUiProtocolLink } from './sandboxUiProtocolWindowPolicy.js'import { wireHostDesktopShortcutRouting } from './shortcutRouter.js'import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.js'+import { TokenStore } from './tokenStore.js'const EVENFIRE_APP_NAME = 'Evenfire'const EVENFIRE_APP_ID = 'ai.evenfire.desktop'@@ -63,7 +64,11 @@ process.stdout?.on?.('error', () => {})process.stderr?.on?.('error', () => {})let mainWindow: BrowserWindow | null = null-const appService = new AppService()+const appService = new AppService(+ devIsolationPlan+ ? { tokenStore: new TokenStore({ isolatedUserDataPath: devIsolationPlan.userDataDir }) }+ : {}+)const sandboxUiDeepLinkQueue = new SandboxUiDeepLinkQueue()// U5: deliver mcp-oauth completions to the renderer, or queue them when the// renderer is not yet ready (cold start), draining after `app:rendererReady`.diff --git a/desktop-app/src/tokenStore.ts b/desktop-app/src/tokenStore.tsindex 12a369b21..8d728fa4a 100644--- a/desktop-app/src/tokenStore.ts+++ b/desktop-app/src/tokenStore.ts@@ -55,6 +55,16 @@ function isKeytarModule(value: unknown): value is KeytarModule {)}+export type TokenStoreOptions = {+ /**+ * Development-isolation contract. The constructor only validates the declared+ * path; every operation verifies it against Electron's actual ready userData+ * directory before touching files. Isolated storage never uses keytar or the+ * shared home-directory fallback.+ */+ isolatedUserDataPath?: string+}+async function loadKeytar(): Promise<KeytarModule | null> {try {const mod = await import('keytar')@@ -71,6 +81,10 @@ async function loadKeytar(): Promise<KeytarModule | null> {}}+async function realPath(value: string): Promise<string> {+ return fs.realpath(value)+}+async function resolvedStorageBase(): Promise<string> {const base = app?.isReady() ? app.getPath('userData') : path.join(os.homedir(), '.evenfire')await fs.mkdir(base, { recursive: true })@@ -142,6 +156,41 @@ async function removeTokenFileDurably(filePath: string): Promise<void> {}export class TokenStore {+ private readonly isolatedUserDataPath: string | undefined++ constructor(options: TokenStoreOptions = {}) {+ const isolatedUserDataPath = options.isolatedUserDataPath+ if (+ isolatedUserDataPath !== undefined &&+ (!isolatedUserDataPath || !path.isAbsolute(isolatedUserDataPath))+ ) {+ throw new Error('Isolated token storage requires an absolute userData path')+ }+ this.isolatedUserDataPath = isolatedUserDataPath+ }++ private async verifiedStorageBase(): Promise<string> {+ if (this.isolatedUserDataPath === undefined) return resolvedStorageBase()+ if (!app?.isReady()) throw new Error('Isolated token storage requires Electron readiness')+ const actual = await realPath(app.getPath('userData'))+ const declared = await realPath(this.isolatedUserDataPath)+ if (actual !== declared) throw new Error('Isolated token storage directory mismatch')+ await fs.mkdir(actual, { recursive: true })+ return actual+ }++ private async encryptedFilePath(envKey: string): Promise<string> {+ const key = String(envKey || '').trim()+ const name = key ? `session-token-${key}.enc` : 'session-token.enc'+ return path.join(await this.verifiedStorageBase(), name)+ }++ private async plainFilePath(envKey: string): Promise<string> {+ const key = String(envKey || '').trim()+ const name = key ? `session-token-${key}.json` : 'session-token.json'+ return path.join(await this.verifiedStorageBase(), name)+ }+/*** Read the session token for `envKey`. Falls back keytar → safeStorage file,* optional older env-key aliases, then does a one-time best-effort migration@@ -157,8 +206,9 @@ export class TokenStore {options: { legacyEnvKeys?: readonly string[] } = {}): Promise<string | null> {assertEnvKey(envKey)+ if (this.isolatedUserDataPath !== undefined) await this.verifiedStorageBase()const account = accountFor(envKey)- const keytar = await loadKeytar()+ const keytar = this.isolatedUserDataPath === undefined ? await loadKeytar() : nullif (keytar) {try {const stored = await keytar.getPassword(SERVICE, account)@@ -171,7 +221,7 @@ export class TokenStore {if (app?.isReady() && safeStorage.isEncryptionAvailable()) {try {- const file = await encryptedFilePath(envKey)+ const file = await this.encryptedFilePath(envKey)const encrypted = await fs.readFile(file)return safeStorage.decryptString(encrypted)} catch {@@ -183,7 +233,7 @@ export class TokenStore {// per-env plain-text file — read it back symmetrically before falling// through to the one-time legacy-global migration.try {- const file = await plainFilePath(envKey)+ const file = await this.plainFilePath(envKey)const raw = await fs.readFile(file, 'utf8')const data = JSON.parse(raw) as { token?: unknown }if (typeof data.token === 'string' && data.token) return data.token@@ -198,7 +248,10 @@ export class TokenStore {)if (migratedScopedToken) return migratedScopedToken- return this.migrateLegacyGlobalToken(envKey, keytar)+ if (this.isolatedUserDataPath === undefined) {+ return this.migrateLegacyGlobalToken(envKey, keytar)+ }+ return null}/**@@ -234,7 +287,7 @@ export class TokenStore {if (app?.isReady() && safeStorage.isEncryptionAvailable()) {try {- const file = await encryptedFilePath(legacyEnvKey)+ const file = await this.encryptedFilePath(legacyEnvKey)const encrypted = await fs.readFile(file)const token = safeStorage.decryptString(encrypted)if (token) {@@ -248,7 +301,7 @@ export class TokenStore {}try {- const file = await plainFilePath(legacyEnvKey)+ const file = await this.plainFilePath(legacyEnvKey)const raw = await fs.readFile(file, 'utf8')const data = JSON.parse(raw) as { token?: unknown }const token = typeof data.token === 'string' && data.token ? data.token : null@@ -322,8 +375,9 @@ export class TokenStore {async setSessionToken(token: string, envKey: string): Promise<void> {assertEnvKey(envKey)+ if (this.isolatedUserDataPath !== undefined) await this.verifiedStorageBase()const account = accountFor(envKey)- const keytar = await loadKeytar()+ const keytar = this.isolatedUserDataPath === undefined ? await loadKeytar() : nullif (keytar) {try {await keytar.setPassword(SERVICE, account, token)@@ -334,12 +388,12 @@ export class TokenStore {}if (app?.isReady() && safeStorage.isEncryptionAvailable()) {- const file = await encryptedFilePath(envKey)+ const file = await this.encryptedFilePath(envKey)await writeTokenFileAtomic(file, safeStorage.encryptString(token))return}- const file = await plainFilePath(envKey)+ const file = await this.plainFilePath(envKey)await writeTokenFileAtomic(file, JSON.stringify({ token }))}@@ -348,6 +402,7 @@ export class TokenStore {options: { legacyEnvKeys?: readonly string[] } = {}): Promise<void> {assertEnvKey(envKey)+ if (this.isolatedUserDataPath !== undefined) await this.verifiedStorageBase()const legacyEnvKeys = Array.from(new Set((options.legacyEnvKeys ?? [])@@ -357,7 +412,7 @@ export class TokenStore {)for (const legacyEnvKey of legacyEnvKeys) assertEnvKey(legacyEnvKey)const scopedEnvKeys = [envKey, ...legacyEnvKeys]- const keytar = await loadKeytar()+ const keytar = this.isolatedUserDataPath === undefined ? await loadKeytar() : nullif (keytar) {const deleteKeychainPassword = async (account: string) => {try {@@ -375,15 +430,22 @@ export class TokenStore {}// Always clean up file-based storage regardless of keychain result,// since prior versions may have written both stores.- await Promise.all([+ const scopedFileRemovals = [...scopedEnvKeys.flatMap(scopedEnvKey => [- encryptedFilePath(scopedEnvKey)+ this.encryptedFilePath(scopedEnvKey).then(file => fs.unlink(file)).catch(() => {}),- plainFilePath(scopedEnvKey)+ this.plainFilePath(scopedEnvKey).then(file => fs.unlink(file)).catch(() => {}),]),+ ]+ if (this.isolatedUserDataPath !== undefined) {+ await Promise.all(scopedFileRemovals)+ return+ }+ await Promise.all([+ ...scopedFileRemovals,legacyEncryptedFilePath().then(file => fs.unlink(file)).catch(() => {}),diff --git a/desktop-app/test/e2e-playwright/gfs-agent-large-file-cli.test.ts b/desktop-app/test/e2e-playwright/gfs-agent-large-file-cli.test.tsindex 14170997f..87ce70e7d 100644--- a/desktop-app/test/e2e-playwright/gfs-agent-large-file-cli.test.ts+++ b/desktop-app/test/e2e-playwright/gfs-agent-large-file-cli.test.ts@@ -5,28 +5,26 @@* E2E contract (e2e-test-guardian):* - Real user journey: login → Files → visible upload of an exact 3,836,961-byte* CSV → exact managed agent chat → governed download → user-visible- * `shell_exec` approval → completed tool stepper and bounded response.+ * attended shell approval → completed tool stepper and bounded response.* - Business signals: the download step reports a workspace file; the approved- * Node command reports the independently generated CSV record count and a- * sentinel located beyond the former 3 MiB boundary.+ * generated program reports the independent data-record count and columns,+ * plus the last record ID beyond the former 3 MiB boundary.* - Setup shortcuts: managed agent/folder fixture seeding and the local CSV* file are named preconditions. No provider-route mock, storage mutation,* direct API trigger, or broad network mock is used.*/import { type Locator, type Page, expect, test } from '@playwright/test'-import { randomUUID } from 'node:crypto'import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { getGfsChildResourceSummary, getGfsGrantSummary } from '../../../tests/e2e/gfsUiFixtures'import { exactNameFilter } from './helpers/agentLocators'-import { type ManagedGfsAgent, getManagedAgentDisplayName } from './helpers/gfsAgentDiscovery'+import { getManagedAgentDisplayName } from './helpers/gfsAgentDiscovery'import { assertGfsInfraHealthy } from './helpers/gfsFixtures'import {type AgentGfsLargeFileFixtures,seedAgentGfsLargeFileFixtures,} from './helpers/gfsLargeFileAgentFixture'-import { largeCsvProofCommand, largeCsvProofProgram } from './helpers/gfsLargeFileCliCommand'import {GFS_LARGE_CSV_SIZE,GFS_OLD_VISUAL_LIMIT,@@ -39,7 +37,6 @@ import { launchAndLogin } from './workflowUi'const OWNER_EMAIL = '[email protected]'const RESPONSE_TIMEOUT_MS = 420_000const PROGRESS_TIMEOUT_MS = 45_000-const runToken = `GFS-LARGE-CLI-${randomUUID()}`async function enterAgentChat(page: Page, agentName: string): Promise<void> {await openAgentsPage(page)@@ -63,13 +60,13 @@ async function enterAgentChat(page: Page, agentName: string): Promise<void> {})}-async function sendTaskAndApproveShell(+async function sendTaskAndWaitForReviewedShell(page: Page,prompt: string,resourceId: string,sourceMode: 'path' | 'reference'): Promise<{ response: Locator; expandButton: Locator }> {- const response = page.getByTestId('agent-response').filter({ hasText: runToken })+ const response = page.getByTestId('agent-response')const approval = page.getByTestId('approval-approve-btn')await page.getByTestId('chat-input').fill(prompt)@@ -79,17 +76,15 @@ async function sendTaskAndApproveShell(await expect(approval).toBeVisible({ timeout: 10_000 })const stepper = page.getByTestId('progress-stepper').filter({ has: approval })await expect(stepper).toBeVisible({ timeout: 10_000 })- await expect(stepper).toContainText('shell_exec')+ await expect(stepper).toContainText('Shell requires approval')const commandPreview = stepper.getByTestId('approval-input-preview')await expect(commandPreview).toBeVisible()- await expect(commandPreview).toContainText('node')- await expect(commandPreview).toContainText('createHash')await expect(commandPreview).toContainText('.gfs-downloads/')await expect(stepper.getByRole('note')).toHaveCount(0)const details = stepper.getByRole('button', { name: /More details/ })await expect(details).toBeVisible()await details.click()- const downloaded = completedToolStepRow(page, 'gfs_download')+ const downloaded = completedToolStepRow(page, /gfs_download|gfs_read/)let receiptPath: stringif (sourceMode === 'path') {await expect(downloaded).toHaveCount(1)@@ -112,26 +107,31 @@ async function sendTaskAndApproveShell(expect(path).toBeTruthy()receiptPath = path!}- await expect(commandPreview).toHaveText(largeCsvProofCommand(runToken, receiptPath))+ await expect(commandPreview).toContainText(receiptPath)await expect(completedToolStepRow(page, 'shell_exec')).toHaveCount(0)- await approval.click()- await expect(approval).toHaveCount(0, { timeout: PROGRESS_TIMEOUT_MS })-- await expect(response).toContainText(/ROWS=/, { timeout: RESPONSE_TIMEOUT_MS })- await expect(response).toContainText(/PROOF=[0-9a-f]{16}/, {+ // The agent creates its own program from the normal business request. A+ // reviewer inspects the complete visible command and approves once in the+ // UI; keyword matching cannot authorize arbitrary generated code.+ await test.info().attach('attended-shell-review-required', {+ contentType: 'text/plain',+ body: 'Review the complete command and referenced script, verify read-only access to this receipt and bounded summary output, then approve once in the owned Desktop window.',+ })+ await expect(approval).toHaveCount(0, { timeout: RESPONSE_TIMEOUT_MS })+ await expect(completedToolStepRow(page, 'shell_exec')).toHaveCount(1, {timeout: RESPONSE_TIMEOUT_MS,})+ await expect(response).toBeVisible({ timeout: RESPONSE_TIMEOUT_MS })const expandButton = page.getByTestId('progress-expand-btn')await expect(expandButton).toHaveCount(1, { timeout: PROGRESS_TIMEOUT_MS })await expect(expandButton).toBeVisible({ timeout: PROGRESS_TIMEOUT_MS })return { response, expandButton }}-function toolStepRow(page: Page, toolName: string): Locator {+function toolStepRow(page: Page, toolName: string | RegExp): Locator {return page.getByTestId(/^step-row-/).filter({ hasText: toolName })}-function completedToolStepRow(page: Page, toolName: string): Locator {+function completedToolStepRow(page: Page, toolName: string | RegExp): Locator {return toolStepRow(page, toolName).filter({has: page.locator('.stepper-step-duration.state-completed'),})@@ -150,7 +150,11 @@ async function stepOutput(row: Locator): Promise<Locator> {return output}-test.describe('GFS agent large-file CLI journey', () => {+test.describe('GFS large-file business analysis with attended approval', () => {+ test.skip(+ process.env.E2E_GFS_ATTENDED_APPROVAL !== '1',+ 'Real-provider acceptance requires a reviewer for the agent-generated shell command.'+ )test.describe.configure({ mode: 'serial' })// Both the provider's approval request and its resumed answer have a bounded// deadline; the default Desktop test timeout must not close Electron first.@@ -188,10 +192,14 @@ test.describe('GFS agent large-file CLI journey', () => {})for (const sourceMode of ['path', 'reference'] as const) {- test(`user uploads a 3.8 MiB CSV and approves local processing via ${sourceMode}`, async () => {+ test(`user asks for CSV record count and columns via ${sourceMode}`, async () => {const { app, page } = await launchAndLogin(OWNER_EMAIL)+ const desktopContext = app.context()+ let ownedTraceStarted = falselet sourceBefore: NonNullable<ReturnType<typeof getGfsChildResourceSummary>>try {+ await desktopContext.tracing.start({ screenshots: true, snapshots: true, sources: false })+ ownedTraceStarted = trueawait test.step('user uploads the exact CSV through Files', async () => {await openResourcesNavItem(page, 'nav-files')await expect(page.getByRole('heading', { name: 'Files', exact: true })).toBeVisible()@@ -268,15 +276,14 @@ test.describe('GFS agent large-file CLI journey', () => {}const prompt =(sourceMode === 'path'- ? `Download "/${fixtures.granted.name}/${csv.fileName}" from GFS drive main with clerum__gfs_download. `- : 'Process the attached file using the ready workspace receipt prepared by the Host. ') +- 'Do not print or file_read the whole file. Use exactly one approved shell_exec ' +- 'Node.js command with the receipt path as an argument. Count complete CSV records including the header, ' +- 'never raw newlines. Use exactly this read-only program, preserving its single-quoted shell argument and all bytes: ' +- `node -e '${largeCsvProofProgram(runToken)}' '<receipt path>'. ` +- 'Replace only <receipt path> with the relative path from the successful download receipt. ' +- `Return the command stdout unchanged: RUN=${runToken} ROWS=<record count> PROOF=<16 hex characters>.`- const result = await sendTaskAndApproveShell(+ ? `Analiza el CSV "${csv.fileName}" de la carpeta "${fixtures.granted.name}" en EvenDrive. `+ : 'Analiza el CSV que adjunté. ') ++ 'Dime cuántos registros de datos contiene, sin contar la cabecera, y cuáles son sus columnas. ' ++ (csv.source === 'synthetic'+ ? 'Incluye también el identificador del último registro. '+ : '') ++ 'Mantén el archivo original sin cambios y responde con un resumen breve.'+ const result = await sendTaskAndWaitForReviewedShell(page,prompt,sourceBefore.resourceId,@@ -289,12 +296,12 @@ test.describe('GFS agent large-file CLI journey', () => {await test.step('tool stepper proves governed transfer and local execution', async () => {if ((await expandButton.getAttribute('aria-expanded')) === 'false')await expandButton.click()- const downloadRow = completedToolStepRow(page, 'gfs_download')+ const downloadRow = completedToolStepRow(page, /gfs_download|gfs_read/)await expect(downloadRow).toHaveCount(sourceMode === 'path' ? 1 : 0, { timeout: 15_000 })if (sourceMode === 'path') {await expect(downloadRow).toBeVisible({ timeout: 15_000 })await expect(downloadRow.locator('.stepper-step-duration.state-error')).toHaveCount(0)- await expect(downloadRow).toContainText('gfs_download')+ await expect(downloadRow).toContainText(/gfs_download|gfs_read/)} else {await expect(toolStepRow(page, 'gfs_download')).toHaveCount(0)await expect(toolStepRow(page, 'gfs_read')).toHaveCount(0)@@ -305,13 +312,18 @@ test.describe('GFS agent large-file CLI journey', () => {await expect(shellRow).toBeVisible({ timeout: 15_000 })await expect(shellRow.locator('.stepper-step-duration.state-error')).toHaveCount(0)const shellOutput = await stepOutput(shellRow)- const expectedRows = new RegExp(`\\bROWS=${csv.recordCount}(?=\\s|$)`)- const expectedProof = new RegExp(`\\bPROOF=${csv.tailProof}(?=\\s|$)`)+ const count = String(csv.recordCount - 1)+ const expectedRows = new RegExp(`(?<![0-9])${count.split('').join('[.,\\s]*')}(?![0-9])`)await expect(shellOutput).toContainText(expectedRows)- await expect(shellOutput).toContainText(expectedProof)-- await expect(response).toContainText(expectedRows)- await expect(response).toContainText(expectedProof)+ await expect(response).toContainText(expectedRows, { timeout: RESPONSE_TIMEOUT_MS })+ if (csv.source === 'synthetic') {+ for (const column of ['id', 'record name', 'notes,value', 'value']) {+ await expect(shellOutput).toContainText(column)+ await expect(response).toContainText(column)+ }+ await expect(shellOutput).toContainText('record-final')+ await expect(response).toContainText('record-final')+ }await expect(response).not.toContainText('zzzzzzzzzz')})@@ -335,14 +347,37 @@ test.describe('GFS agent large-file CLI journey', () => {// Capture the owned test window while it is still alive. Automatic// post-test screenshots cannot recover a window already closed here.if (!page.isClosed()) {- await test.info().attach('large-file-desktop-failure', {- contentType: 'image/png',- body: await page.screenshot(),- })+ try {+ await test.info().attach('large-file-desktop-failure', {+ contentType: 'image/png',+ body: await page.screenshot({ timeout: 5_000 }),+ })+ } catch {+ // A stalled renderer must not replace the original journey error.+ await test.info().attach('large-file-screenshot-unavailable', {+ contentType: 'text/plain',+ body: 'The owned Electron window did not produce a screenshot within five seconds.',+ })+ }}throw error} finally {- await app.close()+ try {+ if (ownedTraceStarted) {+ try {+ await desktopContext.tracing.stop({+ path: test.info().outputPath('large-file-electron-context-trace.zip'),+ })+ } catch {+ await test.info().attach('large-file-context-trace-unavailable', {+ contentType: 'text/plain',+ body: 'The owned Electron context did not save its diagnostic trace.',+ })+ }+ }+ } finally {+ await app.close()+ }}})}diff --git a/desktop-app/test/e2e-playwright/workflowUi.ts b/desktop-app/test/e2e-playwright/workflowUi.tsindex 405565c31..660f70587 100644--- a/desktop-app/test/e2e-playwright/workflowUi.ts+++ b/desktop-app/test/e2e-playwright/workflowUi.ts@@ -1,3 +1,6 @@+// E2E_GUARDIAN_IPC_FLOW: Desktop login and business interactions delegate their+// requests to Electron's main process. Readiness is asserted through visible+// identity and page state; renderer HTTP aliases do not observe these requests.import {type ElectronApplication,type Locator,@@ -11,7 +14,9 @@ import fs from 'node:fs'import http from 'node:http'import os from 'node:os'import path from 'node:path'+import { pathToFileURL } from 'node:url'import { E2E_TEST_EMAIL } from '../../../tests/e2e/testUser'+import { DEV_ISOLATION_ENV, devIsolationPaths } from '../../src/devIsolation'import type {PendingWorkflowApproval,WorkflowRecipeListResult,@@ -263,27 +268,13 @@ export async function apiRequest(throw new Error('apiRequest retry loop exhausted')}-export async function clearSession() {- try {- execFileSync('security', ['delete-generic-password', '-s', 'Evenfire', '-a', 'session-token'], {- encoding: 'utf-8',- timeout: 5_000,- })- } catch {- // The keychain item may not exist on a fresh machine.- }- const sessionFile = path.join(os.homedir(), '.evenfire', 'session-token.json')- try {- fs.unlinkSync(sessionFile)- } catch {- // The session file may not exist on a fresh machine.- }- const sessionEncFile = path.join(os.homedir(), '.clerum-desktop', 'session-token.enc')- try {- fs.unlinkSync(sessionEncFile)- } catch {- // The encrypted session file may not exist on a fresh machine.- }+/**+ * @deprecated launchAndLogin creates a fresh isolated profile for every run.+ * Retain this non-destructive entry point for existing specs; clearing a global+ * keychain account or home-directory session would affect the official app.+ */+export async function clearSession(): Promise<void> {+ // A fresh per-run profile replaces global cleanup. No shared state is read.}export async function loginAs(@@ -525,48 +516,65 @@ export async function launchAndLogin(email = E2E_EMAIL): Promise<{ app: ElectronApplication; page: Page }> {assertDesktopBuildMatchesSource()- await clearSession()await loginAs(email)- const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-e2e-electron-'))+ const runDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'evenfire-e2e-isolated-')))+ const isolatedPaths = devIsolationPaths(runDir)+ fs.mkdirSync(isolatedPaths.userDataDir, { mode: 0o700 })+ const compiledAppPath = fs.realpathSync(path.join(DESKTOP_APP_ROOT, 'dist'))+ const rpcUrl = process.env.RPC_PROXY_BASE_URL || 'http://127.0.0.1:8094'let app: ElectronApplicationtry {app = await electron.launch({- args: [`--user-data-dir=${userDataDir}`, path.resolve(__dirname, '../../dist/main.js')],+ args: [`--user-data-dir=${isolatedPaths.userDataDir}`, path.join(compiledAppPath, 'main.js')],env: {...process.env,+ EVENFIRE_DEV_ISOLATION: '1',+ [DEV_ISOLATION_ENV.runDir]: runDir,+ [DEV_ISOLATION_ENV.restUrl]: EXT_API,+ [DEV_ISOLATION_ENV.rpcUrl]: rpcUrl,+ [DEV_ISOLATION_ENV.target]: path.basename(runDir),+ [DEV_ISOLATION_ENV.appPath]: compiledAppPath,+ [DEV_ISOLATION_ENV.pr]: process.env.E2E_DESKTOP_PR_NUMBER || '',EVENFIRE_RENDERER_URL: '',EXTERNAL_REST_API_BASE_URL: EXT_API,- RPC_PROXY_BASE_URL: process.env.RPC_PROXY_BASE_URL || 'http://127.0.0.1:8094',- // Isolate the desktop runtime-config from the global appData profile- // store. Without this, a stale persisted profile (e.g. a prior run's- // random port-forward) is auto-activated and overrides the injected- // localhost URLs, so login fetches a dead port (ECONNREFUSED). Pointing- // at a non-existent file in the per-test userDataDir yields zero stored- // profiles, so the app falls back to the localhost/env config. No-op in- // CI (clean appData); fixes local runs polluted by a real desktop login.- CLERUM_DESKTOP_CONFIG_PATH:- process.env.CLERUM_DESKTOP_CONFIG_PATH ||- path.join(userDataDir, 'e2e-runtime-config.json'),+ RPC_PROXY_BASE_URL: rpcUrl,+ CLERUM_DESKTOP_CONFIG_PATH: isolatedPaths.configPath,},})} catch (error) {- fs.rmSync(userDataDir, { recursive: true, force: true })+ fs.rmSync(runDir, { recursive: true, force: true })throw error}- app.on('close', () => fs.rmSync(userDataDir, { recursive: true, force: true }))+ app.on('close', () => fs.rmSync(runDir, { recursive: true, force: true }))const page = await app.firstWindow()await page.waitForLoadState('domcontentloaded')+ try {+ // These are public process identities, never credentials or environment+ // dumps. Refuse an installed app, another checkout or a shared profile.+ const runtime = await app.evaluate(({ app }) => ({+ executablePath: process.execPath,+ appPath: app.getAppPath(),+ userData: app.getPath('userData'),+ isPackaged: app.isPackaged,+ }))+ const verifiedElectronPath = require('electron') as unknown as string+ expect(fs.realpathSync(runtime.executablePath)).toBe(fs.realpathSync(verifiedElectronPath))+ expect(fs.realpathSync(runtime.appPath)).toBe(compiledAppPath)+ expect(fs.realpathSync(runtime.userData)).toBe(fs.realpathSync(isolatedPaths.userDataDir))+ expect(runtime.isPackaged).toBe(false)+ expect(page.url()).toBe(pathToFileURL(path.join(DESKTOP_APP_ROOT, 'ui-dist/index.html')).href)+ } catch (error) {+ await app.close().catch(() => undefined)+ throw error+ }+const emailInput = page.locator('#email-input')const passwordInput = page.locator('#password-input')const settingsMenuButton = page.getByTestId('nav-settings-menu')- const authenticatedShell = page- .getByTestId('nav-chat')- .or(settingsMenuButton)- .or(page.getByTestId('notification-bell'))- .first()+ const authenticatedShell = settingsMenuButtonconst userDisplayName = page.getByTestId('user-display-name')try {@@ -638,7 +646,7 @@ export async function launchAndLogin(identityVerified = true} catch {await page.keyboard.press('Escape')- await page.waitForTimeout(1_000)+ await expect(signedInAccount).toBeHidden({ timeout: 7_000 })}}// The account section inside the popover resolves from its own fetch,@@ -671,7 +679,7 @@ export async function openWorkflowsPage(page: Page): Promise<void> {export async function expectWorkflowsPageShell(page: Page): Promise<void> {const currentDesktopShell = page.getByRole('heading', { name: 'Plugins', exact: true })const currentDashboardShell = page.getByRole('heading', { name: /Workflow Recipes/ })- await expect(currentDesktopShell.or(currentDashboardShell).first()).toBeVisible({+ await expect(currentDesktopShell.or(currentDashboardShell)).toBeVisible({timeout: 15_000,})}@@ -679,8 +687,7 @@ export async function expectWorkflowsPageShell(page: Page): Promise<void> {export function workflowRow(page: Page, workflowName: string) {return page.locator('.workflows-list-card .da-grid__row')- .filter({ hasText: workflowName })- .first()+ .filter({ has: page.getByText(workflowName, { exact: true }) })}export async function selectWorkflow(diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 7a702113a..3d9a15dd4 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.486",+ "version": "0.1.487","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.486",+ "version": "0.1.487","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 668c9959f..edc364693 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.486",+ "version": "0.1.487","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/internalTools/gfs.ts b/mcp-host/src/internalTools/gfs.tsindex 6c7ca0e75..6e411c376 100644--- a/mcp-host/src/internalTools/gfs.ts+++ b/mcp-host/src/internalTools/gfs.ts@@ -252,6 +252,28 @@ const driveResourceParams = {},} as const+const DOWNLOAD_RESOURCE_ID_PATTERN =+ '^(?:[0-9a-fA-F]{32}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$'+const DOWNLOAD_RESOURCE_ID = new RegExp(DOWNLOAD_RESOURCE_ID_PATTERN)+const downloadDriveResourceParams = {+ ...driveResourceParams,+ properties: {+ ...driveResourceParams.properties,+ resourceId: {+ ...driveResourceParams.properties.resourceId,+ pattern: DOWNLOAD_RESOURCE_ID_PATTERN,+ },+ },+} as const++function downloadTargetError(args: Record<string, unknown>): string | null {+ if (typeof args.drive !== 'string' || args.drive.length === 0)+ return 'drive must be the non-empty GFS drive name returned by discovery.'+ if (typeof args.resourceId !== 'string' || !DOWNLOAD_RESOURCE_ID.test(args.resourceId))+ return 'resourceId must be the observed 32-hex or dashed UUID from clerum__gfs_accessible/clerum__gfs_list; filenames, paths, and gfs:// URIs are not resource IDs.'+ return null+}+/*** #666 — the version a file reference of the turn's message pins, and the* version gfsc reported instead when the reference was stale.@@ -653,9 +675,9 @@ export function buildGfsReadTools(description:'Download a GFS file to this caller workspace without putting its contents in model context. Returns source metadata, SHA-256, exact size, version, expiry, and a relative workspace path for approved local processing.',parameters: {- ...driveResourceParams,+ ...downloadDriveResourceParams,properties: {- ...driveResourceParams.properties,+ ...downloadDriveResourceParams.properties,expectedVersion: {type: 'integer',minimum: 0,@@ -664,6 +686,8 @@ export function buildGfsReadTools(},},execute: async (args, _outputDir, options): Promise<InternalToolResult> => {+ const inputError = downloadTargetError(args)+ if (inputError) return invalidArgs(inputError)const { expectedVersion: requestedVersion, ...target } = argsif (requestedVersion !== undefined && !isValidIfMatch(requestedVersion))return invalidArgs('expectedVersion must be a non-negative integer.')diff --git a/mcp-host/src/internalTools/gfsDownloadDiagnostics.test.ts b/mcp-host/src/internalTools/gfsDownloadDiagnostics.test.tsindex 5f50067ac..fcdec1ebb 100644--- a/mcp-host/src/internalTools/gfsDownloadDiagnostics.test.ts+++ b/mcp-host/src/internalTools/gfsDownloadDiagnostics.test.ts@@ -98,15 +98,15 @@ describe('GFS download failure diagnostics', () => {{ drive: 'main/private', resourceId: 'gfs://main/private' },{ drive: 'a'.repeat(65), resourceId: '/unit-only/private/path' },{ drive: 'main\n', resourceId: `${target.resourceId}\n` },- ])('omits unsafe or unbounded target identifiers: %j', async args => {+ ])('rejects unsafe or unbounded targets before diagnostics: %j', async args => {const { tool, download } = harness()- download.mockRejectedValue(new Error(`gfsc 403: ${privateDetail}`))- await tool.execute(args, '/unit-only-output-path')+ const result = await tool.execute(args, '/unit-only-output-path')- expect(vi.mocked(logger.warn).mock.calls).toEqual([- [{ component: 'GfsDownload', httpStatus: 403, errorClass: 'Error' }, warningMessage],- ])+ expect(result.success).toBe(false)+ expect(result.error).not.toContain(privateDetail)+ expect(download).not.toHaveBeenCalled()+ expect(logger.warn).not.toHaveBeenCalled()})it('does not trust arbitrary status, name or code fields, or an HTTP phrase inside the body', async () => {diff --git a/mcp-host/src/internalTools/gfsLargeFile.test.ts b/mcp-host/src/internalTools/gfsLargeFile.test.tsindex f679a085f..da1a1892f 100644--- a/mcp-host/src/internalTools/gfsLargeFile.test.ts+++ b/mcp-host/src/internalTools/gfsLargeFile.test.ts@@ -64,6 +64,16 @@ function fakeDownloadStore(): GfsDownloadStore {} as unknown as GfsDownloadStore}+function spyDownloadStore() {+ return {+ reusableReceipt: vi.fn(),+ createTransfer: vi.fn(),+ publish: vi.fn(),+ fail: vi.fn(),+ readManagedFilePrefix: vi.fn(),+ }+}+describe('GFS large-file tool routing', () => {it('does not expose generic workspace delivery without a store', () => {expect(@@ -184,6 +194,88 @@ describe('GFS large-file tool routing', () => {)})+ it.each([+ ['path', { drive: 'main', resourceId: '/private/path/input.csv' }],+ ['GFS URI', { drive: 'main', resourceId: `gfs://main/${target.resourceId}` }],+ ['missing resourceId', { drive: 'main' }],+ ['invalid resourceId', { drive: 'main', resourceId: 'input.csv' }],+ [+ 'malformed hyphen groups',+ { drive: 'main', resourceId: `${'a'.repeat(8)}-${'b'.repeat(24)}` },+ ],+ ])('rejects a %s before client or store work', async (_kind, args) => {+ const download = vi.fn()+ const store = spyDownloadStore()+ const gfs = client({ download })+ const tool = buildGfsReadTools(gfs, {+ referencedFiles: new Map(),+ downloadStore: store as unknown as GfsDownloadStore,+ callerIdentity: 'caller-a',+ callerWorkspacePath: callerWorkspace,+ }).find(item => item.name === 'clerum__gfs_download')!+ const properties = tool.parameters.properties as {+ resourceId: { pattern?: string }+ }++ const result = await tool.execute(args, '/tmp')++ const pattern = new RegExp(String(properties.resourceId.pattern))+ expect(pattern.test(target.resourceId)).toBe(true)+ expect(pattern.test('AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA')).toBe(true)+ expect(pattern.test(`${'a'.repeat(8)}-${'b'.repeat(24)}`)).toBe(false)+ expect(result).toEqual({+ success: false,+ error:+ 'resourceId must be the observed 32-hex or dashed UUID from clerum__gfs_accessible/clerum__gfs_list; filenames, paths, and gfs:// URIs are not resource IDs.',+ })+ expect(download).not.toHaveBeenCalled()+ expect(gfs.accessible).not.toHaveBeenCalled()+ expect(gfs.list).not.toHaveBeenCalled()+ expect(gfs.read).not.toHaveBeenCalled()+ expect(gfs.readMetadata).not.toHaveBeenCalled()+ expect(gfs.stat).not.toHaveBeenCalled()+ expect(gfs.resolve).not.toHaveBeenCalled()+ expect(store.reusableReceipt).not.toHaveBeenCalled()+ expect(store.createTransfer).not.toHaveBeenCalled()+ expect(store.publish).not.toHaveBeenCalled()+ expect(store.fail).not.toHaveBeenCalled()+ })++ it('keeps dashed UUID input working', async () => {+ const dashed = [+ target.resourceId.slice(0, 8),+ target.resourceId.slice(8, 12),+ target.resourceId.slice(12, 16),+ target.resourceId.slice(16, 20),+ target.resourceId.slice(20),+ ]+ .join('-')+ .toUpperCase()+ const download = vi.fn(async () => ({+ id: 'download-dashed',+ source,+ path: '.gfs-downloads/download-dashed/source',+ sizeBytes: 1,+ sha256: 'd'.repeat(64),+ expiresAt: '2026-10-08T00:00:00.000Z',+ }))+ const store = spyDownloadStore()+ const tool = buildGfsReadTools(client({ download }), {+ referencedFiles: new Map(),+ downloadStore: store as unknown as GfsDownloadStore,+ callerIdentity: 'caller-a',+ callerWorkspacePath: callerWorkspace,+ }).find(item => item.name === 'clerum__gfs_download')!++ const { outcome } = await result(tool, { drive: target.drive, resourceId: dashed })++ expect(outcome.success).toBe(true)+ expect(download).toHaveBeenCalledWith(+ { drive: target.drive, resourceId: dashed },+ expect.objectContaining({ store, callerIdentity: 'caller-a' })+ )+ })+it.each([['binary', Buffer.from([0xff, 0x00, 0xfe, 0x01])],['SVG', Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"></svg>')],