Skip to content

Commit 62775de

Browse files
committed
fix(auth): use atomic writes and error recovery for auth.json (#37) (#48)
1 parent 855c460 commit 62775de

2 files changed

Lines changed: 24 additions & 11 deletions

File tree

‎packages/opencode/src/auth/index.ts‎

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { Global } from "../global"
33
import fs from "fs/promises"
44
import z from "zod"
55
import { Lock } from "../util/lock"
6+
import * as crypto from "crypto"
7+
import { Log } from "../util/log"
68

79
export const OAUTH_DUMMY_KEY = "opencode-oauth-dummy-key"
810

@@ -47,15 +49,22 @@ export namespace Auth {
4749
const release = await Lock.read("auth")
4850
try {
4951
const file = Bun.file(filepath)
50-
52+
5153
if (!(await file.exists())) return {}
52-
53-
const data = await file.json()
54-
54+
55+
let data: unknown
56+
try {
57+
data = await file.json()
58+
} catch (error) {
59+
Log.Default.warn("auth.json corrupted or unreadable, returning empty", { error })
60+
return {}
61+
}
62+
5563
if (typeof data !== "object" || data === null) {
56-
throw new Error("auth.json contains invalid data")
64+
Log.Default.warn("auth.json contains invalid data, returning empty")
65+
return {}
5766
}
58-
67+
5968
return Object.entries(data).reduce(
6069
(acc, [key, value]) => {
6170
const parsed = Info.safeParse(value)
@@ -86,8 +95,10 @@ export namespace Auth {
8695
}
8796

8897
data[key] = info
89-
await Bun.write(file, JSON.stringify(data, null, 2))
90-
await fs.chmod(filepath, 0o600)
98+
const temp = filepath + ".tmp." + crypto.randomUUID()
99+
await Bun.write(temp, JSON.stringify(data, null, 2))
100+
await fs.chmod(temp, 0o600)
101+
await fs.rename(temp, filepath)
91102
} finally {
92103
release[Symbol.dispose]()
93104
}
@@ -109,8 +120,10 @@ export namespace Auth {
109120
}
110121

111122
delete data[key]
112-
await Bun.write(file, JSON.stringify(data, null, 2))
113-
await fs.chmod(filepath, 0o600)
123+
const temp = filepath + ".tmp." + crypto.randomUUID()
124+
await Bun.write(temp, JSON.stringify(data, null, 2))
125+
await fs.chmod(temp, 0o600)
126+
await fs.rename(temp, filepath)
114127
} finally {
115128
release[Symbol.dispose]()
116129
}

‎packages/opencode/src/plugin/codex.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ export async function CodexAuthPlugin(input: PluginInput): Promise<Hooks> {
353353
provider: "openai",
354354
async loader(getAuth, provider) {
355355
const auth = await getAuth()
356-
if (auth.type !== "oauth") return {}
356+
if (!auth || auth.type !== "oauth") return {}
357357

358358
// Filter models to only allowed Codex models for OAuth
359359
const allowedModels = new Set([

0 commit comments

Comments
 (0)