fix(app): persist a rotated Codex refresh token in the desktop quota reader

The desktop app's Codex quota reader is a copy of the CLI's and carried
the same fault: two await points between parsing the token grant and
writing auth.json, a rotated refresh token dropped when the grant had no
access token or the file could not be re-read, a silent failed write,
and the caller's abort passed into the grant request. Ported the CLI
fix so the two files match apart from import specifiers.
This commit is contained in:
iamtoruk 2026-09-02 22:10:37 -07:00
parent e95ea95769
commit ae1b2d797c
4 changed files with 427 additions and 37 deletions

View file

@ -0,0 +1,243 @@
// @vitest-environment node
// What happens to `~/.codex/auth.json` when the desktop app refreshes a Codex login.
//
// The grant retires the refresh token on disk the moment the endpoint accepts it, so
// everything between parsing the response and having the new one on disk is a window in
// which losing the process signs the user out of Codex. These run against a real credential
// file, because the write is the thing being pinned.
import { readFileSync } from 'node:fs'
import { mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { fetchCodexQuota } from './codex'
const NOW = Date.parse('2026-09-02T12:00:00.000Z')
const OLD_REFRESH = 'refresh-token-that-the-grant-retires'
const NEW_REFRESH = 'refresh-token-the-grant-returns'
let root: string
let authPath: string
// `last_refresh` is older than the eight-day staleness window, so every fetch here takes the
// proactive refresh path.
function authDoc(): Record<string, unknown> {
return {
auth_mode: 'chatgpt',
tokens: {
access_token: 'access-old',
refresh_token: OLD_REFRESH,
id_token: 'id-old',
account_id: 'account-1',
},
last_refresh: new Date(NOW - 30 * 86_400_000).toISOString(),
}
}
async function writeAuth(doc: Record<string, unknown>, mode = 0o600): Promise<void> {
// A real login file is private to its user, and readSecureFile rejects group or world bits.
await writeFile(authPath, `${JSON.stringify(doc, null, 2)}\n`, { encoding: 'utf8', mode })
}
async function readAuth(): Promise<Record<string, any>> {
return JSON.parse(await readFile(authPath, 'utf8')) as Record<string, any>
}
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
}
const rotatedGrant = () => json({ access_token: 'access-new', refresh_token: NEW_REFRESH, id_token: 'id-new' })
const usagePayload = () => json({
plan_type: 'pro',
rate_limit: { primary_window: { used_percent: 10, limit_window_seconds: 18_000 } },
})
type Handler = () => Response | Promise<Response>
function routes(handlers: { token: Handler; usage: Handler }): typeof fetch {
return (async (input: unknown) => {
const url = typeof input === 'string' ? input : String((input as { url?: string }).url ?? input)
return url.includes('auth.openai.com') ? handlers.token() : handlers.usage()
}) as unknown as typeof fetch
}
beforeEach(async () => {
root = await mkdtemp(path.join(tmpdir(), 'codeburn-app-codex-refresh-'))
authPath = path.join(root, 'auth.json')
})
afterEach(async () => {
vi.restoreAllMocks()
await rm(root, { recursive: true, force: true })
})
describe('Codex quota credential rotation', () => {
it('writes the rotated refresh token to auth.json and leaves no temp file behind', async () => {
await writeAuth(authDoc())
const result = await fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({ token: rotatedGrant, usage: usagePayload }),
})
expect(result.quota.connection).toBe('connected')
const saved = await readAuth()
expect(saved.tokens.refresh_token).toBe(NEW_REFRESH)
expect(saved.tokens.access_token).toBe('access-new')
expect(saved.tokens.id_token).toBe('id-new')
expect(saved.tokens.account_id).toBe('account-1')
expect(saved.auth_mode).toBe('chatgpt')
expect(saved.last_refresh).toBe(new Date(NOW).toISOString())
expect(await readdir(root)).toEqual(['auth.json'])
})
it('keeps the rotated refresh token when the quota request fails after the refresh', async () => {
await writeAuth(authDoc())
const result = await fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({ token: rotatedGrant, usage: () => json({ error: 'boom' }, 500) }),
})
expect(result.quota.connection).toBe('transientFailure')
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
it('has the rotated refresh token on disk before it makes another request', async () => {
await writeAuth(authDoc())
// The renderer's poll is racing a per-provider timeout, and quit reaps the main process
// outright, so anything still awaited after the grant can simply be killed. Reading the
// file from inside the next request proves the write already completed.
let onDiskAtUsage: string | null = null
const result = await fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({
token: rotatedGrant,
usage: () => {
onDiskAtUsage = readFileSync(authPath, 'utf8')
throw Object.assign(new Error('The operation was aborted.'), { name: 'AbortError' })
},
}),
})
expect(result.quota.connection).toBe('transientFailure')
expect(onDiskAtUsage).not.toBeNull()
expect(JSON.parse(onDiskAtUsage!).tokens.refresh_token).toBe(NEW_REFRESH)
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
it('persists a rotated refresh token even when the grant returns no access token', async () => {
await writeAuth(authDoc())
await fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({ token: () => json({ refresh_token: NEW_REFRESH }), usage: usagePayload }),
})
const saved = await readAuth()
expect(saved.tokens.refresh_token).toBe(NEW_REFRESH)
expect(saved.tokens.access_token).toBe('access-old')
})
it('falls back to the credential it holds when the merge re-read fails', async () => {
await writeAuth(authDoc())
await fetchCodexQuota({
authPath,
now: () => NOW,
readFileSync: () => { throw new Error('EBUSY: resource busy or locked') },
fetch: routes({ token: rotatedGrant, usage: usagePayload }),
})
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
it('reports a credential write it could not complete instead of failing silently', async () => {
await writeAuth(authDoc())
const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined)
await fetchCodexQuota({
authPath,
now: () => NOW,
writeFileSync: () => { throw new Error('EROFS: read-only file system') },
fetch: routes({ token: rotatedGrant, usage: usagePayload }),
})
expect(errors).toHaveBeenCalledTimes(1)
const message = String(errors.mock.calls[0]?.[0])
expect(message).toContain(authPath)
expect(message).toContain('codex login')
expect(message).not.toContain(NEW_REFRESH)
})
it('discards the rotation rather than resurrecting a login that was removed', async () => {
await writeAuth(authDoc())
const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined)
await fetchCodexQuota({
authPath,
now: () => NOW,
// The Codex CLI signed the user out between our read and the grant.
readFileSync: () => null,
fetch: routes({ token: rotatedGrant, usage: usagePayload }),
})
expect((await readAuth()).tokens.refresh_token).toBe(OLD_REFRESH)
expect(errors).toHaveBeenCalledTimes(1)
})
it('sends the grant on its own timeout rather than the caller’s abort signal', async () => {
await writeAuth(authDoc())
const caller = new AbortController()
const signals: Array<AbortSignal | null | undefined> = []
await fetchCodexQuota({
authPath,
now: () => NOW,
signal: caller.signal,
fetch: (async (input: unknown, init?: RequestInit) => {
const url = typeof input === 'string' ? input : String(input)
signals.push(init?.signal)
if (url.includes('auth.openai.com')) {
// A per-provider timeout firing here would cancel a rotation nothing can undo.
caller.abort()
return rotatedGrant()
}
return usagePayload()
}) as unknown as typeof fetch,
})
// The grant request never carried the caller's signal, so aborting it did not reach it.
expect(signals[0]?.aborted).toBe(false)
// The usage request that follows does carry it, which is what the abort is for.
expect(signals[1]?.aborted).toBe(true)
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
// POSIX mode bits do not exist on Windows, where the ACL carries the privacy.
it.skipIf(process.platform === 'win32')('rewrites the credential with the permissions it already had', async () => {
for (const mode of [0o600, 0o400]) {
await rm(authPath, { force: true })
await writeAuth(authDoc(), mode)
const before = (await stat(authPath)).mode & 0o777
await fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({ token: rotatedGrant, usage: usagePayload }),
})
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
expect((await stat(authPath)).mode & 0o777).toBe(before)
expect(before & 0o077).toBe(0)
}
})
})

View file

@ -205,9 +205,17 @@ describe('Codex quota', () => {
const fetchMock = vi.fn(async (url: string) => url.includes('/oauth/token')
? new Response(JSON.stringify({ access_token: 'new-access', refresh_token: 'new-refresh', id_token: 'new-id' }), { status: 200 })
: new Response(JSON.stringify({ plan_type: 'pro', rate_limit: {} }), { status: 200 }))
const writeFile = vi.fn(async () => undefined)
await fetchCodexQuota({ fetch: fetchMock as typeof fetch, readFile: vi.fn(async () => JSON.stringify(stale)), writeFile, now: () => now })
const saved = JSON.parse((writeFile.mock.calls[0]! as unknown as [string, string])[1])
const writeFileSync = vi.fn(() => undefined)
await fetchCodexQuota({
fetch: fetchMock as typeof fetch,
readFile: vi.fn(async () => JSON.stringify(stale)),
// The rotated tokens merge into whatever auth.json holds at that moment, not into the
// copy this call read before the grant.
readFileSync: vi.fn(() => JSON.stringify(stale)),
writeFileSync,
now: () => now,
})
const saved = JSON.parse((writeFileSync.mock.calls[0]! as unknown as [string, string])[1])
expect(saved.OPENAI_API_KEY).toBe('preserve-me')
expect(saved.tokens).toMatchObject({ access_token: 'new-access', refresh_token: 'new-refresh', id_token: 'new-id', account_id: 'acct_1' })
expect((fetchMock.mock.calls[0]! as unknown as [string, RequestInit])[1].method).toBe('POST')
@ -227,13 +235,13 @@ describe('Codex menubar keychain source', () => {
it('resolves quota from the menubar keychain when auth.json is absent, read-only', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ plan_type: 'pro', rate_limit: { primary_window: { used_percent: 10, reset_at: 1_800_000_000, limit_window_seconds: 18_000 } } }), { status: 200 }))
const keychain = vi.fn(async () => ({ status: 'found' as const, value: menubarRecord }))
const writeFile = vi.fn(async () => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => null), writeFile, keychain, allowKeychain: true })
const writeFileSync = vi.fn(() => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => null), writeFileSync, keychain, allowKeychain: true })
expect(result.quota.connection).toBe('connected')
expect(result.quota.planLabel).toBe('Pro')
const init = (fetchMock.mock.calls[0]! as unknown as [string, RequestInit])[1]
expect(init.headers).toMatchObject({ Authorization: 'Bearer eyJmenubar.token.sig', 'ChatGPT-Account-Id': 'acct_mb' })
expect(writeFile).not.toHaveBeenCalled()
expect(writeFileSync).not.toHaveBeenCalled()
expect(keychain).toHaveBeenCalledWith('org.agentseal.codeburn.menubar.codex.oauth.v1')
})
@ -244,22 +252,22 @@ describe('Codex menubar keychain source', () => {
const fetchMock = vi.fn(async (_url: string, init?: RequestInit) => (init?.headers as Record<string, string>).Authorization === 'Bearer eyJrotated.token.sig'
? new Response(JSON.stringify({ plan_type: 'pro', rate_limit: {} }), { status: 200 })
: new Response('', { status: 401 }))
const writeFile = vi.fn(async () => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => null), writeFile, keychain, allowKeychain: true })
const writeFileSync = vi.fn(() => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => null), writeFileSync, keychain, allowKeychain: true })
expect(result.quota.connection).toBe('connected')
expect(fetchMock.mock.calls.every(call => String(call[0]).includes('/wham/usage'))).toBe(true)
expect(keychain).toHaveBeenCalledTimes(2)
expect(writeFile).not.toHaveBeenCalled()
expect(writeFileSync).not.toHaveBeenCalled()
})
it('returns transientFailure on a keychain 401 with no rotation, never writing back', async () => {
const keychain = vi.fn(async () => ({ status: 'found' as const, value: menubarRecord }))
const fetchMock = vi.fn(async (_url: string) => new Response('', { status: 401 }))
const writeFile = vi.fn(async () => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => null), writeFile, keychain, allowKeychain: true })
const writeFileSync = vi.fn(() => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => null), writeFileSync, keychain, allowKeychain: true })
expect(result.quota.connection).toBe('transientFailure')
expect(fetchMock.mock.calls.every(call => String(call[0]).includes('/wham/usage'))).toBe(true)
expect(writeFile).not.toHaveBeenCalled()
expect(writeFileSync).not.toHaveBeenCalled()
})
it('surfaces accessDenied when the menubar keychain is blocked and no file exists', async () => {
@ -273,12 +281,12 @@ describe('Codex menubar keychain source', () => {
it('prefers the menubar keychain over ~/.codex/auth.json and keeps it read-only', async () => {
const keychain = vi.fn(async () => ({ status: 'found' as const, value: menubarRecord }))
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ plan_type: 'plus', rate_limit: {} }), { status: 200 }))
const writeFile = vi.fn(async () => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => JSON.stringify(auth)), writeFile, keychain, allowKeychain: true, now: () => now })
const writeFileSync = vi.fn(() => undefined)
const result = await fetchCodexQuota({ fetch: fetchMock as unknown as typeof fetch, readFile: vi.fn(async () => JSON.stringify(auth)), writeFileSync, keychain, allowKeychain: true, now: () => now })
expect(result.quota.connection).toBe('connected')
const init = (fetchMock.mock.calls[0]! as unknown as [string, RequestInit])[1]
expect(init.headers).toMatchObject({ Authorization: 'Bearer eyJmenubar.token.sig' })
expect(writeFile).not.toHaveBeenCalled()
expect(writeFileSync).not.toHaveBeenCalled()
})
it('falls through to ~/.codex/auth.json when the keychain has no menubar item', async () => {

View file

@ -1,7 +1,7 @@
import os from 'node:os'
import path from 'node:path'
import { atomicWriteSecureFile, fraction, quotaRequestSignal, readKeychainPassword, readSecureFile, sanitizeError } from './security'
import { atomicWriteSecureFileSync, fraction, quotaRequestSignal, readKeychainPassword, readSecureFile, readSecureFileSync, sanitizeError } from './security'
import type { KeychainOutcome } from './security'
import type { QuotaProvider, QuotaWindow } from './types'
@ -11,7 +11,7 @@ const CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'
const EIGHT_DAYS = 8 * 24 * 60 * 60_000
// The CodeBurn menubar caches its ChatGPT-mode Codex OAuth here as a
// `CredentialRecord` JSON blob (accessToken/refreshToken/idToken/accountId/…),
// account "default". Same brand, same machine, already consented — preferred
// account "default". Same brand, same machine, already consented and preferred
// over any OpenAI-owned storage.
const MENUBAR_KEYCHAIN_SERVICE = 'org.agentseal.codeburn.menubar.codex.oauth.v1'
@ -26,7 +26,9 @@ export type CodexDeps = {
authPath: string
openaiAuthPath: string
readFile: typeof readSecureFile
writeFile: typeof atomicWriteSecureFile
// Synchronous by contract, not by convenience: see `persistRotated`.
readFileSync: typeof readSecureFileSync
writeFileSync: typeof atomicWriteSecureFileSync
keychain: (service: string) => Promise<KeychainOutcome>
now: () => number
}
@ -36,7 +38,8 @@ const defaults: CodexDeps = {
authPath: path.join(os.homedir(), '.codex', 'auth.json'),
openaiAuthPath: path.join(os.homedir(), 'Library', 'Application Support', 'com.openai.codex', 'auth.json'),
readFile: readSecureFile,
writeFile: atomicWriteSecureFile,
readFileSync: readSecureFileSync,
writeFileSync: atomicWriteSecureFileSync,
keychain: service => readKeychainPassword(service, ['default', null]),
now: Date.now,
}
@ -104,7 +107,7 @@ async function discoverSource(deps: CodexDeps, allowKeychain: boolean): Promise<
if (fileAuth) return { name: 'authFile', auth: fileAuth, writable: true, reread: () => readAuth(deps) }
// (c) com.openai.codex App Support, only if it holds a plaintext auth JSON
// with a usable token. Tokens encrypted via "Codex Safe Storage" have no
// plaintext access_token here, so they fall through — we never decrypt.
// plaintext access_token here, so they fall through so we never decrypt.
const openaiAuth = await readAuth(deps, deps.openaiAuthPath).catch(() => null)
if (openaiAuth?.tokens?.access_token) {
return { name: 'openaiAppSupport', auth: openaiAuth, writable: false, reread: () => readAuth(deps, deps.openaiAuthPath).catch(() => null) }
@ -238,28 +241,93 @@ export function decodeCodexUsage(body: unknown): QuotaProvider {
}
}
async function refresh(auth: AuthDoc, deps: CodexDeps, signal?: AbortSignal): Promise<AuthDoc | null> {
function str(value: unknown): string | null {
return typeof value === 'string' && value ? value : null
}
/** The document the rotated tokens are merged into: whatever the Codex CLI has
* on disk right now, so a login it wrote since our own read is not clobbered.
* `null` means the login this rotation belongs to is gone (file removed, or no
* longer ChatGPT mode) and writing would resurrect it. An unreadable or
* unparseable file is NOT one of those cases: it falls back to the document we
* already hold, because dropping a rotated refresh token signs the user out. */
function mergeBase(auth: AuthDoc, deps: CodexDeps): AuthDoc | null {
let raw: string | null
try {
raw = deps.readFileSync(deps.authPath)
} catch {
return auth
}
if (raw === null) return null
let latest: unknown
try {
latest = JSON.parse(raw)
} catch {
return auth
}
if (!latest || typeof latest !== 'object') return auth
const doc = latest as AuthDoc
return doc.auth_mode === 'chatgpt' ? doc : null
}
type RotatedTokens = { access: string | null; refresh: string | null; id: string | null }
/**
* Merges the rotated tokens into auth.json and writes them, synchronously and
* atomically. Synchronous from the moment the token response is parsed to the
* moment the file is renamed into place: the grant has already invalidated the
* refresh token on disk, so an abort, a per-provider timeout or the `quota`
* command's `process.exit` landing in an await here would leave the user with
* nothing but a dead token, which reads as being signed out of Codex.
*/
function persistRotated(auth: AuthDoc, rotated: RotatedTokens, deps: CodexDeps): AuthDoc | null {
const base = mergeBase(auth, deps)
if (!base) {
console.error(`Codex refreshed its login but the credential at ${deps.authPath} no longer holds that ChatGPT login, so the new token was discarded. Run \`codex login\` if Codex signs you out.`)
return null
}
const merged: AuthDoc = {
...base,
tokens: {
...base.tokens,
...(rotated.access ? { access_token: rotated.access } : {}),
...(rotated.refresh ? { refresh_token: rotated.refresh } : {}),
...(rotated.id ? { id_token: rotated.id } : {}),
},
last_refresh: new Date(deps.now()).toISOString(),
}
try {
deps.writeFileSync(deps.authPath, `${JSON.stringify(merged, null, 2)}\n`)
} catch (error) {
// Never silent: the token still on disk is the one the grant just killed,
// so the user has to be told why Codex will ask them to sign in again.
console.error(`Codex refresh token rotated but could not be saved to ${deps.authPath}: ${sanitizeError(error)}. Run \`codex login\` if Codex signs you out.`)
return null
}
return merged
}
async function refresh(auth: AuthDoc, deps: CodexDeps): Promise<AuthDoc | null> {
const refreshToken = auth.tokens?.refresh_token
if (!refreshToken) return null
// Deliberately not the caller's abort signal, only this request's own
// timeout: the grant retires the refresh token on disk the moment the
// endpoint accepts it, so a per-provider timeout firing while the response
// is still arriving would cancel a rotation we can no longer undo. A slow
// grant costs the caller nothing, since its own race has already given up.
const response = await deps.fetch(TOKEN_ENDPOINT, {
method: 'POST', signal: quotaRequestSignal(signal),
method: 'POST', signal: quotaRequestSignal(),
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ client_id: CLIENT_ID, grant_type: 'refresh_token', refresh_token: refreshToken, scope: 'openid profile email' }),
})
if (!response.ok) return null
const next = await response.json() as Record<string, unknown>
if (typeof next.access_token !== 'string' || !next.access_token) return null
const latest = await readAuth(deps)
if (!latest || latest.auth_mode !== 'chatgpt') return null
latest.tokens = {
...latest.tokens,
access_token: next.access_token,
...(typeof next.refresh_token === 'string' ? { refresh_token: next.refresh_token } : {}),
...(typeof next.id_token === 'string' ? { id_token: next.id_token } : {}),
}
latest.last_refresh = new Date(deps.now()).toISOString()
await deps.writeFile(deps.authPath, `${JSON.stringify(latest, null, 2)}\n`)
return latest
const rotated: RotatedTokens = { access: str(next.access_token), refresh: str(next.refresh_token), id: str(next.id_token) }
// A rotated refresh token is persisted even when the access token is missing
// or malformed: the grant has already retired the one on disk either way.
if (!rotated.access && !rotated.refresh) return null
const merged = persistRotated(auth, rotated, deps)
return merged?.tokens?.access_token ? merged : null
}
async function usage(auth: AuthDoc, deps: CodexDeps, signal?: AbortSignal): Promise<Response | null> {
@ -287,7 +355,7 @@ export async function fetchCodexQuota(options: Partial<CodexDeps> & { signal?: A
if (source.writable) {
const refreshedAt = typeof auth.last_refresh === 'string' ? Date.parse(auth.last_refresh) : NaN
if (!Number.isFinite(refreshedAt) || deps.now() - refreshedAt > EIGHT_DAYS) {
const next = await refresh(auth, deps, options.signal)
const next = await refresh(auth, deps)
if (next) auth = next
}
}
@ -298,7 +366,7 @@ export async function fetchCodexQuota(options: Partial<CodexDeps> & { signal?: A
if (reread?.tokens?.access_token && reread.tokens.access_token !== auth.tokens?.access_token) {
auth = reread
} else if (source.writable) {
const next = await refresh(reread ?? auth, deps, options.signal)
const next = await refresh(reread ?? auth, deps)
if (!next) return { quota: empty('transientFailure') }
auth = next
} else {

View file

@ -1,5 +1,8 @@
import { execFile } from 'node:child_process'
import { constants, type Stats } from 'node:fs'
import {
chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync,
openSync, readFileSync, renameSync, unlinkSync, writeFileSync, type Stats,
} from 'node:fs'
import { chmod, lstat, mkdir, open, rename, unlink } from 'node:fs/promises'
import path from 'node:path'
import { promisify } from 'node:util'
@ -123,6 +126,74 @@ export async function readSecureFile(filePath: string, maxBytes = 64 * 1024): Pr
}
}
/** Synchronous twin of {@link readSecureFile}, for the rotation path that must
* not yield to the event loop between reading and writing a credential. */
export function readSecureFileSync(filePath: string, maxBytes = 64 * 1024): string | null {
let before: Stats
try {
before = lstatSync(filePath)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
throw error
}
if (before.isSymbolicLink()) throw new Error(`Refusing symbolic link: ${filePath}`)
assertSafeMode(before, filePath)
if (before.size > maxBytes) throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`)
const fd = openSync(filePath, constants.O_RDONLY | NOFOLLOW)
try {
const after = fstatSync(fd)
assertSafeMode(after, filePath)
if (after.dev !== before.dev || after.ino !== before.ino) throw new Error(`Credential file changed while opening: ${filePath}`)
if (after.size > maxBytes) throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`)
return readFileSync(fd, { encoding: 'utf8' })
} finally {
closeSync(fd)
}
}
// Rewrite a credential with exactly the owner-only permissions it already had,
// so a refreshed token neither widens the file the user chose nor drops a
// tighter mode like 0o400. Group or world bits (or Windows, where mode bits are
// not the access control) mean there is nothing safe to copy: use owner rw.
function privateModeFor(filePath: string): number {
if (process.platform === 'win32') return 0o600
try {
const stats = lstatSync(filePath)
if (!stats.isFile()) return 0o600
const mode = stats.mode & 0o777
return mode !== 0 && (mode & 0o077) === 0 ? mode : 0o600
} catch {
return 0o600
}
}
/**
* Writes a credential file atomically and synchronously. Synchronous on
* purpose: a caller holding a freshly rotated token has to get it onto disk
* without an await for an abort, a timeout or a quit to land in.
*/
export function atomicWriteSecureFileSync(filePath: string, contents: string): void {
const mode = privateModeFor(filePath)
const dir = path.dirname(filePath)
mkdirSync(dir, { recursive: true, mode: 0o700 })
const tempPath = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`)
try {
const fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode)
try {
writeFileSync(fd, contents, 'utf8')
fsyncSync(fd)
} finally {
closeSync(fd)
}
if (process.platform !== 'win32') chmodSync(tempPath, mode)
renameSync(tempPath, filePath)
} catch (error) {
try { unlinkSync(tempPath) } catch { /* nothing to clean up */ }
throw error
}
}
export async function atomicWriteSecureFile(filePath: string, contents: string): Promise<void> {
await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 })
const tempPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`)