@stxapp/stx-typescript 0.8.3 → 0.9.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/dist/oauth.cjs CHANGED
@@ -7,7 +7,11 @@
7
7
 
8
8
 
9
9
 
10
- var _chunkSI3EILHNcjs = require('./chunk-SI3EILHN.cjs');
10
+
11
+
12
+
13
+
14
+ var _chunkR77AZ5UHcjs = require('./chunk-R77AZ5UH.cjs');
11
15
 
12
16
  // src/oauth/endpoints.ts
13
17
  var DEFAULT_ENDPOINTS = {
@@ -24,12 +28,12 @@ var WELL_KNOWN = {
24
28
  function resolveOAuthConfig(input) {
25
29
  const env = _nullishCoalesce(_optionalChain([globalThis, 'access', _ => _.process, 'optionalAccess', _2 => _2.env]), () => ( {}));
26
30
  const host = _nullishCoalesce(_nullishCoalesce(input.baseUrl, () => ( env.STX_HOST)), () => ( env.STX_BASE_URL));
27
- if (!host) throw new (0, _chunkSI3EILHNcjs.STXConfigException)("An OAuth base URL is required. Pass { baseUrl } or set STX_HOST.");
31
+ if (!host) throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("An OAuth base URL is required. Pass { baseUrl } or set STX_HOST.");
28
32
  const fetchImpl = _nullishCoalesce(input.fetch, () => ( globalThis.fetch));
29
33
  if (typeof fetchImpl !== "function") {
30
- throw new (0, _chunkSI3EILHNcjs.STXConfigException)("No fetch implementation available. Use Node 18+, or pass { fetch }.");
34
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("No fetch implementation available. Use Node 18+, or pass { fetch }.");
31
35
  }
32
- return { baseUrl: _chunkSI3EILHNcjs.baseUrlFor.call(void 0, null, null, host), fetch: fetchImpl };
36
+ return { baseUrl: _chunkR77AZ5UHcjs.baseUrlFor.call(void 0, null, null, host), fetch: fetchImpl };
33
37
  }
34
38
  function joinUrl(baseUrl, path) {
35
39
  if (/^https?:\/\//i.test(path)) return path;
@@ -37,7 +41,7 @@ function joinUrl(baseUrl, path) {
37
41
  }
38
42
 
39
43
  // src/oauth/errors.ts
40
- var STXOAuthException = class extends _chunkSI3EILHNcjs.STXAuthenticationException {
44
+ var STXOAuthException = class extends _chunkR77AZ5UHcjs.STXAuthenticationException {
41
45
  /** The RFC error code: `invalid_client`, `invalid_grant`, `invalid_scope`, ... */
42
46
 
43
47
 
@@ -45,7 +49,18 @@ var STXOAuthException = class extends _chunkSI3EILHNcjs.STXAuthenticationExcepti
45
49
 
46
50
  /** Seconds to wait when the endpoint answered 429 with Retry-After. */
47
51
 
48
- constructor(error, errorDescription, status, endpoint, retryAfter) {
52
+ /**
53
+ * STX's own, narrower reason, when the answer carries one. `account_pending`
54
+ * on an `invalid_grant` means the member's STX account is still being
55
+ * verified.
56
+ */
57
+
58
+ /**
59
+ * On an `invalid_scope` from the authorize callback, the scope the sign-in
60
+ * asked for (from the pending sign-in), so the cause can be named.
61
+ */
62
+
63
+ constructor(error, errorDescription, status, endpoint, retryAfter, errorReason) {
49
64
  super(`OAuth ${endpoint} ${status} ${error}${errorDescription ? `: ${errorDescription}` : ""}`, {
50
65
  statusCode: status,
51
66
  path: endpoint
@@ -54,14 +69,80 @@ var STXOAuthException = class extends _chunkSI3EILHNcjs.STXAuthenticationExcepti
54
69
  this.errorDescription = errorDescription;
55
70
  this.endpoint = endpoint;
56
71
  this.retryAfter = retryAfter;
72
+ this.errorReason = errorReason;
57
73
  }
58
74
  };
59
- var STXGrantRevokedException = class extends _chunkSI3EILHNcjs.STXAuthenticationException {
75
+ var STXAccessDeniedException = class extends STXOAuthException {
76
+ };
77
+ var STXAccountPendingException = class extends STXOAuthException {
78
+ };
79
+ var STXTermsNotAcceptedException = class extends STXOAuthException {
80
+ };
81
+ function callbackError(error, errorDescription, endpoint) {
82
+ const Class = error === "account_pending" ? STXAccountPendingException : error === "terms_required" ? STXTermsNotAcceptedException : error === "access_denied" ? STXAccessDeniedException : STXOAuthException;
83
+ return new Class(error, errorDescription, 400, endpoint);
84
+ }
85
+ var STXGrantRevokedException = class extends _chunkR77AZ5UHcjs.STXAuthenticationException {
60
86
  constructor(message = "OAuth grant revoked: the member must re-authorize.") {
61
87
  super(message, { statusCode: 400 });
62
88
  }
63
89
  };
64
90
 
91
+ // src/oauth/metadata.ts
92
+ async function discoverMetadata(baseUrl, opts = {}) {
93
+ const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);
94
+ const meta = doc;
95
+ if (typeof meta.issuer !== "string" || typeof meta.authorization_endpoint !== "string" || typeof meta.token_endpoint !== "string") {
96
+ throw httpError(
97
+ 200,
98
+ JSON.stringify(doc),
99
+ WELL_KNOWN.authorizationServer + " (missing issuer/authorization_endpoint/token_endpoint)"
100
+ );
101
+ }
102
+ return meta;
103
+ }
104
+ async function discoverProtectedResource(baseUrl, opts = {}) {
105
+ const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.protectedResource, opts);
106
+ const meta = doc;
107
+ if (typeof meta.resource !== "string" || !Array.isArray(meta.authorization_servers)) {
108
+ throw httpError(
109
+ 200,
110
+ JSON.stringify(doc),
111
+ WELL_KNOWN.protectedResource + " (missing resource/authorization_servers)"
112
+ );
113
+ }
114
+ return meta;
115
+ }
116
+ async function fetchWellKnown(baseUrl, path, opts) {
117
+ const cfg = resolveOAuthConfig({ baseUrl, fetch: opts.fetch });
118
+ const res = await cfg.fetch(joinUrl(cfg.baseUrl, path), {
119
+ method: "GET",
120
+ headers: { Accept: "application/json" }
121
+ });
122
+ const text = await res.text();
123
+ if (res.status === 404 || _chunkR77AZ5UHcjs.isEdgeBlock.call(void 0, res.status, text)) {
124
+ throw new (0, _chunkR77AZ5UHcjs.STXNotAvailableException)("oauth", new URL(cfg.baseUrl).host, {
125
+ statusCode: res.status,
126
+ body: text,
127
+ method: "GET",
128
+ path
129
+ });
130
+ }
131
+ if (!res.ok) throw httpError(res.status, text, path);
132
+ try {
133
+ return JSON.parse(text);
134
+ } catch (e) {
135
+ throw httpError(res.status, text, path);
136
+ }
137
+ }
138
+ function httpError(status, text, path) {
139
+ return new (0, _chunkR77AZ5UHcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
140
+ statusCode: status,
141
+ body: text,
142
+ path
143
+ });
144
+ }
145
+
65
146
  // src/oauth/pkce.ts
66
147
  function base64url(bytes) {
67
148
  let bin = "";
@@ -106,12 +187,12 @@ async function registerClient(request, opts = {}) {
106
187
  let doc;
107
188
  try {
108
189
  doc = JSON.parse(text);
109
- } catch (e) {
110
- throw httpError(res.status, text, path);
190
+ } catch (e2) {
191
+ throw httpError2(res.status, text, path);
111
192
  }
112
193
  const reg = doc;
113
194
  if (typeof reg.client_id !== "string" || reg.client_id === "") {
114
- throw httpError(res.status, text, path + " (missing client_id)");
195
+ throw httpError2(res.status, text, path + " (missing client_id)");
115
196
  }
116
197
  return reg;
117
198
  }
@@ -123,10 +204,11 @@ async function registerClient(request, opts = {}) {
123
204
  err.error_description,
124
205
  res.status,
125
206
  path,
126
- Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0
207
+ Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0,
208
+ err.error_reason
127
209
  );
128
210
  }
129
- throw httpError(res.status, text, path);
211
+ throw httpError2(res.status, text, path);
130
212
  }
131
213
  function rfcError(text) {
132
214
  try {
@@ -134,14 +216,15 @@ function rfcError(text) {
134
216
  if (typeof obj.error !== "string") return null;
135
217
  return {
136
218
  error: obj.error,
137
- error_description: typeof obj.error_description === "string" ? obj.error_description : void 0
219
+ error_description: typeof obj.error_description === "string" ? obj.error_description : void 0,
220
+ error_reason: typeof obj.error_reason === "string" ? obj.error_reason : void 0
138
221
  };
139
- } catch (e2) {
222
+ } catch (e3) {
140
223
  return null;
141
224
  }
142
225
  }
143
- function httpError(status, text, path) {
144
- return new (0, _chunkSI3EILHNcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
226
+ function httpError2(status, text, path) {
227
+ return new (0, _chunkR77AZ5UHcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
145
228
  statusCode: status,
146
229
  body: text,
147
230
  path
@@ -161,9 +244,7 @@ var MemberScopes = {
161
244
  /** Deposit and withdrawal history (read only). */
162
245
  TRANSFERS_READ: "transfers.read",
163
246
  /** Place and cancel orders; arm `cancel_on_disconnect`. */
164
- ORDERS_WRITE: "orders.write",
165
- /** Accept the terms and conditions. */
166
- TERMS_WRITE: "terms.write"
247
+ ORDERS_WRITE: "orders.write"
167
248
  };
168
249
  var AppScopes = {
169
250
  /** The market catalog (`GET /api/v1/markets`) and the market data channels. */
@@ -182,9 +263,9 @@ var LEGACY_SCOPES = {
182
263
  portfolio: MemberScopes.PORTFOLIO_READ,
183
264
  history: MemberScopes.ORDERS_READ,
184
265
  transfers: MemberScopes.TRANSFERS_READ,
185
- trade: MemberScopes.ORDERS_WRITE,
186
- onboarding: MemberScopes.TERMS_WRITE
266
+ trade: MemberScopes.ORDERS_WRITE
187
267
  };
268
+ var RETIRED_SCOPES = /* @__PURE__ */ new Set(["terms.write", "onboarding"]);
188
269
  function canonicalScope(scope) {
189
270
  return _nullishCoalesce(LEGACY_SCOPES[scope], () => ( scope));
190
271
  }
@@ -192,7 +273,7 @@ function parseScopes(scope) {
192
273
  if (!scope) return [];
193
274
  const out = [];
194
275
  for (const raw of scope.split(/\s+/)) {
195
- if (!raw) continue;
276
+ if (!raw || RETIRED_SCOPES.has(raw)) continue;
196
277
  const s = canonicalScope(raw);
197
278
  if (!out.includes(s)) out.push(s);
198
279
  }
@@ -216,6 +297,8 @@ var OAuthClient = (_class = class _OAuthClient {
216
297
 
217
298
 
218
299
 
300
+ /** The discovery document this client was built from, if any. */
301
+
219
302
 
220
303
  /**
221
304
  * In-flight refreshes per token store and member, shared by every session
@@ -234,6 +317,7 @@ var OAuthClient = (_class = class _OAuthClient {
234
317
  this.clientSecret = opts.clientSecret || void 0;
235
318
  this.redirectUri = opts.redirectUri;
236
319
  this.scope = normalizeScope(opts.scope);
320
+ this.metadata = opts.metadata;
237
321
  this.endpoints = {
238
322
  authorize: _nullishCoalesce(_optionalChain([opts, 'access', _3 => _3.endpoints, 'optionalAccess', _4 => _4.authorize]), () => ( DEFAULT_ENDPOINTS.authorize)),
239
323
  token: _nullishCoalesce(_optionalChain([opts, 'access', _5 => _5.endpoints, 'optionalAccess', _6 => _6.token]), () => ( DEFAULT_ENDPOINTS.token)),
@@ -249,6 +333,7 @@ var OAuthClient = (_class = class _OAuthClient {
249
333
  static fromMetadata(metadata, opts) {
250
334
  return new _OAuthClient({
251
335
  ...opts,
336
+ metadata,
252
337
  baseUrl: _nullishCoalesce(opts.baseUrl, () => ( metadata.issuer)),
253
338
  endpoints: {
254
339
  authorize: metadata.authorization_endpoint,
@@ -258,6 +343,27 @@ var OAuthClient = (_class = class _OAuthClient {
258
343
  }
259
344
  });
260
345
  }
346
+ /**
347
+ * Fetch the exchange's discovery document and build a client from it. Throws
348
+ * `STXNotAvailableException` (feature `oauth`) on an exchange without OAuth,
349
+ * so an app can tell "not here yet" from a misconfiguration at start-up.
350
+ *
351
+ * const oauth = await OAuthClient.discover({
352
+ * baseUrl: "https://demo.stxapp.io",
353
+ * clientId: process.env.STX_CLIENT_ID!,
354
+ * clientSecret: process.env.STX_CLIENT_SECRET,
355
+ * redirectUri: "https://your.app/stx/callback",
356
+ * });
357
+ */
358
+ static async discover(opts) {
359
+ const discovery = opts.fetch ? { fetch: opts.fetch } : {};
360
+ const metadata = await discoverMetadata(opts.baseUrl, discovery);
361
+ return _OAuthClient.fromMetadata(metadata, { ...opts, baseUrl: _nullishCoalesce(opts.baseUrl, () => ( metadata.issuer)) });
362
+ }
363
+ /** The exchange host, e.g. `"demo.stxapp.io"`. */
364
+ get host() {
365
+ return new URL(this.baseUrl).host;
366
+ }
261
367
  /** True for a public client (no secret): PKCE-only, no app tokens. */
262
368
  get isPublic() {
263
369
  return this.clientSecret === void 0;
@@ -277,7 +383,11 @@ var OAuthClient = (_class = class _OAuthClient {
277
383
  scope: params.scope,
278
384
  prompt: params.prompt,
279
385
  redirectUri: params.redirectUri,
280
- extraParams: params.extraParams
386
+ extraParams: {
387
+ ...params.connection ? { connection: params.connection } : {},
388
+ ...params.loginHint ? { login_hint: params.loginHint } : {},
389
+ ..._nullishCoalesce(params.extraParams, () => ( {}))
390
+ }
281
391
  });
282
392
  return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };
283
393
  }
@@ -292,7 +402,7 @@ var OAuthClient = (_class = class _OAuthClient {
292
402
  */
293
403
  async beginAuthorization(pending, params = {}) {
294
404
  const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
295
- if (!redirectUri) throw new (0, _chunkSI3EILHNcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
405
+ if (!redirectUri) throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
296
406
  const auth = await this.authorizationUrl({ ...params, redirectUri });
297
407
  await pending.put(auth.state, {
298
408
  codeVerifier: auth.codeVerifier,
@@ -305,7 +415,7 @@ var OAuthClient = (_class = class _OAuthClient {
305
415
  }
306
416
  /**
307
417
  * Finish a sign-in from the callback's query. Checks for an `error` from
308
- * the exchange (the member denied consent: `access_denied`), consumes the
418
+ * the exchange (`access_denied`, `account_pending`, `terms_required`), consumes the
309
419
  * `state` (single use; unknown or expired throws `invalid_state`), exchanges
310
420
  * the code with the stored PKCE verifier and, when `store` is given, saves
311
421
  * the tokens under `memberKey` (a string, or a function of the `data` passed
@@ -317,7 +427,38 @@ var OAuthClient = (_class = class _OAuthClient {
317
427
  * for a used, expired or mismatched code).
318
428
  */
319
429
  async completeAuthorization(pending, callback, opts = {}) {
320
- return this.redeemAuthorization(await readCallback(pending, callback, this.endpoints.authorize), opts);
430
+ let read;
431
+ try {
432
+ read = await readCallback(pending, callback, this.endpoints.authorize);
433
+ } catch (err) {
434
+ if (err instanceof STXOAuthException && err.error === "invalid_scope") {
435
+ throw _nullishCoalesce(this.unofferedScope(_nullishCoalesce(err.requestedScope, () => ( this.scope)), err), () => ( err));
436
+ }
437
+ throw err;
438
+ }
439
+ return this.redeemAuthorization(read, opts);
440
+ }
441
+ /**
442
+ * `STXNotAvailableException` for the first scope in `requested` that the
443
+ * discovery document does not list, or undefined when every scope is listed
444
+ * or there is no document to check against.
445
+ */
446
+ unofferedScope(requested, cause) {
447
+ const offered = _optionalChain([this, 'access', _11 => _11.metadata, 'optionalAccess', _12 => _12.scopes_supported]);
448
+ if (!offered || !requested) return void 0;
449
+ const missing = parseScopes(requested).find((s) => !offered.includes(s));
450
+ if (!missing) return void 0;
451
+ return new (0, _chunkR77AZ5UHcjs.STXNotAvailableException)(`scope:${missing}`, this.host, { statusCode: 400, cause });
452
+ }
453
+ /** `STXNotAvailableException` (feature `oauth`) for an OAuth endpoint the exchange does not have. */
454
+ oauthMissing(status, text, endpoint) {
455
+ if (status !== 404 && !_chunkR77AZ5UHcjs.isEdgeBlock.call(void 0, status, text)) return void 0;
456
+ return new (0, _chunkR77AZ5UHcjs.STXNotAvailableException)("oauth", this.host, {
457
+ statusCode: status,
458
+ body: text,
459
+ method: "POST",
460
+ path: pathOf(endpoint)
461
+ });
321
462
  }
322
463
  /**
323
464
  * The second half of `completeAuthorization()`: exchange a callback already
@@ -334,7 +475,7 @@ var OAuthClient = (_class = class _OAuthClient {
334
475
  let memberKey;
335
476
  if (opts.store) {
336
477
  memberKey = typeof opts.memberKey === "function" ? opts.memberKey(entry.data) : opts.memberKey;
337
- if (!memberKey) throw new (0, _chunkSI3EILHNcjs.STXConfigException)("Pass memberKey along with store.");
478
+ if (!memberKey) throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("Pass memberKey along with store.");
338
479
  await opts.store.set(memberKey, tokenSetToStored(tokens));
339
480
  }
340
481
  return { tokens, scopes: parseScopes(tokens.scope), data: entry.data, memberKey };
@@ -343,7 +484,7 @@ var OAuthClient = (_class = class _OAuthClient {
343
484
  buildAuthorizeUrl(params) {
344
485
  const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
345
486
  if (!redirectUri) {
346
- throw new (0, _chunkSI3EILHNcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
487
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
347
488
  }
348
489
  const url = new URL(joinUrl(this.baseUrl, this.endpoints.authorize));
349
490
  const search = {
@@ -365,7 +506,7 @@ var OAuthClient = (_class = class _OAuthClient {
365
506
  exchangeCode(args) {
366
507
  const redirectUri = _nullishCoalesce(args.redirectUri, () => ( this.redirectUri));
367
508
  if (!redirectUri) {
368
- throw new (0, _chunkSI3EILHNcjs.STXConfigException)("redirectUri is required to exchange a code.");
509
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("redirectUri is required to exchange a code.");
369
510
  }
370
511
  return this.postToken(
371
512
  new URLSearchParams({
@@ -383,6 +524,9 @@ var OAuthClient = (_class = class _OAuthClient {
383
524
  * refresh (`invalid_grant`) means the grant was revoked, including STX's
384
525
  * reuse detection tripping on a replayed/retired token, and surfaces as
385
526
  * `STXGrantRevokedException`.
527
+ *
528
+ * While the member has not accepted the current STX terms the refresh still
529
+ * succeeds, and the result carries `termsRequired: true` and `termsUrl`.
386
530
  */
387
531
  refreshToken(refreshToken) {
388
532
  return this.postToken(
@@ -406,7 +550,7 @@ var OAuthClient = (_class = class _OAuthClient {
406
550
  */
407
551
  clientCredentials(scope) {
408
552
  if (this.isPublic) {
409
- throw new (0, _chunkSI3EILHNcjs.STXConfigException)(
553
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)(
410
554
  "client_credentials needs a client secret; a public client cannot mint an app token."
411
555
  );
412
556
  }
@@ -430,7 +574,10 @@ var OAuthClient = (_class = class _OAuthClient {
430
574
  return provider;
431
575
  }
432
576
  // ---- Revoke (RFC 7009) --------------------------------------------------
433
- /** Revoke a token (either kind kills the pair). Always resolves on a 200. */
577
+ /**
578
+ * Revoke a token. A refresh token ends the member's grant (every token on it);
579
+ * an access token revokes only its pair. Always resolves on a 200.
580
+ */
434
581
  async revoke(token, tokenTypeHint) {
435
582
  const body = new URLSearchParams({ token });
436
583
  if (tokenTypeHint) body.set("token_type_hint", tokenTypeHint);
@@ -441,7 +588,7 @@ var OAuthClient = (_class = class _OAuthClient {
441
588
  });
442
589
  if (!res.ok) {
443
590
  const text = await res.text().catch(() => "");
444
- throw this.oauthError(res.status, text, this.endpoints.revoke);
591
+ throw _nullishCoalesce(this.oauthMissing(res.status, text, this.endpoints.revoke), () => ( this.oauthError(res.status, text, this.endpoints.revoke)));
445
592
  }
446
593
  }
447
594
  /**
@@ -454,14 +601,14 @@ var OAuthClient = (_class = class _OAuthClient {
454
601
  const tokens = await store.get(memberKey);
455
602
  let revoked = false;
456
603
  try {
457
- if (_optionalChain([tokens, 'optionalAccess', _11 => _11.refreshToken])) {
604
+ if (_optionalChain([tokens, 'optionalAccess', _13 => _13.refreshToken])) {
458
605
  await this.revoke(tokens.refreshToken, "refresh_token");
459
606
  revoked = true;
460
- } else if (_optionalChain([tokens, 'optionalAccess', _12 => _12.accessToken])) {
607
+ } else if (_optionalChain([tokens, 'optionalAccess', _14 => _14.accessToken])) {
461
608
  await this.revoke(tokens.accessToken, "access_token");
462
609
  revoked = true;
463
610
  }
464
- } catch (e3) {
611
+ } catch (e4) {
465
612
  revoked = false;
466
613
  } finally {
467
614
  await store.delete(memberKey);
@@ -477,7 +624,9 @@ var OAuthClient = (_class = class _OAuthClient {
477
624
  body: new URLSearchParams({ token }).toString()
478
625
  });
479
626
  const text = await res.text();
480
- if (!res.ok) throw this.oauthError(res.status, text, this.endpoints.introspect);
627
+ if (!res.ok) {
628
+ throw _nullishCoalesce(this.oauthMissing(res.status, text, this.endpoints.introspect), () => ( this.oauthError(res.status, text, this.endpoints.introspect)));
629
+ }
481
630
  return parseJsonBody(text, res.status, this.endpoints.introspect);
482
631
  }
483
632
  // ---- Adapter factories --------------------------------------------------
@@ -510,7 +659,7 @@ var OAuthClient = (_class = class _OAuthClient {
510
659
  */
511
660
  memberClient(store, memberKey, opts = {}) {
512
661
  const { session, ...rest } = opts;
513
- return new (0, _chunkSI3EILHNcjs.STX)({
662
+ return new (0, _chunkR77AZ5UHcjs.STX)({
514
663
  ...rest,
515
664
  host: this.baseUrl,
516
665
  fetch: _nullishCoalesce(rest.fetch, () => ( this.fetch)),
@@ -523,7 +672,7 @@ var OAuthClient = (_class = class _OAuthClient {
523
672
  * market channels. Scope defaults to every app scope the client may hold.
524
673
  */
525
674
  appClient(scope, opts = {}) {
526
- return new (0, _chunkSI3EILHNcjs.STX)({ ...opts, host: this.baseUrl, fetch: _nullishCoalesce(opts.fetch, () => ( this.fetch)), auth: this.app(scope) });
675
+ return new (0, _chunkR77AZ5UHcjs.STX)({ ...opts, host: this.baseUrl, fetch: _nullishCoalesce(opts.fetch, () => ( this.fetch)), auth: this.app(scope) });
527
676
  }
528
677
  /** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */
529
678
  _refreshesFor(store) {
@@ -535,10 +684,13 @@ var OAuthClient = (_class = class _OAuthClient {
535
684
  return map;
536
685
  }
537
686
  // ---- internals ----------------------------------------------------------
538
- /** `client_secret_basic` header, or undefined for a public client. */
687
+ /**
688
+ * `client_secret_basic` header, or undefined for a public client. Both parts
689
+ * are form-urlencoded before base64, as RFC 6749 section 2.3.1 requires.
690
+ */
539
691
  basicAuthHeader() {
540
692
  if (this.clientSecret === void 0) return void 0;
541
- const raw = `${this.clientId}:${this.clientSecret}`;
693
+ const raw = `${formEncode(this.clientId)}:${formEncode(this.clientSecret)}`;
542
694
  return "Basic " + Buffer.from(raw).toString("base64");
543
695
  }
544
696
  formHeaders() {
@@ -562,8 +714,27 @@ var OAuthClient = (_class = class _OAuthClient {
562
714
  });
563
715
  const text = await res.text();
564
716
  if (!res.ok) {
717
+ const missing = this.oauthMissing(res.status, text, this.endpoints.token);
718
+ if (missing) throw missing;
565
719
  const err = rfcError(text);
566
- if (res.status === 400 && _optionalChain([err, 'optionalAccess', _13 => _13.error]) === "invalid_grant" && body.get("grant_type") === "refresh_token") {
720
+ if (_optionalChain([err, 'optionalAccess', _15 => _15.error]) === "invalid_scope") {
721
+ const unoffered = this.unofferedScope(
722
+ _nullishCoalesce(body.get("scope"), () => ( void 0)),
723
+ this.oauthError(res.status, text, this.endpoints.token)
724
+ );
725
+ if (unoffered) throw unoffered;
726
+ }
727
+ if (_optionalChain([err, 'optionalAccess', _16 => _16.error]) === "invalid_grant" && err.error_reason === "account_pending") {
728
+ throw new STXAccountPendingException(
729
+ err.error,
730
+ err.error_description,
731
+ res.status,
732
+ pathOf(this.endpoints.token),
733
+ void 0,
734
+ err.error_reason
735
+ );
736
+ }
737
+ if (res.status === 400 && _optionalChain([err, 'optionalAccess', _17 => _17.error]) === "invalid_grant" && body.get("grant_type") === "refresh_token") {
567
738
  throw new STXGrantRevokedException(
568
739
  err.error_description ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.` : void 0
569
740
  );
@@ -575,14 +746,14 @@ var OAuthClient = (_class = class _OAuthClient {
575
746
  oauthError(status, text, endpoint) {
576
747
  const err = rfcError(text);
577
748
  const path = pathOf(endpoint);
578
- if (err) return new STXOAuthException(err.error, err.error_description, status, path);
749
+ if (err) return new STXOAuthException(err.error, err.error_description, status, path, void 0, err.error_reason);
579
750
  return new STXOAuthException("http_error", text.slice(0, 300) || void 0, status, path);
580
751
  }
581
752
  }, _class);
582
753
  function parseJsonBody(text, status, endpoint) {
583
754
  try {
584
755
  return JSON.parse(text);
585
- } catch (e4) {
756
+ } catch (e5) {
586
757
  throw new STXOAuthException("invalid_response", "Response body is not JSON.", status, pathOf(endpoint));
587
758
  }
588
759
  }
@@ -605,6 +776,11 @@ function parseTokenResponse(json) {
605
776
  set.expiresAt = Date.now() + obj.expires_in * 1e3;
606
777
  }
607
778
  if (typeof obj.scope === "string") set.scope = obj.scope;
779
+ if (typeof obj.id_token === "string") set.idToken = obj.id_token;
780
+ if (obj.terms_required === true) {
781
+ set.termsRequired = true;
782
+ if (typeof obj.terms_url === "string") set.termsUrl = obj.terms_url;
783
+ }
608
784
  return set;
609
785
  }
610
786
  function tokenSetToStored(set) {
@@ -612,9 +788,14 @@ function tokenSetToStored(set) {
612
788
  accessToken: set.accessToken,
613
789
  refreshToken: set.refreshToken,
614
790
  expiresAt: set.expiresAt,
615
- scope: set.scope
791
+ scope: set.scope,
792
+ ...termsState(set)
616
793
  };
617
794
  }
795
+ function termsState(set) {
796
+ if (!set.termsRequired) return {};
797
+ return { termsRequired: true, ...set.termsUrl ? { termsUrl: set.termsUrl } : {} };
798
+ }
618
799
  var AppTokenProvider = (_class2 = class {
619
800
  constructor(client, scope, opts = {}) {;_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);
620
801
  this.client = client;
@@ -647,7 +828,7 @@ var AppTokenProvider = (_class2 = class {
647
828
  }
648
829
  /** The effective scope the exchange granted the current token, if minted. */
649
830
  get grantedScope() {
650
- return _optionalChain([this, 'access', _14 => _14.cached, 'optionalAccess', _15 => _15.scope]);
831
+ return _optionalChain([this, 'access', _18 => _18.cached, 'optionalAccess', _19 => _19.scope]);
651
832
  }
652
833
  async mint() {
653
834
  const set = await this.client.clientCredentials(this.scope);
@@ -699,7 +880,7 @@ var OAuthSessionAuth = (_class4 = class {
699
880
  async tokens() {
700
881
  let tokens = await this.load();
701
882
  if (!tokens) {
702
- throw new (0, _chunkSI3EILHNcjs.STXConfigException)(`No tokens stored for member "${this.memberKey}". Complete the OAuth flow first.`);
883
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)(`No tokens stored for member "${this.memberKey}". Complete the OAuth flow first.`);
703
884
  }
704
885
  if (tokens.refreshToken && tokens.expiresAt !== void 0 && tokens.expiresAt - Date.now() <= this.skewMs) {
705
886
  const refreshed = await this.refresh(tokens.refreshToken);
@@ -709,7 +890,7 @@ var OAuthSessionAuth = (_class4 = class {
709
890
  }
710
891
  /** The granted scopes of the stored tokens, canonical names. */
711
892
  async scopes() {
712
- return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async _16 => _16.scope]));
893
+ return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async _20 => _20.scope]));
713
894
  }
714
895
  async authHeaders(_request) {
715
896
  const tokens = await this.tokens();
@@ -734,7 +915,11 @@ var OAuthSessionAuth = (_class4 = class {
734
915
  * Refresh with rotation, single-flight. Persists the new pair (keeping the
735
916
  * returned refresh token; the old one only if the server omitted it). On a
736
917
  * revoked grant, deletes the store entry and throws
737
- * `STXGrantRevokedException`. A transient failure resolves null.
918
+ * `STXGrantRevokedException`. While the member's account is still being
919
+ * verified, keeps the store entry and throws `STXAccountPendingException`.
920
+ * A refresh that says the member has terms to accept is a success: the pair
921
+ * is stored with `termsRequired` and `termsUrl`, and `onTermsRequired` runs.
922
+ * A transient failure resolves null.
738
923
  */
739
924
  refresh(refreshToken) {
740
925
  const inflight = this.client._refreshesFor(this.store);
@@ -742,24 +927,27 @@ var OAuthSessionAuth = (_class4 = class {
742
927
  if (existing) return existing;
743
928
  const run = async () => {
744
929
  const current = await this.load();
745
- if (_optionalChain([current, 'optionalAccess', _17 => _17.refreshToken]) && current.refreshToken !== refreshToken) return current;
930
+ if (_optionalChain([current, 'optionalAccess', _21 => _21.refreshToken]) && current.refreshToken !== refreshToken) return current;
746
931
  try {
747
932
  const set = await this.client.refreshToken(refreshToken);
748
933
  const stored = {
749
934
  accessToken: set.accessToken,
750
935
  refreshToken: _nullishCoalesce(set.refreshToken, () => ( refreshToken)),
751
936
  expiresAt: set.expiresAt,
752
- scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess', _18 => _18.scope])))
937
+ scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess', _22 => _22.scope]))),
938
+ ...termsState(set)
753
939
  };
754
940
  await this.store.set(this.memberKey, stored);
755
- await _optionalChain([this, 'access', _19 => _19.opts, 'access', _20 => _20.onRefresh, 'optionalCall', _21 => _21(stored)]);
941
+ await _optionalChain([this, 'access', _23 => _23.opts, 'access', _24 => _24.onRefresh, 'optionalCall', _25 => _25(stored)]);
942
+ if (stored.termsUrl) await _optionalChain([this, 'access', _26 => _26.opts, 'access', _27 => _27.onTermsRequired, 'optionalCall', _28 => _28({ termsUrl: stored.termsUrl })]);
756
943
  return stored;
757
944
  } catch (err) {
758
945
  if (err instanceof STXGrantRevokedException) {
759
946
  await this.store.delete(this.memberKey);
760
- await _optionalChain([this, 'access', _22 => _22.opts, 'access', _23 => _23.onGrantRevoked, 'optionalCall', _24 => _24(err)]);
947
+ await _optionalChain([this, 'access', _29 => _29.opts, 'access', _30 => _30.onGrantRevoked, 'optionalCall', _31 => _31(err)]);
761
948
  throw err;
762
949
  }
950
+ if (err instanceof STXAccountPendingException) throw err;
763
951
  return null;
764
952
  }
765
953
  };
@@ -793,10 +981,13 @@ var OAuthAppAuth = (_class5 = class {
793
981
  * just dropped.
794
982
  */
795
983
  async websocketHeaders(context) {
796
- const token = _optionalChain([context, 'optionalAccess', _25 => _25.reconnect]) === false ? await this.tokens.get() : await this.tokens.fresh();
984
+ const token = _optionalChain([context, 'optionalAccess', _32 => _32.reconnect]) === false ? await this.tokens.get() : await this.tokens.fresh();
797
985
  return { "x-stx-oauth-token": token };
798
986
  }
799
987
  }, _class5);
988
+ function formEncode(value) {
989
+ return new URLSearchParams({ v: value }).toString().slice(2);
990
+ }
800
991
  function normalizeScope(scope) {
801
992
  if (scope === void 0) return void 0;
802
993
  return typeof scope === "string" ? scope : formatScopes(scope);
@@ -805,13 +996,12 @@ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPO
805
996
  const q = callbackParams(callback);
806
997
  const where = pathOf(authorizeEndpoint);
807
998
  const error = q.get("error");
808
- if (error) throw new STXOAuthException(error, _nullishCoalesce(q.get("error_description"), () => ( void 0)), 400, where);
809
999
  const code = q.get("code");
810
1000
  const state = q.get("state");
811
- if (!code || !state) {
1001
+ if (!error && (!code || !state)) {
812
1002
  throw new STXOAuthException("invalid_request", "The callback carries no code or no state.", 400, where);
813
1003
  }
814
- const entry = await pending.take(state);
1004
+ const entry = state ? await pending.take(state) : null;
815
1005
  if (!entry) {
816
1006
  throw new STXOAuthException(
817
1007
  "invalid_state",
@@ -820,6 +1010,11 @@ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPO
820
1010
  where
821
1011
  );
822
1012
  }
1013
+ if (error) {
1014
+ const err = callbackError(error, _nullishCoalesce(q.get("error_description"), () => ( void 0)), where);
1015
+ err.requestedScope = entry.scope;
1016
+ throw err;
1017
+ }
823
1018
  return { code, pending: entry };
824
1019
  }
825
1020
  function callbackParams(input) {
@@ -836,56 +1031,325 @@ function callbackParams(input) {
836
1031
  function pathOf(endpoint) {
837
1032
  try {
838
1033
  return /^https?:\/\//i.test(endpoint) ? new URL(endpoint).pathname : endpoint;
839
- } catch (e5) {
1034
+ } catch (e6) {
840
1035
  return endpoint;
841
1036
  }
842
1037
  }
843
1038
 
844
- // src/oauth/metadata.ts
845
- async function discoverMetadata(baseUrl, opts = {}) {
846
- const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);
847
- const meta = doc;
848
- if (typeof meta.issuer !== "string" || typeof meta.authorization_endpoint !== "string" || typeof meta.token_endpoint !== "string") {
849
- throw httpError2(
850
- 200,
851
- JSON.stringify(doc),
852
- WELL_KNOWN.authorizationServer + " (missing issuer/authorization_endpoint/token_endpoint)"
853
- );
854
- }
855
- return meta;
1039
+ // src/oauth/terms.ts
1040
+ function termsUrlWithReturn(termsUrl, returnTo) {
1041
+ const hashAt = termsUrl.indexOf("#");
1042
+ const base = hashAt === -1 ? termsUrl : termsUrl.slice(0, hashAt);
1043
+ const hash = hashAt === -1 ? "" : termsUrl.slice(hashAt);
1044
+ const queryAt = base.indexOf("?");
1045
+ const path = queryAt === -1 ? base : base.slice(0, queryAt);
1046
+ const params = new URLSearchParams(queryAt === -1 ? "" : base.slice(queryAt + 1));
1047
+ params.set("return_to", returnTo);
1048
+ return `${path}?${params.toString()}${hash}`;
856
1049
  }
857
- async function discoverProtectedResource(baseUrl, opts = {}) {
858
- const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.protectedResource, opts);
859
- const meta = doc;
860
- if (typeof meta.resource !== "string" || !Array.isArray(meta.authorization_servers)) {
861
- throw httpError2(
862
- 200,
863
- JSON.stringify(doc),
864
- WELL_KNOWN.protectedResource + " (missing resource/authorization_servers)"
1050
+
1051
+ // src/oauth/connect.ts
1052
+ function createConnect(opts) {
1053
+ if (!opts.issuer) throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("issuer is required.");
1054
+ if (!opts.clientId || !opts.clientSecret) throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("clientId and clientSecret are required.");
1055
+ if (!opts.redirectUri) throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("redirectUri is required.");
1056
+ const issuer = opts.issuer.replace(/\/+$/, "");
1057
+ const fetchImpl = _nullishCoalesce(opts.fetch, () => ( globalThis.fetch));
1058
+ if (typeof fetchImpl !== "function") {
1059
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("No fetch implementation available. Use Node 18+, or pass { fetch }.");
1060
+ }
1061
+ const skew = _nullishCoalesce(opts.clockSkewSeconds, () => ( 60));
1062
+ let config;
1063
+ let client;
1064
+ let keys;
1065
+ const configuration = () => {
1066
+ config ??= fetchJson(fetchImpl, joinUrl(issuer, "/.well-known/openid-configuration"), "connect").then((doc) => {
1067
+ const c = doc;
1068
+ if (typeof c.issuer !== "string" || typeof c.authorization_endpoint !== "string" || typeof c.token_endpoint !== "string" || typeof c.jwks_uri !== "string") {
1069
+ throw new STXOAuthException(
1070
+ "invalid_configuration",
1071
+ "The discovery document is incomplete.",
1072
+ 0,
1073
+ "/.well-known/openid-configuration"
1074
+ );
1075
+ }
1076
+ if (c.issuer.replace(/\/+$/, "") !== issuer) {
1077
+ throw new STXOAuthException(
1078
+ "invalid_configuration",
1079
+ `The discovery issuer ${c.issuer} does not match ${issuer}.`,
1080
+ 0,
1081
+ "/.well-known/openid-configuration"
1082
+ );
1083
+ }
1084
+ return c;
1085
+ });
1086
+ config.catch(() => {
1087
+ config = void 0;
1088
+ });
1089
+ return config;
1090
+ };
1091
+ const oauth = () => {
1092
+ client ??= configuration().then(
1093
+ (c) => new OAuthClient({
1094
+ baseUrl: issuer,
1095
+ clientId: opts.clientId,
1096
+ clientSecret: opts.clientSecret,
1097
+ redirectUri: opts.redirectUri,
1098
+ fetch: fetchImpl,
1099
+ endpoints: {
1100
+ authorize: c.authorization_endpoint,
1101
+ token: c.token_endpoint,
1102
+ ...c.revocation_endpoint ? { revoke: c.revocation_endpoint } : {}
1103
+ }
1104
+ })
865
1105
  );
1106
+ client.catch(() => {
1107
+ client = void 0;
1108
+ });
1109
+ return client;
1110
+ };
1111
+ const jwks = async (refresh = false) => {
1112
+ if (refresh) keys = void 0;
1113
+ keys ??= configuration().then((c) => fetchJson(fetchImpl, c.jwks_uri)).then((doc) => {
1114
+ const list = doc.keys;
1115
+ if (!Array.isArray(list))
1116
+ throw new STXOAuthException("invalid_configuration", "The key set has no keys.", 0, "jwks_uri");
1117
+ return list;
1118
+ });
1119
+ keys.catch(() => {
1120
+ keys = void 0;
1121
+ });
1122
+ return keys;
1123
+ };
1124
+ return {
1125
+ configuration,
1126
+ async start(params = {}) {
1127
+ const c = await oauth();
1128
+ const pkce = await createPkce();
1129
+ const state = generateState();
1130
+ const nonce = generateState();
1131
+ const redirectUri = _nullishCoalesce(params.redirectUri, () => ( opts.redirectUri));
1132
+ const extraParams = { nonce };
1133
+ if (params.connection) extraParams.connection = params.connection;
1134
+ if (params.loginHint) extraParams.login_hint = params.loginHint;
1135
+ const url = c.buildAuthorizeUrl({
1136
+ state,
1137
+ codeChallenge: pkce.codeChallenge,
1138
+ scope: withOpenId(_nullishCoalesce(params.scopes, () => ( opts.scopes))),
1139
+ prompt: params.prompt,
1140
+ redirectUri,
1141
+ extraParams
1142
+ });
1143
+ return { url, state, codeVerifier: pkce.codeVerifier, nonce, redirectUri };
1144
+ },
1145
+ async finish(callback, saved) {
1146
+ const q = callbackParams(callback);
1147
+ const where = pathOf2((await configuration()).authorization_endpoint);
1148
+ const error = q.get("error");
1149
+ const code = q.get("code");
1150
+ const state = q.get("state");
1151
+ if (!error && (!code || !state)) {
1152
+ throw new STXOAuthException("invalid_request", "The callback carries no code or no state.", 400, where);
1153
+ }
1154
+ if (!state || !_optionalChain([saved, 'optionalAccess', _33 => _33.state]) || !constantTimeEqual(state, saved.state)) {
1155
+ throw new STXOAuthException("invalid_state", "The state does not match this sign-in; start again.", 400, where);
1156
+ }
1157
+ if (error) throw callbackError(error, _nullishCoalesce(q.get("error_description"), () => ( void 0)), where);
1158
+ const c = await oauth();
1159
+ const tokens = await c.exchangeCode({
1160
+ code,
1161
+ codeVerifier: saved.codeVerifier,
1162
+ redirectUri: _nullishCoalesce(saved.redirectUri, () => ( opts.redirectUri))
1163
+ });
1164
+ const idToken = tokens.idToken;
1165
+ if (!idToken) {
1166
+ throw new STXOAuthException(
1167
+ "invalid_id_token",
1168
+ "The token response has no id_token; request the openid scope.",
1169
+ 0,
1170
+ "/oauth/token"
1171
+ );
1172
+ }
1173
+ const claims = await verifyIdToken(idToken, {
1174
+ issuer: (await configuration()).issuer,
1175
+ clientId: opts.clientId,
1176
+ nonce: saved.nonce,
1177
+ skew,
1178
+ keys: jwks
1179
+ });
1180
+ return { tokens: { ...tokens, idToken }, identity: identityFrom(claims) };
1181
+ },
1182
+ async userInfo(accessToken, expected = {}) {
1183
+ const endpoint = (await configuration()).userinfo_endpoint;
1184
+ if (!endpoint) {
1185
+ throw new STXOAuthException(
1186
+ "invalid_configuration",
1187
+ "The discovery document names no userinfo endpoint.",
1188
+ 0,
1189
+ "/.well-known/openid-configuration"
1190
+ );
1191
+ }
1192
+ const where = pathOf2(endpoint);
1193
+ const res = await fetchImpl(endpoint, {
1194
+ method: "GET",
1195
+ headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}` }
1196
+ });
1197
+ const text = await res.text();
1198
+ if (res.status === 404 || _chunkR77AZ5UHcjs.isEdgeBlock.call(void 0, res.status, text)) {
1199
+ throw new (0, _chunkR77AZ5UHcjs.STXNotAvailableException)("connect", new URL(endpoint).host, {
1200
+ statusCode: res.status,
1201
+ body: text,
1202
+ method: "GET",
1203
+ path: where
1204
+ });
1205
+ }
1206
+ let body;
1207
+ try {
1208
+ body = JSON.parse(text);
1209
+ } catch (e7) {
1210
+ body = void 0;
1211
+ }
1212
+ const claims = body && typeof body === "object" ? body : {};
1213
+ if (!res.ok) {
1214
+ const error = typeof claims.error === "string" ? claims.error : res.status === 401 ? "invalid_token" : "error";
1215
+ const description = typeof claims.error_description === "string" ? claims.error_description : void 0;
1216
+ const reason = typeof claims.error_reason === "string" ? claims.error_reason : void 0;
1217
+ throw new STXOAuthException(error, description, res.status, where, void 0, reason);
1218
+ }
1219
+ const fail = (why) => {
1220
+ throw new STXOAuthException("invalid_userinfo", why, 0, where);
1221
+ };
1222
+ if (typeof claims.sub !== "string" || claims.sub === "") fail("The userinfo answer has no subject.");
1223
+ if (expected.sub !== void 0 && claims.sub !== expected.sub) {
1224
+ fail("The userinfo answer is about a different member.");
1225
+ }
1226
+ return identityFrom(claims);
1227
+ },
1228
+ async refresh(refreshToken) {
1229
+ return (await oauth()).refreshToken(refreshToken);
1230
+ },
1231
+ async revoke(token, tokenTypeHint) {
1232
+ return (await oauth()).revoke(token, tokenTypeHint);
1233
+ },
1234
+ async disconnect(tokens) {
1235
+ const client2 = await oauth();
1236
+ if (tokens.refreshToken) return client2.revoke(tokens.refreshToken, "refresh_token");
1237
+ return client2.revoke(tokens.accessToken, "access_token");
1238
+ }
1239
+ };
1240
+ }
1241
+ function pathOf2(url) {
1242
+ try {
1243
+ return new URL(url).pathname;
1244
+ } catch (e8) {
1245
+ return url;
866
1246
  }
867
- return meta;
868
1247
  }
869
- async function fetchWellKnown(baseUrl, path, opts) {
870
- const cfg = resolveOAuthConfig({ baseUrl, fetch: opts.fetch });
871
- const res = await cfg.fetch(joinUrl(cfg.baseUrl, path), {
872
- method: "GET",
873
- headers: { Accept: "application/json" }
874
- });
1248
+ function identityFrom(claims) {
1249
+ return {
1250
+ sub: claims.sub,
1251
+ ...typeof claims.email === "string" ? { email: claims.email } : {},
1252
+ ...claims.email_verified !== void 0 ? { emailVerified: claims.email_verified === true || claims.email_verified === "true" } : {},
1253
+ claims
1254
+ };
1255
+ }
1256
+ function withOpenId(scopes) {
1257
+ const list = scopes === void 0 ? [] : typeof scopes === "string" ? scopes.split(/\s+/) : [...scopes];
1258
+ const set = new Set(list.filter(Boolean));
1259
+ set.delete("openid");
1260
+ return formatScopes(["openid", ...set]);
1261
+ }
1262
+ async function fetchJson(fetchImpl, url, feature) {
1263
+ const res = await fetchImpl(url, { method: "GET", headers: { Accept: "application/json" } });
875
1264
  const text = await res.text();
876
- if (!res.ok) throw httpError2(res.status, text, path);
1265
+ if (feature && (res.status === 404 || _chunkR77AZ5UHcjs.isEdgeBlock.call(void 0, res.status, text))) {
1266
+ throw new (0, _chunkR77AZ5UHcjs.STXNotAvailableException)(feature, new URL(url).host, {
1267
+ statusCode: res.status,
1268
+ body: text,
1269
+ method: "GET",
1270
+ path: new URL(url).pathname
1271
+ });
1272
+ }
1273
+ if (!res.ok) {
1274
+ throw new STXOAuthException("invalid_configuration", `GET ${url} returned ${res.status}.`, res.status, url);
1275
+ }
877
1276
  try {
878
1277
  return JSON.parse(text);
879
- } catch (e6) {
880
- throw httpError2(res.status, text, path);
1278
+ } catch (e9) {
1279
+ throw new STXOAuthException("invalid_configuration", `GET ${url} did not return JSON.`, res.status, url);
881
1280
  }
882
1281
  }
883
- function httpError2(status, text, path) {
884
- return new (0, _chunkSI3EILHNcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
885
- statusCode: status,
886
- body: text,
887
- path
888
- });
1282
+ var ALGORITHMS = {
1283
+ RS256: {
1284
+ import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
1285
+ verify: { name: "RSASSA-PKCS1-v1_5" }
1286
+ },
1287
+ ES256: {
1288
+ import: { name: "ECDSA", namedCurve: "P-256" },
1289
+ verify: { name: "ECDSA", hash: "SHA-256" }
1290
+ }
1291
+ };
1292
+ async function verifyIdToken(token, expected) {
1293
+ const fail = (why) => {
1294
+ throw new STXOAuthException("invalid_id_token", why, 0, "/oauth/token");
1295
+ };
1296
+ const parts = token.split(".");
1297
+ if (parts.length !== 3) fail("The ID token is not a JWT.");
1298
+ const [h, p, s] = parts;
1299
+ const header = decodeJson(h);
1300
+ const claims = decodeJson(p);
1301
+ if (!header || !claims) return fail("The ID token is malformed.");
1302
+ const alg = _nullishCoalesce(header.alg, () => ( ""));
1303
+ const algorithm = ALGORITHMS[alg];
1304
+ if (!algorithm) return fail(`Unsupported ID token algorithm ${alg}.`);
1305
+ const pick = (list) => list.find((k) => (header.kid ? k.kid === header.kid : true) && (!k.alg || k.alg === alg) && k.use !== "enc");
1306
+ let jwk = pick(await expected.keys());
1307
+ if (!jwk && header.kid) jwk = pick(await expected.keys(true));
1308
+ if (!jwk) return fail("No published key matches the ID token.");
1309
+ const { kid: _kid, alg: _alg, use: _use, key_ops: _ops, ...material } = jwk;
1310
+ const key = await crypto.subtle.importKey("jwk", material, algorithm.import, false, [
1311
+ "verify"
1312
+ ]);
1313
+ const ok = await crypto.subtle.verify(
1314
+ algorithm.verify,
1315
+ key,
1316
+ base64urlDecode(s),
1317
+ new TextEncoder().encode(`${h}.${p}`)
1318
+ );
1319
+ if (!ok) fail("The ID token signature does not verify.");
1320
+ if (claims.iss !== expected.issuer) fail("The ID token was issued by someone else.");
1321
+ const aud = claims.aud;
1322
+ const audiences = Array.isArray(aud) ? aud : [aud];
1323
+ if (!audiences.includes(expected.clientId)) fail("The ID token is for another app.");
1324
+ if (audiences.length > 1 && claims.azp !== expected.clientId) fail("The ID token is for another app.");
1325
+ const now = Math.floor(Date.now() / 1e3);
1326
+ if (typeof claims.exp !== "number" || claims.exp + expected.skew < now) fail("The ID token has expired.");
1327
+ if (typeof claims.iat === "number" && claims.iat - expected.skew > now) fail("The ID token is not valid yet.");
1328
+ if (typeof claims.nonce !== "string" || !constantTimeEqual(claims.nonce, expected.nonce)) {
1329
+ fail("The ID token nonce does not match this sign-in.");
1330
+ }
1331
+ if (typeof claims.sub !== "string" || claims.sub === "") fail("The ID token has no subject.");
1332
+ return claims;
1333
+ }
1334
+ function decodeJson(segment) {
1335
+ try {
1336
+ return JSON.parse(new TextDecoder().decode(base64urlDecode(segment)));
1337
+ } catch (e10) {
1338
+ return void 0;
1339
+ }
1340
+ }
1341
+ function base64urlDecode(segment) {
1342
+ const b64 = segment.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((segment.length + 3) % 4);
1343
+ const bin = atob(b64);
1344
+ const out = new Uint8Array(bin.length);
1345
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1346
+ return out;
1347
+ }
1348
+ function constantTimeEqual(a, b) {
1349
+ if (a.length !== b.length) return false;
1350
+ let diff = 0;
1351
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1352
+ return diff === 0;
889
1353
  }
890
1354
 
891
1355
  // src/oauth/tokenStore.ts
@@ -965,5 +1429,13 @@ var MemoryPendingAuthorizationStore = (_class7 = class {constructor() { _class7.
965
1429
 
966
1430
 
967
1431
 
968
- exports.ALL_APP_SCOPES = ALL_APP_SCOPES; exports.ALL_MEMBER_SCOPES = ALL_MEMBER_SCOPES; exports.AppScopes = AppScopes; exports.AppTokenProvider = AppTokenProvider; exports.DEFAULT_ENDPOINTS = DEFAULT_ENDPOINTS; exports.LEGACY_SCOPES = LEGACY_SCOPES; exports.MemberScopes = MemberScopes; exports.MemoryPendingAuthorizationStore = MemoryPendingAuthorizationStore; exports.MemoryTokenStore = MemoryTokenStore; exports.OAuthAppAuth = OAuthAppAuth; exports.OAuthBearerAuth = OAuthBearerAuth; exports.OAuthClient = OAuthClient; exports.OAuthSessionAuth = OAuthSessionAuth; exports.STXAuthenticationException = _chunkSI3EILHNcjs.STXAuthenticationException; exports.STXForbiddenException = _chunkSI3EILHNcjs.STXForbiddenException; exports.STXGrantRevokedException = STXGrantRevokedException; exports.STXInsufficientScopeException = _chunkSI3EILHNcjs.STXInsufficientScopeException; exports.STXInvalidTokenException = _chunkSI3EILHNcjs.STXInvalidTokenException; exports.STXOAuthException = STXOAuthException; exports.Scopes = Scopes; exports.WELL_KNOWN = WELL_KNOWN; exports.base64url = base64url; exports.canonicalScope = canonicalScope; exports.codeChallengeS256 = codeChallengeS256; exports.createPkce = createPkce; exports.discoverMetadata = discoverMetadata; exports.discoverProtectedResource = discoverProtectedResource; exports.formatScopes = formatScopes; exports.generateCodeVerifier = generateCodeVerifier; exports.generateState = generateState; exports.isAppScope = isAppScope; exports.isMemberScope = isMemberScope; exports.joinUrl = joinUrl; exports.parseScopes = parseScopes; exports.parseTokenResponse = parseTokenResponse; exports.readCallback = readCallback; exports.registerClient = registerClient; exports.rfcError = rfcError; exports.tokenSetToStored = tokenSetToStored;
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+
1440
+ exports.ALL_APP_SCOPES = ALL_APP_SCOPES; exports.ALL_MEMBER_SCOPES = ALL_MEMBER_SCOPES; exports.AppScopes = AppScopes; exports.AppTokenProvider = AppTokenProvider; exports.DEFAULT_ENDPOINTS = DEFAULT_ENDPOINTS; exports.LEGACY_SCOPES = LEGACY_SCOPES; exports.MemberScopes = MemberScopes; exports.MemoryPendingAuthorizationStore = MemoryPendingAuthorizationStore; exports.MemoryTokenStore = MemoryTokenStore; exports.OAuthAppAuth = OAuthAppAuth; exports.OAuthBearerAuth = OAuthBearerAuth; exports.OAuthClient = OAuthClient; exports.OAuthSessionAuth = OAuthSessionAuth; exports.STXAccessDeniedException = STXAccessDeniedException; exports.STXAccountPendingException = STXAccountPendingException; exports.STXAuthenticationException = _chunkR77AZ5UHcjs.STXAuthenticationException; exports.STXForbiddenException = _chunkR77AZ5UHcjs.STXForbiddenException; exports.STXGrantRevokedException = STXGrantRevokedException; exports.STXIPNotAllowedException = _chunkR77AZ5UHcjs.STXIPNotAllowedException; exports.STXInsufficientScopeException = _chunkR77AZ5UHcjs.STXInsufficientScopeException; exports.STXInvalidTokenException = _chunkR77AZ5UHcjs.STXInvalidTokenException; exports.STXNotAvailableException = _chunkR77AZ5UHcjs.STXNotAvailableException; exports.STXOAuthException = STXOAuthException; exports.STXTermsNotAcceptedException = STXTermsNotAcceptedException; exports.STXTermsRequiredException = _chunkR77AZ5UHcjs.STXTermsRequiredException; exports.Scopes = Scopes; exports.WELL_KNOWN = WELL_KNOWN; exports.base64url = base64url; exports.canonicalScope = canonicalScope; exports.codeChallengeS256 = codeChallengeS256; exports.createConnect = createConnect; exports.createPkce = createPkce; exports.discoverMetadata = discoverMetadata; exports.discoverProtectedResource = discoverProtectedResource; exports.formatScopes = formatScopes; exports.generateCodeVerifier = generateCodeVerifier; exports.generateState = generateState; exports.isAppScope = isAppScope; exports.isMemberScope = isMemberScope; exports.joinUrl = joinUrl; exports.parseScopes = parseScopes; exports.parseTokenResponse = parseTokenResponse; exports.readCallback = readCallback; exports.registerClient = registerClient; exports.rfcError = rfcError; exports.termsUrlWithReturn = termsUrlWithReturn; exports.tokenSetToStored = tokenSetToStored;
969
1441
  //# sourceMappingURL=oauth.cjs.map