@@ -32,6 +32,8 @@ const providerID = Provider.ID.openai |
32 | 32 | const integrationID = Integration.ID.make("openai") |
33 | 33 | const methodID = Integration.MethodID.make("chatgpt-token-sharing") |
34 | 34 | const modelCacheKey = (clientID: string) => `models:${clientID}` |
| 35 | +// Clients whose refresh token OpenAI rejected. Signing in while the active connection is one of these reconnects it. |
| 36 | +const expiredKey = "chatgpt-expired-clients" |
35 | 37 | // Used when the catalog has no Sign in with ChatGPT list. gpt-5.5 is rejected there. |
36 | 38 | const fallbackModels = new Set([ |
37 | 39 | "gpt-5.6-luna", |
@@ -94,15 +96,24 @@ const decodeCachedModels = Schema.decodeUnknownOption(Schema.Array(RemoteModel)) |
94 | 96 | const decodeInvalidGrant = Schema.decodeUnknownOption( |
95 | 97 | Schema.fromJsonString(Schema.Struct({ error: Schema.Literal("invalid_grant") })), |
96 | 98 | ) |
| 99 | +const decodeExpired = Schema.decodeUnknownOption(Schema.Array(Schema.String)) |
| 100 | +const expiredClients = (storage: Context["storage"]) => |
| 101 | + storage |
| 102 | + .get(expiredKey) |
| 103 | + .pipe(Effect.map((value) => Option.getOrElse(decodeExpired(value), (): readonly string[] => []))) |
| 104 | +const Metadata = Schema.Struct({ |
| 105 | + clientID: Schema.String, |
| 106 | + scopes: Schema.optional(Schema.Array(Schema.String)), |
| 107 | + email: Schema.optional(Schema.String), |
| 108 | +}) |
97 | 109 | const decodeMetadata = Schema.decodeUnknownOption( |
98 | 110 | Schema.Struct({ |
99 | | - clientID: Schema.String, |
100 | | - scopes: Schema.optional(Schema.Array(Schema.String)), |
| 111 | + ...Metadata.fields, |
101 | 112 | models: Schema.optional(Schema.Array(RemoteModel)), |
102 | 113 | }), |
103 | 114 | ) |
104 | 115 |
|
105 | | -const signIn = (app: App.Info, savedClientID: () => string | undefined, storage: Context["storage"]) => |
| 116 | +const signIn = (app: App.Info, active: () => Credential.OAuth | undefined, storage: Context["storage"]) => |
106 | 117 | ({ |
107 | 118 | integrationID, |
108 | 119 | method: { |
@@ -118,7 +129,12 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage: |
118 | 129 | const pkce = yield* Effect.promise(generatePKCE) |
119 | 130 | const state = randomValue() |
120 | 131 | const nonce = randomValue() |
121 | | - const savedID = savedClientID() |
| 132 | + // Each issued client only accepts its own ChatGPT account. Signing in while connected adds another account, |
| 133 | + // which needs a new client, unless the active connection has expired and this reconnects it. |
| 134 | + const metadata = Option.getOrUndefined(decodeMetadata(active()?.metadata)) |
| 135 | + const expired = yield* expiredClients(storage) |
| 136 | + const reconnect = metadata && expired.includes(metadata.clientID) ? metadata : undefined |
| 137 | + const savedID = reconnect?.clientID |
122 | 138 | // `response` is the browser's pending callback request; a pasted redirect has none. |
123 | 139 | const received = yield* Deferred.make<{ code: string; clientID?: string; response?: ServerResponse }, Error>() |
124 | 140 | // Lazy so runtimes without a loopback listener (workerd) never evaluate node:http. |
@@ -163,7 +179,7 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage: |
163 | 179 | const redirect = `http://127.0.0.1:${port}/auth/callback` |
164 | 180 | return { |
165 | 181 | mode: "auto" as const, |
166 | | - url: authorizeURL(redirect, pkce, state, nonce, savedID, hostID), |
| 182 | + url: authorizeURL(redirect, pkce, state, nonce, savedID, hostID, reconnect), |
167 | 183 | instructions: "Complete authorization in your browser. This window will close automatically.", |
168 | 184 | callback: Effect.gen(function* () { |
169 | 185 | const result = yield* Deferred.await(received) |
@@ -194,8 +210,14 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage: |
194 | 210 | ), |
195 | 211 | ) |
196 | 212 | if (!tokens.id_token) return yield* Effect.fail(new Error("ChatGPT sign-in did not return an ID token.")) |
197 | | - yield* verifyIDToken(tokens.id_token, clientID, nonce) |
198 | | - return credential(tokens, clientID) |
| 213 | + const email = yield* verifyIDToken(tokens.id_token, clientID, nonce) |
| 214 | + const stale = yield* expiredClients(storage) |
| 215 | + if (stale.includes(clientID)) |
| 216 | + yield* storage.set( |
| 217 | + expiredKey, |
| 218 | + stale.filter((id) => id !== clientID), |
| 219 | + ) |
| 220 | + return credential(tokens, { clientID, email }) |
199 | 221 | }).pipe( |
200 | 222 | Effect.tap(() => respond()), |
201 | 223 | Effect.tapError((error) => respond(error instanceof Error ? error.message : "ChatGPT sign-in failed")), |
@@ -209,7 +231,17 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage: |
209 | 231 | }), |
210 | 232 | } |
211 | 233 | }), |
212 | | - refresh: (value) => refresh(value, app), |
| 234 | + refresh: (value) => |
| 235 | + refresh(value, app).pipe( |
| 236 | + Effect.tapError((error) => |
| 237 | + Effect.gen(function* () { |
| 238 | + const clientID = Option.getOrUndefined(decodeMetadata(value.metadata))?.clientID |
| 239 | + if (!(error instanceof SignInExpired) || !clientID) return |
| 240 | + const expired = yield* expiredClients(storage) |
| 241 | + if (!expired.includes(clientID)) yield* storage.set(expiredKey, [...expired, clientID]) |
| 242 | + }), |
| 243 | + ), |
| 244 | + ), |
213 | 245 | revoke: (value) => revoke(value, app), |
214 | 246 | }) satisfies IntegrationOAuthMethodRegistration |
215 | 247 |
|
@@ -250,9 +282,7 @@ export const ChatGPTPlugin = define({ |
250 | 282 | }) |
251 | 283 |
|
252 | 284 | yield* ctx.integration.transform((editor) => { |
253 | | - editor.method.update( |
254 | | - signIn(ctx.app, () => Option.getOrUndefined(decodeMetadata(chatgpt?.metadata))?.clientID, ctx.storage), |
255 | | - ) |
| 285 | + editor.method.update(signIn(ctx.app, () => chatgpt, ctx.storage)) |
256 | 286 | }) |
257 | 287 | yield* Effect.forEach( |
258 | 288 | yield* credentials.list(Integration.ID.make("openai")), |
@@ -424,7 +454,7 @@ export function refresh(value: Credential.OAuth, app: App.Info, url = tokenURL) |
424 | 454 | }, |
425 | 455 | "This ChatGPT sign-in has expired or was revoked. Connect again.", |
426 | 456 | ) |
427 | | - return credential(tokens, metadata.clientID, metadata.scopes) |
| 457 | + return credential(tokens, metadata) |
428 | 458 | }) |
429 | 459 | } |
430 | 460 |
|
@@ -524,32 +554,40 @@ export function verifyIDToken( |
524 | 554 | }) |
525 | 555 | if (typeof payload.sub !== "string" || !payload.sub.trim()) throw new Error("ID token subject is missing") |
526 | 556 | if (payload.nonce !== nonce) throw new Error("ID token nonce does not match this sign-in attempt") |
| 557 | + return typeof payload.email === "string" ? payload.email : undefined |
527 | 558 | }, |
528 | 559 | catch: (cause) => new Error("ChatGPT sign-in returned an invalid ID token.", { cause }), |
529 | 560 | }) |
530 | 561 | } |
531 | 562 |
|
| 563 | +class SignInExpired extends Error {} |
| 564 | + |
532 | 565 | // `rejected` replaces the error when OpenAI answers invalid_grant, which means different things per grant type. |
533 | 566 | function request<A>(url: string, init: RequestInit, rejected?: string) { |
534 | 567 | return Effect.tryPromise({ |
535 | 568 | try: async (signal) => { |
536 | 569 | const response = await fetch(url, { ...init, signal }) |
537 | 570 | if (response.ok) return response.json() as Promise<A> |
538 | | - if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new Error(rejected) |
| 571 | + if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new SignInExpired(rejected) |
539 | 572 | throw new Error(`Request failed: ${response.status}`) |
540 | 573 | }, |
541 | 574 | catch: (cause) => cause, |
542 | 575 | }) |
543 | 576 | } |
544 | 577 |
|
545 | | -function credential(tokens: TokenResponse, clientID: string, scopes?: ReadonlyArray<string>) { |
| 578 | +// `email` preselects the account when it reconnects, and goes away with the credential on logout. |
| 579 | +function credential(tokens: TokenResponse, metadata: typeof Metadata.Type) { |
546 | 580 | return Credential.OAuth.make({ |
547 | 581 | type: "oauth", |
548 | 582 | methodID, |
549 | 583 | refresh: tokens.refresh_token, |
550 | 584 | access: tokens.access_token, |
551 | 585 | expires: Date.now() + (tokens.expires_in ?? 3600) * 1000, |
552 | | - metadata: { clientID, scopes: tokens.scope?.split(" ").filter(Boolean) ?? scopes ?? [] }, |
| 586 | + metadata: { |
| 587 | + clientID: metadata.clientID, |
| 588 | + scopes: tokens.scope?.split(" ").filter(Boolean) ?? metadata.scopes ?? [], |
| 589 | + ...(metadata.email ? { email: metadata.email } : {}), |
| 590 | + }, |
553 | 591 | }) |
554 | 592 | } |
555 | 593 |
|
@@ -575,11 +613,14 @@ function authorizeURL( |
575 | 613 | nonce: string, |
576 | 614 | savedID: string | undefined, |
577 | 615 | hostID: string, |
| 616 | + account?: { email?: string }, |
578 | 617 | ) { |
579 | 618 | return `${issuer}/api/accounts/authorize?${new URLSearchParams({ |
580 | 619 | client_id: savedID ?? registrationClientID, |
581 | 620 | ...(savedID ? {} : { agent_name_hint: agentName }), |
582 | 621 | ext_agent_host_id: hostID, |
| 622 | + // Preselect the account being reconnected. |
| 623 | + ...(account?.email ? { login_hint: account.email } : {}), |
583 | 624 | // Enable only for user-requested consent retries after OpenAI confirms deployment; |
584 | 625 | // ordinary sign-ins must not force reconsent. |
585 | 626 | // force_reconsent: "true", |
|