@glideidentity/glide-be-node-magical-auth 3.0.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
@@ -24,8 +24,12 @@ __export(index_exports, {
24
24
  BINDING_COOKIE_MAX_AGE: () => BINDING_COOKIE_MAX_AGE,
25
25
  BINDING_COOKIE_PREFIX: () => BINDING_COOKIE_PREFIX,
26
26
  BadRequestError: () => BadRequestError,
27
+ BiometricVerification: () => BiometricVerification,
27
28
  BrowserMismatchError: () => BrowserMismatchError,
29
+ CarrierAppUnavailableError: () => CarrierAppUnavailableError,
28
30
  CarrierNotEligibleError: () => CarrierNotEligibleError,
31
+ CarrierRejectedError: () => CarrierRejectedError,
32
+ CarrierTemporarilyUnavailableError: () => CarrierTemporarilyUnavailableError,
29
33
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
30
34
  DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
31
35
  DesktopWaitError: () => DesktopWaitError,
@@ -38,10 +42,12 @@ __export(index_exports, {
38
42
  MagicalAuthClient: () => MagicalAuthClient,
39
43
  MagicalAuthError: () => MagicalAuthError,
40
44
  MissingBindingCookieError: () => MissingBindingCookieError,
45
+ PREPARE_MULTIPLE_MAX: () => PREPARE_MULTIPLE_MAX,
41
46
  PhoneNumberMismatchError: () => PhoneNumberMismatchError,
42
47
  RateLimitError: () => RateLimitError,
43
48
  SENSITIVE_KEYS: () => SENSITIVE_KEYS,
44
49
  ServiceUnavailableError: () => ServiceUnavailableError,
50
+ SessionMetadataParentStrategy: () => SessionMetadataParentStrategy,
45
51
  SessionNotEligibleError: () => SessionNotEligibleError,
46
52
  SessionNotFoundError: () => SessionNotFoundError,
47
53
  SessionStatus: () => SessionStatus,
@@ -51,6 +57,9 @@ __export(index_exports, {
51
57
  UseCase: () => UseCase,
52
58
  VERSION: () => VERSION,
53
59
  ValidationError: () => ValidationError,
60
+ VerificationRecordError: () => VerificationRecordError,
61
+ VerificationRecordErrorCode: () => VerificationRecordErrorCode,
62
+ actionHash: () => actionHash,
54
63
  assertValidFeCode: () => assertValidFeCode,
55
64
  buildClearBindingCookieHeader: () => buildClearBindingCookieHeader,
56
65
  buildSetBindingCookieHeader: () => buildSetBindingCookieHeader,
@@ -71,7 +80,7 @@ module.exports = __toCommonJS(index_exports);
71
80
  var import_node_module = require("module");
72
81
 
73
82
  // src/client.ts
74
- var import_node_crypto2 = require("crypto");
83
+ var import_node_crypto5 = require("crypto");
75
84
 
76
85
  // src/internal/http.ts
77
86
  var defaultHttpClient = {
@@ -105,6 +114,9 @@ var ErrorCode = {
105
114
  SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
106
115
  INVALID_VERIFICATION: "INVALID_VERIFICATION",
107
116
  CARRIER_NOT_ELIGIBLE: "CARRIER_NOT_ELIGIBLE",
117
+ CARRIER_REJECTED: "CARRIER_REJECTED",
118
+ CARRIER_APP_UNAVAILABLE: "CARRIER_APP_UNAVAILABLE",
119
+ CARRIER_TEMPORARILY_UNAVAILABLE: "CARRIER_TEMPORARILY_UNAVAILABLE",
108
120
  UNSUPPORTED_PLATFORM: "UNSUPPORTED_PLATFORM",
109
121
  PHONE_NUMBER_MISMATCH: "PHONE_NUMBER_MISMATCH",
110
122
  INVALID_CREDENTIAL_FORMAT: "INVALID_CREDENTIAL_FORMAT",
@@ -130,9 +142,17 @@ var MagicalAuthError = class extends Error {
130
142
  */
131
143
  status;
132
144
  /**
133
- * Request ID for debugging/support.
145
+ * The id of this request, the same value as the `X-Request-ID` response
146
+ * header. Quote it to Glide support.
134
147
  */
135
148
  requestId;
149
+ /**
150
+ * The session the failed request was about, once the server had read it from
151
+ * the request. Undefined when the request failed before naming a session, on
152
+ * operations that have none (eligibility, prepare), and from servers older
153
+ * than the release that added it.
154
+ */
155
+ sessionKey;
136
156
  /**
137
157
  * Additional error details.
138
158
  */
@@ -201,6 +221,26 @@ var CarrierNotEligibleError = class extends MagicalAuthError {
201
221
  this.name = "CarrierNotEligibleError";
202
222
  }
203
223
  };
224
+ var CarrierRejectedError = class extends MagicalAuthError {
225
+ constructor(message = "The carrier rejected the authentication request", requestId, details) {
226
+ super(message, "CARRIER_REJECTED", 422, requestId, details);
227
+ this.name = "CarrierRejectedError";
228
+ }
229
+ };
230
+ var CarrierAppUnavailableError = class extends MagicalAuthError {
231
+ constructor(message = "Carrier app unavailable on the phone that scanned the QR code", requestId, details) {
232
+ super(message, "CARRIER_APP_UNAVAILABLE", 422, requestId, details);
233
+ this.name = "CarrierAppUnavailableError";
234
+ }
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
+ };
204
244
  var UnsupportedPlatformError = class extends MagicalAuthError {
205
245
  constructor(message = "Platform not supported", requestId) {
206
246
  super(message, "UNSUPPORTED_PLATFORM", 422, requestId);
@@ -281,9 +321,32 @@ var MissingBindingCookieError = class extends DeviceBindingError {
281
321
  var DesktopWaitError = class extends MagicalAuthError {
282
322
  waitResponse;
283
323
  constructor(waitResponse) {
284
- super(waitResponse.message, "DESKTOP_WAIT", 202);
324
+ super(waitResponse.message, "DESKTOP_WAIT", 202, waitResponse.request_id);
285
325
  this.name = "DesktopWaitError";
286
326
  this.waitResponse = waitResponse;
327
+ Object.assign(this, { sessionKey: waitResponse.session_key });
328
+ }
329
+ };
330
+ var VerificationRecordErrorCode = {
331
+ MALFORMED: "MALFORMED",
332
+ DISALLOWED_HEADER: "DISALLOWED_HEADER",
333
+ UNKNOWN_KEY: "UNKNOWN_KEY",
334
+ BAD_SIGNATURE: "BAD_SIGNATURE",
335
+ WRONG_ISSUER: "WRONG_ISSUER",
336
+ WRONG_AUDIENCE: "WRONG_AUDIENCE",
337
+ EXPIRED: "EXPIRED",
338
+ NOT_YET_VALID: "NOT_YET_VALID",
339
+ NONCE_MISMATCH: "NONCE_MISMATCH",
340
+ ORIGIN_MISMATCH: "ORIGIN_MISMATCH",
341
+ UNSUPPORTED_VERSION: "UNSUPPORTED_VERSION",
342
+ REVOKED_KEY: "REVOKED_KEY",
343
+ RECORD_UNAVAILABLE: "RECORD_UNAVAILABLE",
344
+ STEP_UP_REJECTED: "STEP_UP_REJECTED"
345
+ };
346
+ var VerificationRecordError = class extends MagicalAuthError {
347
+ constructor(code, message) {
348
+ super(`verification record: ${code}: ${message}`, code, 0);
349
+ this.name = "VerificationRecordError";
287
350
  }
288
351
  };
289
352
  function parseRetryAfter(headers) {
@@ -302,9 +365,10 @@ function parseRetryAfter(headers) {
302
365
  return void 0;
303
366
  }
304
367
  function createErrorFromResponse(response, headers) {
305
- const { code, message, request_id, details, status, trace_id, span_id, timestamp, service } = response;
368
+ const { code, message, request_id, session_key, details, status, trace_id, span_id, timestamp, service } = response;
306
369
  const error = createTypedError(code, message, request_id, details, status, headers);
307
370
  return Object.assign(error, {
371
+ sessionKey: session_key,
308
372
  traceId: trace_id,
309
373
  spanId: span_id,
310
374
  timestamp,
@@ -312,6 +376,8 @@ function createErrorFromResponse(response, headers) {
312
376
  });
313
377
  }
314
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;
315
381
  switch (code) {
316
382
  case "BAD_REQUEST":
317
383
  return new BadRequestError(message, request_id);
@@ -328,6 +394,25 @@ function createTypedError(code, message, request_id, details, status, headers) {
328
394
  return new SessionNotFoundError(message, request_id);
329
395
  case "CARRIER_NOT_ELIGIBLE":
330
396
  return new CarrierNotEligibleError(message, request_id);
397
+ case "CARRIER_REJECTED":
398
+ return new CarrierRejectedError(
399
+ message,
400
+ request_id,
401
+ details
402
+ );
403
+ case "CARRIER_APP_UNAVAILABLE":
404
+ return new CarrierAppUnavailableError(
405
+ message,
406
+ request_id,
407
+ details
408
+ );
409
+ case "CARRIER_TEMPORARILY_UNAVAILABLE":
410
+ return new CarrierTemporarilyUnavailableError(
411
+ message,
412
+ parseRetryAfter(headers) ?? detailRetry,
413
+ request_id,
414
+ details
415
+ );
331
416
  case "UNSUPPORTED_PLATFORM":
332
417
  return new UnsupportedPlatformError(message, request_id);
333
418
  case "INVALID_CREDENTIAL_FORMAT":
@@ -350,12 +435,15 @@ function createTypedError(code, message, request_id, details, status, headers) {
350
435
  case "MISSING_BINDING_COOKIE":
351
436
  return new MissingBindingCookieError(message, request_id);
352
437
  case "RATE_LIMIT_EXCEEDED":
353
- return new RateLimitError(message, parseRetryAfter(headers), request_id);
438
+ return new RateLimitError(message, parseRetryAfter(headers) ?? detailRetry, request_id);
354
439
  case "INTERNAL_SERVER_ERROR":
355
440
  return new InternalServerError(message, request_id);
356
441
  case "SERVICE_UNAVAILABLE":
357
442
  return new ServiceUnavailableError(message, request_id);
358
443
  default:
444
+ if (status === 429) {
445
+ return new RateLimitError(message, parseRetryAfter(headers) ?? detailRetry, request_id);
446
+ }
359
447
  return new MagicalAuthError(
360
448
  message,
361
449
  code,
@@ -392,7 +480,9 @@ var TokenManager = class {
392
480
  * in progress, subsequent calls will await the same promise.
393
481
  *
394
482
  * @returns A valid access token
395
- * @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)
396
486
  */
397
487
  async getToken() {
398
488
  if (this.token && Date.now() < this.expiresAt) {
@@ -429,17 +519,28 @@ var TokenManager = class {
429
519
  body: "grant_type=client_credentials"
430
520
  });
431
521
  if (!response.ok) {
432
- let errorMessage = "Token request failed";
522
+ let errorMessage2 = "Token request failed";
523
+ let oauthError;
433
524
  try {
434
525
  const errorBody = await response.json();
526
+ oauthError = errorBody.error;
435
527
  if (errorBody.error_description) {
436
- errorMessage = errorBody.error_description;
528
+ errorMessage2 = errorBody.error_description;
437
529
  } else if (errorBody.error) {
438
- errorMessage = errorBody.error;
530
+ errorMessage2 = errorBody.error;
439
531
  }
440
532
  } catch {
441
533
  }
442
- throw new UnauthorizedError(errorMessage);
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
+ }
543
+ throw new UnauthorizedError(errorMessage2);
443
544
  }
444
545
  const data = await response.json();
445
546
  if (!data.access_token) {
@@ -600,12 +701,14 @@ function validateCookieAttr(name, value) {
600
701
  throw new Error("Invalid cookie path: must start with '/'");
601
702
  }
602
703
  }
603
- function getCompletionPageHtml(completeEndpoint) {
704
+ function getCompletionPageHtml(completeEndpoint, options) {
604
705
  if (!completeEndpoint.startsWith("/") || completeEndpoint.startsWith("//")) {
605
706
  throw new Error(
606
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.'
607
708
  );
608
709
  }
710
+ const serializedCompleteEndpoint = JSON.stringify(completeEndpoint).replace(/</g, "\\u003c");
711
+ const beacon = options?.beacon === true;
609
712
  return `<!DOCTYPE html>
610
713
  <html lang="en">
611
714
  <head>
@@ -673,34 +776,177 @@ function getCompletionPageHtml(completeEndpoint) {
673
776
  <div class="badge">Action required</div>
674
777
  </div>
675
778
  <script>
676
- (async function() {
779
+ ${beacon ? `(async function() {
677
780
  var fragment = new URLSearchParams(window.location.hash.substring(1));
678
781
  var aggCode = fragment.get('agg_code');
679
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');
680
818
 
681
819
  window.history.replaceState(null, '', window.location.pathname + window.location.search);
682
820
 
683
821
  if (!aggCode || !sessionKey) {
822
+ sendPageBeacon('invalid_link');
684
823
  showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');
685
824
  return;
686
825
  }
687
826
 
688
827
  try {
689
- var res = await fetch(${JSON.stringify(completeEndpoint)}, {
828
+ var res = await fetch(${serializedCompleteEndpoint}, {
690
829
  method: 'POST',
691
830
  credentials: 'include',
692
831
  headers: { 'Content-Type': 'application/json' },
693
832
  body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })
694
833
  });
695
834
 
835
+ var outcome = { ok: !!res.ok, status: res.status };
696
836
  if (res.ok) {
837
+ sendPageBeacon('post_outcome', outcome);
697
838
  var signalKey = 'glide_signal_' + sessionKey;
839
+ var sigmetaKey = 'glide_sigmeta_' + sessionKey;
840
+ var signalStored = false;
698
841
  try {
699
842
  localStorage.setItem(signalKey, sessionKey);
843
+ signalStored = true;
844
+ localStorage.setItem(sigmetaKey, String(Date.now()));
845
+ } catch(e) {}
846
+ if (signalStored) {
700
847
  setTimeout(function() {
701
- try { localStorage.removeItem(signalKey); } catch(e) {}
702
- }, 5000);
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}, {
930
+ method: 'POST',
931
+ credentials: 'include',
932
+ headers: { 'Content-Type': 'application/json' },
933
+ body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })
934
+ });
935
+
936
+ if (res.ok) {
937
+ var signalKey = 'glide_signal_' + sessionKey;
938
+ var sigmetaKey = 'glide_sigmeta_' + sessionKey;
939
+ var signalStored = false;
940
+ try {
941
+ localStorage.setItem(signalKey, sessionKey);
942
+ signalStored = true;
943
+ localStorage.setItem(sigmetaKey, String(Date.now()));
703
944
  } catch(e) {}
945
+ if (signalStored) {
946
+ setTimeout(function() {
947
+ try { localStorage.removeItem(signalKey); localStorage.removeItem(sigmetaKey); } catch(e) {}
948
+ }, 600000);
949
+ }
704
950
  tryClose();
705
951
  } else {
706
952
  var code = '';
@@ -730,7 +976,7 @@ function getCompletionPageHtml(completeEndpoint) {
730
976
  document.getElementById('hint').textContent = 'You may close this tab.';
731
977
  document.getElementById('hint').classList.remove('hidden');
732
978
  }, 300);
733
- }
979
+ }`}
734
980
 
735
981
  function showError(title, points, illust) {
736
982
  document.getElementById('loading').classList.add('hidden');
@@ -765,8 +1011,11 @@ var AuthenticationStrategy = {
765
1011
  TS43: "ts43",
766
1012
  LINK: "link",
767
1013
  DESKTOP: "desktop",
1014
+ PASSKEY: "passkey",
1015
+ CALL: "call",
768
1016
  NONE: ""
769
1017
  };
1018
+ var SessionMetadataParentStrategy = "parent_strategy";
770
1019
  var SessionStatus = {
771
1020
  PENDING: "pending",
772
1021
  SCANNED: "scanned",
@@ -774,6 +1023,16 @@ var SessionStatus = {
774
1023
  COMPLETED: "completed",
775
1024
  FAILED: "failed"
776
1025
  };
1026
+ var BiometricVerification = {
1027
+ VERIFIED: "VERIFIED",
1028
+ FAILED: "FAILED",
1029
+ NOT_ENROLLED: "NOT_ENROLLED",
1030
+ UNSUPPORTED: "UNSUPPORTED",
1031
+ NOT_REQUESTED: "NOT_REQUESTED"
1032
+ };
1033
+
1034
+ // src/models/prepare-multiple.ts
1035
+ var PREPARE_MULTIPLE_MAX = 10;
777
1036
 
778
1037
  // src/validation.ts
779
1038
  function validatePrepareRequest(request) {
@@ -814,6 +1073,18 @@ function validateGetPhoneNumberRequest(request) {
814
1073
  throw new ValidationError("Request validation failed", errors);
815
1074
  }
816
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
+ }
817
1088
  function validateSessionId(sessionId) {
818
1089
  if (!sessionId) {
819
1090
  throw new ValidationError("Request validation failed", {
@@ -861,11 +1132,599 @@ function validateEligibilityRequest(request) {
861
1132
  throw new ValidationError("Request validation failed", errors);
862
1133
  }
863
1134
  }
1135
+ function validatePrepareMultipleRequest(request) {
1136
+ if (request == null) {
1137
+ throw new ValidationError("Request validation failed", {
1138
+ request: "request is required"
1139
+ });
1140
+ }
1141
+ const numbers = request.phone_numbers;
1142
+ let message = null;
1143
+ if (!Array.isArray(numbers) || numbers.length === 0) {
1144
+ message = "phone_numbers must contain at least one number";
1145
+ } else if (numbers.length > PREPARE_MULTIPLE_MAX) {
1146
+ message = `phone_numbers must contain at most ${PREPARE_MULTIPLE_MAX} numbers`;
1147
+ } else if (Array.from(numbers).some((n) => typeof n !== "string" || !n.trim())) {
1148
+ message = "phone_numbers must not contain blank entries";
1149
+ }
1150
+ if (message) {
1151
+ throw new ValidationError("Request validation failed", { phone_numbers: message });
1152
+ }
1153
+ }
1154
+
1155
+ // src/verification-record/jwk.ts
1156
+ var import_node_crypto2 = require("crypto");
1157
+
1158
+ // src/verification-record/decode.ts
1159
+ var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]*$/;
1160
+ function decodeBase64URL(segment) {
1161
+ if (!BASE64URL_ALPHABET.test(segment) || segment.length % 4 === 1) {
1162
+ return null;
1163
+ }
1164
+ const bytes = Buffer.from(segment, "base64url");
1165
+ return bytes.toString("base64url") === segment ? bytes : null;
1166
+ }
1167
+ function isJsonObject(value) {
1168
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1169
+ }
1170
+ function parseJsonObject(text) {
1171
+ try {
1172
+ const value = JSON.parse(text);
1173
+ return isJsonObject(value) ? value : null;
1174
+ } catch {
1175
+ return null;
1176
+ }
1177
+ }
1178
+ function member(obj, name) {
1179
+ return Object.hasOwn(obj, name) ? obj[name] : void 0;
1180
+ }
1181
+ var MemberReader = class {
1182
+ constructor(obj) {
1183
+ this.obj = obj;
1184
+ }
1185
+ obj;
1186
+ ok = true;
1187
+ str(name) {
1188
+ return this.read(name, (v) => typeof v === "string");
1189
+ }
1190
+ bool(name) {
1191
+ return this.read(name, (v) => typeof v === "boolean");
1192
+ }
1193
+ int(name) {
1194
+ return this.read(name, (v) => Number.isSafeInteger(v));
1195
+ }
1196
+ /** A nested object member; absent yields undefined. Present null is a wrong type. */
1197
+ object(name) {
1198
+ return this.read(name, isJsonObject);
1199
+ }
1200
+ read(name, accept) {
1201
+ if (!Object.hasOwn(this.obj, name)) return void 0;
1202
+ const value = this.obj[name];
1203
+ if (accept(value)) return value;
1204
+ this.ok = false;
1205
+ return void 0;
1206
+ }
1207
+ };
1208
+
1209
+ // src/verification-record/jwk.ts
1210
+ var RECORD_ALG = "ES256";
1211
+ function parseJWKS(body) {
1212
+ const doc = parseJsonObject(body);
1213
+ if (!doc) {
1214
+ throw new Error("JWKS is not a JSON object");
1215
+ }
1216
+ const entries = member(doc, "keys");
1217
+ if (!Array.isArray(entries)) {
1218
+ throw new Error("JWKS keys is not an array");
1219
+ }
1220
+ const keys = [];
1221
+ for (const entry of entries) {
1222
+ if (!isJsonObject(entry)) continue;
1223
+ const r = new MemberReader(entry);
1224
+ const k = {
1225
+ kty: r.str("kty") ?? "",
1226
+ crv: r.str("crv") ?? "",
1227
+ use: r.str("use") ?? "",
1228
+ alg: r.str("alg") ?? "",
1229
+ kid: r.str("kid") ?? "",
1230
+ x: r.str("x") ?? "",
1231
+ y: r.str("y") ?? ""
1232
+ };
1233
+ if (r.ok) keys.push(k);
1234
+ }
1235
+ return keys;
1236
+ }
1237
+ function recordPublicKey(k) {
1238
+ if (k.kty !== "EC" || k.crv !== "P-256" || k.use !== "sig" || k.alg !== RECORD_ALG) {
1239
+ throw new Error("JWK is not an EC P-256 ES256 signing key");
1240
+ }
1241
+ const x = decodeBase64URL(k.x);
1242
+ const y = decodeBase64URL(k.y);
1243
+ if (!x || !y || x.length !== 32 || y.length !== 32) {
1244
+ throw new Error("JWK coordinates are not 32-byte base64url");
1245
+ }
1246
+ try {
1247
+ return (0, import_node_crypto2.createPublicKey)({ key: { kty: "EC", crv: "P-256", x: k.x, y: k.y }, format: "jwk" });
1248
+ } catch {
1249
+ throw new Error("JWK point is not on P-256");
1250
+ }
1251
+ }
1252
+
1253
+ // src/verification-record/jwks.ts
1254
+ var DEFAULT_MAX_AGE_SECONDS = 300;
1255
+ var REFRESH_INTERVAL_MS = 6e4;
1256
+ var MAX_JWKS_BYTES = 1 << 20;
1257
+ var JWKS_PATH = "/.well-known/us/jwks.json";
1258
+ var RecordKeyCache = class {
1259
+ constructor(baseUrl, httpClient, timeoutMs) {
1260
+ this.baseUrl = baseUrl;
1261
+ this.httpClient = httpClient;
1262
+ this.timeoutMs = timeoutMs;
1263
+ }
1264
+ baseUrl;
1265
+ httpClient;
1266
+ timeoutMs;
1267
+ now = Date.now;
1268
+ keys = null;
1269
+ expiresAt = 0;
1270
+ lastRefresh = -Infinity;
1271
+ backoffUntil = -Infinity;
1272
+ queue = Promise.resolve();
1273
+ key(kid) {
1274
+ const run = this.queue.then(() => this.resolve(kid));
1275
+ this.queue = run.catch(() => void 0);
1276
+ return run;
1277
+ }
1278
+ /**
1279
+ * Refetches when the cache has expired, or when kid is missing and the last
1280
+ * refresh is at least 60 s old. After a failed refresh the previous keys are
1281
+ * kept and further refreshes are refused for 60 s.
1282
+ */
1283
+ async resolve(kid) {
1284
+ const now = this.now();
1285
+ const cached = this.keys?.has(kid) ?? false;
1286
+ const expired = this.keys === null || now >= this.expiresAt;
1287
+ if (expired || !cached && now - this.lastRefresh >= REFRESH_INTERVAL_MS) {
1288
+ if (now < this.backoffUntil) {
1289
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, "record key fetch is backing off after a failure");
1290
+ }
1291
+ try {
1292
+ await this.refresh(now);
1293
+ } catch (e) {
1294
+ this.backoffUntil = now + REFRESH_INTERVAL_MS;
1295
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `fetch record keys: ${errorMessage(e)}`);
1296
+ }
1297
+ }
1298
+ const jwk = this.keys?.get(kid);
1299
+ if (!jwk) {
1300
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not published`);
1301
+ }
1302
+ try {
1303
+ return recordPublicKey(jwk);
1304
+ } catch (e) {
1305
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid}: ${errorMessage(e)}`);
1306
+ }
1307
+ }
1308
+ async refresh(now) {
1309
+ this.lastRefresh = now;
1310
+ const doc = await this.fetch(`${this.baseUrl}${JWKS_PATH}`);
1311
+ const keys = /* @__PURE__ */ new Map();
1312
+ for (const k of doc.keys) {
1313
+ if (!keys.has(k.kid)) keys.set(k.kid, k);
1314
+ }
1315
+ this.keys = keys;
1316
+ this.expiresAt = now + doc.maxAgeSeconds * 1e3;
1317
+ }
1318
+ async fetch(url) {
1319
+ const controller = new AbortController();
1320
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1321
+ try {
1322
+ const response = await this.httpClient.request({
1323
+ method: "GET",
1324
+ url,
1325
+ headers: { Accept: "application/json" },
1326
+ signal: controller.signal
1327
+ });
1328
+ if (response.status !== 200) {
1329
+ throw new Error(`${url}: HTTP ${response.status}`);
1330
+ }
1331
+ const body = await response.text();
1332
+ if (Buffer.byteLength(body, "utf8") > MAX_JWKS_BYTES) {
1333
+ throw new Error(`${url}: JWKS is larger than 1 MiB`);
1334
+ }
1335
+ const keys = prefixErrors(url, () => parseJWKS(body));
1336
+ return { keys, maxAgeSeconds: cacheMaxAge(response.headers?.get("cache-control") ?? null) };
1337
+ } catch (e) {
1338
+ if (controller.signal.aborted) {
1339
+ throw new Error(`${url}: timed out after ${this.timeoutMs}ms`);
1340
+ }
1341
+ throw e;
1342
+ } finally {
1343
+ clearTimeout(timer);
1344
+ }
1345
+ }
1346
+ };
1347
+ function cacheMaxAge(cacheControl) {
1348
+ for (const directive of (cacheControl ?? "").split(",")) {
1349
+ const trimmed = directive.trim();
1350
+ const eq = trimmed.indexOf("=");
1351
+ if (eq < 0 || trimmed.slice(0, eq).toLowerCase() !== "max-age") continue;
1352
+ const value = trimmed.slice(eq + 1);
1353
+ const seconds = /^[+-]?\d+$/.test(value) ? Number(value) : NaN;
1354
+ if (Number.isSafeInteger(seconds) && seconds >= 0) return seconds;
1355
+ }
1356
+ return DEFAULT_MAX_AGE_SECONDS;
1357
+ }
1358
+ function prefixErrors(url, fn) {
1359
+ try {
1360
+ return fn();
1361
+ } catch (e) {
1362
+ throw new Error(`${url}: ${errorMessage(e)}`);
1363
+ }
1364
+ }
1365
+ function errorMessage(e) {
1366
+ return e instanceof Error ? e.message : String(e);
1367
+ }
1368
+
1369
+ // src/verification-record/verify.ts
1370
+ var import_node_crypto3 = require("crypto");
1371
+
1372
+ // src/verification-record/shape.ts
1373
+ var USE_CASE = "VerifyPhoneNumber";
1374
+ var MAX_LIFETIME_SECONDS = 60;
1375
+ var RECORD_VERSION = "1.0";
1376
+ var CARRIER_ROLE = "carrier";
1377
+ var CARRIER_SIGNER_PREFIX = "carrier:";
1378
+ function malformed(message) {
1379
+ return new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, message);
1380
+ }
1381
+ function isNonEmptyString(value) {
1382
+ return typeof value === "string" && value !== "";
1383
+ }
1384
+ function checkClaimShape(obj, iat, exp) {
1385
+ if (typeof member(obj, "verified") !== "boolean") {
1386
+ throw malformed("verified must be a boolean");
1387
+ }
1388
+ for (const name of ["jti", "nonce", "sub"]) {
1389
+ if (!isNonEmptyString(member(obj, name))) {
1390
+ throw malformed(`${name} must be a non-empty string`);
1391
+ }
1392
+ }
1393
+ if (!member(obj, "sub").startsWith("tel:+")) {
1394
+ throw malformed("sub must be tel:+E164");
1395
+ }
1396
+ for (const name of ["origin", "biometric_verification"]) {
1397
+ if (typeof member(obj, name) !== "string") throw malformed(`${name} must be a string`);
1398
+ }
1399
+ if (member(obj, "nbf") !== iat) {
1400
+ throw malformed("nbf must equal iat");
1401
+ }
1402
+ if (member(obj, "use_case") !== USE_CASE) {
1403
+ throw malformed(`use_case must be ${USE_CASE}`);
1404
+ }
1405
+ if (exp < iat + 1 || exp > iat + MAX_LIFETIME_SECONDS) {
1406
+ throw malformed("exp must be 1 to 60 seconds after iat");
1407
+ }
1408
+ const signOffs = readSignOffs(member(obj, "sign_offs"));
1409
+ if (!signOffs) {
1410
+ throw malformed("sign_offs must be an array of well-formed entries");
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
+ }
1422
+ if (!oneCarrierSignOff(signOffs)) {
1423
+ throw malformed("sign_offs must have exactly one carrier:<id> carrier entry");
1424
+ }
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;
1432
+ }
1433
+ function readSignOffs(raw) {
1434
+ if (!Array.isArray(raw)) return null;
1435
+ const signOffs = [];
1436
+ for (const entry of raw) {
1437
+ const signOff = isJsonObject(entry) ? readSignOff(entry) : null;
1438
+ if (!signOff) return null;
1439
+ signOffs.push(signOff);
1440
+ }
1441
+ return signOffs;
1442
+ }
1443
+ function readSignOff(entry) {
1444
+ const r = new MemberReader(entry);
1445
+ const role = r.str("role");
1446
+ const signer = r.str("signer");
1447
+ const status = r.str("status");
1448
+ const reason = r.str("reason");
1449
+ const format = r.str("format");
1450
+ const token = r.str("token");
1451
+ if (!r.ok || !isNonEmptyString(role) || !isNonEmptyString(signer)) return null;
1452
+ const signOff = { role, signer, status };
1453
+ if (reason !== void 0) signOff.reason = reason;
1454
+ if (format !== void 0) signOff.format = format;
1455
+ if (token !== void 0) signOff.token = token;
1456
+ if (status === "unavailable") return isNonEmptyString(reason) ? signOff : null;
1457
+ if (status === "present") return isNonEmptyString(format) && isNonEmptyString(token) ? signOff : null;
1458
+ return null;
1459
+ }
1460
+ function oneCarrierSignOff(signOffs) {
1461
+ const carriers = signOffs.filter((s) => s.role === CARRIER_ROLE);
1462
+ const signer = carriers.length === 1 ? carriers[0]?.signer ?? "" : "";
1463
+ return signer.length > CARRIER_SIGNER_PREFIX.length && signer.startsWith(CARRIER_SIGNER_PREFIX);
1464
+ }
1465
+ function carrierIDMatchesSignOff(id, signOffs) {
1466
+ const signer = signOffs.find((s) => s.role === CARRIER_ROLE)?.signer ?? "";
1467
+ return signer === CARRIER_SIGNER_PREFIX + id;
1468
+ }
1469
+
1470
+ // src/verification-record/claims.ts
1471
+ var IAT_LEEWAY_SECONDS = 60;
1472
+ function checkRecordClaims(payload, want) {
1473
+ const obj = parseJsonObject(payload.toString("utf8"));
1474
+ if (!obj) {
1475
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "payload is not a JSON object");
1476
+ }
1477
+ if (member(obj, "ver") !== RECORD_VERSION) {
1478
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNSUPPORTED_VERSION, 'ver must be "1.0"');
1479
+ }
1480
+ const iss = member(obj, "iss");
1481
+ if (typeof iss !== "string" || iss !== want.issuer) {
1482
+ throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_ISSUER, `iss does not match ${want.issuer}`);
1483
+ }
1484
+ const aud = member(obj, "aud");
1485
+ if (typeof aud !== "string" || aud !== want.audience) {
1486
+ throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_AUDIENCE, "aud does not match the expected audience");
1487
+ }
1488
+ const { iat, exp } = checkRecordTimes(obj, want);
1489
+ const { signOffs, factors } = checkClaimShape(obj, iat, exp);
1490
+ const verified = member(obj, "verified");
1491
+ const r = new MemberReader(obj);
1492
+ const claims = {
1493
+ ver: RECORD_VERSION,
1494
+ iss,
1495
+ aud,
1496
+ iat,
1497
+ nbf: iat,
1498
+ exp,
1499
+ verified,
1500
+ sign_offs: signOffs,
1501
+ factors,
1502
+ jti: r.str("jti") ?? "",
1503
+ nonce: r.str("nonce") ?? "",
1504
+ use_case: r.str("use_case") ?? "",
1505
+ sub: r.str("sub") ?? "",
1506
+ origin: r.str("origin") ?? "",
1507
+ biometric_verification: r.str("biometric_verification") ?? ""
1508
+ };
1509
+ assignDefined(claims, "strategy", r.str("strategy"));
1510
+ assignDefined(claims, "action_hash", r.str("action_hash"));
1511
+ assignDefined(claims, "phone_number_details", readPhoneNumberDetails(r));
1512
+ assignDefined(claims, "carrier", readCarrier(r));
1513
+ assignDefined(claims, "sim_swap", readSwap(r, "sim_swap"));
1514
+ assignDefined(claims, "device_swap", readSwap(r, "device_swap"));
1515
+ assignDefined(claims, "live_call", readLiveCall(r, "live_call"));
1516
+ if (!r.ok) {
1517
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "claims have the wrong JSON types");
1518
+ }
1519
+ if (claims.carrier !== void 0 && !carrierIDMatchesSignOff(claims.carrier.id, signOffs)) {
1520
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "carrier.id must match the carrier sign-off signer");
1521
+ }
1522
+ if (want.nonce !== "" && claims.nonce !== want.nonce) {
1523
+ throw new VerificationRecordError(VerificationRecordErrorCode.NONCE_MISMATCH, "nonce does not match the expected nonce");
1524
+ }
1525
+ if (want.origins.length > 0 && !want.origins.includes(claims.origin)) {
1526
+ throw new VerificationRecordError(VerificationRecordErrorCode.ORIGIN_MISMATCH, "origin is not an expected origin");
1527
+ }
1528
+ return claims;
1529
+ }
1530
+ function checkRecordTimes(obj, want) {
1531
+ const iat = member(obj, "iat");
1532
+ const exp = member(obj, "exp");
1533
+ if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp)) {
1534
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "iat and exp must be integers");
1535
+ }
1536
+ const times = { iat, exp };
1537
+ const now = want.nowSeconds;
1538
+ if (times.iat > now + IAT_LEEWAY_SECONDS) {
1539
+ throw new VerificationRecordError(VerificationRecordErrorCode.NOT_YET_VALID, "iat is in the future");
1540
+ }
1541
+ if (times.exp > now) {
1542
+ return times;
1543
+ }
1544
+ if (!want.allowExpired) {
1545
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record has expired");
1546
+ }
1547
+ if (times.iat < now - want.maxAuditAgeSeconds) {
1548
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record is older than the maximum audit age");
1549
+ }
1550
+ return times;
1551
+ }
1552
+ function signOffResults(signOffs) {
1553
+ return signOffs.map((s) => {
1554
+ if (s.status === "unavailable") {
1555
+ const result = { role: s.role, signer: s.signer, result: "unavailable" };
1556
+ assignDefined(result, "reason", s.reason);
1557
+ return result;
1558
+ }
1559
+ return { role: s.role, signer: s.signer, result: "unverified" };
1560
+ });
1561
+ }
1562
+ function readCarrier(r) {
1563
+ const obj = r.object("carrier");
1564
+ if (!obj) return void 0;
1565
+ const s = new MemberReader(obj);
1566
+ const id = s.str("id");
1567
+ const carrier = { id: id ?? "" };
1568
+ assignDefined(carrier, "name", s.str("name"));
1569
+ assignDefined(carrier, "mvno", s.str("mvno"));
1570
+ r.ok = r.ok && s.ok && !!id;
1571
+ return carrier;
1572
+ }
1573
+ function readPhoneNumberDetails(r) {
1574
+ const obj = r.object("phone_number_details");
1575
+ if (!obj) return void 0;
1576
+ const s = new MemberReader(obj);
1577
+ const d = {
1578
+ country_code: s.int("country_code") ?? 0,
1579
+ national_number: s.str("national_number") ?? "",
1580
+ region_code: s.str("region_code") ?? ""
1581
+ };
1582
+ r.ok = r.ok && s.ok;
1583
+ return d;
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
+ }
1598
+ function readSwap(r, name) {
1599
+ const obj = r.object(name);
1600
+ if (!obj) return void 0;
1601
+ const s = new MemberReader(obj);
1602
+ const info = { checked: s.bool("checked") ?? false };
1603
+ assignDefined(info, "risk_level", s.str("risk_level"));
1604
+ assignDefined(info, "carrier_name", s.str("carrier_name"));
1605
+ assignDefined(info, "reason", s.str("reason"));
1606
+ assignDefined(info, "swapped", s.bool("swapped"));
1607
+ assignDefined(info, "max_age_hours", s.int("max_age_hours"));
1608
+ const band = s.object("age_band");
1609
+ if (band) {
1610
+ const b = new MemberReader(band);
1611
+ info.age_band = { from: b.int("from") ?? -1, to: b.int("to") ?? -1 };
1612
+ s.ok = s.ok && b.ok;
1613
+ }
1614
+ r.ok = r.ok && s.ok;
1615
+ return info;
1616
+ }
1617
+ function assignDefined(target, key, value) {
1618
+ if (value !== void 0) {
1619
+ target[key] = value;
1620
+ }
1621
+ }
1622
+
1623
+ // src/verification-record/verify.ts
1624
+ var RECORD_TYP = "glide-verification+jwt";
1625
+ var DEFAULT_MAX_AUDIT_AGE_SECONDS = 90 * 24 * 60 * 60;
1626
+ var MAX_RECORD_BYTES = 16 * 1024;
1627
+ var RECORD_KIDS = [
1628
+ "glide-record-signing-key-ecdsa-es256-us-2026",
1629
+ "glide-record-signing-key-ecdsa-es256-eu-2026"
1630
+ ];
1631
+ var REVOKED_RECORD_KIDS = [];
1632
+ async function verifyVerificationRecord(record, options, ctx) {
1633
+ const opts = options ?? {};
1634
+ const nowMs = (opts.now ? opts.now() : /* @__PURE__ */ new Date()).getTime();
1635
+ if (!Number.isFinite(nowMs)) {
1636
+ throw new TypeError("options.now must return a valid Date");
1637
+ }
1638
+ const parsed = parseRecord(record);
1639
+ checkRecordKid(parsed.kid, opts.revokedKids ?? []);
1640
+ const key = await ctx.keys.key(parsed.kid);
1641
+ verifyRecordSignature(parsed, key);
1642
+ const maxAuditAge = opts.maxAuditAgeSeconds ?? 0;
1643
+ const claims = checkRecordClaims(parsed.payload, {
1644
+ issuer: opts.issuer ? opts.issuer : ctx.baseUrl.replace(/\/+$/, ""),
1645
+ audience: opts.expectedAudience ? opts.expectedAudience : ctx.clientId,
1646
+ nonce: opts.expectedNonce ?? "",
1647
+ origins: opts.expectedOrigin ?? [],
1648
+ allowExpired: opts.allowExpired === true,
1649
+ maxAuditAgeSeconds: Number.isFinite(maxAuditAge) && maxAuditAge > 0 ? maxAuditAge : DEFAULT_MAX_AUDIT_AGE_SECONDS,
1650
+ nowSeconds: Math.floor(nowMs / 1e3)
1651
+ });
1652
+ return { claims, signOffResults: signOffResults(claims.sign_offs) };
1653
+ }
1654
+ function parseRecord(record) {
1655
+ if (record === void 0 || record === null || record === "") {
1656
+ throw new VerificationRecordError(VerificationRecordErrorCode.RECORD_UNAVAILABLE, "no verification record");
1657
+ }
1658
+ if (typeof record === "string" && Buffer.byteLength(record, "utf8") > MAX_RECORD_BYTES) {
1659
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is larger than 16 KiB");
1660
+ }
1661
+ const segments = typeof record === "string" ? record.split(".") : [];
1662
+ if (segments.length !== 3) {
1663
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is not a compact JWS");
1664
+ }
1665
+ const decoded = segments.map(decodeBase64URL);
1666
+ const [header, payload, signature] = decoded;
1667
+ if (!header || !payload || !signature) {
1668
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record segment is not base64url");
1669
+ }
1670
+ const headerObj = parseJsonObject(header.toString("utf8"));
1671
+ if (!headerObj) {
1672
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "header is not a JSON object");
1673
+ }
1674
+ return {
1675
+ kid: checkRecordHeader(headerObj),
1676
+ signingInput: Buffer.from(`${segments[0]}.${segments[1]}`, "ascii"),
1677
+ payload,
1678
+ signature
1679
+ };
1680
+ }
1681
+ function checkRecordHeader(header) {
1682
+ const alg = member(header, "alg");
1683
+ const typ = member(header, "typ");
1684
+ const kid = member(header, "kid");
1685
+ if (Object.keys(header).length !== 3 || typeof alg !== "string" || typeof typ !== "string" || typeof kid !== "string") {
1686
+ throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header must contain exactly alg, typ and kid");
1687
+ }
1688
+ if (alg !== RECORD_ALG || typ !== RECORD_TYP) {
1689
+ throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header alg/typ not allowed");
1690
+ }
1691
+ return kid;
1692
+ }
1693
+ function checkRecordKid(kid, revoked) {
1694
+ if (REVOKED_RECORD_KIDS.includes(kid) || revoked.includes(kid)) {
1695
+ throw new VerificationRecordError(VerificationRecordErrorCode.REVOKED_KEY, `kid ${kid} is revoked`);
1696
+ }
1697
+ if (!RECORD_KIDS.includes(kid)) {
1698
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not a record signing key`);
1699
+ }
1700
+ }
1701
+ function verifyRecordSignature(record, key) {
1702
+ if (record.signature.length !== 64) {
1703
+ throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature is not 64 bytes");
1704
+ }
1705
+ let valid = false;
1706
+ try {
1707
+ valid = (0, import_node_crypto3.verify)("sha256", record.signingInput, { key, dsaEncoding: "ieee-p1363" }, record.signature);
1708
+ } catch {
1709
+ valid = false;
1710
+ }
1711
+ if (!valid) {
1712
+ throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature does not verify");
1713
+ }
1714
+ }
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
+ }
864
1722
 
865
1723
  // src/client.ts
866
1724
  var MagicalAuthClient = class {
867
1725
  config;
868
1726
  tokenManager;
1727
+ recordKeys;
869
1728
  /**
870
1729
  * Creates a new MagicalAuthClient instance.
871
1730
  *
@@ -887,6 +1746,11 @@ var MagicalAuthClient = class {
887
1746
  this.config.httpClient,
888
1747
  this.config.logger
889
1748
  );
1749
+ this.recordKeys = new RecordKeyCache(
1750
+ this.config.baseUrl.replace(/\/+$/, ""),
1751
+ this.config.httpClient,
1752
+ this.config.timeout
1753
+ );
890
1754
  }
891
1755
  /**
892
1756
  * Check authentication eligibility for a phone number or PLMN.
@@ -911,9 +1775,10 @@ var MagicalAuthClient = class {
911
1775
  /**
912
1776
  * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
913
1777
  *
914
- * Automatically generates `fe_code` / `fe_hash` for device binding. If the aggregator
915
- * selects the 'link' strategy, `feCode` is included in the result so the caller can
916
- * 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()`.
917
1782
  *
918
1783
  * @param request - Prepare request parameters
919
1784
  * @param options - Per-request options (e.g., correlationId)
@@ -928,7 +1793,11 @@ var MagicalAuthClient = class {
928
1793
  const nonce = request.nonce || generateNonce();
929
1794
  const feCode = generateFeCode();
930
1795
  const feHash = computeFeHash(feCode);
931
- const requestWithHash = { ...request, nonce, fe_hash: feHash };
1796
+ const requestWithHash = {
1797
+ ...request,
1798
+ nonce,
1799
+ fe_hash: feHash
1800
+ };
932
1801
  const response = await this.doRequest(
933
1802
  "POST",
934
1803
  "/magic-auth/v2/auth/prepare",
@@ -936,8 +1805,9 @@ var MagicalAuthClient = class {
936
1805
  options
937
1806
  );
938
1807
  const result = { ...response };
939
- if (response.authentication_strategy === AuthenticationStrategy.LINK) {
940
- 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;
941
1811
  result.feCode = linkData.fe_code ?? feCode;
942
1812
  }
943
1813
  this.config.logger.debug("Auth prepared", {
@@ -946,6 +1816,39 @@ var MagicalAuthClient = class {
946
1816
  });
947
1817
  return result;
948
1818
  }
1819
+ /**
1820
+ * Prepares authentication for several phone numbers at once.
1821
+ *
1822
+ * Fans out one ordinary {@link prepare} call per number, so each number gets
1823
+ * its own carrier resolution, residency routing and session. Per-number
1824
+ * failures are returned as items rather than thrown; this only throws
1825
+ * {@link ValidationError}, and only before any request is issued.
1826
+ *
1827
+ * @param request - Shared prepare fields plus `phone_numbers` (1..10)
1828
+ * @param options - Per-request options (e.g., correlationId)
1829
+ * @returns One result per input number, in input order
1830
+ * @throws {ValidationError} If the list is empty, over the cap, has blank entries, or a shared prepare field is invalid
1831
+ */
1832
+ async prepareMultiple(request, options) {
1833
+ validatePrepareMultipleRequest(request);
1834
+ const { phone_numbers: phoneNumbers, nonce: _nonce, ...shared } = request;
1835
+ const derived = phoneNumbers.map(
1836
+ (phone_number) => ({ ...shared, phone_number })
1837
+ );
1838
+ for (const single of derived) {
1839
+ validatePrepareRequest(single);
1840
+ }
1841
+ this.config.logger.debug("Preparing auth for multiple numbers", {
1842
+ count: phoneNumbers.length
1843
+ });
1844
+ const settled = await Promise.allSettled(
1845
+ derived.map((single) => this.prepare(single, options))
1846
+ );
1847
+ return settled.map((outcome, index) => {
1848
+ const phone_number = phoneNumbers[index];
1849
+ return outcome.status === "fulfilled" ? { phone_number, ok: true, result: outcome.value } : { phone_number, ok: false, error: asMagicalAuthError(outcome.reason) };
1850
+ });
1851
+ }
949
1852
  /**
950
1853
  * Validates device binding codes and completes a link protocol session.
951
1854
  *
@@ -1003,6 +1906,51 @@ var MagicalAuthClient = class {
1003
1906
  this.config.logger.debug("Phone verification complete", { verified: response.verified });
1004
1907
  return response;
1005
1908
  }
1909
+ /**
1910
+ * Verifies a verification record returned by {@link verifyPhoneNumber}: the
1911
+ * ES256 signature against Glide's published record keys, then issuer,
1912
+ * the expected audience (default this client's ID), validity window, shape, nonce and origin.
1913
+ *
1914
+ * A missing or empty record fails with `RECORD_UNAVAILABLE`, so a caller
1915
+ * that requires records can pass `response.verification_record` straight in.
1916
+ *
1917
+ * @param record - Compact JWS from `VerifyPhoneNumberResponse.verification_record`
1918
+ * @param options - Expected nonce, expected audience, expected origins, audit mode, issuer override, extra revoked kids, clock
1919
+ * @returns The verified claims and how each sign-off was treated
1920
+ * @throws {VerificationRecordError} On any failed check; `code` is a {@link VerificationRecordErrorCode}
1921
+ */
1922
+ async verifyVerificationRecord(record, options) {
1923
+ return verifyVerificationRecord(record, options, {
1924
+ baseUrl: this.config.baseUrl,
1925
+ clientId: this.config.clientId,
1926
+ keys: this.recordKeys
1927
+ });
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
+ }
1006
1954
  /**
1007
1955
  * Retrieves the phone number associated with the device using digital credentials.
1008
1956
  *
@@ -1032,6 +1980,26 @@ var MagicalAuthClient = class {
1032
1980
  });
1033
1981
  return response;
1034
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
+ }
1035
2003
  /**
1036
2004
  * Reports when a user clicks the invoke/authenticate button.
1037
2005
  *
@@ -1209,13 +2177,20 @@ var MagicalAuthClient = class {
1209
2177
  };
1210
2178
  var ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1211
2179
  function generateNonce(length = 32) {
1212
- const bytes = (0, import_node_crypto2.randomBytes)(length);
2180
+ const bytes = (0, import_node_crypto5.randomBytes)(length);
1213
2181
  let result = "";
1214
2182
  for (let i = 0; i < length; i++) {
1215
2183
  result += ALPHANUMERIC.charAt(bytes[i] % ALPHANUMERIC.length);
1216
2184
  }
1217
2185
  return result;
1218
2186
  }
2187
+ function asMagicalAuthError(reason) {
2188
+ if (reason instanceof MagicalAuthError) {
2189
+ return reason;
2190
+ }
2191
+ const message = reason instanceof Error ? reason.message : "Prepare failed";
2192
+ return new MagicalAuthError(message, "UNKNOWN_ERROR", 0);
2193
+ }
1219
2194
 
1220
2195
  // src/logger.ts
1221
2196
  function createLogger(config = {}) {
@@ -1266,8 +2241,12 @@ var VERSION = _require("../package.json").version;
1266
2241
  BINDING_COOKIE_MAX_AGE,
1267
2242
  BINDING_COOKIE_PREFIX,
1268
2243
  BadRequestError,
2244
+ BiometricVerification,
1269
2245
  BrowserMismatchError,
2246
+ CarrierAppUnavailableError,
1270
2247
  CarrierNotEligibleError,
2248
+ CarrierRejectedError,
2249
+ CarrierTemporarilyUnavailableError,
1271
2250
  DEFAULT_BASE_URL,
1272
2251
  DEFAULT_TIMEOUT,
1273
2252
  DesktopWaitError,
@@ -1280,10 +2259,12 @@ var VERSION = _require("../package.json").version;
1280
2259
  MagicalAuthClient,
1281
2260
  MagicalAuthError,
1282
2261
  MissingBindingCookieError,
2262
+ PREPARE_MULTIPLE_MAX,
1283
2263
  PhoneNumberMismatchError,
1284
2264
  RateLimitError,
1285
2265
  SENSITIVE_KEYS,
1286
2266
  ServiceUnavailableError,
2267
+ SessionMetadataParentStrategy,
1287
2268
  SessionNotEligibleError,
1288
2269
  SessionNotFoundError,
1289
2270
  SessionStatus,
@@ -1293,6 +2274,9 @@ var VERSION = _require("../package.json").version;
1293
2274
  UseCase,
1294
2275
  VERSION,
1295
2276
  ValidationError,
2277
+ VerificationRecordError,
2278
+ VerificationRecordErrorCode,
2279
+ actionHash,
1296
2280
  assertValidFeCode,
1297
2281
  buildClearBindingCookieHeader,
1298
2282
  buildSetBindingCookieHeader,