TypeScript
fix(opencode): read the selected Go key from OpenCode 2's credential store (#26165)
Pavel Olizkod8430c0b9d48
diff --git a/packages/provider-opencode/src/server/status.test.ts b/packages/provider-opencode/src/server/status.test.tsindex 6c16fb9faba..b96036669b5 100644--- a/packages/provider-opencode/src/server/status.test.ts+++ b/packages/provider-opencode/src/server/status.test.ts@@ -226,6 +226,75 @@ it.effect(}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),);+it.effect("prefers the selected stored Go key over the auth.json key OpenCode 2 imported", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const dataHome = yield* fs.makeTempDirectoryScoped();+ yield* fs.makeDirectory(`${dataHome}/opencode`);+ yield* fs.writeFileString(+ `${dataHome}/opencode/auth.json`,+ JSON.stringify({ "opencode-go": { type: "api", key: "imported-key" } }),+ );+ const database = yield* Effect.acquireRelease(+ Effect.sync(() => new NodeSqlite.DatabaseSync(`${dataHome}/opencode/opencode.db`)),+ (database) => Effect.sync(() => database.close()),+ );+ database.exec(+ "CREATE TABLE credential (id text PRIMARY KEY, integration_id text, value text, active integer, time_created integer, time_updated integer)",+ );+ const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?, ?, ?)");+ insert.run(+ "cred_imported",+ "opencode-go",+ JSON.stringify({ type: "key", key: "imported-key" }),+ 0,+ 1,+ 2,+ );+ insert.run(+ "cred_replaced",+ "opencode-go",+ JSON.stringify({ type: "key", key: "replaced-key" }),+ 1,+ 2,+ 2,+ );+ const window = { percent: 1, resetsAt: "2026-09-17T12:00:00.000Z" };+ for (const { replacedStatus, requested } of [+ { replacedStatus: 200, requested: ["replaced-key"] },+ { replacedStatus: 401, requested: ["replaced-key", "imported-key"] },+ ]) {+ const authorizations: string[] = [];+ const limits = yield* readOpenCodeGoUsageLimits({+ enabled: true,+ serverUrl: "",+ environment: { XDG_DATA_HOME: dataHome },+ }).pipe(+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make((request) => {+ const key = (request.headers.authorization ?? "").replace("Bearer ", "");+ authorizations.push(key);+ const status = key === "replaced-key" ? replacedStatus : 200;+ return Effect.succeed(+ HttpClientResponse.fromWeb(+ request,+ Response.json(+ { usage: { rolling: window, weekly: window, monthly: window } },+ { status },+ ),+ ),+ );+ }),+ ),+ );+ NodeAssert.deepEqual(authorizations, requested);+ NodeAssert.equal(limits.unavailable, undefined);+ NodeAssert.equal(limits.windows.length, 3);+ }+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);+it.effect("does not read local credentials for external or disabled OpenCode instances", () =>Effect.gen(function* () {for (const settings of [diff --git a/packages/provider-opencode/src/server/usageLimits.ts b/packages/provider-opencode/src/server/usageLimits.tsindex b3df6b9cd07..e691dc211f9 100644--- a/packages/provider-opencode/src/server/usageLimits.ts+++ b/packages/provider-opencode/src/server/usageLimits.ts@@ -43,7 +43,7 @@ const UsageResponse = Schema.Struct({// Select before decoding so an OAuth or self-hosted connection cannot fall// through to another stored account. NULL-active rows predate the selection flag.-const readConsoleApiKey = (databasePath: string) =>+const readStoredApiKey = (databasePath: string, integrationId: "opencode" | "opencode-go") =>Effect.try(() => {const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });try {@@ -51,10 +51,10 @@ const readConsoleApiKey = (databasePath: string) =>const row = database.prepare(`SELECT value FROM credential- WHERE integration_id = 'opencode' AND active IS NOT 0+ WHERE integration_id = ? AND active IS NOT 0ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,)- .get();+ .get(integrationId);const stored =typeof row?.value === "string"? Option.getOrUndefined(decodeStoredKey(row.value))@@ -108,11 +108,17 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(// Console supplies Go credentials in OpenCode 2. Inline auth explicitly// overrides local credentials, including the Console connection.const databaseFile = env.OPENCODE_DB ?? "opencode.db";- const consoleKey =+ const databasePath = path.resolve(dataHome, "opencode", databaseFile);+ const storedKeys =env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"- ? undefined- : yield* readConsoleApiKey(path.resolve(dataHome, "opencode", databaseFile));- let apiKey = consoleKey || goKey;+ ? []+ : [+ yield* readStoredApiKey(databasePath, "opencode"),+ // OpenCode 2 imports auth.json once, so a replaced Go key only exists here.+ yield* readStoredApiKey(databasePath, "opencode-go"),+ ];+ const keys = [...new Set([...storedKeys, goKey].filter((key): key is string => Boolean(key)))];+ let apiKey = keys[0];if (!apiKey) return unsupported;const client = yield* HttpClient.HttpClient;@@ -123,8 +129,9 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(),);let response = yield* readUsage(apiKey);- if ((response.status === 401 || response.status === 403) && goKey && goKey !== apiKey) {- apiKey = goKey;+ for (const key of keys.slice(1)) {+ if (response.status !== 401 && response.status !== 403) break;+ apiKey = key;response = yield* readUsage(apiKey);}// A valid Zen key can exist without a Go subscription.