Skip to content

Commit db3838c

Browse files
fix(opencode): serialize mcp-auth.json writes to prevent concurrent corruption
McpAuth.set() and remove() used an unguarded read-modify-write pattern. Concurrent token refreshes or client info saves could race, causing one write to overwrite another and potentially corrupt mcp-auth.json. Add a Semaphore(1) so all file mutations are serialised, ensuring each read-modify-write cycle sees the latest file state. Closes anomalyco#29804
1 parent e5cf3ad commit db3838c

1 file changed

Lines changed: 18 additions & 6 deletions

File tree

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

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ export const layer = Layer.effect(
5858
Service,
5959
Effect.gen(function* () {
6060
const fs = yield* AppFileSystem.Service
61+
// Serialise all file mutations — McpAuth.set/remove use a read-modify-write
62+
// pattern. Without a lock, concurrent saves (e.g. token refresh + client info
63+
// save racing at startup) can overwrite each other's changes. (#29804)
64+
const sem = yield* Effect.makeSemaphore(1)
6165

6266
const all = Effect.fn("McpAuth.all")(function* () {
6367
return yield* fs.readJson(filepath).pipe(
@@ -80,15 +84,23 @@ export const layer = Layer.effect(
8084
})
8185

8286
const set = Effect.fn("McpAuth.set")(function* (mcpName: string, entry: Entry, serverUrl?: string) {
83-
const data = yield* all()
84-
if (serverUrl) entry.serverUrl = serverUrl
85-
yield* fs.writeJson(filepath, { ...data, [mcpName]: entry }, 0o600).pipe(Effect.orDie)
87+
yield* sem.withPermit(
88+
Effect.gen(function* () {
89+
const data = yield* all()
90+
if (serverUrl) entry.serverUrl = serverUrl
91+
yield* fs.writeJson(filepath, { ...data, [mcpName]: entry }, 0o600).pipe(Effect.orDie)
92+
}),
93+
)
8694
})
8795

8896
const remove = Effect.fn("McpAuth.remove")(function* (mcpName: string) {
89-
const data = yield* all()
90-
delete data[mcpName]
91-
yield* fs.writeJson(filepath, data, 0o600).pipe(Effect.orDie)
97+
yield* sem.withPermit(
98+
Effect.gen(function* () {
99+
const data = yield* all()
100+
delete data[mcpName]
101+
yield* fs.writeJson(filepath, data, 0o600).pipe(Effect.orDie)
102+
}),
103+
)
92104
})
93105

94106
const updateField = <K extends keyof Entry>(field: K, spanName: string) =>

0 commit comments

Comments
 (0)