@perpetualsystems/typescript-sdk 0.0.0-bootstrap.0 → 0.4.0-next-20261110214241

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.
Files changed (157) hide show
  1. package/README.md +26 -1
  2. package/dist/authorization-code-pkce.d.ts +40 -0
  3. package/dist/authorization-code-pkce.d.ts.map +1 -0
  4. package/dist/authorization-code-pkce.js +272 -0
  5. package/dist/authorization-code-pkce.js.map +1 -0
  6. package/dist/client-credentials.d.ts +18 -0
  7. package/dist/client-credentials.d.ts.map +1 -0
  8. package/dist/client-credentials.js +79 -0
  9. package/dist/client-credentials.js.map +1 -0
  10. package/dist/client-store.d.ts +37 -0
  11. package/dist/client-store.d.ts.map +1 -0
  12. package/dist/client-store.js +138 -0
  13. package/dist/client-store.js.map +1 -0
  14. package/dist/client.d.ts +113 -0
  15. package/dist/client.d.ts.map +1 -0
  16. package/dist/client.js +217 -0
  17. package/dist/client.js.map +1 -0
  18. package/dist/config-dir.d.ts +3 -0
  19. package/dist/config-dir.d.ts.map +1 -0
  20. package/dist/config-dir.js +11 -0
  21. package/dist/config-dir.js.map +1 -0
  22. package/dist/dynamic-registration.d.ts +28 -0
  23. package/dist/dynamic-registration.d.ts.map +1 -0
  24. package/dist/dynamic-registration.js +56 -0
  25. package/dist/dynamic-registration.js.map +1 -0
  26. package/dist/generated/client/client.gen.d.ts +3 -0
  27. package/dist/generated/client/client.gen.d.ts.map +1 -0
  28. package/dist/generated/client/client.gen.js +217 -0
  29. package/dist/generated/client/client.gen.js.map +1 -0
  30. package/dist/generated/client/index.d.ts +11 -0
  31. package/dist/generated/client/index.d.ts.map +1 -0
  32. package/dist/generated/client/index.js +7 -0
  33. package/dist/generated/client/index.js.map +1 -0
  34. package/dist/generated/client/types.gen.d.ts +121 -0
  35. package/dist/generated/client/types.gen.d.ts.map +1 -0
  36. package/dist/generated/client/types.gen.js +3 -0
  37. package/dist/generated/client/types.gen.js.map +1 -0
  38. package/dist/generated/client/utils.gen.d.ts +38 -0
  39. package/dist/generated/client/utils.gen.d.ts.map +1 -0
  40. package/dist/generated/client/utils.gen.js +229 -0
  41. package/dist/generated/client/utils.gen.js.map +1 -0
  42. package/dist/generated/client.gen.d.ts +13 -0
  43. package/dist/generated/client.gen.d.ts.map +1 -0
  44. package/dist/generated/client.gen.js +4 -0
  45. package/dist/generated/client.gen.js.map +1 -0
  46. package/dist/generated/core/auth.gen.d.ts +26 -0
  47. package/dist/generated/core/auth.gen.d.ts.map +1 -0
  48. package/dist/generated/core/auth.gen.js +15 -0
  49. package/dist/generated/core/auth.gen.js.map +1 -0
  50. package/dist/generated/core/bodySerializer.gen.d.ts +26 -0
  51. package/dist/generated/core/bodySerializer.gen.d.ts.map +1 -0
  52. package/dist/generated/core/bodySerializer.gen.js +58 -0
  53. package/dist/generated/core/bodySerializer.gen.js.map +1 -0
  54. package/dist/generated/core/params.gen.d.ts +44 -0
  55. package/dist/generated/core/params.gen.d.ts.map +1 -0
  56. package/dist/generated/core/params.gen.js +110 -0
  57. package/dist/generated/core/params.gen.js.map +1 -0
  58. package/dist/generated/core/pathSerializer.gen.d.ts +34 -0
  59. package/dist/generated/core/pathSerializer.gen.d.ts.map +1 -0
  60. package/dist/generated/core/pathSerializer.gen.js +107 -0
  61. package/dist/generated/core/pathSerializer.gen.js.map +1 -0
  62. package/dist/generated/core/queryKeySerializer.gen.d.ts +19 -0
  63. package/dist/generated/core/queryKeySerializer.gen.d.ts.map +1 -0
  64. package/dist/generated/core/queryKeySerializer.gen.js +93 -0
  65. package/dist/generated/core/queryKeySerializer.gen.js.map +1 -0
  66. package/dist/generated/core/serverSentEvents.gen.d.ts +72 -0
  67. package/dist/generated/core/serverSentEvents.gen.d.ts.map +1 -0
  68. package/dist/generated/core/serverSentEvents.gen.js +133 -0
  69. package/dist/generated/core/serverSentEvents.gen.js.map +1 -0
  70. package/dist/generated/core/types.gen.d.ts +84 -0
  71. package/dist/generated/core/types.gen.d.ts.map +1 -0
  72. package/dist/generated/core/types.gen.js +3 -0
  73. package/dist/generated/core/types.gen.js.map +1 -0
  74. package/dist/generated/core/utils.gen.d.ts +20 -0
  75. package/dist/generated/core/utils.gen.d.ts.map +1 -0
  76. package/dist/generated/core/utils.gen.js +88 -0
  77. package/dist/generated/core/utils.gen.js.map +1 -0
  78. package/dist/generated/enum-values.gen.d.ts +331 -0
  79. package/dist/generated/enum-values.gen.d.ts.map +1 -0
  80. package/dist/generated/enum-values.gen.js +332 -0
  81. package/dist/generated/enum-values.gen.js.map +1 -0
  82. package/dist/generated/file-schemas.gen.d.ts +14 -0
  83. package/dist/generated/file-schemas.gen.d.ts.map +1 -0
  84. package/dist/generated/file-schemas.gen.js +3786 -0
  85. package/dist/generated/file-schemas.gen.js.map +1 -0
  86. package/dist/generated/index.d.ts +3 -0
  87. package/dist/generated/index.d.ts.map +1 -0
  88. package/dist/generated/index.js +3 -0
  89. package/dist/generated/index.js.map +1 -0
  90. package/dist/generated/sdk.gen.d.ts +1713 -0
  91. package/dist/generated/sdk.gen.d.ts.map +1 -0
  92. package/dist/generated/sdk.gen.js +10574 -0
  93. package/dist/generated/sdk.gen.js.map +1 -0
  94. package/dist/generated/spec-source.gen.d.ts +8 -0
  95. package/dist/generated/spec-source.gen.d.ts.map +1 -0
  96. package/dist/generated/spec-source.gen.js +9 -0
  97. package/dist/generated/spec-source.gen.js.map +1 -0
  98. package/dist/generated/types.gen.d.ts +30382 -0
  99. package/dist/generated/types.gen.d.ts.map +1 -0
  100. package/dist/generated/types.gen.js +3 -0
  101. package/dist/generated/types.gen.js.map +1 -0
  102. package/dist/index.d.ts +21 -0
  103. package/dist/index.d.ts.map +1 -0
  104. package/dist/index.js +16 -0
  105. package/dist/index.js.map +1 -0
  106. package/dist/oauth-request-error.d.ts +26 -0
  107. package/dist/oauth-request-error.d.ts.map +1 -0
  108. package/dist/oauth-request-error.js +47 -0
  109. package/dist/oauth-request-error.js.map +1 -0
  110. package/dist/refresh-token.d.ts +50 -0
  111. package/dist/refresh-token.d.ts.map +1 -0
  112. package/dist/refresh-token.js +83 -0
  113. package/dist/refresh-token.js.map +1 -0
  114. package/dist/token-store.d.ts +38 -0
  115. package/dist/token-store.d.ts.map +1 -0
  116. package/dist/token-store.js +195 -0
  117. package/dist/token-store.js.map +1 -0
  118. package/openapi/openapi.json +128387 -0
  119. package/package.json +66 -4
  120. package/src/__tests__/authorization-code-pkce.test.ts +245 -0
  121. package/src/__tests__/client-credentials.test.ts +360 -0
  122. package/src/__tests__/client-store.test.ts +139 -0
  123. package/src/__tests__/client.test.ts +529 -0
  124. package/src/__tests__/config-dir.test.ts +22 -0
  125. package/src/__tests__/dynamic-registration.test.ts +181 -0
  126. package/src/__tests__/oauth-request-error.test.ts +148 -0
  127. package/src/__tests__/refresh-token.test.ts +206 -0
  128. package/src/__tests__/token-store.test.ts +449 -0
  129. package/src/authorization-code-pkce.ts +417 -0
  130. package/src/client-credentials.ts +127 -0
  131. package/src/client-store.ts +182 -0
  132. package/src/client.ts +261 -0
  133. package/src/config-dir.ts +12 -0
  134. package/src/dynamic-registration.ts +109 -0
  135. package/src/generated/client/client.gen.ts +277 -0
  136. package/src/generated/client/index.ts +27 -0
  137. package/src/generated/client/types.gen.ts +218 -0
  138. package/src/generated/client/utils.gen.ts +316 -0
  139. package/src/generated/client.gen.ts +16 -0
  140. package/src/generated/core/auth.gen.ts +48 -0
  141. package/src/generated/core/bodySerializer.gen.ts +82 -0
  142. package/src/generated/core/params.gen.ts +178 -0
  143. package/src/generated/core/pathSerializer.gen.ts +171 -0
  144. package/src/generated/core/queryKeySerializer.gen.ts +117 -0
  145. package/src/generated/core/serverSentEvents.gen.ts +242 -0
  146. package/src/generated/core/types.gen.ts +110 -0
  147. package/src/generated/core/utils.gen.ts +140 -0
  148. package/src/generated/enum-values.gen.ts +332 -0
  149. package/src/generated/file-schemas.gen.ts +3800 -0
  150. package/src/generated/index.ts +4 -0
  151. package/src/generated/sdk.gen.ts +10992 -0
  152. package/src/generated/spec-source.gen.ts +9 -0
  153. package/src/generated/types.gen.ts +32415 -0
  154. package/src/index.ts +55 -0
  155. package/src/oauth-request-error.ts +75 -0
  156. package/src/refresh-token.ts +142 -0
  157. package/src/token-store.ts +252 -0
@@ -0,0 +1,417 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer, type Server } from "node:http";
3
+ import type { AddressInfo } from "node:net";
4
+ import { normalizeEndpoint } from "./token-store.js";
5
+ import {
6
+ OAUTH_REQUEST_TIMEOUT_MS,
7
+ oauthHttpError,
8
+ oauthTransportError,
9
+ readOAuthBody,
10
+ } from "./oauth-request-error.js";
11
+
12
+ export interface AuthorizationCodePkceOptions {
13
+ endpoint: string;
14
+ /** OAuth client_id (typically obtained via dynamic registration). */
15
+ clientId: string;
16
+ /** Optional client_secret. PKCE alone is sufficient for public clients,
17
+ * but the Perpetual backend may issue a secret on registration; if so
18
+ * it must be sent on the token exchange. */
19
+ clientSecret?: string;
20
+ /** Loopback redirect URI registered with the authorization server.
21
+ * The CLI must listen on the host:port specified here. */
22
+ redirectUri: string;
23
+ /** Optional space-separated scopes. */
24
+ scope?: string;
25
+ /** Override fetch for testing */
26
+ _fetch?: typeof fetch;
27
+ /** Override browser open for testing */
28
+ _openUrl?: (url: string) => Promise<void>;
29
+ /** Where to write user-facing progress messages (defaults to stderr). */
30
+ log?: (message: string) => void;
31
+ /** Cap how long we wait for the user to complete the browser flow. */
32
+ timeoutMs?: number;
33
+ /** Limit for the token exchange request itself. */
34
+ requestTimeoutMs?: number;
35
+ }
36
+
37
+ export interface AuthorizationCodePkceResult {
38
+ token: string;
39
+ refreshToken?: string;
40
+ expiresIn?: number;
41
+ tokenType: string;
42
+ }
43
+
44
+ const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes — generous for SSO flows
45
+
46
+ function base64url(buf: Buffer): string {
47
+ return buf
48
+ .toString("base64")
49
+ .replace(/=/g, "")
50
+ .replace(/\+/g, "-")
51
+ .replace(/\//g, "_");
52
+ }
53
+
54
+ function generatePkcePair(): { verifier: string; challenge: string } {
55
+ // 32 random bytes → ~43 base64url chars (within RFC 7636 §4.1 length range)
56
+ const verifier = base64url(randomBytes(32));
57
+ const challenge = base64url(createHash("sha256").update(verifier).digest());
58
+ return { verifier, challenge };
59
+ }
60
+
61
+ interface AwaitedCallback {
62
+ code: string;
63
+ state: string;
64
+ }
65
+
66
+ /**
67
+ * Start a one-shot localhost HTTP server that resolves with the OAuth
68
+ * callback's code+state. Guards against double-resolve from kept-alive
69
+ * connections delivering a second framed request after the first /callback
70
+ * hit, and against late server-error events firing after we've already
71
+ * settled. Closes the socket forcibly after responding so a misbehaving
72
+ * client cannot pipeline another request on the same connection.
73
+ */
74
+ function awaitCallback(
75
+ server: Server,
76
+ expectedState: string,
77
+ timeoutMs: number,
78
+ ): Promise<AwaitedCallback> {
79
+ return new Promise((resolve, reject) => {
80
+ let settled = false;
81
+ const settle = (action: () => void) => {
82
+ if (settled) return;
83
+ settled = true;
84
+ clearTimeout(timer);
85
+ server.removeAllListeners("request");
86
+ server.removeAllListeners("error");
87
+ server.close();
88
+ action();
89
+ };
90
+
91
+ const timer = setTimeout(() => {
92
+ settle(() =>
93
+ reject(
94
+ new Error(
95
+ `Authorization timed out after ${Math.round(timeoutMs / 1000)}s. ` +
96
+ "Re-run the command and complete the browser flow.",
97
+ ),
98
+ ),
99
+ );
100
+ }, timeoutMs);
101
+
102
+ server.on("request", (req, res) => {
103
+ // Surface socket errors instead of letting them become uncaught
104
+ // exceptions when the client disconnects mid-response.
105
+ req.on("error", () => {});
106
+ res.on("error", () => {});
107
+
108
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
109
+ // Only handle /callback; ignore favicon and other browser noise.
110
+ if (url.pathname !== "/callback") {
111
+ res.writeHead(404).end();
112
+ return;
113
+ }
114
+
115
+ // Guard against late re-entry: if we've already settled, just close
116
+ // the connection cleanly.
117
+ if (settled) {
118
+ res.writeHead(410).end();
119
+ req.socket.destroy();
120
+ return;
121
+ }
122
+
123
+ const error = url.searchParams.get("error");
124
+ const errorDescription = url.searchParams.get("error_description");
125
+ const code = url.searchParams.get("code");
126
+ const state = url.searchParams.get("state");
127
+
128
+ const respond = (status: number, html: string) => {
129
+ res.writeHead(status, {
130
+ "Content-Type": "text/html; charset=utf-8",
131
+ "Cache-Control": "no-store",
132
+ "X-Content-Type-Options": "nosniff",
133
+ });
134
+ res.end(html, () => {
135
+ // Forcibly close the socket so kept-alive can't pipeline another
136
+ // request that re-enters this handler post-settle.
137
+ req.socket.destroy();
138
+ });
139
+ };
140
+
141
+ if (error) {
142
+ respond(
143
+ 400,
144
+ `<!doctype html><html><body style="font-family:sans-serif;padding:2em">` +
145
+ `<h1>Authorization failed</h1>` +
146
+ `<p>${escapeHtml(error)}: ${escapeHtml(errorDescription ?? "")}</p>` +
147
+ `<p>You may close this window and return to the terminal.</p>` +
148
+ `</body></html>`,
149
+ );
150
+ settle(() =>
151
+ reject(
152
+ new Error(
153
+ `Authorization server returned error: ${error}${errorDescription ? `: ${errorDescription}` : ""}`,
154
+ ),
155
+ ),
156
+ );
157
+ return;
158
+ }
159
+
160
+ if (!code || !state) {
161
+ respond(
162
+ 400,
163
+ `<!doctype html><html><body><h1>Invalid callback</h1></body></html>`,
164
+ );
165
+ settle(() =>
166
+ reject(
167
+ new Error("Authorization callback missing required code or state"),
168
+ ),
169
+ );
170
+ return;
171
+ }
172
+
173
+ if (state !== expectedState) {
174
+ // CSRF guard: state must match what we sent.
175
+ respond(
176
+ 400,
177
+ `<!doctype html><html><body><h1>State mismatch</h1></body></html>`,
178
+ );
179
+ settle(() =>
180
+ reject(
181
+ new Error(
182
+ "Authorization callback state does not match -- possible CSRF; aborting",
183
+ ),
184
+ ),
185
+ );
186
+ return;
187
+ }
188
+
189
+ respond(
190
+ 200,
191
+ `<!doctype html><html><body style="font-family:sans-serif;padding:2em">` +
192
+ `<h1>Authorization complete</h1>` +
193
+ `<p>You may close this window and return to the terminal.</p>` +
194
+ `</body></html>`,
195
+ );
196
+ settle(() => resolve({ code, state }));
197
+ });
198
+
199
+ server.once("error", (e) => {
200
+ settle(() => reject(e));
201
+ });
202
+ });
203
+ }
204
+
205
+ function escapeHtml(s: string): string {
206
+ return s
207
+ .replace(/&/g, "&amp;")
208
+ .replace(/</g, "&lt;")
209
+ .replace(/>/g, "&gt;")
210
+ .replace(/"/g, "&quot;");
211
+ }
212
+
213
+ /**
214
+ * Listen on a loopback port matching `redirectUri`. If the URI has port 0,
215
+ * bind to a random free port and return a URI with the assigned port.
216
+ *
217
+ * Returns the server (already listening) plus the redirect URI to use,
218
+ * which may differ from the input when port 0 was requested.
219
+ */
220
+ async function startLoopbackServer(
221
+ redirectUri: string,
222
+ ): Promise<{ server: Server; redirectUri: string }> {
223
+ const url = new URL(redirectUri);
224
+ if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost") {
225
+ throw new Error(
226
+ `redirectUri must use loopback host (127.0.0.1 or localhost); got "${url.hostname}"`,
227
+ );
228
+ }
229
+ // Reject non-http schemes: we serve plaintext HTTP locally. An https://
230
+ // URI would cause the browser to attempt TLS to our plaintext server
231
+ // and fail with a confusing protocol error mid-flow.
232
+ if (url.protocol !== "http:") {
233
+ throw new Error(
234
+ `redirectUri must use http:// for loopback (we serve plaintext); got "${url.protocol}"`,
235
+ );
236
+ }
237
+ // Enforce the /callback path: the request handler only matches that
238
+ // path, so registering anything else with the AS produces a callback
239
+ // that we'd 404 and time out on.
240
+ if (url.pathname !== "/callback") {
241
+ throw new Error(
242
+ `redirectUri path must be /callback (the SDK only handles that path); got "${url.pathname}"`,
243
+ );
244
+ }
245
+
246
+ const server = createServer();
247
+ const port = url.port === "" || url.port === "0" ? 0 : Number(url.port);
248
+ await new Promise<void>((resolve, reject) => {
249
+ const onError = (e: Error) => reject(e);
250
+ server.once("error", onError);
251
+ server.listen(port, url.hostname, () => {
252
+ server.removeListener("error", onError);
253
+ resolve();
254
+ });
255
+ });
256
+
257
+ const addr = server.address() as AddressInfo;
258
+ url.port = String(addr.port);
259
+ return { server, redirectUri: url.toString() };
260
+ }
261
+
262
+ /**
263
+ * Execute the OAuth 2.0 Authorization Code flow with PKCE (RFC 6749 §4.1
264
+ * + RFC 7636), opening the user's browser to authorize and catching the
265
+ * redirect on a localhost loopback per RFC 8252.
266
+ *
267
+ * Replaces the prior device-code flow which the Perpetual backend no
268
+ * longer supports.
269
+ */
270
+ export async function executeAuthorizationCodePkce(
271
+ options: AuthorizationCodePkceOptions,
272
+ ): Promise<AuthorizationCodePkceResult> {
273
+ const {
274
+ endpoint,
275
+ clientId,
276
+ clientSecret,
277
+ redirectUri,
278
+ scope,
279
+ _fetch: fetchFn = fetch,
280
+ _openUrl,
281
+ log = (msg: string) => process.stderr.write(msg),
282
+ timeoutMs = DEFAULT_TIMEOUT_MS,
283
+ requestTimeoutMs = OAUTH_REQUEST_TIMEOUT_MS,
284
+ } = options;
285
+
286
+ const normalizedEndpoint = normalizeEndpoint(endpoint);
287
+ const { verifier, challenge } = generatePkcePair();
288
+ const state = base64url(randomBytes(16));
289
+
290
+ const { server, redirectUri: actualRedirectUri } =
291
+ await startLoopbackServer(redirectUri);
292
+
293
+ try {
294
+ const authorizeUrl = new URL(`${normalizedEndpoint}/api/oauth/authorize`);
295
+ authorizeUrl.searchParams.set("response_type", "code");
296
+ authorizeUrl.searchParams.set("client_id", clientId);
297
+ authorizeUrl.searchParams.set("redirect_uri", actualRedirectUri);
298
+ authorizeUrl.searchParams.set("code_challenge", challenge);
299
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
300
+ authorizeUrl.searchParams.set("state", state);
301
+ if (scope) authorizeUrl.searchParams.set("scope", scope);
302
+
303
+ const authorizeUrlStr = authorizeUrl.toString();
304
+
305
+ // Arm the callback listener BEFORE opening the browser. A fast SSO
306
+ // redirect (e.g. when the user is already signed in) can deliver the
307
+ // /callback hit microseconds after the browser launches; if the
308
+ // listener weren't yet attached, that request would 404 silently and
309
+ // we'd wait the full timeout.
310
+ const callbackPromise = awaitCallback(server, state, timeoutMs);
311
+
312
+ log("Opening browser for authorization...\n");
313
+ log(
314
+ ` ACTION REQUIRED if browser doesn't open -- visit this URL manually:\n ${authorizeUrlStr}\n\n`,
315
+ );
316
+
317
+ // Best-effort browser open; the URL is also printed above.
318
+ try {
319
+ if (_openUrl) {
320
+ await _openUrl(authorizeUrlStr);
321
+ } else {
322
+ const openModule = await import("open");
323
+ await openModule.default(authorizeUrlStr);
324
+ }
325
+ } catch (openError) {
326
+ const detail =
327
+ openError instanceof Error ? openError.message : String(openError);
328
+ log(
329
+ ` (Could not open browser automatically: ${detail}. Please visit the URL above.)\n`,
330
+ );
331
+ }
332
+
333
+ log("Waiting for authorization...\n");
334
+ const callback = await callbackPromise;
335
+
336
+ // Exchange authorization code for token (RFC 6749 §4.1.3).
337
+ const tokenUrl = `${normalizedEndpoint}/api/oauth/token`;
338
+ const body = new URLSearchParams({
339
+ grant_type: "authorization_code",
340
+ code: callback.code,
341
+ redirect_uri: actualRedirectUri,
342
+ client_id: clientId,
343
+ code_verifier: verifier,
344
+ });
345
+ if (clientSecret) body.set("client_secret", clientSecret);
346
+
347
+ let response: Response;
348
+ try {
349
+ response = await fetchFn(tokenUrl, {
350
+ method: "POST",
351
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
352
+ body: body.toString(),
353
+ signal: AbortSignal.timeout(requestTimeoutMs),
354
+ });
355
+ } catch (networkError) {
356
+ throw oauthTransportError("Token exchange", tokenUrl, networkError);
357
+ }
358
+
359
+ const text = await readOAuthBody("Token exchange", tokenUrl, response);
360
+
361
+ if (!response.ok) {
362
+ throw oauthHttpError("Token exchange", response, text);
363
+ }
364
+
365
+ let data: Record<string, unknown>;
366
+ try {
367
+ data = JSON.parse(text);
368
+ } catch (parseError) {
369
+ const detail =
370
+ parseError instanceof Error ? parseError.message : String(parseError);
371
+ throw new Error(
372
+ `Token response is not valid JSON (${response.status}): ${text.slice(0, 200) || response.statusText} (${detail})`,
373
+ );
374
+ }
375
+
376
+ if (typeof data.access_token !== "string" || !data.access_token) {
377
+ throw new Error("Token response missing access_token");
378
+ }
379
+ const tokenType =
380
+ typeof data.token_type === "string" ? data.token_type : "Bearer";
381
+ if (tokenType.toLowerCase() !== "bearer") {
382
+ throw new Error(
383
+ `Unsupported token type: "${tokenType}". Only Bearer tokens are supported.`,
384
+ );
385
+ }
386
+
387
+ let expiresIn: number | undefined;
388
+ if (data.expires_in !== undefined) {
389
+ if (
390
+ typeof data.expires_in === "number" &&
391
+ Number.isFinite(data.expires_in) &&
392
+ data.expires_in > 0
393
+ ) {
394
+ expiresIn = data.expires_in;
395
+ } else {
396
+ log(
397
+ `Warning: token response contained invalid expires_in: ${JSON.stringify(data.expires_in)}, ignoring\n`,
398
+ );
399
+ }
400
+ }
401
+
402
+ return {
403
+ token: data.access_token,
404
+ refreshToken:
405
+ typeof data.refresh_token === "string" ? data.refresh_token : undefined,
406
+ expiresIn,
407
+ tokenType,
408
+ };
409
+ } finally {
410
+ // Defensive: awaitCallback closes on every code path, but we want to
411
+ // be sure the listener is gone if startup succeeded but the URL open
412
+ // step threw before awaitCallback was reached.
413
+ if (server.listening) {
414
+ server.close();
415
+ }
416
+ }
417
+ }
@@ -0,0 +1,127 @@
1
+ import { normalizeEndpoint } from "./token-store.js";
2
+ import {
3
+ OAUTH_REQUEST_TIMEOUT_MS,
4
+ oauthHttpError,
5
+ oauthTransportError,
6
+ readOAuthBody,
7
+ } from "./oauth-request-error.js";
8
+
9
+ export interface ClientCredentialsOptions {
10
+ endpoint: string;
11
+ clientId: string;
12
+ clientSecret: string;
13
+ /** Override fetch for testing */
14
+ _fetch?: typeof fetch;
15
+ requestTimeoutMs?: number;
16
+ }
17
+
18
+ export interface ClientCredentialsResponse {
19
+ access_token: string;
20
+ token_type: string;
21
+ expires_in?: number;
22
+ }
23
+
24
+ /**
25
+ * Exchange client credentials for an access token (OAuth 2.0 Client Credentials Grant, RFC 6749 §4.4).
26
+ */
27
+ export async function exchangeClientCredentials(
28
+ options: ClientCredentialsOptions,
29
+ ): Promise<ClientCredentialsResponse> {
30
+ const {
31
+ endpoint,
32
+ clientId,
33
+ clientSecret,
34
+ _fetch: fetchFn = fetch,
35
+ requestTimeoutMs = OAUTH_REQUEST_TIMEOUT_MS,
36
+ } = options;
37
+
38
+ const url = `${normalizeEndpoint(endpoint)}/api/oauth/token`;
39
+ let response: Response;
40
+ try {
41
+ response = await fetchFn(url, {
42
+ method: "POST",
43
+ // RFC 6749 §4.4.2 + §3.2 specify form-encoded request body for the
44
+ // token endpoint. The Perpetual backend rejects JSON bodies with
45
+ // "unsupported_grant_type" (the parser can't read the field).
46
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
47
+ body: new URLSearchParams({
48
+ grant_type: "client_credentials",
49
+ client_id: clientId,
50
+ client_secret: clientSecret,
51
+ }).toString(),
52
+ signal: AbortSignal.timeout(requestTimeoutMs),
53
+ });
54
+ } catch (networkError) {
55
+ throw oauthTransportError("Client credentials exchange", url, networkError);
56
+ }
57
+
58
+ const body = await readOAuthBody(
59
+ "Client credentials exchange",
60
+ url,
61
+ response,
62
+ );
63
+ if (!response.ok) {
64
+ throw oauthHttpError("Client credentials exchange", response, body);
65
+ }
66
+
67
+ let data: Record<string, unknown>;
68
+ try {
69
+ data = JSON.parse(body);
70
+ } catch (parseError) {
71
+ const detail =
72
+ parseError instanceof Error ? parseError.message : String(parseError);
73
+ throw new Error(
74
+ `Client credentials response is not valid JSON (${response.status}): ${body.slice(0, 200) || response.statusText} (${detail})`,
75
+ );
76
+ }
77
+
78
+ if (!data.access_token || typeof data.access_token !== "string") {
79
+ throw new Error("Client credentials response missing access_token");
80
+ }
81
+
82
+ // Validate token_type: must be "Bearer" (case-insensitive) if present
83
+ if (data.token_type) {
84
+ if (
85
+ typeof data.token_type !== "string" ||
86
+ data.token_type.toLowerCase() !== "bearer"
87
+ ) {
88
+ throw new Error(
89
+ `Unsupported token type: "${data.token_type}". Only Bearer tokens are supported.`,
90
+ );
91
+ }
92
+ }
93
+
94
+ // Validate expires_in if present: must be a finite positive number.
95
+ // Unlike requestDeviceCode (which throws on invalid values because they
96
+ // poison the polling deadline), here we already have the token so we
97
+ // log a warning and omit the invalid value.
98
+ let expiresIn: number | undefined;
99
+ if (data.expires_in !== undefined) {
100
+ if (
101
+ typeof data.expires_in !== "number" ||
102
+ !Number.isFinite(data.expires_in) ||
103
+ data.expires_in <= 0
104
+ ) {
105
+ try {
106
+ process.stderr.write(
107
+ `Warning: client credentials response contained invalid expires_in: ${JSON.stringify(data.expires_in)}, ignoring\n`,
108
+ );
109
+ } catch {
110
+ // Best-effort warning — don't let a broken stderr discard a valid token
111
+ }
112
+ expiresIn = undefined;
113
+ } else {
114
+ expiresIn = data.expires_in;
115
+ }
116
+ }
117
+
118
+ // Ensure token_type is set (RFC 6749 §5.1 requires it, default to Bearer)
119
+ const result: ClientCredentialsResponse = {
120
+ access_token: data.access_token,
121
+ token_type:
122
+ typeof data.token_type === "string" ? data.token_type : "Bearer",
123
+ ...(expiresIn !== undefined ? { expires_in: expiresIn } : {}),
124
+ };
125
+
126
+ return result;
127
+ }