Skip to content

Commit 5b968bd

Browse files
authored
fix(core): redeem browser login code with PKCE (#6)
1 parent 2b89cb0 commit 5b968bd

3 files changed

Lines changed: 169 additions & 67 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ Open the model picker or run `/connect`, pick **LLM Gateway** or **LLM Gateway D
8585
Config lives in `~/.config/devpass-code/devpass-code.jsonc` and per project in `devpass-code.json` or `.devpass-code/`. Existing `opencode.json` files and `.opencode/` directories are read too.
8686

8787
- `DEVPASS_APP_URL` / `LLMGATEWAY_APP_URL` — override the dashboard URL used for browser login (defaults to `https://llmgateway.io`).
88+
- `DEVPASS_INTERNAL_API_URL` / `LLMGATEWAY_INTERNAL_API_URL` — override the API that redeems the browser login code (defaults to `https://internal.llmgateway.io`).
8889
- `LLMGATEWAY_API_URL` — override the gateway API (defaults to `https://api.llmgateway.io/v1`).
8990
- `LLMGATEWAY_API_KEY` — provide an API key via the environment instead of logging in.
9091

‎packages/core/src/plugin/provider/llmgateway.ts‎

Lines changed: 107 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration"
22
import { define } from "@opencode/plugin/effect/plugin"
3-
import { Deferred, Effect, Schema } from "effect"
4-
import type { Server } from "node:http"
3+
import { Clock, Deferred, Effect, Option, Schema } from "effect"
4+
import type { Server, ServerResponse } from "node:http"
55
import { App } from "../../app.js"
66
import { Credential } from "../../credential.js"
77
import { Hash } from "@opencode/util/hash"
@@ -12,54 +12,88 @@ import { OauthCallbackPage } from "../../oauth/page.js"
1212

1313
const appURL = () =>
1414
(process.env.DEVPASS_APP_URL || process.env.LLMGATEWAY_APP_URL || "https://llmgateway.io").replace(/\/+$/, "")
15+
const internalAPIURL = () =>
16+
(
17+
process.env.DEVPASS_INTERNAL_API_URL ||
18+
process.env.LLMGATEWAY_INTERNAL_API_URL ||
19+
"https://internal.llmgateway.io"
20+
).replace(/\/+$/, "")
1521
const browserMethodID = Integration.MethodID.make("browser")
16-
// Keys minted by the browser flow do not expire (the latest representable Date); the gateway revokes them.
17-
const keyLifetime = 8_640_000_000_000_000
22+
// Keys with no expiry are stored with the latest representable Date; the gateway revokes them.
23+
const maxExpiry = 8_640_000_000_000_000
1824

1925
const providers = [
2026
{ id: "llmgateway", name: "LLM Gateway", org: "default" },
2127
{ id: "llmgateway-devpass", name: "LLM Gateway DevPass", org: "devpass" },
2228
] as const
2329

30+
const Token = Schema.Struct({
31+
api_key: Schema.String.check(Schema.isMinLength(1)),
32+
expires_at: Schema.NullOr(Schema.String),
33+
})
34+
const decodeToken = Schema.decodeUnknownOption(Schema.fromJsonString(Token))
35+
const decodeTokenError = Schema.decodeUnknownOption(
36+
Schema.fromJsonString(Schema.Struct({ error_description: Schema.optional(Schema.String) })),
37+
)
38+
39+
// The dashboard hands the loopback a one-time code, never the key; the CLI redeems it with its PKCE verifier.
2440
const browser = (provider: (typeof providers)[number]) =>
2541
({
2642
integrationID: provider.id,
2743
method: { id: browserMethodID, type: "oauth", label: "Log in with browser" },
44+
// The dashboard mints a regular API key; once it expires, the user logs in again.
45+
refresh: (value) =>
46+
Clock.currentTimeMillis.pipe(
47+
Effect.flatMap((now) =>
48+
value.expires > now
49+
? Effect.succeed(value)
50+
: Effect.fail(new Error(`${provider.name} API key expired. Log in with browser again.`)),
51+
),
52+
),
2853
authorize: () =>
2954
Effect.gen(function* () {
30-
const state = Array.from(crypto.getRandomValues(new Uint8Array(24)), (byte) =>
31-
byte.toString(16).padStart(2, "0"),
32-
).join("")
33-
const received = yield* Deferred.make<string, Error>()
55+
const verifier = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url")
56+
const challenge = Buffer.from(
57+
yield* Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))),
58+
).toString("base64url")
59+
const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url")
60+
const received = yield* Deferred.make<{ code: string; response: ServerResponse }, Error>()
3461
// Lazy so runtimes without a loopback listener never evaluate node:http.
3562
const { createServer } = yield* Effect.promise(() => import("node:http"))
3663
const server = createServer((request, response) => {
3764
const url = new URL(request.url ?? "/", "http://127.0.0.1")
38-
if (url.pathname !== "/callback") {
65+
if (request.method !== "GET" || url.pathname !== "/callback") {
3966
response.writeHead(404).end("Not found")
4067
return
4168
}
42-
const error = url.searchParams.get("error")
43-
const key = url.searchParams.get("key")
44-
const failure =
45-
error ?? (!key || url.searchParams.get("state") !== state ? "Invalid authorization response" : undefined)
46-
if (failure || !key) {
47-
Effect.runFork(Deferred.fail(received, new Error(failure ?? "Missing API key")))
69+
const code = url.searchParams.get("code")
70+
const error =
71+
url.searchParams.get("state") !== state
72+
? "Invalid authorization response"
73+
: (url.searchParams.get("error") ?? (code ? undefined : "Missing authorization code"))
74+
if (error || !code) {
75+
const message = error ?? "Missing authorization code"
4876
response
4977
.writeHead(400, { "Content-Type": "text/html; charset=utf-8" })
50-
.end(OauthCallbackPage.error(failure ?? "Missing API key", { provider: "LLM Gateway" }))
78+
.end(OauthCallbackPage.error(message, { provider: "LLM Gateway" }))
79+
Effect.runSync(Deferred.fail(received, new Error(message)))
5180
return
5281
}
53-
Effect.runFork(Deferred.succeed(received, key))
54-
response
55-
.writeHead(200, { "Content-Type": "text/html; charset=utf-8" })
56-
.end(OauthCallbackPage.success({ provider: "LLM Gateway" }))
82+
if (!Effect.runSync(Deferred.succeed(received, { code, response })))
83+
response.writeHead(409).end("Authorization callback already received")
5784
})
85+
yield* Effect.addFinalizer(() =>
86+
Effect.sync(() => {
87+
server.close()
88+
server.closeAllConnections()
89+
}),
90+
)
5891
const port = yield* listen(server)
59-
yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))
6092
const params = new URLSearchParams({
6193
callback: `http://127.0.0.1:${port}/callback`,
6294
state,
95+
code_challenge: challenge,
96+
code_challenge_method: "S256",
6397
source: "devpass-code",
6498
org: provider.org,
6599
name: "DevPass Code CLI",
@@ -69,21 +103,62 @@ const browser = (provider: (typeof providers)[number]) =>
69103
url: `${appURL()}/connect/cli?${params.toString()}`,
70104
instructions: "Approve DevPass Code in your browser, then return to your terminal.",
71105
expiresAt: Date.now() + 5 * 60 * 1000,
72-
callback: Deferred.await(received).pipe(
73-
Effect.map((key) =>
74-
Credential.OAuth.make({
75-
type: "oauth",
76-
methodID: browserMethodID,
77-
access: key,
78-
refresh: "",
79-
expires: keyLifetime,
80-
}),
81-
),
82-
),
106+
callback: Effect.gen(function* () {
107+
const request = yield* Deferred.await(received)
108+
const respond = (error?: string) =>
109+
Effect.sync(() =>
110+
request.response
111+
.writeHead(error ? 400 : 200, { "Content-Type": "text/html; charset=utf-8" })
112+
.end(
113+
error
114+
? OauthCallbackPage.error(error, { provider: "LLM Gateway" })
115+
: OauthCallbackPage.success({ provider: "LLM Gateway" }),
116+
),
117+
)
118+
return yield* exchangeCode(request.code, verifier).pipe(
119+
Effect.tap(() => respond()),
120+
Effect.tapError((error) => respond(error.message)),
121+
// Bun's server.closeAllConnections() leaves an unanswered callback response pending.
122+
Effect.onInterrupt(() => Effect.sync(() => request.response.destroy())),
123+
)
124+
}),
83125
}
84126
}),
85127
}) satisfies IntegrationOAuthMethodRegistration
86128

129+
function exchangeCode(code: string, verifier: string) {
130+
return Effect.gen(function* () {
131+
const response = yield* Effect.tryPromise({
132+
try: (signal) =>
133+
fetch(`${internalAPIURL()}/public/cli-auth/token`, {
134+
method: "POST",
135+
signal,
136+
headers: { "Content-Type": "application/json" },
137+
body: JSON.stringify({ code, code_verifier: verifier }),
138+
}),
139+
catch: () => new Error("LLM Gateway token exchange request failed"),
140+
})
141+
const body = yield* Effect.promise(() => response.text().catch(() => ""))
142+
if (!response.ok) {
143+
const detail = Option.getOrUndefined(decodeTokenError(body))?.error_description
144+
return yield* Effect.fail(
145+
new Error(detail ? `LLM Gateway login failed: ${detail}` : `LLM Gateway login failed (${response.status})`),
146+
)
147+
}
148+
const token = Option.getOrUndefined(decodeToken(body))
149+
const expires = token?.expires_at ? Date.parse(token.expires_at) : maxExpiry
150+
if (!token || !Number.isSafeInteger(expires))
151+
return yield* Effect.fail(new Error("Invalid LLM Gateway token response"))
152+
return Credential.OAuth.make({
153+
type: "oauth",
154+
methodID: browserMethodID,
155+
access: token.api_key,
156+
refresh: "",
157+
expires,
158+
})
159+
})
160+
}
161+
87162
function listen(server: Server) {
88163
return Effect.callback<number, Error>((resume) => {
89164
const onError = (error: Error) => resume(Effect.fail(error))

‎packages/core/test/plugin/provider-llmgateway.test.ts‎

Lines changed: 61 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -201,50 +201,76 @@ describe("LLMGatewayPlugin", () => {
201201
}),
202202
)
203203

204-
it.live("stores the key the dashboard hands back to the loopback server", () =>
204+
it.live("redeems the one-time code from the loopback with the PKCE verifier", () =>
205205
Effect.gen(function* () {
206206
yield* addPlugin()
207207
const integrations = yield* Integration.Service
208208
const credentials = yield* Credential.Service
209209
const integrationID = Integration.ID.make("llmgateway-devpass")
210-
const attempt = yield* integrations.oauth.connect({
211-
integrationID,
212-
methodID: Integration.MethodID.make("browser"),
213-
label: "DevPass",
214-
})
215-
const url = new URL(attempt.url)
216-
expect(url.origin + url.pathname).toBe("https://llmgateway.io/connect/cli")
217-
expect(url.searchParams.get("org")).toBe("devpass")
218-
expect(url.searchParams.get("source")).toBe("devpass-code")
219-
const callback = new URL(url.searchParams.get("callback") ?? "")
220-
expect(callback.hostname).toBe("127.0.0.1")
210+
const exchanges: { code: string; code_verifier: string }[] = []
211+
const token = {
212+
status: 200,
213+
body: { api_key: "llmgtwy_minted", expires_at: "2099-01-01T00:00:00.000Z" } as object,
214+
}
215+
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
216+
if (String(input) !== "https://internal.llmgateway.io/public/cli-auth/token") return realFetch(input, init)
217+
exchanges.push(JSON.parse(String(init?.body)))
218+
return Response.json(token.body, { status: token.status })
219+
}) as typeof fetch
220+
const connect = () =>
221+
integrations.oauth
222+
.connect({ integrationID, methodID: Integration.MethodID.make("browser"), label: "DevPass" })
223+
.pipe(Effect.map((attempt) => ({ attempt, url: new URL(attempt.url) })))
224+
const callback = (url: URL, params: Record<string, string>) => {
225+
const target = new URL(url.searchParams.get("callback") ?? "")
226+
for (const [key, value] of Object.entries(params)) target.searchParams.set(key, value)
227+
return Effect.promise(() => realFetch(target, { headers: { Connection: "close" } }))
228+
}
229+
const settled = (attemptID: Integration.AttemptID) =>
230+
integrations.oauth.status({ integrationID, attemptID }).pipe(
231+
Effect.repeat({
232+
until: (value) => value.status !== "pending",
233+
schedule: Schedule.spaced("1 millis"),
234+
times: 100,
235+
}),
236+
)
221237

222-
const forged = new URL(callback)
223-
forged.searchParams.set("state", "wrong")
224-
forged.searchParams.set("key", "llmgtwy_forged")
225-
expect((yield* Effect.promise(() => fetch(forged, { headers: { Connection: "close" } }))).status).toBe(400)
226-
expect((yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).status).toBe("failed")
238+
const forged = yield* connect()
239+
expect(forged.url.origin + forged.url.pathname).toBe("https://llmgateway.io/connect/cli")
240+
expect(forged.url.searchParams.get("org")).toBe("devpass")
241+
expect(forged.url.searchParams.get("source")).toBe("devpass-code")
242+
expect(forged.url.searchParams.get("code_challenge_method")).toBe("S256")
243+
expect(new URL(forged.url.searchParams.get("callback") ?? "").hostname).toBe("127.0.0.1")
244+
expect((yield* callback(forged.url, { state: "wrong", code: "forged" })).status).toBe(400)
245+
expect((yield* settled(forged.attempt.attemptID)).status).toBe("failed")
227246

228-
const retry = yield* integrations.oauth.connect({
229-
integrationID,
230-
methodID: Integration.MethodID.make("browser"),
231-
label: "DevPass",
232-
})
233-
const next = new URL(retry.url)
234-
const ok = new URL(next.searchParams.get("callback") ?? "")
235-
ok.searchParams.set("state", next.searchParams.get("state") ?? "")
236-
ok.searchParams.set("key", "llmgtwy_minted")
237-
expect((yield* Effect.promise(() => fetch(ok, { headers: { Connection: "close" } }))).status).toBe(200)
238-
const status = yield* integrations.oauth.status({ integrationID, attemptID: retry.attemptID }).pipe(
239-
Effect.repeat({
240-
until: (value) => value.status !== "pending",
241-
schedule: Schedule.spaced("1 millis"),
242-
times: 100,
243-
}),
247+
token.status = 400
248+
token.body = { error: "invalid_grant", error_description: "The login code is invalid" }
249+
const rejected = yield* connect()
250+
expect(
251+
(yield* callback(rejected.url, { state: rejected.url.searchParams.get("state") ?? "", code: "stale" })).status,
252+
).toBe(400)
253+
expect((yield* settled(rejected.attempt.attemptID)).status).toBe("failed")
254+
255+
token.status = 200
256+
token.body = { api_key: "llmgtwy_minted", expires_at: "2099-01-01T00:00:00.000Z" }
257+
const ok = yield* connect()
258+
expect(
259+
(yield* callback(ok.url, { state: ok.url.searchParams.get("state") ?? "", code: "one-time" })).status,
260+
).toBe(200)
261+
expect((yield* settled(ok.attempt.attemptID)).status).toBe("complete")
262+
const exchange = exchanges.at(-1)
263+
expect(exchange?.code).toBe("one-time")
264+
expect(new Bun.CryptoHasher("sha256").update(exchange?.code_verifier ?? "").digest("base64url")).toBe(
265+
ok.url.searchParams.get("code_challenge") ?? "",
244266
)
245-
expect(status.status).toBe("complete")
246267
const saved = (yield* credentials.list(integrationID)).find((item) => item.label === "DevPass")?.value
247-
expect(saved).toMatchObject({ type: "oauth", access: "llmgtwy_minted", refresh: "" })
268+
expect(saved).toMatchObject({
269+
type: "oauth",
270+
access: "llmgtwy_minted",
271+
refresh: "",
272+
expires: Date.parse("2099-01-01T00:00:00.000Z"),
273+
})
248274
}),
249275
)
250276

0 commit comments

Comments
 (0)