diff --git a/README.md b/README.md index b1e1bf42..090c0e17 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ Open the model picker or run `/connect`, pick **LLM Gateway** or **LLM Gateway D 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. - `DEVPASS_APP_URL` / `LLMGATEWAY_APP_URL` — override the dashboard URL used for browser login (defaults to `https://llmgateway.io`). +- `DEVPASS_INTERNAL_API_URL` / `LLMGATEWAY_INTERNAL_API_URL` — override the API that redeems the browser login code (defaults to `https://internal.llmgateway.io`). - `LLMGATEWAY_API_URL` — override the gateway API (defaults to `https://api.llmgateway.io/v1`). - `LLMGATEWAY_API_KEY` — provide an API key via the environment instead of logging in. diff --git a/packages/core/src/plugin/provider/llmgateway.ts b/packages/core/src/plugin/provider/llmgateway.ts index c2be5a36..90dcb8cf 100644 --- a/packages/core/src/plugin/provider/llmgateway.ts +++ b/packages/core/src/plugin/provider/llmgateway.ts @@ -1,7 +1,7 @@ import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration" import { define } from "@opencode/plugin/effect/plugin" -import { Deferred, Effect, Schema } from "effect" -import type { Server } from "node:http" +import { Clock, Deferred, Effect, Option, Schema } from "effect" +import type { Server, ServerResponse } from "node:http" import { App } from "../../app.js" import { Credential } from "../../credential.js" import { Hash } from "@opencode/util/hash" @@ -12,54 +12,88 @@ import { OauthCallbackPage } from "../../oauth/page.js" const appURL = () => (process.env.DEVPASS_APP_URL || process.env.LLMGATEWAY_APP_URL || "https://llmgateway.io").replace(/\/+$/, "") +const internalAPIURL = () => + ( + process.env.DEVPASS_INTERNAL_API_URL || + process.env.LLMGATEWAY_INTERNAL_API_URL || + "https://internal.llmgateway.io" + ).replace(/\/+$/, "") const browserMethodID = Integration.MethodID.make("browser") -// Keys minted by the browser flow do not expire (the latest representable Date); the gateway revokes them. -const keyLifetime = 8_640_000_000_000_000 +// Keys with no expiry are stored with the latest representable Date; the gateway revokes them. +const maxExpiry = 8_640_000_000_000_000 const providers = [ { id: "llmgateway", name: "LLM Gateway", org: "default" }, { id: "llmgateway-devpass", name: "LLM Gateway DevPass", org: "devpass" }, ] as const +const Token = Schema.Struct({ + api_key: Schema.String.check(Schema.isMinLength(1)), + expires_at: Schema.NullOr(Schema.String), +}) +const decodeToken = Schema.decodeUnknownOption(Schema.fromJsonString(Token)) +const decodeTokenError = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Struct({ error_description: Schema.optional(Schema.String) })), +) + +// The dashboard hands the loopback a one-time code, never the key; the CLI redeems it with its PKCE verifier. const browser = (provider: (typeof providers)[number]) => ({ integrationID: provider.id, method: { id: browserMethodID, type: "oauth", label: "Log in with browser" }, + // The dashboard mints a regular API key; once it expires, the user logs in again. + refresh: (value) => + Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => + value.expires > now + ? Effect.succeed(value) + : Effect.fail(new Error(`${provider.name} API key expired. Log in with browser again.`)), + ), + ), authorize: () => Effect.gen(function* () { - const state = Array.from(crypto.getRandomValues(new Uint8Array(24)), (byte) => - byte.toString(16).padStart(2, "0"), - ).join("") - const received = yield* Deferred.make() + const verifier = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url") + const challenge = Buffer.from( + yield* Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))), + ).toString("base64url") + const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url") + const received = yield* Deferred.make<{ code: string; response: ServerResponse }, Error>() // Lazy so runtimes without a loopback listener never evaluate node:http. const { createServer } = yield* Effect.promise(() => import("node:http")) const server = createServer((request, response) => { const url = new URL(request.url ?? "/", "http://127.0.0.1") - if (url.pathname !== "/callback") { + if (request.method !== "GET" || url.pathname !== "/callback") { response.writeHead(404).end("Not found") return } - const error = url.searchParams.get("error") - const key = url.searchParams.get("key") - const failure = - error ?? (!key || url.searchParams.get("state") !== state ? "Invalid authorization response" : undefined) - if (failure || !key) { - Effect.runFork(Deferred.fail(received, new Error(failure ?? "Missing API key"))) + const code = url.searchParams.get("code") + const error = + url.searchParams.get("state") !== state + ? "Invalid authorization response" + : (url.searchParams.get("error") ?? (code ? undefined : "Missing authorization code")) + if (error || !code) { + const message = error ?? "Missing authorization code" response .writeHead(400, { "Content-Type": "text/html; charset=utf-8" }) - .end(OauthCallbackPage.error(failure ?? "Missing API key", { provider: "LLM Gateway" })) + .end(OauthCallbackPage.error(message, { provider: "LLM Gateway" })) + Effect.runSync(Deferred.fail(received, new Error(message))) return } - Effect.runFork(Deferred.succeed(received, key)) - response - .writeHead(200, { "Content-Type": "text/html; charset=utf-8" }) - .end(OauthCallbackPage.success({ provider: "LLM Gateway" })) + if (!Effect.runSync(Deferred.succeed(received, { code, response }))) + response.writeHead(409).end("Authorization callback already received") }) + yield* Effect.addFinalizer(() => + Effect.sync(() => { + server.close() + server.closeAllConnections() + }), + ) const port = yield* listen(server) - yield* Effect.addFinalizer(() => Effect.sync(() => server.close())) const params = new URLSearchParams({ callback: `http://127.0.0.1:${port}/callback`, state, + code_challenge: challenge, + code_challenge_method: "S256", source: "devpass-code", org: provider.org, name: "DevPass Code CLI", @@ -69,21 +103,62 @@ const browser = (provider: (typeof providers)[number]) => url: `${appURL()}/connect/cli?${params.toString()}`, instructions: "Approve DevPass Code in your browser, then return to your terminal.", expiresAt: Date.now() + 5 * 60 * 1000, - callback: Deferred.await(received).pipe( - Effect.map((key) => - Credential.OAuth.make({ - type: "oauth", - methodID: browserMethodID, - access: key, - refresh: "", - expires: keyLifetime, - }), - ), - ), + callback: Effect.gen(function* () { + const request = yield* Deferred.await(received) + const respond = (error?: string) => + Effect.sync(() => + request.response + .writeHead(error ? 400 : 200, { "Content-Type": "text/html; charset=utf-8" }) + .end( + error + ? OauthCallbackPage.error(error, { provider: "LLM Gateway" }) + : OauthCallbackPage.success({ provider: "LLM Gateway" }), + ), + ) + return yield* exchangeCode(request.code, verifier).pipe( + Effect.tap(() => respond()), + Effect.tapError((error) => respond(error.message)), + // Bun's server.closeAllConnections() leaves an unanswered callback response pending. + Effect.onInterrupt(() => Effect.sync(() => request.response.destroy())), + ) + }), } }), }) satisfies IntegrationOAuthMethodRegistration +function exchangeCode(code: string, verifier: string) { + return Effect.gen(function* () { + const response = yield* Effect.tryPromise({ + try: (signal) => + fetch(`${internalAPIURL()}/public/cli-auth/token`, { + method: "POST", + signal, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ code, code_verifier: verifier }), + }), + catch: () => new Error("LLM Gateway token exchange request failed"), + }) + const body = yield* Effect.promise(() => response.text().catch(() => "")) + if (!response.ok) { + const detail = Option.getOrUndefined(decodeTokenError(body))?.error_description + return yield* Effect.fail( + new Error(detail ? `LLM Gateway login failed: ${detail}` : `LLM Gateway login failed (${response.status})`), + ) + } + const token = Option.getOrUndefined(decodeToken(body)) + const expires = token?.expires_at ? Date.parse(token.expires_at) : maxExpiry + if (!token || !Number.isSafeInteger(expires)) + return yield* Effect.fail(new Error("Invalid LLM Gateway token response")) + return Credential.OAuth.make({ + type: "oauth", + methodID: browserMethodID, + access: token.api_key, + refresh: "", + expires, + }) + }) +} + function listen(server: Server) { return Effect.callback((resume) => { const onError = (error: Error) => resume(Effect.fail(error)) diff --git a/packages/core/test/plugin/provider-llmgateway.test.ts b/packages/core/test/plugin/provider-llmgateway.test.ts index 59b2431f..25640e90 100644 --- a/packages/core/test/plugin/provider-llmgateway.test.ts +++ b/packages/core/test/plugin/provider-llmgateway.test.ts @@ -201,50 +201,76 @@ describe("LLMGatewayPlugin", () => { }), ) - it.live("stores the key the dashboard hands back to the loopback server", () => + it.live("redeems the one-time code from the loopback with the PKCE verifier", () => Effect.gen(function* () { yield* addPlugin() const integrations = yield* Integration.Service const credentials = yield* Credential.Service const integrationID = Integration.ID.make("llmgateway-devpass") - const attempt = yield* integrations.oauth.connect({ - integrationID, - methodID: Integration.MethodID.make("browser"), - label: "DevPass", - }) - const url = new URL(attempt.url) - expect(url.origin + url.pathname).toBe("https://llmgateway.io/connect/cli") - expect(url.searchParams.get("org")).toBe("devpass") - expect(url.searchParams.get("source")).toBe("devpass-code") - const callback = new URL(url.searchParams.get("callback") ?? "") - expect(callback.hostname).toBe("127.0.0.1") + const exchanges: { code: string; code_verifier: string }[] = [] + const token = { + status: 200, + body: { api_key: "llmgtwy_minted", expires_at: "2099-01-01T00:00:00.000Z" } as object, + } + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + if (String(input) !== "https://internal.llmgateway.io/public/cli-auth/token") return realFetch(input, init) + exchanges.push(JSON.parse(String(init?.body))) + return Response.json(token.body, { status: token.status }) + }) as typeof fetch + const connect = () => + integrations.oauth + .connect({ integrationID, methodID: Integration.MethodID.make("browser"), label: "DevPass" }) + .pipe(Effect.map((attempt) => ({ attempt, url: new URL(attempt.url) }))) + const callback = (url: URL, params: Record) => { + const target = new URL(url.searchParams.get("callback") ?? "") + for (const [key, value] of Object.entries(params)) target.searchParams.set(key, value) + return Effect.promise(() => realFetch(target, { headers: { Connection: "close" } })) + } + const settled = (attemptID: Integration.AttemptID) => + integrations.oauth.status({ integrationID, attemptID }).pipe( + Effect.repeat({ + until: (value) => value.status !== "pending", + schedule: Schedule.spaced("1 millis"), + times: 100, + }), + ) - const forged = new URL(callback) - forged.searchParams.set("state", "wrong") - forged.searchParams.set("key", "llmgtwy_forged") - expect((yield* Effect.promise(() => fetch(forged, { headers: { Connection: "close" } }))).status).toBe(400) - expect((yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).status).toBe("failed") + const forged = yield* connect() + expect(forged.url.origin + forged.url.pathname).toBe("https://llmgateway.io/connect/cli") + expect(forged.url.searchParams.get("org")).toBe("devpass") + expect(forged.url.searchParams.get("source")).toBe("devpass-code") + expect(forged.url.searchParams.get("code_challenge_method")).toBe("S256") + expect(new URL(forged.url.searchParams.get("callback") ?? "").hostname).toBe("127.0.0.1") + expect((yield* callback(forged.url, { state: "wrong", code: "forged" })).status).toBe(400) + expect((yield* settled(forged.attempt.attemptID)).status).toBe("failed") - const retry = yield* integrations.oauth.connect({ - integrationID, - methodID: Integration.MethodID.make("browser"), - label: "DevPass", - }) - const next = new URL(retry.url) - const ok = new URL(next.searchParams.get("callback") ?? "") - ok.searchParams.set("state", next.searchParams.get("state") ?? "") - ok.searchParams.set("key", "llmgtwy_minted") - expect((yield* Effect.promise(() => fetch(ok, { headers: { Connection: "close" } }))).status).toBe(200) - const status = yield* integrations.oauth.status({ integrationID, attemptID: retry.attemptID }).pipe( - Effect.repeat({ - until: (value) => value.status !== "pending", - schedule: Schedule.spaced("1 millis"), - times: 100, - }), + token.status = 400 + token.body = { error: "invalid_grant", error_description: "The login code is invalid" } + const rejected = yield* connect() + expect( + (yield* callback(rejected.url, { state: rejected.url.searchParams.get("state") ?? "", code: "stale" })).status, + ).toBe(400) + expect((yield* settled(rejected.attempt.attemptID)).status).toBe("failed") + + token.status = 200 + token.body = { api_key: "llmgtwy_minted", expires_at: "2099-01-01T00:00:00.000Z" } + const ok = yield* connect() + expect( + (yield* callback(ok.url, { state: ok.url.searchParams.get("state") ?? "", code: "one-time" })).status, + ).toBe(200) + expect((yield* settled(ok.attempt.attemptID)).status).toBe("complete") + const exchange = exchanges.at(-1) + expect(exchange?.code).toBe("one-time") + expect(new Bun.CryptoHasher("sha256").update(exchange?.code_verifier ?? "").digest("base64url")).toBe( + ok.url.searchParams.get("code_challenge") ?? "", ) - expect(status.status).toBe("complete") const saved = (yield* credentials.list(integrationID)).find((item) => item.label === "DevPass")?.value - expect(saved).toMatchObject({ type: "oauth", access: "llmgtwy_minted", refresh: "" }) + expect(saved).toMatchObject({ + type: "oauth", + access: "llmgtwy_minted", + refresh: "", + expires: Date.parse("2099-01-01T00:00:00.000Z"), + }) }), )