@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.js CHANGED
@@ -4,10 +4,14 @@ import {
4
4
  STXAuthenticationException,
5
5
  STXConfigException,
6
6
  STXForbiddenException,
7
+ STXIPNotAllowedException,
7
8
  STXInsufficientScopeException,
8
9
  STXInvalidTokenException,
9
- baseUrlFor
10
- } from "./chunk-SIYERAKK.js";
10
+ STXNotAvailableException,
11
+ STXTermsRequiredException,
12
+ baseUrlFor,
13
+ isEdgeBlock
14
+ } from "./chunk-46XK6VDD.js";
11
15
 
12
16
  // src/oauth/endpoints.ts
13
17
  var DEFAULT_ENDPOINTS = {
@@ -45,7 +49,18 @@ var STXOAuthException = class extends STXAuthenticationException {
45
49
  endpoint;
46
50
  /** Seconds to wait when the endpoint answered 429 with Retry-After. */
47
51
  retryAfter;
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
+ errorReason;
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
+ requestedScope;
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 STXAuthenticationException {
54
69
  this.errorDescription = errorDescription;
55
70
  this.endpoint = endpoint;
56
71
  this.retryAfter = retryAfter;
72
+ this.errorReason = errorReason;
57
73
  }
58
74
  };
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
+ }
59
85
  var STXGrantRevokedException = class extends 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 || isEdgeBlock(res.status, text)) {
124
+ throw new 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 {
135
+ throw httpError(res.status, text, path);
136
+ }
137
+ }
138
+ function httpError(status, text, path) {
139
+ return new 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 = "";
@@ -107,11 +188,11 @@ async function registerClient(request, opts = {}) {
107
188
  try {
108
189
  doc = JSON.parse(text);
109
190
  } catch {
110
- throw httpError(res.status, text, path);
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,13 +216,14 @@ 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
222
  } catch {
140
223
  return null;
141
224
  }
142
225
  }
143
- function httpError(status, text, path) {
226
+ function httpError2(status, text, path) {
144
227
  return new STXAPIException(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
145
228
  statusCode: status,
146
229
  body: text,
@@ -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 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 _OAuthClient {
216
297
  redirectUri;
217
298
  scope;
218
299
  endpoints;
300
+ /** The discovery document this client was built from, if any. */
301
+ metadata;
219
302
  fetch;
220
303
  /**
221
304
  * In-flight refreshes per token store and member, shared by every session
@@ -234,6 +317,7 @@ var OAuthClient = 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: opts.endpoints?.authorize ?? DEFAULT_ENDPOINTS.authorize,
239
323
  token: opts.endpoints?.token ?? DEFAULT_ENDPOINTS.token,
@@ -249,6 +333,7 @@ var OAuthClient = class _OAuthClient {
249
333
  static fromMetadata(metadata, opts) {
250
334
  return new _OAuthClient({
251
335
  ...opts,
336
+ metadata,
252
337
  baseUrl: opts.baseUrl ?? metadata.issuer,
253
338
  endpoints: {
254
339
  authorize: metadata.authorization_endpoint,
@@ -258,6 +343,27 @@ var OAuthClient = 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: 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 _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
+ ...params.extraParams ?? {}
390
+ }
281
391
  });
282
392
  return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };
283
393
  }
@@ -305,7 +415,7 @@ var OAuthClient = 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 _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 this.unofferedScope(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 = this.metadata?.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 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 && !isEdgeBlock(status, text)) return void 0;
456
+ return new 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
@@ -383,6 +524,9 @@ var OAuthClient = 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(
@@ -430,7 +574,10 @@ var OAuthClient = 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 _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 this.oauthMissing(res.status, text, this.endpoints.revoke) ?? this.oauthError(res.status, text, this.endpoints.revoke);
445
592
  }
446
593
  }
447
594
  /**
@@ -477,7 +624,9 @@ var OAuthClient = 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 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 --------------------------------------------------
@@ -535,10 +684,13 @@ var OAuthClient = 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,7 +714,26 @@ var OAuthClient = 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);
720
+ if (err?.error === "invalid_scope") {
721
+ const unoffered = this.unofferedScope(
722
+ body.get("scope") ?? void 0,
723
+ this.oauthError(res.status, text, this.endpoints.token)
724
+ );
725
+ if (unoffered) throw unoffered;
726
+ }
727
+ if (err?.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
+ }
566
737
  if (res.status === 400 && err?.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
@@ -575,7 +746,7 @@ var OAuthClient = 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
  };
@@ -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 = class {
619
800
  constructor(client, scope, opts = {}) {
620
801
  this.client = client;
@@ -734,7 +915,11 @@ var OAuthSessionAuth = 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);
@@ -749,10 +934,12 @@ var OAuthSessionAuth = class {
749
934
  accessToken: set.accessToken,
750
935
  refreshToken: set.refreshToken ?? refreshToken,
751
936
  expiresAt: set.expiresAt,
752
- scope: set.scope ?? current?.scope
937
+ scope: set.scope ?? current?.scope,
938
+ ...termsState(set)
753
939
  };
754
940
  await this.store.set(this.memberKey, stored);
755
941
  await this.opts.onRefresh?.(stored);
942
+ if (stored.termsUrl) await this.opts.onTermsRequired?.({ termsUrl: stored.termsUrl });
756
943
  return stored;
757
944
  } catch (err) {
758
945
  if (err instanceof STXGrantRevokedException) {
@@ -760,6 +947,7 @@ var OAuthSessionAuth = class {
760
947
  await this.opts.onGrantRevoked?.(err);
761
948
  throw err;
762
949
  }
950
+ if (err instanceof STXAccountPendingException) throw err;
763
951
  return null;
764
952
  }
765
953
  };
@@ -797,6 +985,9 @@ var OAuthAppAuth = class {
797
985
  return { "x-stx-oauth-token": token };
798
986
  }
799
987
  };
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, 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, 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) {
@@ -841,51 +1036,320 @@ function pathOf(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 STXConfigException("issuer is required.");
1054
+ if (!opts.clientId || !opts.clientSecret) throw new STXConfigException("clientId and clientSecret are required.");
1055
+ if (!opts.redirectUri) throw new STXConfigException("redirectUri is required.");
1056
+ const issuer = opts.issuer.replace(/\/+$/, "");
1057
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
1058
+ if (typeof fetchImpl !== "function") {
1059
+ throw new STXConfigException("No fetch implementation available. Use Node 18+, or pass { fetch }.");
1060
+ }
1061
+ const skew = 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 = 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(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 || !saved?.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, 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: 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 || isEdgeBlock(res.status, text)) {
1199
+ throw new 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 {
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 {
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 || isEdgeBlock(res.status, text))) {
1266
+ throw new 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
1278
  } catch {
880
- throw httpError2(res.status, text, path);
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 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 = 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 {
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
@@ -939,17 +1403,24 @@ export {
939
1403
  OAuthBearerAuth,
940
1404
  OAuthClient,
941
1405
  OAuthSessionAuth,
1406
+ STXAccessDeniedException,
1407
+ STXAccountPendingException,
942
1408
  STXAuthenticationException,
943
1409
  STXForbiddenException,
944
1410
  STXGrantRevokedException,
1411
+ STXIPNotAllowedException,
945
1412
  STXInsufficientScopeException,
946
1413
  STXInvalidTokenException,
1414
+ STXNotAvailableException,
947
1415
  STXOAuthException,
1416
+ STXTermsNotAcceptedException,
1417
+ STXTermsRequiredException,
948
1418
  Scopes,
949
1419
  WELL_KNOWN,
950
1420
  base64url,
951
1421
  canonicalScope,
952
1422
  codeChallengeS256,
1423
+ createConnect,
953
1424
  createPkce,
954
1425
  discoverMetadata,
955
1426
  discoverProtectedResource,
@@ -964,6 +1435,7 @@ export {
964
1435
  readCallback,
965
1436
  registerClient,
966
1437
  rfcError,
1438
+ termsUrlWithReturn,
967
1439
  tokenSetToStored
968
1440
  };
969
1441
  //# sourceMappingURL=oauth.js.map