Skip to content

Commit 4044c24

Browse files
committed
fix(opencode): read the selected Go key from OpenCode 2's credential store
1 parent 8f0b729 commit 4044c24

2 files changed

Lines changed: 85 additions & 9 deletions

File tree

‎packages/provider-opencode/src/server/status.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,75 @@ it.effect(
226226
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
227227
);
228228

229+
it.effect("prefers the selected stored Go key over the auth.json key OpenCode 2 imported", () =>
230+
Effect.gen(function* () {
231+
const fs = yield* FileSystem.FileSystem;
232+
const dataHome = yield* fs.makeTempDirectoryScoped();
233+
yield* fs.makeDirectory(`${dataHome}/opencode`);
234+
yield* fs.writeFileString(
235+
`${dataHome}/opencode/auth.json`,
236+
JSON.stringify({ "opencode-go": { type: "api", key: "imported-key" } }),
237+
);
238+
const database = yield* Effect.acquireRelease(
239+
Effect.sync(() => new NodeSqlite.DatabaseSync(`${dataHome}/opencode/opencode.db`)),
240+
(database) => Effect.sync(() => database.close()),
241+
);
242+
database.exec(
243+
"CREATE TABLE credential (id text PRIMARY KEY, integration_id text, value text, active integer, time_created integer, time_updated integer)",
244+
);
245+
const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?, ?, ?)");
246+
insert.run(
247+
"cred_imported",
248+
"opencode-go",
249+
JSON.stringify({ type: "key", key: "imported-key" }),
250+
0,
251+
1,
252+
2,
253+
);
254+
insert.run(
255+
"cred_replaced",
256+
"opencode-go",
257+
JSON.stringify({ type: "key", key: "replaced-key" }),
258+
1,
259+
2,
260+
2,
261+
);
262+
const window = { percent: 1, resetsAt: "2026-09-17T12:00:00.000Z" };
263+
for (const { replacedStatus, requested } of [
264+
{ replacedStatus: 200, requested: ["replaced-key"] },
265+
{ replacedStatus: 401, requested: ["replaced-key", "imported-key"] },
266+
]) {
267+
const authorizations: string[] = [];
268+
const limits = yield* readOpenCodeGoUsageLimits({
269+
enabled: true,
270+
serverUrl: "",
271+
environment: { XDG_DATA_HOME: dataHome },
272+
}).pipe(
273+
Effect.provideService(
274+
HttpClient.HttpClient,
275+
HttpClient.make((request) => {
276+
const key = (request.headers.authorization ?? "").replace("Bearer ", "");
277+
authorizations.push(key);
278+
const status = key === "replaced-key" ? replacedStatus : 200;
279+
return Effect.succeed(
280+
HttpClientResponse.fromWeb(
281+
request,
282+
Response.json(
283+
{ usage: { rolling: window, weekly: window, monthly: window } },
284+
{ status },
285+
),
286+
),
287+
);
288+
}),
289+
),
290+
);
291+
NodeAssert.deepEqual(authorizations, requested);
292+
NodeAssert.equal(limits.unavailable, undefined);
293+
NodeAssert.equal(limits.windows.length, 3);
294+
}
295+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
296+
);
297+
229298
it.effect("does not read local credentials for external or disabled OpenCode instances", () =>
230299
Effect.gen(function* () {
231300
for (const settings of [

‎packages/provider-opencode/src/server/usageLimits.ts‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,18 +43,18 @@ const UsageResponse = Schema.Struct({
4343

4444
// Select before decoding so an OAuth or self-hosted connection cannot fall
4545
// through to another stored account. NULL-active rows predate the selection flag.
46-
const readConsoleApiKey = (databasePath: string) =>
46+
const readStoredApiKey = (databasePath: string, integrationId: "opencode" | "opencode-go") =>
4747
Effect.try(() => {
4848
const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
4949
try {
5050
database.exec("PRAGMA busy_timeout = 100");
5151
const row = database
5252
.prepare(
5353
`SELECT value FROM credential
54-
WHERE integration_id = 'opencode' AND active IS NOT 0
54+
WHERE integration_id = ? AND active IS NOT 0
5555
ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
5656
)
57-
.get();
57+
.get(integrationId);
5858
const stored =
5959
typeof row?.value === "string"
6060
? Option.getOrUndefined(decodeStoredKey(row.value))
@@ -108,11 +108,17 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
108108
// Console supplies Go credentials in OpenCode 2. Inline auth explicitly
109109
// overrides local credentials, including the Console connection.
110110
const databaseFile = env.OPENCODE_DB ?? "opencode.db";
111-
const consoleKey =
111+
const databasePath = path.resolve(dataHome, "opencode", databaseFile);
112+
const storedKeys =
112113
env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"
113-
? undefined
114-
: yield* readConsoleApiKey(path.resolve(dataHome, "opencode", databaseFile));
115-
let apiKey = consoleKey || goKey;
114+
? []
115+
: [
116+
yield* readStoredApiKey(databasePath, "opencode"),
117+
// OpenCode 2 imports auth.json once, so a replaced Go key only exists here.
118+
yield* readStoredApiKey(databasePath, "opencode-go"),
119+
];
120+
const keys = [...new Set([...storedKeys, goKey].filter((key): key is string => Boolean(key)))];
121+
let apiKey = keys[0];
116122
if (!apiKey) return unsupported;
117123

118124
const client = yield* HttpClient.HttpClient;
@@ -123,8 +129,9 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
123129
),
124130
);
125131
let response = yield* readUsage(apiKey);
126-
if ((response.status === 401 || response.status === 403) && goKey && goKey !== apiKey) {
127-
apiKey = goKey;
132+
for (const key of keys.slice(1)) {
133+
if (response.status !== 401 && response.status !== 403) break;
134+
apiKey = key;
128135
response = yield* readUsage(apiKey);
129136
}
130137
// A valid Zen key can exist without a Go subscription.

0 commit comments

Comments
 (0)