@godspeedai/cognate-provider-openai-oauth 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @godspeedai/cognate-provider-openai-oauth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sign in with ChatGPT (SIWC) for open-source, locally hosted Cognate runs: an OAuth/OIDC
4
+ credential adapter and a governed subscription-backed Responses provider.
5
+
6
+ - Dynamic client registration (`dynamic_agent_client` → issued `oaiapp_...` id) with a stable
7
+ per-host `ext_agent_host_id`.
8
+ - PKCE S256, fresh `state`/`nonce` per attempt, loopback callback on `127.0.0.1` (only the port
9
+ varies), system-browser handoff without a shell.
10
+ - ID-token validation against OpenAI's JWKS (RS256/ES256 only), issuer/audience/expiry/nonce
11
+ checks, `sub` as the account identity.
12
+ - Atomic, 0600 credential records per issued client id; refresh-token rotation replaces the
13
+ whole token set under a single-flight lock.
14
+ - Revocation on sign-out; automation use is a separate, secret-free, explicit local consent
15
+ record enforced by `assertSubscriptionUse` (see `@godspeedai/cognate-provider-auth`).
16
+ - Plan-backed inference goes through the Responses adapter with the SIWC preview constraints
17
+ enforced: `store:false`, `stream:true`, no `temperature`/`max_output_tokens`/system-role input.
18
+
19
+ This package never reads credentials from other applications (Codex, OpenCode, …) and never
20
+ places tokens in URLs, logs, or durable events. A bearer token typed into a field is not an
21
+ OAuth sign-in; use `@godspeedai/cognate-provider-auth` sources for that case.
22
+
23
+ Conformance: `bun test packages/provider-openai-oauth/test`.
24
+
25
+ License: Apache-2.0.
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@godspeedai/cognate-provider-openai-oauth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Sign in with ChatGPT (SIWC) OAuth/OIDC credential adapter: dynamic client registration, PKCE sign-in, validated tokens, rotating refresh, and governed subscription inference.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/GodSpeedAI/Cognate.git",
10
+ "directory": "packages/provider-openai-oauth"
11
+ },
12
+ "engines": {
13
+ "bun": ">=1.4.0"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "exports": {
22
+ ".": "./src/index.ts"
23
+ },
24
+ "dependencies": {
25
+ "@godspeedai/cognate-capabilities": "^0.2.0",
26
+ "@godspeedai/cognate-provider-auth": "^0.2.0",
27
+ "@godspeedai/cognate-provider-openai-responses": "^0.2.0"
28
+ }
29
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./protocol.ts";
2
+ export * from "./jwt.ts";
3
+ export * from "./store.ts";
4
+ export * from "./session.ts";
5
+ export * from "./provider.ts";
package/src/jwt.ts ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Minimal JWT validation against a JWKS. RS256 and ES256 only — the algorithms OpenAI's
3
+ * discovery documents publish — so an `alg` confusion or "none" token cannot pass.
4
+ * No third-party JWT library: the validation surface is small and fully tested here.
5
+ */
6
+ import { createHash, createPublicKey, randomBytes, verify as cryptoVerify } from "node:crypto";
7
+ import type { HttpFetch } from "./protocol.ts";
8
+
9
+ export interface Jwk {
10
+ readonly kty: string;
11
+ readonly kid?: string;
12
+ readonly alg?: string;
13
+ readonly use?: string;
14
+ readonly n?: string;
15
+ readonly e?: string;
16
+ readonly crv?: string;
17
+ readonly x?: string;
18
+ readonly y?: string;
19
+ readonly [key: string]: unknown;
20
+ }
21
+
22
+ export interface ValidatedIdToken {
23
+ readonly issuer: string;
24
+ readonly subject: string;
25
+ readonly audience: string;
26
+ readonly nonce: string | undefined;
27
+ readonly claims: Readonly<Record<string, unknown>>;
28
+ }
29
+
30
+ export class IdTokenError extends Error {
31
+ constructor(reason: string) {
32
+ super(`siwc: id token rejected (${reason})`);
33
+ }
34
+ }
35
+
36
+ interface JwksCache {
37
+ readonly keys: readonly Jwk[];
38
+ readonly fetchedAt: number;
39
+ }
40
+
41
+ /** Keys are cached briefly; an unfamiliar kid forces exactly one refresh (never a loop). */
42
+ export class JwksClient {
43
+ #cache: JwksCache | undefined;
44
+ #refreshing: Promise<readonly Jwk[]> | undefined;
45
+ constructor(private readonly jwksUri: string, private readonly fetchFn: HttpFetch = fetch, private readonly ttlMs = 300_000) {}
46
+
47
+ async keyFor(kid: string | undefined, alg: string): Promise<Jwk> {
48
+ if (!this.#cache || Date.now() - this.#cache.fetchedAt > this.ttlMs) await this.#refresh();
49
+ const found = this.#select(kid, alg);
50
+ if (found) return found;
51
+ await this.#refresh();
52
+ const retry = this.#select(kid, alg);
53
+ if (!retry) throw new IdTokenError("no JWKS key matches kid/alg");
54
+ return retry;
55
+ }
56
+
57
+ #select(kid: string | undefined, alg: string): Jwk | undefined {
58
+ const keys = this.#cache?.keys ?? [];
59
+ return keys.find((key) => (kid === undefined || key.kid === kid) && (key.alg === undefined || key.alg === alg) && key.use !== "enc");
60
+ }
61
+
62
+ async #refresh(): Promise<void> {
63
+ if (this.#refreshing) return void (await this.#refreshing);
64
+ this.#refreshing = (async () => {
65
+ const response = await this.fetchFn(this.jwksUri, {});
66
+ if (!response.ok) throw new IdTokenError(`JWKS fetch failed (HTTP ${response.status})`);
67
+ const document = (await response.json()) as { keys?: unknown };
68
+ if (!Array.isArray(document.keys)) throw new IdTokenError("JWKS document has no keys array");
69
+ const keys = document.keys.filter((k): k is Jwk => !!k && typeof k === "object" && ((k as Jwk).kty === "RSA" || (k as Jwk).kty === "EC"));
70
+ this.#cache = { keys, fetchedAt: Date.now() };
71
+ return keys;
72
+ })();
73
+ try {
74
+ await this.#refreshing;
75
+ } finally {
76
+ this.#refreshing = undefined;
77
+ }
78
+ }
79
+ }
80
+
81
+ export function base64UrlDecode(segment: string): Uint8Array {
82
+ const normalized = segment.replace(/-/g, "+").replace(/_/g, "/");
83
+ const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
84
+ const binary = atob(padded);
85
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
86
+ }
87
+
88
+ export interface IdTokenValidation {
89
+ readonly jwks: JwksClient;
90
+ readonly issuer: string;
91
+ readonly audience: string;
92
+ readonly nonce: string | undefined;
93
+ readonly now?: () => number;
94
+ readonly clockSkewSeconds?: number;
95
+ }
96
+
97
+ /** Verifies signature (against JWKS), iss, aud, exp/nbf/iat with small skew, and nonce. */
98
+ export async function validateIdToken(idToken: string, options: IdTokenValidation): Promise<ValidatedIdToken> {
99
+ const parts = idToken.split(".");
100
+ if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) throw new IdTokenError("malformed token structure");
101
+ let header: { alg?: unknown; kid?: unknown }, claims: Record<string, unknown>;
102
+ try {
103
+ header = JSON.parse(new TextDecoder().decode(base64UrlDecode(parts[0]))) as { alg?: unknown; kid?: unknown };
104
+ claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(parts[1]))) as Record<string, unknown>;
105
+ } catch {
106
+ throw new IdTokenError("undecodable header or payload");
107
+ }
108
+ const alg = typeof header.alg === "string" ? header.alg : undefined;
109
+ const kid = typeof header.kid === "string" ? header.kid : undefined;
110
+ if (alg !== "RS256" && alg !== "ES256") throw new IdTokenError(`unsupported alg ${String(alg)}`);
111
+ const jwk = await options.jwks.keyFor(kid, alg);
112
+ const signed = new TextEncoder().encode(`${parts[0]}.${parts[1]}`);
113
+ const signature = base64UrlDecode(parts[2]);
114
+ // ES256 JWS signatures are raw r||s; node expects ieee-p1363 for WebCrypto parity.
115
+ const valid = cryptoVerify("sha256", signed, { key: createPublicKey({ key: jwk as never, format: "jwk" }), dsaEncoding: "ieee-p1363" }, signature);
116
+ if (!valid) throw new IdTokenError("signature verification failed");
117
+
118
+ const now = Math.floor((options.now?.() ?? Date.now()) / 1000);
119
+ const skew = options.clockSkewSeconds ?? 60;
120
+ const issuer = typeof claims.iss === "string" ? claims.iss : undefined;
121
+ if (issuer !== options.issuer) throw new IdTokenError(`issuer mismatch: ${issuer ?? "missing"}`);
122
+ const audience = claims.aud;
123
+ const audienceOk = typeof audience === "string" ? audience === options.audience : Array.isArray(audience) && audience.includes(options.audience);
124
+ if (!audienceOk) throw new IdTokenError("audience does not include the issued client id");
125
+ if (typeof claims.exp !== "number" || claims.exp <= now - skew) throw new IdTokenError("token expired");
126
+ if (claims.nbf !== undefined && (typeof claims.nbf !== "number" || claims.nbf > now + skew)) throw new IdTokenError("token not yet valid");
127
+ if (claims.iat !== undefined && typeof claims.iat !== "number") throw new IdTokenError("malformed iat");
128
+ const subject = typeof claims.sub === "string" && claims.sub ? claims.sub : undefined;
129
+ if (!subject) throw new IdTokenError("missing subject");
130
+ if (options.nonce !== undefined && claims.nonce !== options.nonce) throw new IdTokenError("nonce mismatch");
131
+ return { issuer, subject, audience: options.audience, nonce: typeof claims.nonce === "string" ? claims.nonce : undefined, claims };
132
+ }
133
+
134
+ /** PKCE S256: base64url(SHA-256(verifier)), unpadded. */
135
+ export function pkceChallenge(verifier: string): string {
136
+ return createHash("sha256").update(verifier).digest("base64url");
137
+ }
138
+
139
+ export function randomToken(bytes = 32): string {
140
+ return Buffer.from(randomBytes(bytes)).toString("base64url");
141
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Sign in with ChatGPT (SIWC) wire constants and request builders, per the current official
3
+ * documentation (developers.openai.com/siwc). Production endpoints are only defaults: every
4
+ * entry point accepts overrides so conformance tests run against a deterministic fake issuer.
5
+ */
6
+ export const OPENAI_ISSUER = "https://auth.openai.com";
7
+ export const OPENAI_DISCOVERY_URL = `${OPENAI_ISSUER}/.well-known/openid-configuration`;
8
+ export const OPENAI_AUTHORIZATION_ENDPOINT = `${OPENAI_ISSUER}/api/accounts/authorize`;
9
+ export const OPENAI_TOKEN_ENDPOINT = `${OPENAI_ISSUER}/api/accounts/oauth/token`;
10
+ export const OPENAI_JWKS_URI = `${OPENAI_ISSUER}/.well-known/jwks.json`;
11
+ /** The only resource (and Responses origin) this flow covers. */
12
+ export const OPENAI_API_RESOURCE = "https://api.openai.com/v1";
13
+ /** First-registration client id; the callback returns the issued id (oaiapp_...). Never stored. */
14
+ export const DYNAMIC_AGENT_CLIENT_ID = "dynamic_agent_client";
15
+ /** Plan-usage scope whose absence means "signed in, but not authorized for plan-backed inference". */
16
+ export const PLAN_USE_SCOPE = "chatgpt.tokens.use.direct";
17
+ export const SIWC_SCOPES = ["openid", "profile", "email", "offline_access", "resource.invoke", PLAN_USE_SCOPE] as const;
18
+ /** Loopback callback path is fixed; only the port may vary between sign-ins. */
19
+ export const LOOPBACK_CALLBACK_PATH = "/auth/callback";
20
+
21
+ export interface DiscoveryDocument {
22
+ readonly issuer: string;
23
+ readonly authorization_endpoint: string;
24
+ readonly token_endpoint: string;
25
+ readonly jwks_uri: string;
26
+ readonly revocation_endpoint: string;
27
+ }
28
+
29
+ export type HttpFetch = (input: string | URL | RequestInfo, init?: RequestInit) => Promise<Response>;
30
+
31
+ /** Discovery is cached per process; tests inject their own fetch and URL anyway. */
32
+ export async function discoverEndpoints(discoveryUrl: string = OPENAI_DISCOVERY_URL, fetchFn: HttpFetch = fetch): Promise<DiscoveryDocument> {
33
+ const response = await fetchFn(discoveryUrl, {});
34
+ if (!response.ok) throw new Error(`siwc: discovery failed (HTTP ${response.status})`);
35
+ const document = (await response.json()) as Partial<DiscoveryDocument>;
36
+ for (const key of ["issuer", "authorization_endpoint", "token_endpoint", "jwks_uri", "revocation_endpoint"] as const) {
37
+ if (typeof document[key] !== "string") throw new Error(`siwc: discovery document is missing ${key}`);
38
+ }
39
+ return document as DiscoveryDocument;
40
+ }
41
+
42
+ export interface AuthorizationAttempt {
43
+ /** Exact URL for the system browser. Never log it: id_token_hint may be embedded. */
44
+ readonly authorizeUrl: string;
45
+ readonly state: string;
46
+ readonly nonce: string;
47
+ readonly codeVerifier: string;
48
+ /** The exact loopback redirect URI used in both the authorization request and the exchange. */
49
+ readonly redirectUri: string;
50
+ }
51
+
52
+ export interface AuthorizeOptions {
53
+ readonly authorizationEndpoint: string;
54
+ readonly clientId: string;
55
+ /** Stable opaque host identifier (urn:uuid:..., JWK-thumbprint URN, or did:key). */
56
+ readonly extAgentHostId: string;
57
+ readonly redirectUri: string;
58
+ readonly appName?: string;
59
+ /** Retained (possibly expired) ID token identifying the re-authorizing account. */
60
+ readonly idTokenHint?: string;
61
+ readonly loginHint?: string;
62
+ readonly state: string;
63
+ readonly nonce: string;
64
+ readonly codeChallenge: string;
65
+ /** force_reconsent/prompt=consent are opt-in; ordinary sign-ins must not force consent. */
66
+ readonly forceConsent?: boolean;
67
+ }
68
+
69
+ /** Builds the authorization URL. Every value is URL-encoded; scope is the complete SIWC set. */
70
+ export function buildAuthorizationUrl(options: AuthorizeOptions): string {
71
+ const params = new URLSearchParams({
72
+ client_id: options.clientId,
73
+ ext_agent_host_id: options.extAgentHostId,
74
+ response_type: "code",
75
+ redirect_uri: options.redirectUri,
76
+ scope: SIWC_SCOPES.join(" "),
77
+ resource: OPENAI_API_RESOURCE,
78
+ state: options.state,
79
+ nonce: options.nonce,
80
+ code_challenge_method: "S256",
81
+ code_challenge: options.codeChallenge,
82
+ });
83
+ if (options.appName) params.set("agent_name_hint", options.appName);
84
+ if (options.idTokenHint) params.set("id_token_hint", options.idTokenHint);
85
+ if (options.loginHint) params.set("login_hint", options.loginHint);
86
+ if (options.forceConsent) params.set("prompt", "consent");
87
+ return `${options.authorizationEndpoint}?${params.toString()}`;
88
+ }
89
+
90
+ export type ParsedCallback =
91
+ | { readonly kind: "success"; readonly code: string; readonly state?: string; readonly clientId?: string; readonly scope?: string }
92
+ | { readonly kind: "error"; readonly state?: string; readonly error: string; readonly errorDescription?: string };
93
+
94
+ /** Strict callback parsing: unknown parameters are ignored, nothing is echoed back. */
95
+ export function parseCallback(query: URLSearchParams): ParsedCallback {
96
+ const state = query.get("state") ?? undefined;
97
+ const error = query.get("error");
98
+ if (error) return { kind: "error", state, error, errorDescription: query.get("error_description") ?? undefined };
99
+ const code = query.get("code");
100
+ if (!code) return { kind: "error", state, error: "invalid_request", errorDescription: "callback has neither code nor error" };
101
+ const clientId = query.get("client_id") ?? undefined;
102
+ const scope = query.get("scope") ?? undefined;
103
+ return { kind: "success", code, state, clientId, scope };
104
+ }
105
+
106
+ export interface TokenResponse {
107
+ readonly accessToken: string;
108
+ readonly refreshToken: string;
109
+ readonly idToken: string;
110
+ readonly tokenType: string;
111
+ readonly expiresInSeconds: number;
112
+ readonly grantedScopes: readonly string[];
113
+ }
114
+
115
+ /** Form-encoded token request (authorization_code). No client secret in this public-client flow. */
116
+ export async function exchangeAuthorizationCode(options: {
117
+ readonly tokenEndpoint: string;
118
+ readonly clientId: string;
119
+ readonly code: string;
120
+ readonly codeVerifier: string;
121
+ readonly redirectUri: string;
122
+ readonly fetch?: HttpFetch;
123
+ readonly signal?: AbortSignal;
124
+ }): Promise<TokenResponse> {
125
+ const body = new URLSearchParams({
126
+ grant_type: "authorization_code",
127
+ client_id: options.clientId,
128
+ code: options.code,
129
+ code_verifier: options.codeVerifier,
130
+ redirect_uri: options.redirectUri,
131
+ resource: OPENAI_API_RESOURCE,
132
+ });
133
+ return tokenRequest(options.tokenEndpoint, body, options.fetch, options.signal);
134
+ }
135
+
136
+ export async function refreshTokens(options: {
137
+ readonly tokenEndpoint: string;
138
+ readonly clientId: string;
139
+ readonly refreshToken: string;
140
+ readonly fetch?: HttpFetch;
141
+ readonly signal?: AbortSignal;
142
+ }): Promise<TokenResponse> {
143
+ const body = new URLSearchParams({
144
+ grant_type: "refresh_token",
145
+ client_id: options.clientId,
146
+ refresh_token: options.refreshToken,
147
+ resource: OPENAI_API_RESOURCE,
148
+ // Omit scope to retain the original grant.
149
+ });
150
+ return tokenRequest(options.tokenEndpoint, body, options.fetch, options.signal);
151
+ }
152
+
153
+ async function tokenRequest(endpoint: string, body: URLSearchParams, fetchFn: HttpFetch = fetch, signal?: AbortSignal): Promise<TokenResponse> {
154
+ let response: Response;
155
+ try {
156
+ response = await fetchFn(endpoint, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: body.toString(), signal });
157
+ } catch {
158
+ throw new Error("siwc: token endpoint unreachable");
159
+ }
160
+ if (!response.ok) throw await tokenEndpointError(response);
161
+ let raw: Record<string, unknown>;
162
+ try {
163
+ raw = (await response.json()) as Record<string, unknown>;
164
+ } catch {
165
+ throw new Error("siwc: token endpoint returned invalid JSON");
166
+ }
167
+ const accessToken = raw.access_token, refreshToken = raw.refresh_token, idToken = raw.id_token;
168
+ if (typeof accessToken !== "string" || typeof refreshToken !== "string" || typeof idToken !== "string") {
169
+ throw new Error("siwc: token response is missing required tokens");
170
+ }
171
+ const scope = typeof raw.scope === "string" ? raw.scope.split(" ").filter(Boolean) : [];
172
+ return {
173
+ accessToken,
174
+ refreshToken,
175
+ idToken,
176
+ tokenType: typeof raw.token_type === "string" ? raw.token_type : "Bearer",
177
+ expiresInSeconds: typeof raw.expires_in === "number" ? raw.expires_in : 3600,
178
+ grantedScopes: scope,
179
+ };
180
+ }
181
+
182
+ /** Refresh failures that mean "this token set will never work again" (per SIWC error reference). */
183
+ const TERMINAL_REFRESH_CODES = new Set([
184
+ "invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_expired",
185
+ "refresh_token_invalidated", "refresh_token_reused",
186
+ ]);
187
+
188
+ export class TokenRefreshError extends Error {
189
+ constructor(readonly code: string, readonly httpStatus: number | undefined, readonly terminal: boolean) {
190
+ super(`siwc: refresh failed (${code})`);
191
+ }
192
+ }
193
+
194
+ async function tokenEndpointError(response: Response): Promise<Error> {
195
+ let code = "unknown_error";
196
+ try {
197
+ const raw = (await response.json()) as Record<string, unknown>;
198
+ if (typeof raw.error === "string") code = raw.error;
199
+ } catch {
200
+ // Diagnostic only; the body may be {"detail": "..."} — never echoed further.
201
+ }
202
+ if (response.status >= 500) return new TokenRefreshError(code, response.status, false);
203
+ return new TokenRefreshError(code, response.status, TERMINAL_REFRESH_CODES.has(code));
204
+ }
205
+
206
+ /** Revocation: an empty 200 is success, including for an already-invalid token. */
207
+ export async function revokeToken(options: {
208
+ readonly revocationEndpoint: string;
209
+ readonly clientId: string;
210
+ readonly refreshToken: string;
211
+ readonly fetch?: HttpFetch;
212
+ readonly signal?: AbortSignal;
213
+ }): Promise<void> {
214
+ const fetchFn = options.fetch ?? fetch;
215
+ const body = new URLSearchParams({ token: options.refreshToken, token_type_hint: "refresh_token", client_id: options.clientId });
216
+ let response: Response;
217
+ try {
218
+ response = await fetchFn(options.revocationEndpoint, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: body.toString(), signal: options.signal });
219
+ } catch {
220
+ throw new Error("siwc: revocation endpoint unreachable; local tokens cleared but remote revocation was not confirmed");
221
+ }
222
+ if (response.status >= 500) throw new Error(`siwc: revocation not confirmed (HTTP ${response.status}); retry or disconnect in ChatGPT Settings`);
223
+ // 200 (or any 4xx: already invalid) counts as confirmed per the SIWC error reference.
224
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Subscription-backed (ChatGPT plan) Responses provider. Wraps the shared Responses adapter so
3
+ * that EVERY request honors the SIWC preview constraints: store:false, stream:true, no
4
+ * temperature/max_output_tokens/system-role input items on this route. Settlement still requires
5
+ * response.completed; partial output is never a settled success.
6
+ */
7
+ import { ModelProviderError, type ModelRequest, type ModelProvider, type ModelDelta, type ModelResponse } from "@godspeedai/cognate-capabilities";
8
+ import { assertSubscriptionUse, type UsageMode } from "@godspeedai/cognate-provider-auth";
9
+ import { openAIResponses } from "@godspeedai/cognate-provider-openai-responses";
10
+ import { subscriptionCredentialSource, subscriptionGrant, type SiwcOptions } from "./session.ts";
11
+
12
+ export interface SubscriptionProviderOptions {
13
+ readonly id: string;
14
+ readonly model: string;
15
+ readonly clientId: string;
16
+ readonly siwc: SiwcOptions;
17
+ /** Resolved per request: interactive by default, automation only with recorded consent. */
18
+ readonly usageMode?: () => UsageMode;
19
+ readonly fetch?: Parameters<typeof openAIResponses>[0]["fetch"];
20
+ readonly timeoutMs?: number;
21
+ }
22
+
23
+ /**
24
+ * SIWC preview constraint: system-role input items are rejected on this route. System text moves
25
+ * to the request's `instructions`; temperature/max_tokens are stripped (the plan route requires
26
+ * omitting them). Used only for plan-backed requests — direct API-key traffic keeps the
27
+ * untouched adapter.
28
+ */
29
+ export function subscriptionRequest(request: ModelRequest): ModelRequest {
30
+ const system = request.messages.filter((message) => message.role === "system").map((message) => message.content).join("\n\n");
31
+ return {
32
+ ...request,
33
+ messages: request.messages.filter((message) => message.role !== "system"),
34
+ ...(system ? { instructions: [request.instructions, system].filter(Boolean).join("\n\n") } : {}),
35
+ temperature: undefined,
36
+ maxTokens: undefined,
37
+ };
38
+ }
39
+
40
+ export function subscriptionResponsesProvider(options: SubscriptionProviderOptions): ModelProvider {
41
+ const credentials = subscriptionCredentialSource(options.siwc, options.clientId);
42
+ const usageMode = options.usageMode ?? (() => "interactive" as const);
43
+ const provider = openAIResponses({
44
+ id: options.id,
45
+ baseURL: "https://api.openai.com/v1",
46
+ model: options.model,
47
+ credentials: {
48
+ acquire: async (signal?: AbortSignal) => {
49
+ // Local governance first: automation needs recorded consent, independent of token validity.
50
+ const grant = await subscriptionGrant(options.siwc, options.clientId);
51
+ assertSubscriptionUse(grant, usageMode());
52
+ return credentials.acquire(signal);
53
+ },
54
+ },
55
+ ...(options.fetch ? { fetch: options.fetch } : {}),
56
+ ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
57
+ });
58
+ return {
59
+ id: `openai-subscription:${options.id}`,
60
+ model: options.model,
61
+ features: { ...provider.features, stream: true },
62
+ // generate() is served through the stream so every plan-backed request is stream:true
63
+ // (a preview requirement); settlement still requires response.completed.
64
+ async generate(request: ModelRequest, signal?: AbortSignal): Promise<ModelResponse> {
65
+ const mapped = subscriptionRequest(request);
66
+ let final: ModelResponse | undefined;
67
+ for await (const delta of provider.stream(mapped, signal)) {
68
+ if (delta.type === "done") final = delta.response;
69
+ }
70
+ if (!final) throw new ModelProviderError("malformed_response", "subscription stream settled without a final response");
71
+ return final;
72
+ },
73
+ async *stream(request: ModelRequest, signal?: AbortSignal): AsyncIterable<ModelDelta> {
74
+ yield* provider.stream(subscriptionRequest(request), signal);
75
+ },
76
+ };
77
+ }
package/src/session.ts ADDED
@@ -0,0 +1,325 @@
1
+ /**
2
+ * SIWC session lifecycle: system-browser sign-in over a loopback callback, strict callback and
3
+ * ID-token validation, single-flight refresh with atomic rotation, revocation, and the
4
+ * per-request CredentialSource lease. Secrets never enter logs, errors, or events: every error
5
+ * path here carries at most status codes and issuer-minted error codes.
6
+ */
7
+ import { spawn } from "node:child_process";
8
+ import type { CredentialLease, CredentialSource, SubscriptionGrant } from "@godspeedai/cognate-provider-auth";
9
+ import {
10
+ DYNAMIC_AGENT_CLIENT_ID, LOOPBACK_CALLBACK_PATH, PLAN_USE_SCOPE, TokenRefreshError,
11
+ buildAuthorizationUrl, discoverEndpoints, exchangeAuthorizationCode, parseCallback, refreshTokens, revokeToken,
12
+ type HttpFetch, type ParsedCallback,
13
+ } from "./protocol.ts";
14
+ import { JwksClient, pkceChallenge, randomToken, validateIdToken } from "./jwt.ts";
15
+ import {
16
+ approveAutomation, automationApproved, clearAccountTokens, ensureHostId, fromTokenResponse,
17
+ listAccountRecords, readAccountRecord, revokeAutomationApproval, writeAccountRecord,
18
+ type AccountRecord,
19
+ } from "./store.ts";
20
+
21
+ export type { AccountRecord };
22
+ export { approveAutomation, automationApproved, listAccountRecords, revokeAutomationApproval, ensureHostId };
23
+ export { PLAN_USE_SCOPE };
24
+
25
+ export interface SiwcOptions {
26
+ /** App-local credential directory (see store.accountsDirectory for the default layout). */
27
+ readonly accountsDir: string;
28
+ /** The app's real name, used as agent_name_hint on initial dynamic registration. */
29
+ readonly appName: string;
30
+ /** Defaults to the production discovery document; tests point this at a fake issuer. */
31
+ readonly discoveryUrl?: string;
32
+ readonly fetch?: HttpFetch;
33
+ /** Opens the authorization URL in the system browser; tests capture the URL instead. */
34
+ readonly openBrowser?: (url: string) => void | Promise<void>;
35
+ /** Fixed port for the loopback listener; default is an ephemeral port (only the port may vary). */
36
+ readonly loopbackPort?: number;
37
+ readonly now?: () => number;
38
+ readonly clockSkewSeconds?: number;
39
+ readonly signal?: AbortSignal;
40
+ }
41
+
42
+ export interface SignInHints {
43
+ /** Re-authorize a specific saved registration (its issued client id). */
44
+ readonly clientId?: string;
45
+ readonly idTokenHint?: string;
46
+ readonly loginHint?: string;
47
+ /** Set when the operator explicitly (re-)requests plan usage after an earlier decline. */
48
+ readonly forceConsent?: boolean;
49
+ }
50
+
51
+ export interface SignedIn {
52
+ readonly record: AccountRecord;
53
+ /** True when the granted scopes include chatgpt.tokens.use.direct. */
54
+ readonly planUseEnabled: boolean;
55
+ }
56
+
57
+ interface PendingAttempt {
58
+ readonly state: string;
59
+ readonly nonce: string;
60
+ readonly codeVerifier: string;
61
+ readonly isRegistration: boolean;
62
+ readonly reauthSubject?: string;
63
+ }
64
+
65
+ /** One loopback sign-in attempt. The listener starts before the browser opens. */
66
+ export async function signIn(options: SiwcOptions, hints: SignInHints = {}): Promise<SignedIn> {
67
+ const now = options.now?.() ?? Date.now();
68
+ const discovery = await discoverEndpoints(options.discoveryUrl ?? "https://auth.openai.com/.well-known/openid-configuration", options.fetch);
69
+ const hostId = await ensureHostId(options.accountsDir);
70
+
71
+ const expected = hints.clientId ? await readAccountRecord(options.accountsDir, hints.clientId) : undefined;
72
+ if (hints.clientId && !expected) throw new Error("siwc: no saved registration for the requested account");
73
+
74
+ const attempt: PendingAttempt = {
75
+ state: randomToken(),
76
+ nonce: randomToken(),
77
+ codeVerifier: randomToken(48),
78
+ isRegistration: !hints.clientId,
79
+ reauthSubject: expected?.subject,
80
+ };
81
+ const listener = await startLoopbackListener(options.loopbackPort, options.signal);
82
+ try {
83
+ // Only the port may vary between sign-ins; scheme/host/path are fixed (127.0.0.1 + /auth/callback).
84
+ const redirectUri = `http://127.0.0.1:${listener.port}${LOOPBACK_CALLBACK_PATH}`;
85
+ const authorizeUrl = buildAuthorizationUrl({
86
+ authorizationEndpoint: discovery.authorization_endpoint,
87
+ clientId: hints.clientId ?? DYNAMIC_AGENT_CLIENT_ID,
88
+ extAgentHostId: hostId,
89
+ redirectUri,
90
+ appName: attempt.isRegistration ? options.appName : undefined,
91
+ idTokenHint: hints.idTokenHint ?? (expected?.idToken ? expected.idToken : undefined),
92
+ loginHint: hints.loginHint ?? expected?.email,
93
+ state: attempt.state,
94
+ nonce: attempt.nonce,
95
+ codeChallenge: pkceChallenge(attempt.codeVerifier),
96
+ forceConsent: hints.forceConsent,
97
+ });
98
+ await (options.openBrowser ?? defaultOpenBrowser)(authorizeUrl);
99
+
100
+ const callback = await listener.waitForCallback(attempt.state);
101
+ if (callback.kind === "error") throw new Error(`siwc: authorization ended with ${callback.error}`);
102
+ // Registration must return an issued client id; reauthorization must not switch clients.
103
+ let clientId = hints.clientId;
104
+ if (attempt.isRegistration) {
105
+ if (!callback.clientId) throw new Error("siwc: registration callback lacked an issued client id; registration is incomplete");
106
+ if (callback.clientId === DYNAMIC_AGENT_CLIENT_ID) throw new Error("siwc: callback returned the dynamic entrypoint id, not an issued client id");
107
+ clientId = callback.clientId;
108
+ } else if (callback.clientId && callback.clientId !== clientId) {
109
+ throw new Error("siwc: callback supplied a different client id than the pending registration; rejected");
110
+ }
111
+
112
+ const tokens = await exchangeAuthorizationCode({
113
+ tokenEndpoint: discovery.token_endpoint,
114
+ clientId: clientId!,
115
+ code: callback.code,
116
+ codeVerifier: attempt.codeVerifier,
117
+ redirectUri,
118
+ fetch: options.fetch,
119
+ signal: options.signal,
120
+ });
121
+
122
+ const jwks = new JwksClient(discovery.jwks_uri, options.fetch);
123
+ const validated = await validateIdToken(tokens.idToken, {
124
+ jwks,
125
+ issuer: discovery.issuer,
126
+ audience: clientId!,
127
+ nonce: attempt.nonce,
128
+ now: options.now,
129
+ clockSkewSeconds: options.clockSkewSeconds,
130
+ });
131
+ // Reauthorization must stay on the selected account before anything is overwritten.
132
+ if (!attempt.isRegistration && attempt.reauthSubject && validated.subject !== attempt.reauthSubject) {
133
+ throw new Error("siwc: validated identity does not match the selected account; credentials not replaced");
134
+ }
135
+
136
+ const previous = await readAccountRecord(options.accountsDir, clientId!);
137
+ const email = typeof validated.claims.email === "string" ? validated.claims.email : previous?.email;
138
+ const record = fromTokenResponse(
139
+ { subject: validated.subject, issuer: discovery.issuer, ...(email ? { email } : {}), clientId: clientId!, extAgentHostId: hostId },
140
+ tokens,
141
+ now,
142
+ );
143
+ await writeAccountRecord(options.accountsDir, record);
144
+ const callbackScopes = (callback.scope ?? "").split(" ").filter(Boolean);
145
+ return { record, planUseEnabled: record.grantedScopes.includes(PLAN_USE_SCOPE) || callbackScopes.includes(PLAN_USE_SCOPE) };
146
+ } finally {
147
+ await listener.close();
148
+ }
149
+ }
150
+
151
+ /** Single-flight map keyed by client id: concurrent callers share one rotation. */
152
+ const inFlightRefreshes = new Map<string, Promise<AccountRecord>>();
153
+
154
+ export async function refreshAccount(options: SiwcOptions, clientId: string): Promise<AccountRecord> {
155
+ const existing = inFlightRefreshes.get(clientId);
156
+ if (existing) return existing;
157
+ const task = (async (): Promise<AccountRecord> => {
158
+ const record = await readAccountRecord(options.accountsDir, clientId);
159
+ if (!record?.refreshToken) throw new Error("siwc: no refreshable credentials for this account; sign in again");
160
+ const discovery = await discoverEndpoints(options.discoveryUrl ?? "https://auth.openai.com/.well-known/openid-configuration", options.fetch);
161
+ try {
162
+ const tokens = await refreshTokens({
163
+ tokenEndpoint: discovery.token_endpoint,
164
+ clientId: record.clientId,
165
+ refreshToken: record.refreshToken,
166
+ fetch: options.fetch,
167
+ signal: options.signal,
168
+ });
169
+ // Rotation replaces access token, refresh token, scopes and expiry together, atomically.
170
+ const updated = fromTokenResponse(
171
+ { subject: record.subject, issuer: record.issuer, ...(record.email ? { email: record.email } : {}), clientId: record.clientId, extAgentHostId: record.extAgentHostId },
172
+ tokens,
173
+ options.now?.() ?? Date.now(),
174
+ );
175
+ await writeAccountRecord(options.accountsDir, updated);
176
+ return updated;
177
+ } catch (error) {
178
+ if (error instanceof TokenRefreshError && error.terminal) {
179
+ // Unusable token set: keep the registration mapping, clear the tokens, require sign-in.
180
+ await clearAccountTokens(options.accountsDir, clientId);
181
+ }
182
+ throw error;
183
+ }
184
+ })();
185
+ inFlightRefreshes.set(clientId, task);
186
+ try {
187
+ return await task;
188
+ } finally {
189
+ inFlightRefreshes.delete(clientId);
190
+ }
191
+ }
192
+
193
+ /** Refresh errors that mean the token set will never work again (per the SIWC error reference). */
194
+ export { TokenRefreshError } from "./protocol.ts";
195
+
196
+ /**
197
+ * Signs out: stop using tokens, revoke the renewable session remotely, then clear local token
198
+ * material while retaining the account/client mapping and host id.
199
+ */
200
+ export async function signOut(options: SiwcOptions, clientId: string): Promise<{ remoteRevoked: boolean }> {
201
+ const record = await readAccountRecord(options.accountsDir, clientId);
202
+ if (!record?.refreshToken) return { remoteRevoked: false };
203
+ const discovery = await discoverEndpoints(options.discoveryUrl ?? "https://auth.openai.com/.well-known/openid-configuration", options.fetch);
204
+ await revokeToken({ revocationEndpoint: discovery.revocation_endpoint, clientId: record.clientId, refreshToken: record.refreshToken, fetch: options.fetch, signal: options.signal });
205
+ await clearAccountTokens(options.accountsDir, clientId);
206
+ return { remoteRevoked: true };
207
+ }
208
+
209
+ const EXPIRY_MARGIN_MS = 60_000;
210
+
211
+ /** A CredentialSource that leases a valid access token per request and refreshes near expiry. */
212
+ export function subscriptionCredentialSource(options: SiwcOptions, clientId: string): CredentialSource & { grant(): Promise<{ subject: string; scopes: readonly string[] }> } {
213
+ return {
214
+ async acquire(_signal?: AbortSignal): Promise<CredentialLease> {
215
+ let record = await readAccountRecord(options.accountsDir, clientId);
216
+ if (!record?.accessToken) throw new Error("siwc: account is not signed in; complete sign-in first");
217
+ if (record.expiresAt - EXPIRY_MARGIN_MS <= (options.now?.() ?? Date.now())) {
218
+ record = await refreshAccount(options, clientId);
219
+ }
220
+ if (!record.grantedScopes.includes(PLAN_USE_SCOPE)) {
221
+ throw new Error("siwc: ChatGPT plan use is not authorized for this account (scope chatgpt.tokens.use.direct was not granted)");
222
+ }
223
+ return {
224
+ headers: { authorization: `Bearer ${record.accessToken}` },
225
+ expiresAt: record.expiresAt,
226
+ identityRef: record.subject,
227
+ grantedScopes: record.grantedScopes,
228
+ };
229
+ },
230
+ async grant() {
231
+ const record = await readAccountRecord(options.accountsDir, clientId);
232
+ if (!record) throw new Error("siwc: account is not signed in");
233
+ return { subject: record.subject, scopes: record.grantedScopes };
234
+ },
235
+ };
236
+ }
237
+
238
+ /** The local policy grant consumed by assertSubscriptionUse (provider-auth). */
239
+ export async function subscriptionGrant(options: SiwcOptions, clientId: string): Promise<SubscriptionGrant> {
240
+ const record = await readAccountRecord(options.accountsDir, clientId);
241
+ if (!record) throw new Error("siwc: account is not signed in");
242
+ return {
243
+ identityRef: record.subject,
244
+ scopes: record.grantedScopes,
245
+ automationApproved: await automationApproved(options.accountsDir, record.subject),
246
+ };
247
+ }
248
+
249
+ /** Explicit, separately-recorded automation authorization (local policy, independent of tokens). */
250
+ export async function ensureAutomationGrant(options: SiwcOptions, clientId: string, note?: string): Promise<void> {
251
+ const record = await readAccountRecord(options.accountsDir, clientId);
252
+ if (!record) throw new Error("siwc: account is not signed in");
253
+ await approveAutomation(options.accountsDir, record.subject, note);
254
+ }
255
+
256
+ interface LoopbackListener {
257
+ readonly port: number;
258
+ waitForCallback(expectedState: string): Promise<ParsedCallback>;
259
+ close(): Promise<void>;
260
+ }
261
+
262
+ /**
263
+ * Binds 127.0.0.1 (never "localhost") on the permitted loopback interface and resolves exactly
264
+ * one callback. The response page is static; reflected callback parameters would be injection.
265
+ */
266
+ async function startLoopbackListener(port = 0, signal?: AbortSignal): Promise<LoopbackListener> {
267
+ let resolveCallback: ((value: ParsedCallback) => void) | undefined;
268
+ const callbackPromise = new Promise<ParsedCallback>((resolve) => {
269
+ resolveCallback = resolve;
270
+ });
271
+ const server = Bun.serve({
272
+ hostname: "127.0.0.1",
273
+ port,
274
+ fetch(request) {
275
+ const url = new URL(request.url);
276
+ if (url.pathname !== LOOPBACK_CALLBACK_PATH) return new Response("Not found", { status: 404 });
277
+ const parsed = parseCallback(url.searchParams);
278
+ resolveCallback?.(parsed);
279
+ const page = parsed.kind === "success"
280
+ ? "<!doctype html><title>Sign in complete</title><p>Sign-in complete. You can close this window and return to the app.</p>"
281
+ : "<!doctype html><title>Sign in failed</title><p>Sign-in did not complete. Return to the app for details.</p>";
282
+ return new Response(page, { headers: { "content-type": "text/html; charset=utf-8" } });
283
+ },
284
+ });
285
+ signal?.addEventListener("abort", () => resolveCallback?.({ kind: "error", error: "cancelled" }), { once: true });
286
+ return {
287
+ // Bun's Server types mark port optional; after a successful bind it is always set.
288
+ port: server.port ?? 0,
289
+ waitForCallback: (expectedState: string) =>
290
+ Promise.race([
291
+ callbackPromise.then((parsed) => {
292
+ // State must match the pending attempt before anything is used.
293
+ if (parsed.state !== expectedState) throw new Error("siwc: callback state mismatch; possible CSRF, attempt rejected");
294
+ return parsed;
295
+ }),
296
+ new Promise<never>((_, reject) => {
297
+ const timer = setTimeout(() => reject(new Error("siwc: timed out waiting for the authorization callback")), 10 * 60_000);
298
+ timer.unref?.();
299
+ }),
300
+ ]),
301
+ close: async () => {
302
+ server.stop(true);
303
+ },
304
+ };
305
+ }
306
+
307
+ /** Opens the system browser without a shell: each platform's opener is spawned directly. */
308
+ function defaultOpenBrowser(url: string): void {
309
+ const candidates: readonly (readonly string[])[] = process.platform === "darwin"
310
+ ? [["open", url]]
311
+ : process.platform === "win32"
312
+ ? [["cmd", "/c", "start", "", url]]
313
+ : [["xdg-open", url]];
314
+ for (const candidate of candidates) {
315
+ try {
316
+ const child = spawn(candidate[0]!, candidate.slice(1) as string[], { stdio: "ignore", detached: true });
317
+ child.on("error", () => {});
318
+ child.unref();
319
+ return;
320
+ } catch {
321
+ // Try the next opener; total failure surfaces when the loop ends.
322
+ }
323
+ }
324
+ throw new Error("siwc: could not open a system browser; open the authorization URL manually");
325
+ }
package/src/store.ts ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Local credential persistence for SIWC accounts: one protected record per issued client id +
3
+ * verified identity, written atomically with owner-only permissions, refresh-token rotation
4
+ * replacing the whole token set together. Automation consent is stored SEPARATELY, in a
5
+ * secret-free record — durable event logs and this consent file never contain tokens.
6
+ */
7
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
8
+ import { dirname, join } from "node:path";
9
+ import { randomUUID } from "node:crypto";
10
+ import type { TokenResponse } from "./protocol.ts";
11
+
12
+ export interface AccountRecord {
13
+ /** Validated ID-token identity — sub, never email alone. */
14
+ readonly subject: string;
15
+ readonly issuer: string;
16
+ readonly email?: string;
17
+ readonly clientId: string;
18
+ readonly extAgentHostId: string;
19
+ /** Retained for the next id_token_hint; may be expired by definition. */
20
+ readonly idToken: string;
21
+ readonly accessToken: string;
22
+ readonly refreshToken: string;
23
+ readonly expiresAt: number;
24
+ readonly grantedScopes: readonly string[];
25
+ readonly savedAt: number;
26
+ }
27
+
28
+ /** Secret-free, separately-stored usage authorization evidence (spec §32). */
29
+ export interface AutomationConsent {
30
+ readonly subject: string;
31
+ readonly approvedAt: number;
32
+ /** Human-readable recording of what the operator approved; never contains credentials. */
33
+ readonly note?: string;
34
+ }
35
+
36
+ export function accountsDirectory(options: { readonly home: string; readonly appName: string }): string {
37
+ return join(options.home, ".config", options.appName, "openai");
38
+ }
39
+
40
+ export function accountPath(accountsDir: string, clientId: string): string {
41
+ // Client ids are issuer-minted (oaiapp_...); validate so a crafted id cannot traverse paths.
42
+ if (!/^[A-Za-z0-9_-]{8,128}$/.test(clientId)) throw new Error("siwc: malformed client id");
43
+ return join(accountsDir, "accounts", `${clientId}.json`);
44
+ }
45
+
46
+ export async function writeAccountRecord(accountsDir: string, record: AccountRecord): Promise<void> {
47
+ const path = accountPath(accountsDir, record.clientId);
48
+ await mkdir(dirname(path), { recursive: true });
49
+ // Write-then-rename keeps readers from ever seeing a torn record.
50
+ const temp = `${path}.${randomUUID()}.tmp`;
51
+ await writeFile(temp, JSON.stringify(record, null, 2), { mode: 0o600 });
52
+ await chmod(temp, 0o600);
53
+ await rename(temp, path);
54
+ }
55
+
56
+ export async function readAccountRecord(accountsDir: string, clientId: string): Promise<AccountRecord | undefined> {
57
+ try {
58
+ const raw = JSON.parse(await readFile(accountPath(accountsDir, clientId), "utf8")) as AccountRecord;
59
+ if (typeof raw.clientId !== "string" || typeof raw.refreshToken !== "string") return undefined;
60
+ return raw;
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ }
65
+
66
+ export async function listAccountRecords(accountsDir: string): Promise<AccountRecord[]> {
67
+ const dir = join(accountsDir, "accounts");
68
+ const records: AccountRecord[] = [];
69
+ const names = await readdirNames(dir);
70
+ for (const name of names.filter((n) => n.endsWith(".json"))) {
71
+ try {
72
+ records.push(JSON.parse(await readFile(join(dir, name), "utf8")) as AccountRecord);
73
+ } catch {
74
+ // A torn/unreadable record is skipped, never crashed on.
75
+ }
76
+ }
77
+ return records.sort((a, b) => a.savedAt - b.savedAt);
78
+ }
79
+
80
+ async function readdirNames(dir: string): Promise<string[]> {
81
+ try {
82
+ const { readdir } = await import("node:fs/promises");
83
+ return await readdir(dir);
84
+ } catch {
85
+ return [];
86
+ }
87
+ }
88
+
89
+ /** Clears token material but keeps the client/identity mapping for a later sign-in. */
90
+ export async function clearAccountTokens(accountsDir: string, clientId: string): Promise<void> {
91
+ const record = await readAccountRecord(accountsDir, clientId);
92
+ if (!record) return;
93
+ await writeAccountRecord(accountsDir, {
94
+ ...record, accessToken: "", refreshToken: "", idToken: "", expiresAt: 0, savedAt: Date.now(),
95
+ });
96
+ }
97
+
98
+ export async function removeAccountRecord(accountsDir: string, clientId: string): Promise<void> {
99
+ await rm(accountPath(accountsDir, clientId), { force: true });
100
+ }
101
+
102
+ export function fromTokenResponse(base: Omit<AccountRecord, "accessToken" | "refreshToken" | "idToken" | "expiresAt" | "grantedScopes" | "savedAt">, tokens: TokenResponse, now: number): AccountRecord {
103
+ return {
104
+ ...base,
105
+ idToken: tokens.idToken,
106
+ accessToken: tokens.accessToken,
107
+ refreshToken: tokens.refreshToken,
108
+ expiresAt: now + tokens.expiresInSeconds * 1000,
109
+ grantedScopes: tokens.grantedScopes,
110
+ savedAt: now,
111
+ };
112
+ }
113
+
114
+ const consentPath = (accountsDir: string, subject: string): string =>
115
+ join(accountsDir, "automation", `${subject.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
116
+
117
+ export async function approveAutomation(accountsDir: string, subject: string, note?: string): Promise<void> {
118
+ const path = consentPath(accountsDir, subject);
119
+ await mkdir(dirname(path), { recursive: true });
120
+ const consent: AutomationConsent = { subject, approvedAt: Date.now(), ...(note ? { note } : {}) };
121
+ const temp = `${path}.${randomUUID()}.tmp`;
122
+ await writeFile(temp, JSON.stringify(consent, null, 2), { mode: 0o600 });
123
+ await rename(temp, path);
124
+ }
125
+
126
+ export async function automationApproved(accountsDir: string, subject: string): Promise<boolean> {
127
+ try {
128
+ const consent = JSON.parse(await readFile(consentPath(accountsDir, subject), "utf8")) as AutomationConsent;
129
+ return consent.subject === subject && typeof consent.approvedAt === "number";
130
+ } catch {
131
+ return false;
132
+ }
133
+ }
134
+
135
+ export async function revokeAutomationApproval(accountsDir: string, subject: string): Promise<void> {
136
+ await rm(consentPath(accountsDir, subject), { force: true });
137
+ }
138
+
139
+ /**
140
+ * Stable per-host ext_agent_host_id (urn:uuid form). Created once and reused; it is an opaque
141
+ * label, never a credential, and is kept beside the runtime it identifies.
142
+ */
143
+ export async function ensureHostId(accountsDir: string): Promise<string> {
144
+ const path = join(accountsDir, "host-id");
145
+ try {
146
+ const existing = (await readFile(path, "utf8")).trim();
147
+ if (/^urn:uuid:[0-9a-f-]{36}$/.test(existing)) return existing;
148
+ } catch {
149
+ // First run on this host.
150
+ }
151
+ const hostId = `urn:uuid:${randomUUID()}`;
152
+ await mkdir(dirname(path), { recursive: true });
153
+ const temp = `${path}.${randomUUID()}.tmp`;
154
+ await writeFile(temp, `${hostId}\n`, { mode: 0o600 });
155
+ await rename(temp, path);
156
+ return hostId;
157
+ }