@@ -3,6 +3,8 @@ import { Global } from "../global"
33import fs from "fs/promises"
44import z from "zod"
55import { Lock } from "../util/lock"
6+ import * as crypto from "crypto"
7+ import { Log } from "../util/log"
68
79export 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 }
0 commit comments