11import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration"
22import { 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"
55import { App } from "../../app.js"
66import { Credential } from "../../credential.js"
77import { Hash } from "@opencode/util/hash"
@@ -12,54 +12,88 @@ import { OauthCallbackPage } from "../../oauth/page.js"
1212
1313const 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 ( / \/ + $ / , "" )
1521const 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
1925const 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.
2440const 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+
87162function listen ( server : Server ) {
88163 return Effect . callback < number , Error > ( ( resume ) => {
89164 const onError = ( error : Error ) => resume ( Effect . fail ( error ) )
0 commit comments