@stxapp/stx-typescript 0.9.0-alpha.1 → 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 _chunk33AQCUGMcjs = require('./chunk-33AQCUGM.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, _chunk33AQCUGMcjs.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, _chunk33AQCUGMcjs.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: _chunk33AQCUGMcjs.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 _chunk33AQCUGMcjs.STXAuthenticationException {
44
+ var STXOAuthException = class extends _chunkR77AZ5UHcjs.STXAuthenticationException {
41
45
  /** The RFC error code: `invalid_client`, `invalid_grant`, `invalid_scope`, ... */
42
46
 
43
47
 
@@ -51,6 +55,11 @@ var STXOAuthException = class extends _chunk33AQCUGMcjs.STXAuthenticationExcepti
51
55
  * verified.
52
56
  */
53
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
+
54
63
  constructor(error, errorDescription, status, endpoint, retryAfter, errorReason) {
55
64
  super(`OAuth ${endpoint} ${status} ${error}${errorDescription ? `: ${errorDescription}` : ""}`, {
56
65
  statusCode: status,
@@ -67,16 +76,73 @@ var STXAccessDeniedException = class extends STXOAuthException {
67
76
  };
68
77
  var STXAccountPendingException = class extends STXOAuthException {
69
78
  };
79
+ var STXTermsNotAcceptedException = class extends STXOAuthException {
80
+ };
70
81
  function callbackError(error, errorDescription, endpoint) {
71
- const Class = error === "account_pending" ? STXAccountPendingException : error === "access_denied" ? STXAccessDeniedException : STXOAuthException;
82
+ const Class = error === "account_pending" ? STXAccountPendingException : error === "terms_required" ? STXTermsNotAcceptedException : error === "access_denied" ? STXAccessDeniedException : STXOAuthException;
72
83
  return new Class(error, errorDescription, 400, endpoint);
73
84
  }
74
- var STXGrantRevokedException = class extends _chunk33AQCUGMcjs.STXAuthenticationException {
85
+ var STXGrantRevokedException = class extends _chunkR77AZ5UHcjs.STXAuthenticationException {
75
86
  constructor(message = "OAuth grant revoked: the member must re-authorize.") {
76
87
  super(message, { statusCode: 400 });
77
88
  }
78
89
  };
79
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
+
80
146
  // src/oauth/pkce.ts
81
147
  function base64url(bytes) {
82
148
  let bin = "";
@@ -121,12 +187,12 @@ async function registerClient(request, opts = {}) {
121
187
  let doc;
122
188
  try {
123
189
  doc = JSON.parse(text);
124
- } catch (e) {
125
- throw httpError(res.status, text, path);
190
+ } catch (e2) {
191
+ throw httpError2(res.status, text, path);
126
192
  }
127
193
  const reg = doc;
128
194
  if (typeof reg.client_id !== "string" || reg.client_id === "") {
129
- throw httpError(res.status, text, path + " (missing client_id)");
195
+ throw httpError2(res.status, text, path + " (missing client_id)");
130
196
  }
131
197
  return reg;
132
198
  }
@@ -142,7 +208,7 @@ async function registerClient(request, opts = {}) {
142
208
  err.error_reason
143
209
  );
144
210
  }
145
- throw httpError(res.status, text, path);
211
+ throw httpError2(res.status, text, path);
146
212
  }
147
213
  function rfcError(text) {
148
214
  try {
@@ -153,12 +219,12 @@ function rfcError(text) {
153
219
  error_description: typeof obj.error_description === "string" ? obj.error_description : void 0,
154
220
  error_reason: typeof obj.error_reason === "string" ? obj.error_reason : void 0
155
221
  };
156
- } catch (e2) {
222
+ } catch (e3) {
157
223
  return null;
158
224
  }
159
225
  }
160
- function httpError(status, text, path) {
161
- return new (0, _chunk33AQCUGMcjs.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)}`, {
162
228
  statusCode: status,
163
229
  body: text,
164
230
  path
@@ -178,9 +244,7 @@ var MemberScopes = {
178
244
  /** Deposit and withdrawal history (read only). */
179
245
  TRANSFERS_READ: "transfers.read",
180
246
  /** Place and cancel orders; arm `cancel_on_disconnect`. */
181
- ORDERS_WRITE: "orders.write",
182
- /** Accept the terms and conditions. */
183
- TERMS_WRITE: "terms.write"
247
+ ORDERS_WRITE: "orders.write"
184
248
  };
185
249
  var AppScopes = {
186
250
  /** The market catalog (`GET /api/v1/markets`) and the market data channels. */
@@ -199,9 +263,9 @@ var LEGACY_SCOPES = {
199
263
  portfolio: MemberScopes.PORTFOLIO_READ,
200
264
  history: MemberScopes.ORDERS_READ,
201
265
  transfers: MemberScopes.TRANSFERS_READ,
202
- trade: MemberScopes.ORDERS_WRITE,
203
- onboarding: MemberScopes.TERMS_WRITE
266
+ trade: MemberScopes.ORDERS_WRITE
204
267
  };
268
+ var RETIRED_SCOPES = /* @__PURE__ */ new Set(["terms.write", "onboarding"]);
205
269
  function canonicalScope(scope) {
206
270
  return _nullishCoalesce(LEGACY_SCOPES[scope], () => ( scope));
207
271
  }
@@ -209,7 +273,7 @@ function parseScopes(scope) {
209
273
  if (!scope) return [];
210
274
  const out = [];
211
275
  for (const raw of scope.split(/\s+/)) {
212
- if (!raw) continue;
276
+ if (!raw || RETIRED_SCOPES.has(raw)) continue;
213
277
  const s = canonicalScope(raw);
214
278
  if (!out.includes(s)) out.push(s);
215
279
  }
@@ -233,6 +297,8 @@ var OAuthClient = (_class = class _OAuthClient {
233
297
 
234
298
 
235
299
 
300
+ /** The discovery document this client was built from, if any. */
301
+
236
302
 
237
303
  /**
238
304
  * In-flight refreshes per token store and member, shared by every session
@@ -251,6 +317,7 @@ var OAuthClient = (_class = class _OAuthClient {
251
317
  this.clientSecret = opts.clientSecret || void 0;
252
318
  this.redirectUri = opts.redirectUri;
253
319
  this.scope = normalizeScope(opts.scope);
320
+ this.metadata = opts.metadata;
254
321
  this.endpoints = {
255
322
  authorize: _nullishCoalesce(_optionalChain([opts, 'access', _3 => _3.endpoints, 'optionalAccess', _4 => _4.authorize]), () => ( DEFAULT_ENDPOINTS.authorize)),
256
323
  token: _nullishCoalesce(_optionalChain([opts, 'access', _5 => _5.endpoints, 'optionalAccess', _6 => _6.token]), () => ( DEFAULT_ENDPOINTS.token)),
@@ -266,6 +333,7 @@ var OAuthClient = (_class = class _OAuthClient {
266
333
  static fromMetadata(metadata, opts) {
267
334
  return new _OAuthClient({
268
335
  ...opts,
336
+ metadata,
269
337
  baseUrl: _nullishCoalesce(opts.baseUrl, () => ( metadata.issuer)),
270
338
  endpoints: {
271
339
  authorize: metadata.authorization_endpoint,
@@ -275,6 +343,27 @@ var OAuthClient = (_class = class _OAuthClient {
275
343
  }
276
344
  });
277
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
+ }
278
367
  /** True for a public client (no secret): PKCE-only, no app tokens. */
279
368
  get isPublic() {
280
369
  return this.clientSecret === void 0;
@@ -313,7 +402,7 @@ var OAuthClient = (_class = class _OAuthClient {
313
402
  */
314
403
  async beginAuthorization(pending, params = {}) {
315
404
  const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
316
- if (!redirectUri) throw new (0, _chunk33AQCUGMcjs.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.");
317
406
  const auth = await this.authorizationUrl({ ...params, redirectUri });
318
407
  await pending.put(auth.state, {
319
408
  codeVerifier: auth.codeVerifier,
@@ -326,7 +415,7 @@ var OAuthClient = (_class = class _OAuthClient {
326
415
  }
327
416
  /**
328
417
  * Finish a sign-in from the callback's query. Checks for an `error` from
329
- * the exchange (`access_denied`, `account_pending`), consumes the
418
+ * the exchange (`access_denied`, `account_pending`, `terms_required`), consumes the
330
419
  * `state` (single use; unknown or expired throws `invalid_state`), exchanges
331
420
  * the code with the stored PKCE verifier and, when `store` is given, saves
332
421
  * the tokens under `memberKey` (a string, or a function of the `data` passed
@@ -338,7 +427,38 @@ var OAuthClient = (_class = class _OAuthClient {
338
427
  * for a used, expired or mismatched code).
339
428
  */
340
429
  async completeAuthorization(pending, callback, opts = {}) {
341
- 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
+ });
342
462
  }
343
463
  /**
344
464
  * The second half of `completeAuthorization()`: exchange a callback already
@@ -355,7 +475,7 @@ var OAuthClient = (_class = class _OAuthClient {
355
475
  let memberKey;
356
476
  if (opts.store) {
357
477
  memberKey = typeof opts.memberKey === "function" ? opts.memberKey(entry.data) : opts.memberKey;
358
- if (!memberKey) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("Pass memberKey along with store.");
478
+ if (!memberKey) throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("Pass memberKey along with store.");
359
479
  await opts.store.set(memberKey, tokenSetToStored(tokens));
360
480
  }
361
481
  return { tokens, scopes: parseScopes(tokens.scope), data: entry.data, memberKey };
@@ -364,7 +484,7 @@ var OAuthClient = (_class = class _OAuthClient {
364
484
  buildAuthorizeUrl(params) {
365
485
  const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
366
486
  if (!redirectUri) {
367
- throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
487
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
368
488
  }
369
489
  const url = new URL(joinUrl(this.baseUrl, this.endpoints.authorize));
370
490
  const search = {
@@ -386,7 +506,7 @@ var OAuthClient = (_class = class _OAuthClient {
386
506
  exchangeCode(args) {
387
507
  const redirectUri = _nullishCoalesce(args.redirectUri, () => ( this.redirectUri));
388
508
  if (!redirectUri) {
389
- throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to exchange a code.");
509
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("redirectUri is required to exchange a code.");
390
510
  }
391
511
  return this.postToken(
392
512
  new URLSearchParams({
@@ -404,6 +524,9 @@ var OAuthClient = (_class = class _OAuthClient {
404
524
  * refresh (`invalid_grant`) means the grant was revoked, including STX's
405
525
  * reuse detection tripping on a replayed/retired token, and surfaces as
406
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`.
407
530
  */
408
531
  refreshToken(refreshToken) {
409
532
  return this.postToken(
@@ -427,7 +550,7 @@ var OAuthClient = (_class = class _OAuthClient {
427
550
  */
428
551
  clientCredentials(scope) {
429
552
  if (this.isPublic) {
430
- throw new (0, _chunk33AQCUGMcjs.STXConfigException)(
553
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)(
431
554
  "client_credentials needs a client secret; a public client cannot mint an app token."
432
555
  );
433
556
  }
@@ -465,7 +588,7 @@ var OAuthClient = (_class = class _OAuthClient {
465
588
  });
466
589
  if (!res.ok) {
467
590
  const text = await res.text().catch(() => "");
468
- 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)));
469
592
  }
470
593
  }
471
594
  /**
@@ -478,14 +601,14 @@ var OAuthClient = (_class = class _OAuthClient {
478
601
  const tokens = await store.get(memberKey);
479
602
  let revoked = false;
480
603
  try {
481
- if (_optionalChain([tokens, 'optionalAccess', _11 => _11.refreshToken])) {
604
+ if (_optionalChain([tokens, 'optionalAccess', _13 => _13.refreshToken])) {
482
605
  await this.revoke(tokens.refreshToken, "refresh_token");
483
606
  revoked = true;
484
- } else if (_optionalChain([tokens, 'optionalAccess', _12 => _12.accessToken])) {
607
+ } else if (_optionalChain([tokens, 'optionalAccess', _14 => _14.accessToken])) {
485
608
  await this.revoke(tokens.accessToken, "access_token");
486
609
  revoked = true;
487
610
  }
488
- } catch (e3) {
611
+ } catch (e4) {
489
612
  revoked = false;
490
613
  } finally {
491
614
  await store.delete(memberKey);
@@ -501,7 +624,9 @@ var OAuthClient = (_class = class _OAuthClient {
501
624
  body: new URLSearchParams({ token }).toString()
502
625
  });
503
626
  const text = await res.text();
504
- 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
+ }
505
630
  return parseJsonBody(text, res.status, this.endpoints.introspect);
506
631
  }
507
632
  // ---- Adapter factories --------------------------------------------------
@@ -534,7 +659,7 @@ var OAuthClient = (_class = class _OAuthClient {
534
659
  */
535
660
  memberClient(store, memberKey, opts = {}) {
536
661
  const { session, ...rest } = opts;
537
- return new (0, _chunk33AQCUGMcjs.STX)({
662
+ return new (0, _chunkR77AZ5UHcjs.STX)({
538
663
  ...rest,
539
664
  host: this.baseUrl,
540
665
  fetch: _nullishCoalesce(rest.fetch, () => ( this.fetch)),
@@ -547,7 +672,7 @@ var OAuthClient = (_class = class _OAuthClient {
547
672
  * market channels. Scope defaults to every app scope the client may hold.
548
673
  */
549
674
  appClient(scope, opts = {}) {
550
- return new (0, _chunk33AQCUGMcjs.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) });
551
676
  }
552
677
  /** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */
553
678
  _refreshesFor(store) {
@@ -589,8 +714,17 @@ var OAuthClient = (_class = class _OAuthClient {
589
714
  });
590
715
  const text = await res.text();
591
716
  if (!res.ok) {
717
+ const missing = this.oauthMissing(res.status, text, this.endpoints.token);
718
+ if (missing) throw missing;
592
719
  const err = rfcError(text);
593
- if (_optionalChain([err, 'optionalAccess', _13 => _13.error]) === "invalid_grant" && err.error_reason === "account_pending") {
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") {
594
728
  throw new STXAccountPendingException(
595
729
  err.error,
596
730
  err.error_description,
@@ -600,7 +734,7 @@ var OAuthClient = (_class = class _OAuthClient {
600
734
  err.error_reason
601
735
  );
602
736
  }
603
- if (res.status === 400 && _optionalChain([err, 'optionalAccess', _14 => _14.error]) === "invalid_grant" && body.get("grant_type") === "refresh_token") {
737
+ if (res.status === 400 && _optionalChain([err, 'optionalAccess', _17 => _17.error]) === "invalid_grant" && body.get("grant_type") === "refresh_token") {
604
738
  throw new STXGrantRevokedException(
605
739
  err.error_description ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.` : void 0
606
740
  );
@@ -619,7 +753,7 @@ var OAuthClient = (_class = class _OAuthClient {
619
753
  function parseJsonBody(text, status, endpoint) {
620
754
  try {
621
755
  return JSON.parse(text);
622
- } catch (e4) {
756
+ } catch (e5) {
623
757
  throw new STXOAuthException("invalid_response", "Response body is not JSON.", status, pathOf(endpoint));
624
758
  }
625
759
  }
@@ -643,6 +777,10 @@ function parseTokenResponse(json) {
643
777
  }
644
778
  if (typeof obj.scope === "string") set.scope = obj.scope;
645
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
+ }
646
784
  return set;
647
785
  }
648
786
  function tokenSetToStored(set) {
@@ -650,9 +788,14 @@ function tokenSetToStored(set) {
650
788
  accessToken: set.accessToken,
651
789
  refreshToken: set.refreshToken,
652
790
  expiresAt: set.expiresAt,
653
- scope: set.scope
791
+ scope: set.scope,
792
+ ...termsState(set)
654
793
  };
655
794
  }
795
+ function termsState(set) {
796
+ if (!set.termsRequired) return {};
797
+ return { termsRequired: true, ...set.termsUrl ? { termsUrl: set.termsUrl } : {} };
798
+ }
656
799
  var AppTokenProvider = (_class2 = class {
657
800
  constructor(client, scope, opts = {}) {;_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);
658
801
  this.client = client;
@@ -685,7 +828,7 @@ var AppTokenProvider = (_class2 = class {
685
828
  }
686
829
  /** The effective scope the exchange granted the current token, if minted. */
687
830
  get grantedScope() {
688
- return _optionalChain([this, 'access', _15 => _15.cached, 'optionalAccess', _16 => _16.scope]);
831
+ return _optionalChain([this, 'access', _18 => _18.cached, 'optionalAccess', _19 => _19.scope]);
689
832
  }
690
833
  async mint() {
691
834
  const set = await this.client.clientCredentials(this.scope);
@@ -737,7 +880,7 @@ var OAuthSessionAuth = (_class4 = class {
737
880
  async tokens() {
738
881
  let tokens = await this.load();
739
882
  if (!tokens) {
740
- throw new (0, _chunk33AQCUGMcjs.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.`);
741
884
  }
742
885
  if (tokens.refreshToken && tokens.expiresAt !== void 0 && tokens.expiresAt - Date.now() <= this.skewMs) {
743
886
  const refreshed = await this.refresh(tokens.refreshToken);
@@ -747,7 +890,7 @@ var OAuthSessionAuth = (_class4 = class {
747
890
  }
748
891
  /** The granted scopes of the stored tokens, canonical names. */
749
892
  async scopes() {
750
- return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async _17 => _17.scope]));
893
+ return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async _20 => _20.scope]));
751
894
  }
752
895
  async authHeaders(_request) {
753
896
  const tokens = await this.tokens();
@@ -774,6 +917,8 @@ var OAuthSessionAuth = (_class4 = class {
774
917
  * revoked grant, deletes the store entry and throws
775
918
  * `STXGrantRevokedException`. While the member's account is still being
776
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.
777
922
  * A transient failure resolves null.
778
923
  */
779
924
  refresh(refreshToken) {
@@ -782,22 +927,24 @@ var OAuthSessionAuth = (_class4 = class {
782
927
  if (existing) return existing;
783
928
  const run = async () => {
784
929
  const current = await this.load();
785
- if (_optionalChain([current, 'optionalAccess', _18 => _18.refreshToken]) && current.refreshToken !== refreshToken) return current;
930
+ if (_optionalChain([current, 'optionalAccess', _21 => _21.refreshToken]) && current.refreshToken !== refreshToken) return current;
786
931
  try {
787
932
  const set = await this.client.refreshToken(refreshToken);
788
933
  const stored = {
789
934
  accessToken: set.accessToken,
790
935
  refreshToken: _nullishCoalesce(set.refreshToken, () => ( refreshToken)),
791
936
  expiresAt: set.expiresAt,
792
- scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess', _19 => _19.scope])))
937
+ scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess', _22 => _22.scope]))),
938
+ ...termsState(set)
793
939
  };
794
940
  await this.store.set(this.memberKey, stored);
795
- await _optionalChain([this, 'access', _20 => _20.opts, 'access', _21 => _21.onRefresh, 'optionalCall', _22 => _22(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 })]);
796
943
  return stored;
797
944
  } catch (err) {
798
945
  if (err instanceof STXGrantRevokedException) {
799
946
  await this.store.delete(this.memberKey);
800
- await _optionalChain([this, 'access', _23 => _23.opts, 'access', _24 => _24.onGrantRevoked, 'optionalCall', _25 => _25(err)]);
947
+ await _optionalChain([this, 'access', _29 => _29.opts, 'access', _30 => _30.onGrantRevoked, 'optionalCall', _31 => _31(err)]);
801
948
  throw err;
802
949
  }
803
950
  if (err instanceof STXAccountPendingException) throw err;
@@ -834,7 +981,7 @@ var OAuthAppAuth = (_class5 = class {
834
981
  * just dropped.
835
982
  */
836
983
  async websocketHeaders(context) {
837
- const token = _optionalChain([context, 'optionalAccess', _26 => _26.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();
838
985
  return { "x-stx-oauth-token": token };
839
986
  }
840
987
  }, _class5);
@@ -863,7 +1010,11 @@ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPO
863
1010
  where
864
1011
  );
865
1012
  }
866
- if (error) throw callbackError(error, _nullishCoalesce(q.get("error_description"), () => ( void 0)), where);
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
+ }
867
1018
  return { code, pending: entry };
868
1019
  }
869
1020
  function callbackParams(input) {
@@ -880,27 +1031,39 @@ function callbackParams(input) {
880
1031
  function pathOf(endpoint) {
881
1032
  try {
882
1033
  return /^https?:\/\//i.test(endpoint) ? new URL(endpoint).pathname : endpoint;
883
- } catch (e5) {
1034
+ } catch (e6) {
884
1035
  return endpoint;
885
1036
  }
886
1037
  }
887
1038
 
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}`;
1049
+ }
1050
+
888
1051
  // src/oauth/connect.ts
889
1052
  function createConnect(opts) {
890
- if (!opts.issuer) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("issuer is required.");
891
- if (!opts.clientId || !opts.clientSecret) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("clientId and clientSecret are required.");
892
- if (!opts.redirectUri) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required.");
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.");
893
1056
  const issuer = opts.issuer.replace(/\/+$/, "");
894
1057
  const fetchImpl = _nullishCoalesce(opts.fetch, () => ( globalThis.fetch));
895
1058
  if (typeof fetchImpl !== "function") {
896
- throw new (0, _chunk33AQCUGMcjs.STXConfigException)("No fetch implementation available. Use Node 18+, or pass { fetch }.");
1059
+ throw new (0, _chunkR77AZ5UHcjs.STXConfigException)("No fetch implementation available. Use Node 18+, or pass { fetch }.");
897
1060
  }
898
1061
  const skew = _nullishCoalesce(opts.clockSkewSeconds, () => ( 60));
899
1062
  let config;
900
1063
  let client;
901
1064
  let keys;
902
1065
  const configuration = () => {
903
- config ??= fetchJson(fetchImpl, joinUrl(issuer, "/.well-known/openid-configuration")).then((doc) => {
1066
+ config ??= fetchJson(fetchImpl, joinUrl(issuer, "/.well-known/openid-configuration"), "connect").then((doc) => {
904
1067
  const c = doc;
905
1068
  if (typeof c.issuer !== "string" || typeof c.authorization_endpoint !== "string" || typeof c.token_endpoint !== "string" || typeof c.jwks_uri !== "string") {
906
1069
  throw new STXOAuthException(
@@ -988,7 +1151,7 @@ function createConnect(opts) {
988
1151
  if (!error && (!code || !state)) {
989
1152
  throw new STXOAuthException("invalid_request", "The callback carries no code or no state.", 400, where);
990
1153
  }
991
- if (!state || !_optionalChain([saved, 'optionalAccess', _27 => _27.state]) || !constantTimeEqual(state, saved.state)) {
1154
+ if (!state || !_optionalChain([saved, 'optionalAccess', _33 => _33.state]) || !constantTimeEqual(state, saved.state)) {
992
1155
  throw new STXOAuthException("invalid_state", "The state does not match this sign-in; start again.", 400, where);
993
1156
  }
994
1157
  if (error) throw callbackError(error, _nullishCoalesce(q.get("error_description"), () => ( void 0)), where);
@@ -1032,10 +1195,18 @@ function createConnect(opts) {
1032
1195
  headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}` }
1033
1196
  });
1034
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
+ }
1035
1206
  let body;
1036
1207
  try {
1037
1208
  body = JSON.parse(text);
1038
- } catch (e6) {
1209
+ } catch (e7) {
1039
1210
  body = void 0;
1040
1211
  }
1041
1212
  const claims = body && typeof body === "object" ? body : {};
@@ -1070,7 +1241,7 @@ function createConnect(opts) {
1070
1241
  function pathOf2(url) {
1071
1242
  try {
1072
1243
  return new URL(url).pathname;
1073
- } catch (e7) {
1244
+ } catch (e8) {
1074
1245
  return url;
1075
1246
  }
1076
1247
  }
@@ -1088,15 +1259,23 @@ function withOpenId(scopes) {
1088
1259
  set.delete("openid");
1089
1260
  return formatScopes(["openid", ...set]);
1090
1261
  }
1091
- async function fetchJson(fetchImpl, url) {
1262
+ async function fetchJson(fetchImpl, url, feature) {
1092
1263
  const res = await fetchImpl(url, { method: "GET", headers: { Accept: "application/json" } });
1093
1264
  const text = await res.text();
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
+ }
1094
1273
  if (!res.ok) {
1095
1274
  throw new STXOAuthException("invalid_configuration", `GET ${url} returned ${res.status}.`, res.status, url);
1096
1275
  }
1097
1276
  try {
1098
1277
  return JSON.parse(text);
1099
- } catch (e8) {
1278
+ } catch (e9) {
1100
1279
  throw new STXOAuthException("invalid_configuration", `GET ${url} did not return JSON.`, res.status, url);
1101
1280
  }
1102
1281
  }
@@ -1155,7 +1334,7 @@ async function verifyIdToken(token, expected) {
1155
1334
  function decodeJson(segment) {
1156
1335
  try {
1157
1336
  return JSON.parse(new TextDecoder().decode(base64urlDecode(segment)));
1158
- } catch (e9) {
1337
+ } catch (e10) {
1159
1338
  return void 0;
1160
1339
  }
1161
1340
  }
@@ -1173,53 +1352,6 @@ function constantTimeEqual(a, b) {
1173
1352
  return diff === 0;
1174
1353
  }
1175
1354
 
1176
- // src/oauth/metadata.ts
1177
- async function discoverMetadata(baseUrl, opts = {}) {
1178
- const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);
1179
- const meta = doc;
1180
- if (typeof meta.issuer !== "string" || typeof meta.authorization_endpoint !== "string" || typeof meta.token_endpoint !== "string") {
1181
- throw httpError2(
1182
- 200,
1183
- JSON.stringify(doc),
1184
- WELL_KNOWN.authorizationServer + " (missing issuer/authorization_endpoint/token_endpoint)"
1185
- );
1186
- }
1187
- return meta;
1188
- }
1189
- async function discoverProtectedResource(baseUrl, opts = {}) {
1190
- const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.protectedResource, opts);
1191
- const meta = doc;
1192
- if (typeof meta.resource !== "string" || !Array.isArray(meta.authorization_servers)) {
1193
- throw httpError2(
1194
- 200,
1195
- JSON.stringify(doc),
1196
- WELL_KNOWN.protectedResource + " (missing resource/authorization_servers)"
1197
- );
1198
- }
1199
- return meta;
1200
- }
1201
- async function fetchWellKnown(baseUrl, path, opts) {
1202
- const cfg = resolveOAuthConfig({ baseUrl, fetch: opts.fetch });
1203
- const res = await cfg.fetch(joinUrl(cfg.baseUrl, path), {
1204
- method: "GET",
1205
- headers: { Accept: "application/json" }
1206
- });
1207
- const text = await res.text();
1208
- if (!res.ok) throw httpError2(res.status, text, path);
1209
- try {
1210
- return JSON.parse(text);
1211
- } catch (e10) {
1212
- throw httpError2(res.status, text, path);
1213
- }
1214
- }
1215
- function httpError2(status, text, path) {
1216
- return new (0, _chunk33AQCUGMcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
1217
- statusCode: status,
1218
- body: text,
1219
- path
1220
- });
1221
- }
1222
-
1223
1355
  // src/oauth/tokenStore.ts
1224
1356
  var MemoryTokenStore = (_class6 = class {constructor() { _class6.prototype.__init8.call(this); }
1225
1357
  __init8() {this.map = /* @__PURE__ */ new Map()}
@@ -1300,5 +1432,10 @@ var MemoryPendingAuthorizationStore = (_class7 = class {constructor() { _class7.
1300
1432
 
1301
1433
 
1302
1434
 
1303
- 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 = _chunk33AQCUGMcjs.STXAuthenticationException; exports.STXForbiddenException = _chunk33AQCUGMcjs.STXForbiddenException; exports.STXGrantRevokedException = STXGrantRevokedException; exports.STXInsufficientScopeException = _chunk33AQCUGMcjs.STXInsufficientScopeException; exports.STXInvalidTokenException = _chunk33AQCUGMcjs.STXInvalidTokenException; exports.STXOAuthException = STXOAuthException; 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.tokenSetToStored = tokenSetToStored;
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;
1304
1441
  //# sourceMappingURL=oauth.cjs.map