@@ -36,6 +36,8 @@ const newAccountMethodID = Integration.MethodID.make("chatgpt-token-sharing-new" |
36 | 36 | // the client instead of registering another app in the user's ChatGPT settings. |
37 | 37 | const profilesKey = "chatgpt-profiles" |
38 | 38 | const lastClientKey = "chatgpt-last-client" |
| 39 | +// Clients whose refresh token OpenAI rejected. Signing in again while only these are saved reconnects one of them. |
| 40 | +const expiredKey = "chatgpt-expired-clients" |
39 | 41 | const modelCacheKey = (clientID: string) => `models:${clientID}` |
40 | 42 | // Used when the catalog has no Sign in with ChatGPT list. gpt-5.5 is rejected there. |
41 | 43 | const fallbackModels = new Set([ |
@@ -101,6 +103,11 @@ const decodeInvalidGrant = Schema.decodeUnknownOption( |
101 | 103 | ) |
102 | 104 | const Profile = Schema.Struct({ subject: Schema.String, email: Schema.optional(Schema.String), idToken: Schema.String }) |
103 | 105 | const decodeProfiles = Schema.decodeUnknownOption(Schema.Record(Schema.String, Profile)) |
| 106 | +const decodeExpired = Schema.decodeUnknownOption(Schema.Array(Schema.String)) |
| 107 | +const expiredClients = (storage: Context["storage"]) => |
| 108 | + storage |
| 109 | + .get(expiredKey) |
| 110 | + .pipe(Effect.map((value) => Option.getOrElse(decodeExpired(value), (): readonly string[] => []))) |
104 | 111 | const decodeMetadata = Schema.decodeUnknownOption( |
105 | 112 | Schema.Struct({ |
106 | 113 | clientID: Schema.String, |
@@ -111,7 +118,7 @@ const decodeMetadata = Schema.decodeUnknownOption( |
111 | 118 |
|
112 | 119 | const signIn = ( |
113 | 120 | app: App.Info, |
114 | | - savedClientID: () => string | undefined, |
| 121 | + savedClients: () => Effect.Effect<ReadonlyArray<string>>, |
115 | 122 | storage: Context["storage"], |
116 | 123 | newAccount = false, |
117 | 124 | ) => |
@@ -132,7 +139,10 @@ const signIn = ( |
132 | 139 | const nonce = randomValue() |
133 | 140 | const profiles = Option.getOrUndefined(decodeProfiles(yield* storage.get(profilesKey))) |
134 | 141 | const last = yield* storage.get(lastClientKey) |
135 | | - const savedID = newAccount ? undefined : (savedClientID() ?? (typeof last === "string" ? last : undefined)) |
| 142 | + const expired = yield* expiredClients(storage) |
| 143 | + // A working saved account means this sign-in adds another one, which needs its own client. |
| 144 | + const adding = (yield* savedClients()).some((id) => !expired.includes(id)) |
| 145 | + const savedID = newAccount || adding || typeof last !== "string" ? undefined : last |
136 | 146 | const profile = savedID ? profiles?.[savedID] : undefined |
137 | 147 | // `response` is the browser's pending callback request; a pasted redirect has none. |
138 | 148 | const received = yield* Deferred.make<{ code: string; clientID?: string; response?: ServerResponse }, Error>() |
@@ -218,6 +228,12 @@ const signIn = ( |
218 | 228 | const saved = Option.getOrUndefined(decodeProfiles(yield* storage.get(profilesKey))) |
219 | 229 | yield* storage.set(profilesKey, { ...saved, [clientID]: { ...identity, idToken: tokens.id_token } }) |
220 | 230 | yield* storage.set(lastClientKey, clientID) |
| 231 | + const stale = yield* expiredClients(storage) |
| 232 | + if (stale.includes(clientID)) |
| 233 | + yield* storage.set( |
| 234 | + expiredKey, |
| 235 | + stale.filter((id) => id !== clientID), |
| 236 | + ) |
221 | 237 | return credential(tokens, clientID) |
222 | 238 | }).pipe( |
223 | 239 | Effect.tap(() => respond()), |
@@ -232,7 +248,17 @@ const signIn = ( |
232 | 248 | }), |
233 | 249 | } |
234 | 250 | }), |
235 | | - refresh: (value) => refresh(value, app), |
| 251 | + refresh: (value) => |
| 252 | + refresh(value, app).pipe( |
| 253 | + Effect.tapError((error) => |
| 254 | + Effect.gen(function* () { |
| 255 | + const clientID = Option.getOrUndefined(decodeMetadata(value.metadata))?.clientID |
| 256 | + if (!(error instanceof SignInExpired) || !clientID) return |
| 257 | + const expired = yield* expiredClients(storage) |
| 258 | + if (!expired.includes(clientID)) yield* storage.set(expiredKey, [...expired, clientID]) |
| 259 | + }), |
| 260 | + ), |
| 261 | + ), |
236 | 262 | revoke: (value) => revoke(value, app), |
237 | 263 | }) satisfies IntegrationOAuthMethodRegistration |
238 | 264 |
|
@@ -281,10 +307,19 @@ export const ChatGPTPlugin = define({ |
281 | 307 | return !Equal.equals(previous, source) |
282 | 308 | }) |
283 | 309 |
|
284 | | - const activeClientID = () => Option.getOrUndefined(decodeMetadata(chatgpt?.metadata))?.clientID |
| 310 | + const savedClients = () => |
| 311 | + credentials.list(integrationID).pipe( |
| 312 | + Effect.map((entries) => |
| 313 | + entries.flatMap((entry) => { |
| 314 | + if (entry.value.type !== "oauth" || entry.value.methodID !== methodID) return [] |
| 315 | + const clientID = Option.getOrUndefined(decodeMetadata(entry.value.metadata))?.clientID |
| 316 | + return clientID ? [clientID] : [] |
| 317 | + }), |
| 318 | + ), |
| 319 | + ) |
285 | 320 | yield* ctx.integration.transform((editor) => { |
286 | | - editor.method.update(signIn(ctx.app, activeClientID, ctx.storage)) |
287 | | - if (known) editor.method.update(signIn(ctx.app, activeClientID, ctx.storage, true)) |
| 321 | + editor.method.update(signIn(ctx.app, savedClients, ctx.storage)) |
| 322 | + if (known) editor.method.update(signIn(ctx.app, savedClients, ctx.storage, true)) |
288 | 323 | }) |
289 | 324 | yield* Effect.forEach( |
290 | 325 | yield* credentials.list(Integration.ID.make("openai")), |
@@ -562,13 +597,15 @@ export function verifyIDToken( |
562 | 597 | }) |
563 | 598 | } |
564 | 599 |
|
| 600 | +class SignInExpired extends Error {} |
| 601 | + |
565 | 602 | // `rejected` replaces the error when OpenAI answers invalid_grant, which means different things per grant type. |
566 | 603 | function request<A>(url: string, init: RequestInit, rejected?: string) { |
567 | 604 | return Effect.tryPromise({ |
568 | 605 | try: async (signal) => { |
569 | 606 | const response = await fetch(url, { ...init, signal }) |
570 | 607 | if (response.ok) return response.json() as Promise<A> |
571 | | - if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new Error(rejected) |
| 608 | + if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new SignInExpired(rejected) |
572 | 609 | throw new Error(`Request failed: ${response.status}`) |
573 | 610 | }, |
574 | 611 | catch: (cause) => cause, |
|