Skip to content

Commit 75403f8

Browse files
committed
fix(opencode): read usage from Console OAuth logins
1 parent dd14848 commit 75403f8

2 files changed

Lines changed: 74 additions & 30 deletions

File tree

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

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ it.effect("reads Go limits with the instance's XDG credentials and preserves res
9696
);
9797

9898
it.effect(
99-
"uses the selected public Console key for Go limits, falling back only on auth rejection",
99+
"uses the selected public Console credential for Go limits, falling back only on auth rejection",
100100
() =>
101101
Effect.gen(function* () {
102102
const fs = yield* FileSystem.FileSystem;
@@ -115,9 +115,14 @@ it.effect(
115115
);
116116
const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?, ?, ?)");
117117
const window = { percent: 1, resetsAt: "2026-09-17T12:00:00.000Z" };
118-
const consoleKey = { type: "key", key: "console-key" };
118+
const consoleKey = {
119+
type: "key",
120+
key: "console-key",
121+
metadata: { orgID: "workspace-id" },
122+
};
119123
const fingerprints = new Map([
120124
["console-key", "3e45cfde9158185930d4cc7020a4e390895574fd54bd8f9631d23a336bbf94f0"],
125+
["oauth-access", "44787b5311d57ff90911ebaf148f0381be1788d003774c3b43029d6fed1d528b"],
121126
["go-key", "d0e590e93fc9bd9353f2b993c0c287391cae505da2a78cb698b75418d2f5367e"],
122127
["inline-key", "85649de18e63305548b6407e185f708483727ee6189cc4bc9512ddb17e23e776"],
123128
]);
@@ -130,7 +135,10 @@ it.effect(
130135
requested,
131136
} of [
132137
{
133-
consoleRow: { ...consoleKey, metadata: { server: "https://opencode.ai/console" } },
138+
consoleRow: {
139+
...consoleKey,
140+
metadata: { server: "https://opencode.ai/console", orgID: "workspace-id" },
141+
},
134142
requested: ["console-key"],
135143
},
136144
{ consoleStatus: 401, requested: ["console-key", "go-key"] },
@@ -141,14 +149,18 @@ it.effect(
141149
consoleRow: {
142150
type: "oauth",
143151
methodID: "device",
144-
access: "token",
152+
access: "oauth-access",
145153
refresh: "refresh",
146-
expires: 0,
154+
expires: 1_800_000_000_000,
155+
metadata: { server: "https://opencode.ai/console", orgID: "workspace-id" },
147156
},
148-
requested: ["go-key"],
157+
requested: ["oauth-access"],
149158
},
150159
{
151-
consoleRow: { ...consoleKey, metadata: { server: "https://console.example" } },
160+
consoleRow: {
161+
...consoleKey,
162+
metadata: { server: "https://console.example", orgID: "workspace-id" },
163+
},
152164
requested: ["go-key"],
153165
},
154166
{ inline: true, requested: ["inline-key"] },
@@ -179,6 +191,7 @@ it.effect(
179191
}
180192
const before = yield* fs.readFile(`${dataHome}/opencode/opencode.db`);
181193
const authorizations: string[] = [];
194+
const workspaceIDs: Array<string | undefined> = [];
182195
const limits = yield* readOpenCodeGoUsageLimits({
183196
enabled: true,
184197
serverUrl: "",
@@ -196,6 +209,7 @@ it.effect(
196209
NodeAssert.equal(request.url, "https://opencode.ai/zen/go/v1/usage");
197210
const key = (request.headers.authorization ?? "").replace("Bearer ", "");
198211
authorizations.push(key);
212+
workspaceIDs.push(request.headers["x-opencode-org-id"]);
199213
// The legacy key is expired in the regression; it only works in fallback scenarios.
200214
const status =
201215
key === "console-key" ? consoleStatus : requested.includes(key) ? 200 : 401;
@@ -212,6 +226,12 @@ it.effect(
212226
),
213227
);
214228
NodeAssert.deepEqual(authorizations, requested);
229+
NodeAssert.deepEqual(
230+
workspaceIDs,
231+
requested.map((key) =>
232+
key === "console-key" || key === "oauth-access" ? "workspace-id" : undefined,
233+
),
234+
);
215235
NodeAssert.deepEqual(yield* fs.readFile(`${dataHome}/opencode/opencode.db`), before);
216236
NodeAssert.equal(
217237
limits.unavailable?.reason,

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

Lines changed: 47 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,24 @@ const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknow
2424
const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String });
2525
const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile));
2626
const decodeApiAuth = Schema.decodeUnknownOption(ApiAuth);
27+
const StoredMetadata = Schema.Struct({
28+
server: Schema.optionalKey(Schema.Unknown),
29+
orgID: Schema.optionalKey(Schema.Unknown),
30+
});
2731
// OpenCode 2's database tags a stored key "key"; auth.json tags it "api".
2832
const StoredKey = Schema.Struct({
2933
type: Schema.Literal("key"),
3034
key: Schema.String,
31-
metadata: Schema.optionalKey(
32-
Schema.NullOr(Schema.Struct({ server: Schema.optionalKey(Schema.Unknown) })),
33-
),
35+
metadata: Schema.optionalKey(Schema.NullOr(StoredMetadata)),
36+
});
37+
const StoredOAuth = Schema.Struct({
38+
type: Schema.Literal("oauth"),
39+
access: Schema.String,
40+
metadata: Schema.optionalKey(Schema.NullOr(StoredMetadata)),
3441
});
35-
const decodeStoredKey = Schema.decodeOption(Schema.fromJsonString(StoredKey));
42+
const decodeStoredCredential = Schema.decodeOption(
43+
Schema.fromJsonString(Schema.Union([StoredKey, StoredOAuth])),
44+
);
3645
const UsageWindow = Schema.Struct({
3746
percent: Schema.Finite,
3847
resetsAt: Schema.DateTimeUtcFromString,
@@ -41,9 +50,9 @@ const UsageResponse = Schema.Struct({
4150
usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
4251
});
4352

44-
// Select before decoding so an OAuth or self-hosted connection cannot fall
45-
// through to another stored account. NULL-active rows predate the selection flag.
46-
const readConsoleApiKey = (databasePath: string) =>
53+
// Select before decoding so an unsupported or self-hosted connection cannot
54+
// fall through to another stored account. NULL-active rows predate the selection flag.
55+
const readConsoleCredential = (databasePath: string) =>
4756
Effect.try(() => {
4857
const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
4958
try {
@@ -57,15 +66,21 @@ const readConsoleApiKey = (databasePath: string) =>
5766
.get();
5867
const stored =
5968
typeof row?.value === "string"
60-
? Option.getOrUndefined(decodeStoredKey(row.value))
69+
? Option.getOrUndefined(decodeStoredCredential(row.value))
6170
: undefined;
6271
const server = stored?.metadata?.server;
6372
if (typeof server === "string") {
6473
const url = new URL(server);
6574
if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
6675
return undefined;
6776
}
68-
return stored?.key.trim();
77+
const token = (stored?.type === "oauth" ? stored.access : stored?.key)?.trim();
78+
if (!token) return undefined;
79+
const orgID = stored?.metadata?.orgID;
80+
return {
81+
token,
82+
...(typeof orgID === "string" ? { workspaceID: orgID } : {}),
83+
};
6984
} finally {
7085
database.close();
7186
}
@@ -108,24 +123,33 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
108123
// Console supplies Go credentials in OpenCode 2. Inline auth explicitly
109124
// overrides local credentials, including the Console connection.
110125
const databaseFile = env.OPENCODE_DB ?? "opencode.db";
111-
const consoleKey =
126+
const consoleCredential =
112127
env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"
113128
? undefined
114-
: yield* readConsoleApiKey(path.resolve(dataHome, "opencode", databaseFile));
115-
let apiKey = consoleKey || goKey;
116-
if (!apiKey) return unsupported;
129+
: yield* readConsoleCredential(path.resolve(dataHome, "opencode", databaseFile));
130+
let credential = consoleCredential ?? (goKey ? { token: goKey } : undefined);
131+
if (!credential) return unsupported;
117132

118133
const client = yield* HttpClient.HttpClient;
119-
const readUsage = (key: string) =>
120-
client.execute(
121-
HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
122-
HttpClientRequest.bearerToken(key),
123-
),
134+
const readUsage = (selected: { readonly token: string; readonly workspaceID?: string }) => {
135+
let request = HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
136+
HttpClientRequest.bearerToken(selected.token),
124137
);
125-
let response = yield* readUsage(apiKey);
126-
if ((response.status === 401 || response.status === 403) && goKey && goKey !== apiKey) {
127-
apiKey = goKey;
128-
response = yield* readUsage(apiKey);
138+
if (selected.workspaceID) {
139+
request = request.pipe(
140+
HttpClientRequest.setHeader("x-opencode-org-id", selected.workspaceID),
141+
);
142+
}
143+
return client.execute(request);
144+
};
145+
let response = yield* readUsage(credential);
146+
if (
147+
(response.status === 401 || response.status === 403) &&
148+
goKey &&
149+
goKey !== credential.token
150+
) {
151+
credential = { token: goKey };
152+
response = yield* readUsage(credential);
129153
}
130154
// A valid Zen key can exist without a Go subscription.
131155
if (response.status === 403) return unsupported;
@@ -160,7 +184,7 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
160184
const crypto = yield* Crypto.Crypto;
161185
// Unkeyed hashes match across environments; random Go keys resist offline guessing.
162186
const credentialFingerprint = yield* crypto
163-
.digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`))
187+
.digest("SHA-256", new TextEncoder().encode(`opencode-go\0${credential.token}`))
164188
.pipe(Effect.map(Hex.encode), Effect.orDie);
165189
return {
166190
...makeUsageLimits({ checkedAt, windows }),

0 commit comments

Comments
 (0)