@glideidentity/glide-be-node-magical-auth 3.2.0 → 3.2.1

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/index.cjs CHANGED
@@ -29,6 +29,7 @@ __export(index_exports, {
29
29
  CarrierAppUnavailableError: () => CarrierAppUnavailableError,
30
30
  CarrierNotEligibleError: () => CarrierNotEligibleError,
31
31
  CarrierRejectedError: () => CarrierRejectedError,
32
+ CarrierTemporarilyUnavailableError: () => CarrierTemporarilyUnavailableError,
32
33
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
33
34
  DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
34
35
  DesktopWaitError: () => DesktopWaitError,
@@ -46,6 +47,7 @@ __export(index_exports, {
46
47
  RateLimitError: () => RateLimitError,
47
48
  SENSITIVE_KEYS: () => SENSITIVE_KEYS,
48
49
  ServiceUnavailableError: () => ServiceUnavailableError,
50
+ SessionMetadataParentStrategy: () => SessionMetadataParentStrategy,
49
51
  SessionNotEligibleError: () => SessionNotEligibleError,
50
52
  SessionNotFoundError: () => SessionNotFoundError,
51
53
  SessionStatus: () => SessionStatus,
@@ -57,6 +59,7 @@ __export(index_exports, {
57
59
  ValidationError: () => ValidationError,
58
60
  VerificationRecordError: () => VerificationRecordError,
59
61
  VerificationRecordErrorCode: () => VerificationRecordErrorCode,
62
+ actionHash: () => actionHash,
60
63
  assertValidFeCode: () => assertValidFeCode,
61
64
  buildClearBindingCookieHeader: () => buildClearBindingCookieHeader,
62
65
  buildSetBindingCookieHeader: () => buildSetBindingCookieHeader,
@@ -77,7 +80,7 @@ module.exports = __toCommonJS(index_exports);
77
80
  var import_node_module = require("module");
78
81
 
79
82
  // src/client.ts
80
- var import_node_crypto4 = require("crypto");
83
+ var import_node_crypto5 = require("crypto");
81
84
 
82
85
  // src/internal/http.ts
83
86
  var defaultHttpClient = {
@@ -113,6 +116,7 @@ var ErrorCode = {
113
116
  CARRIER_NOT_ELIGIBLE: "CARRIER_NOT_ELIGIBLE",
114
117
  CARRIER_REJECTED: "CARRIER_REJECTED",
115
118
  CARRIER_APP_UNAVAILABLE: "CARRIER_APP_UNAVAILABLE",
119
+ CARRIER_TEMPORARILY_UNAVAILABLE: "CARRIER_TEMPORARILY_UNAVAILABLE",
116
120
  UNSUPPORTED_PLATFORM: "UNSUPPORTED_PLATFORM",
117
121
  PHONE_NUMBER_MISMATCH: "PHONE_NUMBER_MISMATCH",
118
122
  INVALID_CREDENTIAL_FORMAT: "INVALID_CREDENTIAL_FORMAT",
@@ -229,6 +233,14 @@ var CarrierAppUnavailableError = class extends MagicalAuthError {
229
233
  this.name = "CarrierAppUnavailableError";
230
234
  }
231
235
  };
236
+ var CarrierTemporarilyUnavailableError = class extends MagicalAuthError {
237
+ retryAfter;
238
+ constructor(message, retryAfter, requestId, details) {
239
+ super(message, "CARRIER_TEMPORARILY_UNAVAILABLE", 422, requestId, details);
240
+ this.name = "CarrierTemporarilyUnavailableError";
241
+ this.retryAfter = retryAfter;
242
+ }
243
+ };
232
244
  var UnsupportedPlatformError = class extends MagicalAuthError {
233
245
  constructor(message = "Platform not supported", requestId) {
234
246
  super(message, "UNSUPPORTED_PLATFORM", 422, requestId);
@@ -328,7 +340,8 @@ var VerificationRecordErrorCode = {
328
340
  ORIGIN_MISMATCH: "ORIGIN_MISMATCH",
329
341
  UNSUPPORTED_VERSION: "UNSUPPORTED_VERSION",
330
342
  REVOKED_KEY: "REVOKED_KEY",
331
- RECORD_UNAVAILABLE: "RECORD_UNAVAILABLE"
343
+ RECORD_UNAVAILABLE: "RECORD_UNAVAILABLE",
344
+ STEP_UP_REJECTED: "STEP_UP_REJECTED"
332
345
  };
333
346
  var VerificationRecordError = class extends MagicalAuthError {
334
347
  constructor(code, message) {
@@ -363,6 +376,8 @@ function createErrorFromResponse(response, headers) {
363
376
  });
364
377
  }
365
378
  function createTypedError(code, message, request_id, details, status, headers) {
379
+ const rawRetry = details?.retry_after_seconds;
380
+ const detailRetry = typeof rawRetry === "number" && Number.isFinite(rawRetry) && rawRetry >= 0 && Number.isInteger(rawRetry) ? rawRetry : void 0;
366
381
  switch (code) {
367
382
  case "BAD_REQUEST":
368
383
  return new BadRequestError(message, request_id);
@@ -391,6 +406,13 @@ function createTypedError(code, message, request_id, details, status, headers) {
391
406
  request_id,
392
407
  details
393
408
  );
409
+ case "CARRIER_TEMPORARILY_UNAVAILABLE":
410
+ return new CarrierTemporarilyUnavailableError(
411
+ message,
412
+ parseRetryAfter(headers) ?? detailRetry,
413
+ request_id,
414
+ details
415
+ );
394
416
  case "UNSUPPORTED_PLATFORM":
395
417
  return new UnsupportedPlatformError(message, request_id);
396
418
  case "INVALID_CREDENTIAL_FORMAT":
@@ -413,12 +435,15 @@ function createTypedError(code, message, request_id, details, status, headers) {
413
435
  case "MISSING_BINDING_COOKIE":
414
436
  return new MissingBindingCookieError(message, request_id);
415
437
  case "RATE_LIMIT_EXCEEDED":
416
- return new RateLimitError(message, parseRetryAfter(headers), request_id);
438
+ return new RateLimitError(message, parseRetryAfter(headers) ?? detailRetry, request_id);
417
439
  case "INTERNAL_SERVER_ERROR":
418
440
  return new InternalServerError(message, request_id);
419
441
  case "SERVICE_UNAVAILABLE":
420
442
  return new ServiceUnavailableError(message, request_id);
421
443
  default:
444
+ if (status === 429) {
445
+ return new RateLimitError(message, parseRetryAfter(headers) ?? detailRetry, request_id);
446
+ }
422
447
  return new MagicalAuthError(
423
448
  message,
424
449
  code,
@@ -455,7 +480,9 @@ var TokenManager = class {
455
480
  * in progress, subsequent calls will await the same promise.
456
481
  *
457
482
  * @returns A valid access token
458
- * @throws {UnauthorizedError} If token fetch fails
483
+ * @throws {RateLimitError} If the token endpoint returns 429 (includes Retry-After when present)
484
+ * @throws {ServiceUnavailableError} If the token endpoint returns 5xx or temporarily_unavailable
485
+ * @throws {UnauthorizedError} For other token fetch failures (e.g. 401)
459
486
  */
460
487
  async getToken() {
461
488
  if (this.token && Date.now() < this.expiresAt) {
@@ -493,8 +520,10 @@ var TokenManager = class {
493
520
  });
494
521
  if (!response.ok) {
495
522
  let errorMessage2 = "Token request failed";
523
+ let oauthError;
496
524
  try {
497
525
  const errorBody = await response.json();
526
+ oauthError = errorBody.error;
498
527
  if (errorBody.error_description) {
499
528
  errorMessage2 = errorBody.error_description;
500
529
  } else if (errorBody.error) {
@@ -502,6 +531,15 @@ var TokenManager = class {
502
531
  }
503
532
  } catch {
504
533
  }
534
+ if (response.status === 429) {
535
+ throw new RateLimitError(errorMessage2, parseRetryAfter(response.headers));
536
+ }
537
+ if (response.status >= 500 || oauthError === "temporarily_unavailable") {
538
+ throw new ServiceUnavailableError(errorMessage2);
539
+ }
540
+ if (response.status === 401 || oauthError === "invalid_client") {
541
+ throw new UnauthorizedError(errorMessage2);
542
+ }
505
543
  throw new UnauthorizedError(errorMessage2);
506
544
  }
507
545
  const data = await response.json();
@@ -663,12 +701,14 @@ function validateCookieAttr(name, value) {
663
701
  throw new Error("Invalid cookie path: must start with '/'");
664
702
  }
665
703
  }
666
- function getCompletionPageHtml(completeEndpoint) {
704
+ function getCompletionPageHtml(completeEndpoint, options) {
667
705
  if (!completeEndpoint.startsWith("/") || completeEndpoint.startsWith("//")) {
668
706
  throw new Error(
669
707
  'completeEndpoint must be a relative path starting with "/" (e.g., "/api/glide/complete"). Cross-origin and protocol-relative endpoints (e.g., "//evil.com/...") are not supported because the page relies on credentials: "include" for cookie-based device binding, which requires same-origin requests.'
670
708
  );
671
709
  }
710
+ const serializedCompleteEndpoint = JSON.stringify(completeEndpoint).replace(/</g, "\\u003c");
711
+ const beacon = options?.beacon === true;
672
712
  return `<!DOCTYPE html>
673
713
  <html lang="en">
674
714
  <head>
@@ -736,20 +776,157 @@ function getCompletionPageHtml(completeEndpoint) {
736
776
  <div class="badge">Action required</div>
737
777
  </div>
738
778
  <script>
739
- (async function() {
779
+ ${beacon ? `(async function() {
740
780
  var fragment = new URLSearchParams(window.location.hash.substring(1));
741
781
  var aggCode = fragment.get('agg_code');
742
782
  var sessionKey = fragment.get('session_key');
783
+ var closeSent = false;
784
+ var survivedSent = false;
785
+ var closeTrigger = '';
786
+ var hiddenAt = 0;
787
+
788
+ function pageFields() {
789
+ var o = { has_agg_code: !!aggCode, has_session_key: !!sessionKey };
790
+ if (sessionKey && /^[A-Za-z0-9_-]{1,64}$/.test(sessionKey)) o.session_key = sessionKey;
791
+ return o;
792
+ }
793
+
794
+ function sendPageBeacon(event, extra) {
795
+ try {
796
+ var payload = Object.assign({ event: event }, pageFields(), extra || {});
797
+ var url = window.location.pathname;
798
+ var body = JSON.stringify(payload);
799
+ try {
800
+ if (navigator.sendBeacon && navigator.sendBeacon(url, new Blob([body], { type: 'application/json' }))) return;
801
+ } catch (e) {}
802
+ fetch(url, {
803
+ method: 'POST',
804
+ headers: { 'Content-Type': 'application/json' },
805
+ body: body,
806
+ keepalive: true,
807
+ credentials: 'same-origin'
808
+ }).catch(function() {});
809
+ } catch (e) {}
810
+ }
811
+
812
+ function showCloseHint() {
813
+ document.getElementById('hint').textContent = 'You may close this tab.';
814
+ document.getElementById('hint').classList.remove('hidden');
815
+ }
816
+
817
+ sendPageBeacon('page_start');
743
818
 
744
819
  window.history.replaceState(null, '', window.location.pathname + window.location.search);
745
820
 
746
821
  if (!aggCode || !sessionKey) {
822
+ sendPageBeacon('invalid_link');
747
823
  showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');
748
824
  return;
749
825
  }
750
826
 
751
827
  try {
752
- var res = await fetch(${JSON.stringify(completeEndpoint)}, {
828
+ var res = await fetch(${serializedCompleteEndpoint}, {
829
+ method: 'POST',
830
+ credentials: 'include',
831
+ headers: { 'Content-Type': 'application/json' },
832
+ body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })
833
+ });
834
+
835
+ var outcome = { ok: !!res.ok, status: res.status };
836
+ if (res.ok) {
837
+ sendPageBeacon('post_outcome', outcome);
838
+ var signalKey = 'glide_signal_' + sessionKey;
839
+ var sigmetaKey = 'glide_sigmeta_' + sessionKey;
840
+ var signalStored = false;
841
+ try {
842
+ localStorage.setItem(signalKey, sessionKey);
843
+ signalStored = true;
844
+ localStorage.setItem(sigmetaKey, String(Date.now()));
845
+ } catch(e) {}
846
+ if (signalStored) {
847
+ setTimeout(function() {
848
+ try { localStorage.removeItem(signalKey); localStorage.removeItem(sigmetaKey); } catch(e) {}
849
+ }, 600000);
850
+ }
851
+ tryClose();
852
+ } else {
853
+ var code = '';
854
+ try { var data = await res.json(); var raw = data && (data.code || data.error); if (typeof raw === 'string' && /^[A-Za-z0-9_.-]{1,64}$/.test(raw)) { code = raw; outcome.code = raw; } } catch (_) {}
855
+ sendPageBeacon('post_outcome', outcome);
856
+ var err = friendlyError(code);
857
+ showError(err.title, err.points, err.illust);
858
+ }
859
+ } catch (e) {
860
+ sendPageBeacon('post_outcome', { ok: false, status: 0 });
861
+ showError('Connection issue', ['We could not reach the server.', 'Check your internet connection and try again.'], 'wifi');
862
+ }
863
+
864
+ function friendlyError(code) {
865
+ switch (code) {
866
+ case 'MISSING_BINDING_COOKIE':
867
+ case 'BROWSER_MISMATCH':
868
+ return { title: 'Open in your default browser', points: ['Carrier verification must be started from your default browser.', 'The redirect will always open in your default browser to complete.'], illust: 'browser' };
869
+ default:
870
+ return { title: 'Verification could not be completed', points: ['Something went wrong during verification.', 'Please go back and try again.'], illust: 'retry' };
871
+ }
872
+ }
873
+
874
+ function reportClose(trigger) {
875
+ if (closeSent) return;
876
+ closeSent = true;
877
+ closeTrigger = trigger;
878
+ sendPageBeacon('close', {
879
+ close_outcome: (trigger === 'timeout' && document.visibilityState === 'visible') ? 'failed' : 'unknown',
880
+ trigger: trigger,
881
+ visibility_state: document.visibilityState
882
+ });
883
+ }
884
+
885
+ function reportTabSurvived() {
886
+ if (!closeSent || survivedSent) return;
887
+ survivedSent = true;
888
+ var hiddenMs = hiddenAt ? Date.now() - hiddenAt : 0;
889
+ if (hiddenMs < 0) hiddenMs = 0;
890
+ sendPageBeacon('tab_survived', { hidden_ms: hiddenMs, trigger: closeTrigger });
891
+ }
892
+
893
+ function tryClose() {
894
+ document.querySelector('.spinner').classList.add('hidden');
895
+ if ((document.hidden || document.visibilityState === 'hidden') && !hiddenAt) hiddenAt = Date.now();
896
+ document.addEventListener('visibilitychange', function() {
897
+ if (document.visibilityState === 'visible') {
898
+ showCloseHint();
899
+ reportTabSurvived();
900
+ hiddenAt = 0;
901
+ return;
902
+ }
903
+ if (!hiddenAt) hiddenAt = Date.now();
904
+ reportClose('visibilitychange');
905
+ });
906
+ window.addEventListener('pagehide', function() {
907
+ if (!hiddenAt) hiddenAt = Date.now();
908
+ reportClose('pagehide');
909
+ });
910
+ window.close();
911
+ try { window.open('', '_self').close(); } catch(e) {}
912
+ setTimeout(function() {
913
+ reportClose('timeout');
914
+ if (document.visibilityState === 'visible') showCloseHint();
915
+ }, 300);
916
+ }` : `(async function() {
917
+ var fragment = new URLSearchParams(window.location.hash.substring(1));
918
+ var aggCode = fragment.get('agg_code');
919
+ var sessionKey = fragment.get('session_key');
920
+
921
+ window.history.replaceState(null, '', window.location.pathname + window.location.search);
922
+
923
+ if (!aggCode || !sessionKey) {
924
+ showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');
925
+ return;
926
+ }
927
+
928
+ try {
929
+ var res = await fetch(${serializedCompleteEndpoint}, {
753
930
  method: 'POST',
754
931
  credentials: 'include',
755
932
  headers: { 'Content-Type': 'application/json' },
@@ -799,7 +976,7 @@ function getCompletionPageHtml(completeEndpoint) {
799
976
  document.getElementById('hint').textContent = 'You may close this tab.';
800
977
  document.getElementById('hint').classList.remove('hidden');
801
978
  }, 300);
802
- }
979
+ }`}
803
980
 
804
981
  function showError(title, points, illust) {
805
982
  document.getElementById('loading').classList.add('hidden');
@@ -834,8 +1011,11 @@ var AuthenticationStrategy = {
834
1011
  TS43: "ts43",
835
1012
  LINK: "link",
836
1013
  DESKTOP: "desktop",
1014
+ PASSKEY: "passkey",
1015
+ CALL: "call",
837
1016
  NONE: ""
838
1017
  };
1018
+ var SessionMetadataParentStrategy = "parent_strategy";
839
1019
  var SessionStatus = {
840
1020
  PENDING: "pending",
841
1021
  SCANNED: "scanned",
@@ -893,6 +1073,18 @@ function validateGetPhoneNumberRequest(request) {
893
1073
  throw new ValidationError("Request validation failed", errors);
894
1074
  }
895
1075
  }
1076
+ function validateDeletePasskeysRequest(request) {
1077
+ const errors = {};
1078
+ if (!/^\+[1-9]\d{6,14}$/.test(request?.phone_number ?? "")) {
1079
+ errors.phone_number = "phone_number must be E.164";
1080
+ }
1081
+ if (!request?.origin) {
1082
+ errors.origin = "origin is required";
1083
+ }
1084
+ if (Object.keys(errors).length > 0) {
1085
+ throw new ValidationError("Request validation failed", errors);
1086
+ }
1087
+ }
896
1088
  function validateSessionId(sessionId) {
897
1089
  if (!sessionId) {
898
1090
  throw new ValidationError("Request validation failed", {
@@ -1217,10 +1409,26 @@ function checkClaimShape(obj, iat, exp) {
1217
1409
  if (!signOffs) {
1218
1410
  throw malformed("sign_offs must be an array of well-formed entries");
1219
1411
  }
1412
+ const factors = readFactors(obj);
1413
+ if (!factors) {
1414
+ throw malformed("factors must be an array of strings");
1415
+ }
1416
+ if (factors.length === 1 && factors[0] === "passkey") {
1417
+ if (signOffs.some((s) => s.role === CARRIER_ROLE)) {
1418
+ throw malformed("a passkey-only record must have no carrier sign-off");
1419
+ }
1420
+ return { signOffs, factors };
1421
+ }
1220
1422
  if (!oneCarrierSignOff(signOffs)) {
1221
1423
  throw malformed("sign_offs must have exactly one carrier:<id> carrier entry");
1222
1424
  }
1223
- return signOffs;
1425
+ return { signOffs, factors };
1426
+ }
1427
+ function readFactors(obj) {
1428
+ const raw = member(obj, "factors");
1429
+ if (raw === void 0) return ["carrier"];
1430
+ if (!Array.isArray(raw) || !raw.every((f) => typeof f === "string")) return null;
1431
+ return raw;
1224
1432
  }
1225
1433
  function readSignOffs(raw) {
1226
1434
  if (!Array.isArray(raw)) return null;
@@ -1278,7 +1486,7 @@ function checkRecordClaims(payload, want) {
1278
1486
  throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_AUDIENCE, "aud does not match the expected audience");
1279
1487
  }
1280
1488
  const { iat, exp } = checkRecordTimes(obj, want);
1281
- const signOffs = checkClaimShape(obj, iat, exp);
1489
+ const { signOffs, factors } = checkClaimShape(obj, iat, exp);
1282
1490
  const verified = member(obj, "verified");
1283
1491
  const r = new MemberReader(obj);
1284
1492
  const claims = {
@@ -1290,6 +1498,7 @@ function checkRecordClaims(payload, want) {
1290
1498
  exp,
1291
1499
  verified,
1292
1500
  sign_offs: signOffs,
1501
+ factors,
1293
1502
  jti: r.str("jti") ?? "",
1294
1503
  nonce: r.str("nonce") ?? "",
1295
1504
  use_case: r.str("use_case") ?? "",
@@ -1298,10 +1507,12 @@ function checkRecordClaims(payload, want) {
1298
1507
  biometric_verification: r.str("biometric_verification") ?? ""
1299
1508
  };
1300
1509
  assignDefined(claims, "strategy", r.str("strategy"));
1510
+ assignDefined(claims, "action_hash", r.str("action_hash"));
1301
1511
  assignDefined(claims, "phone_number_details", readPhoneNumberDetails(r));
1302
1512
  assignDefined(claims, "carrier", readCarrier(r));
1303
1513
  assignDefined(claims, "sim_swap", readSwap(r, "sim_swap"));
1304
1514
  assignDefined(claims, "device_swap", readSwap(r, "device_swap"));
1515
+ assignDefined(claims, "live_call", readLiveCall(r, "live_call"));
1305
1516
  if (!r.ok) {
1306
1517
  throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "claims have the wrong JSON types");
1307
1518
  }
@@ -1371,6 +1582,19 @@ function readPhoneNumberDetails(r) {
1371
1582
  r.ok = r.ok && s.ok;
1372
1583
  return d;
1373
1584
  }
1585
+ function readLiveCall(r, name) {
1586
+ const obj = r.object(name);
1587
+ if (!obj) return void 0;
1588
+ const s = new MemberReader(obj);
1589
+ const status = s.str("status");
1590
+ const info = {
1591
+ status: status ?? ""
1592
+ };
1593
+ assignDefined(info, "carrier_name", s.str("carrier_name"));
1594
+ assignDefined(info, "reason", s.str("reason"));
1595
+ r.ok = r.ok && s.ok && !!status;
1596
+ return info;
1597
+ }
1374
1598
  function readSwap(r, name) {
1375
1599
  const obj = r.object(name);
1376
1600
  if (!obj) return void 0;
@@ -1489,6 +1713,13 @@ function verifyRecordSignature(record, key) {
1489
1713
  }
1490
1714
  }
1491
1715
 
1716
+ // src/verification-record/action-hash.ts
1717
+ var import_node_crypto4 = require("crypto");
1718
+ function actionHash(action) {
1719
+ const canonical = Object.keys(action).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))).map((k) => `${k}=${action[k]}`).join("|");
1720
+ return (0, import_node_crypto4.createHash)("sha256").update(canonical).digest("base64url");
1721
+ }
1722
+
1492
1723
  // src/client.ts
1493
1724
  var MagicalAuthClient = class {
1494
1725
  config;
@@ -1544,9 +1775,10 @@ var MagicalAuthClient = class {
1544
1775
  /**
1545
1776
  * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
1546
1777
  *
1547
- * Automatically generates `fe_code` / `fe_hash` for device binding. If the aggregator
1548
- * selects the 'link' strategy, `feCode` is included in the result so the caller can
1549
- * set it as an HttpOnly cookie via `buildSetBindingCookieHeader()`.
1778
+ * Automatically generates `fe_code` / `fe_hash` for device binding. If the strategy or
1779
+ * its fallback is 'link', `feCode` is included in the result so the caller can set it
1780
+ * as an HttpOnly cookie for the link session (`fallback.session` when the fallback is
1781
+ * link) via `buildSetBindingCookieHeader()`.
1550
1782
  *
1551
1783
  * @param request - Prepare request parameters
1552
1784
  * @param options - Per-request options (e.g., correlationId)
@@ -1573,8 +1805,9 @@ var MagicalAuthClient = class {
1573
1805
  options
1574
1806
  );
1575
1807
  const result = { ...response };
1576
- if (response.authentication_strategy === AuthenticationStrategy.LINK) {
1577
- const linkData = response.data;
1808
+ const link = response.authentication_strategy === AuthenticationStrategy.LINK ? response : response.fallback;
1809
+ if (link?.authentication_strategy === AuthenticationStrategy.LINK) {
1810
+ const linkData = link.data;
1578
1811
  result.feCode = linkData.fe_code ?? feCode;
1579
1812
  }
1580
1813
  this.config.logger.debug("Auth prepared", {
@@ -1693,6 +1926,31 @@ var MagicalAuthClient = class {
1693
1926
  keys: this.recordKeys
1694
1927
  });
1695
1928
  }
1929
+ /**
1930
+ * Verifies a step-up verification record and requires that it is verified,
1931
+ * carries both the `passkey` and `carrier` factors, is bound to `action` and
1932
+ * is for `phoneNumber` (E.164). The record is accepted past `exp` while its
1933
+ * `iat` is within `maxAgeSeconds` (non-finite, zero or negative means 300).
1934
+ * `expectedAudience` is the record aud to require; unset means this client's ID.
1935
+ *
1936
+ * @throws {VerificationRecordError} `EXPIRED` when older than `maxAgeSeconds`, `STEP_UP_REJECTED` when a step-up check fails, or any record verification code
1937
+ */
1938
+ async verifyStepUp(record, action, phoneNumber, maxAgeSeconds = 300, expectedAudience) {
1939
+ const maxAge = Number.isFinite(maxAgeSeconds) && maxAgeSeconds > 0 ? maxAgeSeconds : 300;
1940
+ const rec = await this.verifyVerificationRecord(record, { allowExpired: true, maxAuditAgeSeconds: maxAge, expectedAudience });
1941
+ const c = rec.claims;
1942
+ const reject = (message) => new VerificationRecordError(VerificationRecordErrorCode.STEP_UP_REJECTED, message);
1943
+ if (Math.floor(Date.now() / 1e3) - c.iat > maxAge) {
1944
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record is older than maxAge");
1945
+ }
1946
+ if (!c.verified) throw reject("record is not verified");
1947
+ if (!c.factors.includes("passkey") || !c.factors.includes("carrier")) {
1948
+ throw reject("record lacks the passkey and carrier factors");
1949
+ }
1950
+ if (c.action_hash !== actionHash(action)) throw reject("action_hash does not match the action");
1951
+ if (c.sub !== `tel:${phoneNumber}`) throw reject("sub does not match the phone number");
1952
+ return rec;
1953
+ }
1696
1954
  /**
1697
1955
  * Retrieves the phone number associated with the device using digital credentials.
1698
1956
  *
@@ -1722,6 +1980,26 @@ var MagicalAuthClient = class {
1722
1980
  });
1723
1981
  return response;
1724
1982
  }
1983
+ /**
1984
+ * Deletes every passkey Glide holds for the number on origin, a registered origin of this application.
1985
+ *
1986
+ * @param request - Phone number and origin whose passkeys are deleted
1987
+ * @param options - Per-request options (e.g., correlationId)
1988
+ * @returns The deleted credential ids; empty when there were none
1989
+ * @throws {ValidationError} If phone_number is not E.164 or origin is missing
1990
+ * @throws {ForbiddenError} If origin is not registered to this application
1991
+ * @throws {MagicalAuthError} For other API errors
1992
+ */
1993
+ async deletePasskeys(request, options) {
1994
+ validateDeletePasskeysRequest(request);
1995
+ const response = await this.doRequest(
1996
+ "POST",
1997
+ "/magic-auth/v2/auth/delete-passkeys",
1998
+ request,
1999
+ options
2000
+ );
2001
+ return { ...response, deleted_credential_ids: response?.deleted_credential_ids ?? [] };
2002
+ }
1725
2003
  /**
1726
2004
  * Reports when a user clicks the invoke/authenticate button.
1727
2005
  *
@@ -1899,7 +2177,7 @@ var MagicalAuthClient = class {
1899
2177
  };
1900
2178
  var ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1901
2179
  function generateNonce(length = 32) {
1902
- const bytes = (0, import_node_crypto4.randomBytes)(length);
2180
+ const bytes = (0, import_node_crypto5.randomBytes)(length);
1903
2181
  let result = "";
1904
2182
  for (let i = 0; i < length; i++) {
1905
2183
  result += ALPHANUMERIC.charAt(bytes[i] % ALPHANUMERIC.length);
@@ -1968,6 +2246,7 @@ var VERSION = _require("../package.json").version;
1968
2246
  CarrierAppUnavailableError,
1969
2247
  CarrierNotEligibleError,
1970
2248
  CarrierRejectedError,
2249
+ CarrierTemporarilyUnavailableError,
1971
2250
  DEFAULT_BASE_URL,
1972
2251
  DEFAULT_TIMEOUT,
1973
2252
  DesktopWaitError,
@@ -1985,6 +2264,7 @@ var VERSION = _require("../package.json").version;
1985
2264
  RateLimitError,
1986
2265
  SENSITIVE_KEYS,
1987
2266
  ServiceUnavailableError,
2267
+ SessionMetadataParentStrategy,
1988
2268
  SessionNotEligibleError,
1989
2269
  SessionNotFoundError,
1990
2270
  SessionStatus,
@@ -1996,6 +2276,7 @@ var VERSION = _require("../package.json").version;
1996
2276
  ValidationError,
1997
2277
  VerificationRecordError,
1998
2278
  VerificationRecordErrorCode,
2279
+ actionHash,
1999
2280
  assertValidFeCode,
2000
2281
  buildClearBindingCookieHeader,
2001
2282
  buildSetBindingCookieHeader,