Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): R1-M4 make token migration crash durable
Josué6abc7c9c2f32
diff --git a/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts b/desktop-app/src/__tests__/tokenStore.plainFallback.test.tsindex c8f4d24ad..0c81dad1f 100644--- a/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts+++ b/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts@@ -52,14 +52,14 @@ describe('TokenStore plain-text fallback (no keytar, no safeStorage)', () => {const legacyFile = path.join(userDataDir, 'session-token.json')const scopedFile = path.join(userDataDir, `session-token-${ENV_A}.json`)await fs.writeFile(legacyFile, JSON.stringify({ token: 'legacy-token' }))- const originalWriteFile = fs.writeFile.bind(fs)- vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {- if (String(args[0]) === scopedFile) {+ const originalRename = fs.rename.bind(fs)+ vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {+ if (String(to) === scopedFile) {const error = new Error('disk full') as NodeJS.ErrnoExceptionerror.code = 'ENOSPC'throw error}- return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))+ return originalRename(from, to)})await expect(new TokenStore().getSessionToken(ENV_A)).resolves.toBeNull()@@ -68,6 +68,35 @@ describe('TokenStore plain-text fallback (no keytar, no safeStorage)', () => {token: 'legacy-token',})await expect(fs.access(scopedFile)).rejects.toMatchObject({ code: 'ENOENT' })+ expect((await fs.readdir(userDataDir)).filter(name => name.endsWith('.tmp'))).toEqual([])+ })++ it('flushes the scoped token file and parent directory before acknowledging persistence', async () => {+ const originalOpen = fs.open.bind(fs)+ const syncedPaths: string[] = []+ vi.spyOn(fs, 'open').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ const handle = await originalOpen(...(args as Parameters<typeof fs.open>))+ return {+ writeFile: (value: Parameters<typeof handle.writeFile>[0]) => handle.writeFile(value),+ sync: async () => {+ syncedPaths.push(filePath)+ await handle.sync()+ },+ close: () => handle.close(),+ } as Awaited<ReturnType<typeof fs.open>>+ })++ await new TokenStore().setSessionToken('tok-a', ENV_A)++ expect(+ syncedPaths.some(+ filePath =>+ filePath.startsWith(path.join(userDataDir, `session-token-${ENV_A}.json.`)) &&+ filePath.endsWith('.tmp')+ )+ ).toBe(true)+ expect(syncedPaths).toContain(userDataDir)})it('does not leak the plain-text token across environments', async () => {diff --git a/desktop-app/src/tokenStore.ts b/desktop-app/src/tokenStore.tsindex eaf29b5ea..4d77d8beb 100644--- a/desktop-app/src/tokenStore.ts+++ b/desktop-app/src/tokenStore.ts@@ -1,4 +1,5 @@import { app, safeStorage } from 'electron'+import { randomUUID } from 'node:crypto'import fs from 'node:fs/promises'import os from 'node:os'import path from 'node:path'@@ -99,6 +100,47 @@ async function legacyFilePath(): Promise<string> {return path.join(await resolvedStorageBase(), 'session-token.json')}+function isUnsupportedDirectorySyncError(error: unknown): boolean {+ if (process.platform !== 'win32') return false+ const code = (error as NodeJS.ErrnoException | undefined)?.code+ return code === 'EISDIR' || code === 'EPERM' || code === 'EINVAL' || code === 'ENOTSUP'+}++async function syncDirectory(directoryPath: string): Promise<void> {+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null+ try {+ handle = await fs.open(directoryPath, 'r')+ await handle.sync()+ } catch (error) {+ if (!isUnsupportedDirectorySyncError(error)) throw error+ } finally {+ await handle?.close()+ }+}++async function writeTokenFileAtomic(filePath: string, value: string | Uint8Array): Promise<void> {+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null+ try {+ handle = await fs.open(temporaryPath, 'w', 0o600)+ await handle.writeFile(value)+ await handle.sync()+ await handle.close()+ handle = null+ await fs.rename(temporaryPath, filePath)+ await syncDirectory(path.dirname(filePath))+ } catch (error) {+ await handle?.close().catch(() => undefined)+ await fs.rm(temporaryPath, { force: true }).catch(() => undefined)+ throw error+ }+}++async function removeTokenFileDurably(filePath: string): Promise<void> {+ await fs.unlink(filePath)+ await syncDirectory(path.dirname(filePath))+}+export class TokenStore {/*** Read the session token for `envKey`. Falls back keytar → safeStorage file,@@ -197,7 +239,7 @@ export class TokenStore {const token = safeStorage.decryptString(encrypted)if (token) {await this.setSessionToken(token, envKey)- await fs.unlink(file).catch(() => {})+ await removeTokenFileDurably(file).catch(() => {})return token}} catch {@@ -212,7 +254,7 @@ export class TokenStore {const token = typeof data.token === 'string' && data.token ? data.token : nullif (token) {await this.setSessionToken(token, envKey)- await fs.unlink(file).catch(() => {})+ await removeTokenFileDurably(file).catch(() => {})return token}} catch {@@ -254,7 +296,7 @@ export class TokenStore {const token = safeStorage.decryptString(encrypted)if (token) {await this.setSessionToken(token, envKey)- await fs.unlink(file).catch(() => {})+ await removeTokenFileDurably(file).catch(() => {})return token}} catch {@@ -270,7 +312,7 @@ export class TokenStore {const token = typeof data.token === 'string' && data.token ? data.token : nullif (token) {await this.setSessionToken(token, envKey)- await fs.unlink(file).catch(() => {})+ await removeTokenFileDurably(file).catch(() => {})}return token} catch {@@ -293,12 +335,12 @@ export class TokenStore {if (app?.isReady() && safeStorage.isEncryptionAvailable()) {const file = await encryptedFilePath(envKey)- await fs.writeFile(file, safeStorage.encryptString(token), { mode: 0o600 })+ await writeTokenFileAtomic(file, safeStorage.encryptString(token))return}const file = await plainFilePath(envKey)- await fs.writeFile(file, JSON.stringify({ token }), { encoding: 'utf8', mode: 0o600 })+ await writeTokenFileAtomic(file, JSON.stringify({ token }))}async clearSessionToken(