@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.js CHANGED
@@ -36,6 +36,9 @@ var ErrorCode = {
36
36
  SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
37
37
  INVALID_VERIFICATION: "INVALID_VERIFICATION",
38
38
  CARRIER_NOT_ELIGIBLE: "CARRIER_NOT_ELIGIBLE",
39
+ CARRIER_REJECTED: "CARRIER_REJECTED",
40
+ CARRIER_APP_UNAVAILABLE: "CARRIER_APP_UNAVAILABLE",
41
+ CARRIER_TEMPORARILY_UNAVAILABLE: "CARRIER_TEMPORARILY_UNAVAILABLE",
39
42
  UNSUPPORTED_PLATFORM: "UNSUPPORTED_PLATFORM",
40
43
  PHONE_NUMBER_MISMATCH: "PHONE_NUMBER_MISMATCH",
41
44
  INVALID_CREDENTIAL_FORMAT: "INVALID_CREDENTIAL_FORMAT",
@@ -61,9 +64,17 @@ var MagicalAuthError = class extends Error {
61
64
  */
62
65
  status;
63
66
  /**
64
- * Request ID for debugging/support.
67
+ * The id of this request, the same value as the `X-Request-ID` response
68
+ * header. Quote it to Glide support.
65
69
  */
66
70
  requestId;
71
+ /**
72
+ * The session the failed request was about, once the server had read it from
73
+ * the request. Undefined when the request failed before naming a session, on
74
+ * operations that have none (eligibility, prepare), and from servers older
75
+ * than the release that added it.
76
+ */
77
+ sessionKey;
67
78
  /**
68
79
  * Additional error details.
69
80
  */
@@ -132,6 +143,26 @@ var CarrierNotEligibleError = class extends MagicalAuthError {
132
143
  this.name = "CarrierNotEligibleError";
133
144
  }
134
145
  };
146
+ var CarrierRejectedError = class extends MagicalAuthError {
147
+ constructor(message = "The carrier rejected the authentication request", requestId, details) {
148
+ super(message, "CARRIER_REJECTED", 422, requestId, details);
149
+ this.name = "CarrierRejectedError";
150
+ }
151
+ };
152
+ var CarrierAppUnavailableError = class extends MagicalAuthError {
153
+ constructor(message = "Carrier app unavailable on the phone that scanned the QR code", requestId, details) {
154
+ super(message, "CARRIER_APP_UNAVAILABLE", 422, requestId, details);
155
+ this.name = "CarrierAppUnavailableError";
156
+ }
157
+ };
158
+ var CarrierTemporarilyUnavailableError = class extends MagicalAuthError {
159
+ retryAfter;
160
+ constructor(message, retryAfter, requestId, details) {
161
+ super(message, "CARRIER_TEMPORARILY_UNAVAILABLE", 422, requestId, details);
162
+ this.name = "CarrierTemporarilyUnavailableError";
163
+ this.retryAfter = retryAfter;
164
+ }
165
+ };
135
166
  var UnsupportedPlatformError = class extends MagicalAuthError {
136
167
  constructor(message = "Platform not supported", requestId) {
137
168
  super(message, "UNSUPPORTED_PLATFORM", 422, requestId);
@@ -212,9 +243,32 @@ var MissingBindingCookieError = class extends DeviceBindingError {
212
243
  var DesktopWaitError = class extends MagicalAuthError {
213
244
  waitResponse;
214
245
  constructor(waitResponse) {
215
- super(waitResponse.message, "DESKTOP_WAIT", 202);
246
+ super(waitResponse.message, "DESKTOP_WAIT", 202, waitResponse.request_id);
216
247
  this.name = "DesktopWaitError";
217
248
  this.waitResponse = waitResponse;
249
+ Object.assign(this, { sessionKey: waitResponse.session_key });
250
+ }
251
+ };
252
+ var VerificationRecordErrorCode = {
253
+ MALFORMED: "MALFORMED",
254
+ DISALLOWED_HEADER: "DISALLOWED_HEADER",
255
+ UNKNOWN_KEY: "UNKNOWN_KEY",
256
+ BAD_SIGNATURE: "BAD_SIGNATURE",
257
+ WRONG_ISSUER: "WRONG_ISSUER",
258
+ WRONG_AUDIENCE: "WRONG_AUDIENCE",
259
+ EXPIRED: "EXPIRED",
260
+ NOT_YET_VALID: "NOT_YET_VALID",
261
+ NONCE_MISMATCH: "NONCE_MISMATCH",
262
+ ORIGIN_MISMATCH: "ORIGIN_MISMATCH",
263
+ UNSUPPORTED_VERSION: "UNSUPPORTED_VERSION",
264
+ REVOKED_KEY: "REVOKED_KEY",
265
+ RECORD_UNAVAILABLE: "RECORD_UNAVAILABLE",
266
+ STEP_UP_REJECTED: "STEP_UP_REJECTED"
267
+ };
268
+ var VerificationRecordError = class extends MagicalAuthError {
269
+ constructor(code, message) {
270
+ super(`verification record: ${code}: ${message}`, code, 0);
271
+ this.name = "VerificationRecordError";
218
272
  }
219
273
  };
220
274
  function parseRetryAfter(headers) {
@@ -233,9 +287,10 @@ function parseRetryAfter(headers) {
233
287
  return void 0;
234
288
  }
235
289
  function createErrorFromResponse(response, headers) {
236
- const { code, message, request_id, details, status, trace_id, span_id, timestamp, service } = response;
290
+ const { code, message, request_id, session_key, details, status, trace_id, span_id, timestamp, service } = response;
237
291
  const error = createTypedError(code, message, request_id, details, status, headers);
238
292
  return Object.assign(error, {
293
+ sessionKey: session_key,
239
294
  traceId: trace_id,
240
295
  spanId: span_id,
241
296
  timestamp,
@@ -243,6 +298,8 @@ function createErrorFromResponse(response, headers) {
243
298
  });
244
299
  }
245
300
  function createTypedError(code, message, request_id, details, status, headers) {
301
+ const rawRetry = details?.retry_after_seconds;
302
+ const detailRetry = typeof rawRetry === "number" && Number.isFinite(rawRetry) && rawRetry >= 0 && Number.isInteger(rawRetry) ? rawRetry : void 0;
246
303
  switch (code) {
247
304
  case "BAD_REQUEST":
248
305
  return new BadRequestError(message, request_id);
@@ -259,6 +316,25 @@ function createTypedError(code, message, request_id, details, status, headers) {
259
316
  return new SessionNotFoundError(message, request_id);
260
317
  case "CARRIER_NOT_ELIGIBLE":
261
318
  return new CarrierNotEligibleError(message, request_id);
319
+ case "CARRIER_REJECTED":
320
+ return new CarrierRejectedError(
321
+ message,
322
+ request_id,
323
+ details
324
+ );
325
+ case "CARRIER_APP_UNAVAILABLE":
326
+ return new CarrierAppUnavailableError(
327
+ message,
328
+ request_id,
329
+ details
330
+ );
331
+ case "CARRIER_TEMPORARILY_UNAVAILABLE":
332
+ return new CarrierTemporarilyUnavailableError(
333
+ message,
334
+ parseRetryAfter(headers) ?? detailRetry,
335
+ request_id,
336
+ details
337
+ );
262
338
  case "UNSUPPORTED_PLATFORM":
263
339
  return new UnsupportedPlatformError(message, request_id);
264
340
  case "INVALID_CREDENTIAL_FORMAT":
@@ -281,12 +357,15 @@ function createTypedError(code, message, request_id, details, status, headers) {
281
357
  case "MISSING_BINDING_COOKIE":
282
358
  return new MissingBindingCookieError(message, request_id);
283
359
  case "RATE_LIMIT_EXCEEDED":
284
- return new RateLimitError(message, parseRetryAfter(headers), request_id);
360
+ return new RateLimitError(message, parseRetryAfter(headers) ?? detailRetry, request_id);
285
361
  case "INTERNAL_SERVER_ERROR":
286
362
  return new InternalServerError(message, request_id);
287
363
  case "SERVICE_UNAVAILABLE":
288
364
  return new ServiceUnavailableError(message, request_id);
289
365
  default:
366
+ if (status === 429) {
367
+ return new RateLimitError(message, parseRetryAfter(headers) ?? detailRetry, request_id);
368
+ }
290
369
  return new MagicalAuthError(
291
370
  message,
292
371
  code,
@@ -323,7 +402,9 @@ var TokenManager = class {
323
402
  * in progress, subsequent calls will await the same promise.
324
403
  *
325
404
  * @returns A valid access token
326
- * @throws {UnauthorizedError} If token fetch fails
405
+ * @throws {RateLimitError} If the token endpoint returns 429 (includes Retry-After when present)
406
+ * @throws {ServiceUnavailableError} If the token endpoint returns 5xx or temporarily_unavailable
407
+ * @throws {UnauthorizedError} For other token fetch failures (e.g. 401)
327
408
  */
328
409
  async getToken() {
329
410
  if (this.token && Date.now() < this.expiresAt) {
@@ -360,17 +441,28 @@ var TokenManager = class {
360
441
  body: "grant_type=client_credentials"
361
442
  });
362
443
  if (!response.ok) {
363
- let errorMessage = "Token request failed";
444
+ let errorMessage2 = "Token request failed";
445
+ let oauthError;
364
446
  try {
365
447
  const errorBody = await response.json();
448
+ oauthError = errorBody.error;
366
449
  if (errorBody.error_description) {
367
- errorMessage = errorBody.error_description;
450
+ errorMessage2 = errorBody.error_description;
368
451
  } else if (errorBody.error) {
369
- errorMessage = errorBody.error;
452
+ errorMessage2 = errorBody.error;
370
453
  }
371
454
  } catch {
372
455
  }
373
- throw new UnauthorizedError(errorMessage);
456
+ if (response.status === 429) {
457
+ throw new RateLimitError(errorMessage2, parseRetryAfter(response.headers));
458
+ }
459
+ if (response.status >= 500 || oauthError === "temporarily_unavailable") {
460
+ throw new ServiceUnavailableError(errorMessage2);
461
+ }
462
+ if (response.status === 401 || oauthError === "invalid_client") {
463
+ throw new UnauthorizedError(errorMessage2);
464
+ }
465
+ throw new UnauthorizedError(errorMessage2);
374
466
  }
375
467
  const data = await response.json();
376
468
  if (!data.access_token) {
@@ -531,12 +623,14 @@ function validateCookieAttr(name, value) {
531
623
  throw new Error("Invalid cookie path: must start with '/'");
532
624
  }
533
625
  }
534
- function getCompletionPageHtml(completeEndpoint) {
626
+ function getCompletionPageHtml(completeEndpoint, options) {
535
627
  if (!completeEndpoint.startsWith("/") || completeEndpoint.startsWith("//")) {
536
628
  throw new Error(
537
629
  '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.'
538
630
  );
539
631
  }
632
+ const serializedCompleteEndpoint = JSON.stringify(completeEndpoint).replace(/</g, "\\u003c");
633
+ const beacon = options?.beacon === true;
540
634
  return `<!DOCTYPE html>
541
635
  <html lang="en">
542
636
  <head>
@@ -604,34 +698,177 @@ function getCompletionPageHtml(completeEndpoint) {
604
698
  <div class="badge">Action required</div>
605
699
  </div>
606
700
  <script>
607
- (async function() {
701
+ ${beacon ? `(async function() {
608
702
  var fragment = new URLSearchParams(window.location.hash.substring(1));
609
703
  var aggCode = fragment.get('agg_code');
610
704
  var sessionKey = fragment.get('session_key');
705
+ var closeSent = false;
706
+ var survivedSent = false;
707
+ var closeTrigger = '';
708
+ var hiddenAt = 0;
709
+
710
+ function pageFields() {
711
+ var o = { has_agg_code: !!aggCode, has_session_key: !!sessionKey };
712
+ if (sessionKey && /^[A-Za-z0-9_-]{1,64}$/.test(sessionKey)) o.session_key = sessionKey;
713
+ return o;
714
+ }
715
+
716
+ function sendPageBeacon(event, extra) {
717
+ try {
718
+ var payload = Object.assign({ event: event }, pageFields(), extra || {});
719
+ var url = window.location.pathname;
720
+ var body = JSON.stringify(payload);
721
+ try {
722
+ if (navigator.sendBeacon && navigator.sendBeacon(url, new Blob([body], { type: 'application/json' }))) return;
723
+ } catch (e) {}
724
+ fetch(url, {
725
+ method: 'POST',
726
+ headers: { 'Content-Type': 'application/json' },
727
+ body: body,
728
+ keepalive: true,
729
+ credentials: 'same-origin'
730
+ }).catch(function() {});
731
+ } catch (e) {}
732
+ }
733
+
734
+ function showCloseHint() {
735
+ document.getElementById('hint').textContent = 'You may close this tab.';
736
+ document.getElementById('hint').classList.remove('hidden');
737
+ }
738
+
739
+ sendPageBeacon('page_start');
611
740
 
612
741
  window.history.replaceState(null, '', window.location.pathname + window.location.search);
613
742
 
614
743
  if (!aggCode || !sessionKey) {
744
+ sendPageBeacon('invalid_link');
615
745
  showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');
616
746
  return;
617
747
  }
618
748
 
619
749
  try {
620
- var res = await fetch(${JSON.stringify(completeEndpoint)}, {
750
+ var res = await fetch(${serializedCompleteEndpoint}, {
621
751
  method: 'POST',
622
752
  credentials: 'include',
623
753
  headers: { 'Content-Type': 'application/json' },
624
754
  body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })
625
755
  });
626
756
 
757
+ var outcome = { ok: !!res.ok, status: res.status };
627
758
  if (res.ok) {
759
+ sendPageBeacon('post_outcome', outcome);
628
760
  var signalKey = 'glide_signal_' + sessionKey;
761
+ var sigmetaKey = 'glide_sigmeta_' + sessionKey;
762
+ var signalStored = false;
629
763
  try {
630
764
  localStorage.setItem(signalKey, sessionKey);
765
+ signalStored = true;
766
+ localStorage.setItem(sigmetaKey, String(Date.now()));
767
+ } catch(e) {}
768
+ if (signalStored) {
631
769
  setTimeout(function() {
632
- try { localStorage.removeItem(signalKey); } catch(e) {}
633
- }, 5000);
770
+ try { localStorage.removeItem(signalKey); localStorage.removeItem(sigmetaKey); } catch(e) {}
771
+ }, 600000);
772
+ }
773
+ tryClose();
774
+ } else {
775
+ var code = '';
776
+ 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 (_) {}
777
+ sendPageBeacon('post_outcome', outcome);
778
+ var err = friendlyError(code);
779
+ showError(err.title, err.points, err.illust);
780
+ }
781
+ } catch (e) {
782
+ sendPageBeacon('post_outcome', { ok: false, status: 0 });
783
+ showError('Connection issue', ['We could not reach the server.', 'Check your internet connection and try again.'], 'wifi');
784
+ }
785
+
786
+ function friendlyError(code) {
787
+ switch (code) {
788
+ case 'MISSING_BINDING_COOKIE':
789
+ case 'BROWSER_MISMATCH':
790
+ 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' };
791
+ default:
792
+ return { title: 'Verification could not be completed', points: ['Something went wrong during verification.', 'Please go back and try again.'], illust: 'retry' };
793
+ }
794
+ }
795
+
796
+ function reportClose(trigger) {
797
+ if (closeSent) return;
798
+ closeSent = true;
799
+ closeTrigger = trigger;
800
+ sendPageBeacon('close', {
801
+ close_outcome: (trigger === 'timeout' && document.visibilityState === 'visible') ? 'failed' : 'unknown',
802
+ trigger: trigger,
803
+ visibility_state: document.visibilityState
804
+ });
805
+ }
806
+
807
+ function reportTabSurvived() {
808
+ if (!closeSent || survivedSent) return;
809
+ survivedSent = true;
810
+ var hiddenMs = hiddenAt ? Date.now() - hiddenAt : 0;
811
+ if (hiddenMs < 0) hiddenMs = 0;
812
+ sendPageBeacon('tab_survived', { hidden_ms: hiddenMs, trigger: closeTrigger });
813
+ }
814
+
815
+ function tryClose() {
816
+ document.querySelector('.spinner').classList.add('hidden');
817
+ if ((document.hidden || document.visibilityState === 'hidden') && !hiddenAt) hiddenAt = Date.now();
818
+ document.addEventListener('visibilitychange', function() {
819
+ if (document.visibilityState === 'visible') {
820
+ showCloseHint();
821
+ reportTabSurvived();
822
+ hiddenAt = 0;
823
+ return;
824
+ }
825
+ if (!hiddenAt) hiddenAt = Date.now();
826
+ reportClose('visibilitychange');
827
+ });
828
+ window.addEventListener('pagehide', function() {
829
+ if (!hiddenAt) hiddenAt = Date.now();
830
+ reportClose('pagehide');
831
+ });
832
+ window.close();
833
+ try { window.open('', '_self').close(); } catch(e) {}
834
+ setTimeout(function() {
835
+ reportClose('timeout');
836
+ if (document.visibilityState === 'visible') showCloseHint();
837
+ }, 300);
838
+ }` : `(async function() {
839
+ var fragment = new URLSearchParams(window.location.hash.substring(1));
840
+ var aggCode = fragment.get('agg_code');
841
+ var sessionKey = fragment.get('session_key');
842
+
843
+ window.history.replaceState(null, '', window.location.pathname + window.location.search);
844
+
845
+ if (!aggCode || !sessionKey) {
846
+ showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');
847
+ return;
848
+ }
849
+
850
+ try {
851
+ var res = await fetch(${serializedCompleteEndpoint}, {
852
+ method: 'POST',
853
+ credentials: 'include',
854
+ headers: { 'Content-Type': 'application/json' },
855
+ body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })
856
+ });
857
+
858
+ if (res.ok) {
859
+ var signalKey = 'glide_signal_' + sessionKey;
860
+ var sigmetaKey = 'glide_sigmeta_' + sessionKey;
861
+ var signalStored = false;
862
+ try {
863
+ localStorage.setItem(signalKey, sessionKey);
864
+ signalStored = true;
865
+ localStorage.setItem(sigmetaKey, String(Date.now()));
634
866
  } catch(e) {}
867
+ if (signalStored) {
868
+ setTimeout(function() {
869
+ try { localStorage.removeItem(signalKey); localStorage.removeItem(sigmetaKey); } catch(e) {}
870
+ }, 600000);
871
+ }
635
872
  tryClose();
636
873
  } else {
637
874
  var code = '';
@@ -661,7 +898,7 @@ function getCompletionPageHtml(completeEndpoint) {
661
898
  document.getElementById('hint').textContent = 'You may close this tab.';
662
899
  document.getElementById('hint').classList.remove('hidden');
663
900
  }, 300);
664
- }
901
+ }`}
665
902
 
666
903
  function showError(title, points, illust) {
667
904
  document.getElementById('loading').classList.add('hidden');
@@ -696,8 +933,11 @@ var AuthenticationStrategy = {
696
933
  TS43: "ts43",
697
934
  LINK: "link",
698
935
  DESKTOP: "desktop",
936
+ PASSKEY: "passkey",
937
+ CALL: "call",
699
938
  NONE: ""
700
939
  };
940
+ var SessionMetadataParentStrategy = "parent_strategy";
701
941
  var SessionStatus = {
702
942
  PENDING: "pending",
703
943
  SCANNED: "scanned",
@@ -705,6 +945,16 @@ var SessionStatus = {
705
945
  COMPLETED: "completed",
706
946
  FAILED: "failed"
707
947
  };
948
+ var BiometricVerification = {
949
+ VERIFIED: "VERIFIED",
950
+ FAILED: "FAILED",
951
+ NOT_ENROLLED: "NOT_ENROLLED",
952
+ UNSUPPORTED: "UNSUPPORTED",
953
+ NOT_REQUESTED: "NOT_REQUESTED"
954
+ };
955
+
956
+ // src/models/prepare-multiple.ts
957
+ var PREPARE_MULTIPLE_MAX = 10;
708
958
 
709
959
  // src/validation.ts
710
960
  function validatePrepareRequest(request) {
@@ -745,6 +995,18 @@ function validateGetPhoneNumberRequest(request) {
745
995
  throw new ValidationError("Request validation failed", errors);
746
996
  }
747
997
  }
998
+ function validateDeletePasskeysRequest(request) {
999
+ const errors = {};
1000
+ if (!/^\+[1-9]\d{6,14}$/.test(request?.phone_number ?? "")) {
1001
+ errors.phone_number = "phone_number must be E.164";
1002
+ }
1003
+ if (!request?.origin) {
1004
+ errors.origin = "origin is required";
1005
+ }
1006
+ if (Object.keys(errors).length > 0) {
1007
+ throw new ValidationError("Request validation failed", errors);
1008
+ }
1009
+ }
748
1010
  function validateSessionId(sessionId) {
749
1011
  if (!sessionId) {
750
1012
  throw new ValidationError("Request validation failed", {
@@ -792,11 +1054,599 @@ function validateEligibilityRequest(request) {
792
1054
  throw new ValidationError("Request validation failed", errors);
793
1055
  }
794
1056
  }
1057
+ function validatePrepareMultipleRequest(request) {
1058
+ if (request == null) {
1059
+ throw new ValidationError("Request validation failed", {
1060
+ request: "request is required"
1061
+ });
1062
+ }
1063
+ const numbers = request.phone_numbers;
1064
+ let message = null;
1065
+ if (!Array.isArray(numbers) || numbers.length === 0) {
1066
+ message = "phone_numbers must contain at least one number";
1067
+ } else if (numbers.length > PREPARE_MULTIPLE_MAX) {
1068
+ message = `phone_numbers must contain at most ${PREPARE_MULTIPLE_MAX} numbers`;
1069
+ } else if (Array.from(numbers).some((n) => typeof n !== "string" || !n.trim())) {
1070
+ message = "phone_numbers must not contain blank entries";
1071
+ }
1072
+ if (message) {
1073
+ throw new ValidationError("Request validation failed", { phone_numbers: message });
1074
+ }
1075
+ }
1076
+
1077
+ // src/verification-record/jwk.ts
1078
+ import { createPublicKey } from "crypto";
1079
+
1080
+ // src/verification-record/decode.ts
1081
+ var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]*$/;
1082
+ function decodeBase64URL(segment) {
1083
+ if (!BASE64URL_ALPHABET.test(segment) || segment.length % 4 === 1) {
1084
+ return null;
1085
+ }
1086
+ const bytes = Buffer.from(segment, "base64url");
1087
+ return bytes.toString("base64url") === segment ? bytes : null;
1088
+ }
1089
+ function isJsonObject(value) {
1090
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1091
+ }
1092
+ function parseJsonObject(text) {
1093
+ try {
1094
+ const value = JSON.parse(text);
1095
+ return isJsonObject(value) ? value : null;
1096
+ } catch {
1097
+ return null;
1098
+ }
1099
+ }
1100
+ function member(obj, name) {
1101
+ return Object.hasOwn(obj, name) ? obj[name] : void 0;
1102
+ }
1103
+ var MemberReader = class {
1104
+ constructor(obj) {
1105
+ this.obj = obj;
1106
+ }
1107
+ obj;
1108
+ ok = true;
1109
+ str(name) {
1110
+ return this.read(name, (v) => typeof v === "string");
1111
+ }
1112
+ bool(name) {
1113
+ return this.read(name, (v) => typeof v === "boolean");
1114
+ }
1115
+ int(name) {
1116
+ return this.read(name, (v) => Number.isSafeInteger(v));
1117
+ }
1118
+ /** A nested object member; absent yields undefined. Present null is a wrong type. */
1119
+ object(name) {
1120
+ return this.read(name, isJsonObject);
1121
+ }
1122
+ read(name, accept) {
1123
+ if (!Object.hasOwn(this.obj, name)) return void 0;
1124
+ const value = this.obj[name];
1125
+ if (accept(value)) return value;
1126
+ this.ok = false;
1127
+ return void 0;
1128
+ }
1129
+ };
1130
+
1131
+ // src/verification-record/jwk.ts
1132
+ var RECORD_ALG = "ES256";
1133
+ function parseJWKS(body) {
1134
+ const doc = parseJsonObject(body);
1135
+ if (!doc) {
1136
+ throw new Error("JWKS is not a JSON object");
1137
+ }
1138
+ const entries = member(doc, "keys");
1139
+ if (!Array.isArray(entries)) {
1140
+ throw new Error("JWKS keys is not an array");
1141
+ }
1142
+ const keys = [];
1143
+ for (const entry of entries) {
1144
+ if (!isJsonObject(entry)) continue;
1145
+ const r = new MemberReader(entry);
1146
+ const k = {
1147
+ kty: r.str("kty") ?? "",
1148
+ crv: r.str("crv") ?? "",
1149
+ use: r.str("use") ?? "",
1150
+ alg: r.str("alg") ?? "",
1151
+ kid: r.str("kid") ?? "",
1152
+ x: r.str("x") ?? "",
1153
+ y: r.str("y") ?? ""
1154
+ };
1155
+ if (r.ok) keys.push(k);
1156
+ }
1157
+ return keys;
1158
+ }
1159
+ function recordPublicKey(k) {
1160
+ if (k.kty !== "EC" || k.crv !== "P-256" || k.use !== "sig" || k.alg !== RECORD_ALG) {
1161
+ throw new Error("JWK is not an EC P-256 ES256 signing key");
1162
+ }
1163
+ const x = decodeBase64URL(k.x);
1164
+ const y = decodeBase64URL(k.y);
1165
+ if (!x || !y || x.length !== 32 || y.length !== 32) {
1166
+ throw new Error("JWK coordinates are not 32-byte base64url");
1167
+ }
1168
+ try {
1169
+ return createPublicKey({ key: { kty: "EC", crv: "P-256", x: k.x, y: k.y }, format: "jwk" });
1170
+ } catch {
1171
+ throw new Error("JWK point is not on P-256");
1172
+ }
1173
+ }
1174
+
1175
+ // src/verification-record/jwks.ts
1176
+ var DEFAULT_MAX_AGE_SECONDS = 300;
1177
+ var REFRESH_INTERVAL_MS = 6e4;
1178
+ var MAX_JWKS_BYTES = 1 << 20;
1179
+ var JWKS_PATH = "/.well-known/us/jwks.json";
1180
+ var RecordKeyCache = class {
1181
+ constructor(baseUrl, httpClient, timeoutMs) {
1182
+ this.baseUrl = baseUrl;
1183
+ this.httpClient = httpClient;
1184
+ this.timeoutMs = timeoutMs;
1185
+ }
1186
+ baseUrl;
1187
+ httpClient;
1188
+ timeoutMs;
1189
+ now = Date.now;
1190
+ keys = null;
1191
+ expiresAt = 0;
1192
+ lastRefresh = -Infinity;
1193
+ backoffUntil = -Infinity;
1194
+ queue = Promise.resolve();
1195
+ key(kid) {
1196
+ const run = this.queue.then(() => this.resolve(kid));
1197
+ this.queue = run.catch(() => void 0);
1198
+ return run;
1199
+ }
1200
+ /**
1201
+ * Refetches when the cache has expired, or when kid is missing and the last
1202
+ * refresh is at least 60 s old. After a failed refresh the previous keys are
1203
+ * kept and further refreshes are refused for 60 s.
1204
+ */
1205
+ async resolve(kid) {
1206
+ const now = this.now();
1207
+ const cached = this.keys?.has(kid) ?? false;
1208
+ const expired = this.keys === null || now >= this.expiresAt;
1209
+ if (expired || !cached && now - this.lastRefresh >= REFRESH_INTERVAL_MS) {
1210
+ if (now < this.backoffUntil) {
1211
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, "record key fetch is backing off after a failure");
1212
+ }
1213
+ try {
1214
+ await this.refresh(now);
1215
+ } catch (e) {
1216
+ this.backoffUntil = now + REFRESH_INTERVAL_MS;
1217
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `fetch record keys: ${errorMessage(e)}`);
1218
+ }
1219
+ }
1220
+ const jwk = this.keys?.get(kid);
1221
+ if (!jwk) {
1222
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not published`);
1223
+ }
1224
+ try {
1225
+ return recordPublicKey(jwk);
1226
+ } catch (e) {
1227
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid}: ${errorMessage(e)}`);
1228
+ }
1229
+ }
1230
+ async refresh(now) {
1231
+ this.lastRefresh = now;
1232
+ const doc = await this.fetch(`${this.baseUrl}${JWKS_PATH}`);
1233
+ const keys = /* @__PURE__ */ new Map();
1234
+ for (const k of doc.keys) {
1235
+ if (!keys.has(k.kid)) keys.set(k.kid, k);
1236
+ }
1237
+ this.keys = keys;
1238
+ this.expiresAt = now + doc.maxAgeSeconds * 1e3;
1239
+ }
1240
+ async fetch(url) {
1241
+ const controller = new AbortController();
1242
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1243
+ try {
1244
+ const response = await this.httpClient.request({
1245
+ method: "GET",
1246
+ url,
1247
+ headers: { Accept: "application/json" },
1248
+ signal: controller.signal
1249
+ });
1250
+ if (response.status !== 200) {
1251
+ throw new Error(`${url}: HTTP ${response.status}`);
1252
+ }
1253
+ const body = await response.text();
1254
+ if (Buffer.byteLength(body, "utf8") > MAX_JWKS_BYTES) {
1255
+ throw new Error(`${url}: JWKS is larger than 1 MiB`);
1256
+ }
1257
+ const keys = prefixErrors(url, () => parseJWKS(body));
1258
+ return { keys, maxAgeSeconds: cacheMaxAge(response.headers?.get("cache-control") ?? null) };
1259
+ } catch (e) {
1260
+ if (controller.signal.aborted) {
1261
+ throw new Error(`${url}: timed out after ${this.timeoutMs}ms`);
1262
+ }
1263
+ throw e;
1264
+ } finally {
1265
+ clearTimeout(timer);
1266
+ }
1267
+ }
1268
+ };
1269
+ function cacheMaxAge(cacheControl) {
1270
+ for (const directive of (cacheControl ?? "").split(",")) {
1271
+ const trimmed = directive.trim();
1272
+ const eq = trimmed.indexOf("=");
1273
+ if (eq < 0 || trimmed.slice(0, eq).toLowerCase() !== "max-age") continue;
1274
+ const value = trimmed.slice(eq + 1);
1275
+ const seconds = /^[+-]?\d+$/.test(value) ? Number(value) : NaN;
1276
+ if (Number.isSafeInteger(seconds) && seconds >= 0) return seconds;
1277
+ }
1278
+ return DEFAULT_MAX_AGE_SECONDS;
1279
+ }
1280
+ function prefixErrors(url, fn) {
1281
+ try {
1282
+ return fn();
1283
+ } catch (e) {
1284
+ throw new Error(`${url}: ${errorMessage(e)}`);
1285
+ }
1286
+ }
1287
+ function errorMessage(e) {
1288
+ return e instanceof Error ? e.message : String(e);
1289
+ }
1290
+
1291
+ // src/verification-record/verify.ts
1292
+ import { verify } from "crypto";
1293
+
1294
+ // src/verification-record/shape.ts
1295
+ var USE_CASE = "VerifyPhoneNumber";
1296
+ var MAX_LIFETIME_SECONDS = 60;
1297
+ var RECORD_VERSION = "1.0";
1298
+ var CARRIER_ROLE = "carrier";
1299
+ var CARRIER_SIGNER_PREFIX = "carrier:";
1300
+ function malformed(message) {
1301
+ return new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, message);
1302
+ }
1303
+ function isNonEmptyString(value) {
1304
+ return typeof value === "string" && value !== "";
1305
+ }
1306
+ function checkClaimShape(obj, iat, exp) {
1307
+ if (typeof member(obj, "verified") !== "boolean") {
1308
+ throw malformed("verified must be a boolean");
1309
+ }
1310
+ for (const name of ["jti", "nonce", "sub"]) {
1311
+ if (!isNonEmptyString(member(obj, name))) {
1312
+ throw malformed(`${name} must be a non-empty string`);
1313
+ }
1314
+ }
1315
+ if (!member(obj, "sub").startsWith("tel:+")) {
1316
+ throw malformed("sub must be tel:+E164");
1317
+ }
1318
+ for (const name of ["origin", "biometric_verification"]) {
1319
+ if (typeof member(obj, name) !== "string") throw malformed(`${name} must be a string`);
1320
+ }
1321
+ if (member(obj, "nbf") !== iat) {
1322
+ throw malformed("nbf must equal iat");
1323
+ }
1324
+ if (member(obj, "use_case") !== USE_CASE) {
1325
+ throw malformed(`use_case must be ${USE_CASE}`);
1326
+ }
1327
+ if (exp < iat + 1 || exp > iat + MAX_LIFETIME_SECONDS) {
1328
+ throw malformed("exp must be 1 to 60 seconds after iat");
1329
+ }
1330
+ const signOffs = readSignOffs(member(obj, "sign_offs"));
1331
+ if (!signOffs) {
1332
+ throw malformed("sign_offs must be an array of well-formed entries");
1333
+ }
1334
+ const factors = readFactors(obj);
1335
+ if (!factors) {
1336
+ throw malformed("factors must be an array of strings");
1337
+ }
1338
+ if (factors.length === 1 && factors[0] === "passkey") {
1339
+ if (signOffs.some((s) => s.role === CARRIER_ROLE)) {
1340
+ throw malformed("a passkey-only record must have no carrier sign-off");
1341
+ }
1342
+ return { signOffs, factors };
1343
+ }
1344
+ if (!oneCarrierSignOff(signOffs)) {
1345
+ throw malformed("sign_offs must have exactly one carrier:<id> carrier entry");
1346
+ }
1347
+ return { signOffs, factors };
1348
+ }
1349
+ function readFactors(obj) {
1350
+ const raw = member(obj, "factors");
1351
+ if (raw === void 0) return ["carrier"];
1352
+ if (!Array.isArray(raw) || !raw.every((f) => typeof f === "string")) return null;
1353
+ return raw;
1354
+ }
1355
+ function readSignOffs(raw) {
1356
+ if (!Array.isArray(raw)) return null;
1357
+ const signOffs = [];
1358
+ for (const entry of raw) {
1359
+ const signOff = isJsonObject(entry) ? readSignOff(entry) : null;
1360
+ if (!signOff) return null;
1361
+ signOffs.push(signOff);
1362
+ }
1363
+ return signOffs;
1364
+ }
1365
+ function readSignOff(entry) {
1366
+ const r = new MemberReader(entry);
1367
+ const role = r.str("role");
1368
+ const signer = r.str("signer");
1369
+ const status = r.str("status");
1370
+ const reason = r.str("reason");
1371
+ const format = r.str("format");
1372
+ const token = r.str("token");
1373
+ if (!r.ok || !isNonEmptyString(role) || !isNonEmptyString(signer)) return null;
1374
+ const signOff = { role, signer, status };
1375
+ if (reason !== void 0) signOff.reason = reason;
1376
+ if (format !== void 0) signOff.format = format;
1377
+ if (token !== void 0) signOff.token = token;
1378
+ if (status === "unavailable") return isNonEmptyString(reason) ? signOff : null;
1379
+ if (status === "present") return isNonEmptyString(format) && isNonEmptyString(token) ? signOff : null;
1380
+ return null;
1381
+ }
1382
+ function oneCarrierSignOff(signOffs) {
1383
+ const carriers = signOffs.filter((s) => s.role === CARRIER_ROLE);
1384
+ const signer = carriers.length === 1 ? carriers[0]?.signer ?? "" : "";
1385
+ return signer.length > CARRIER_SIGNER_PREFIX.length && signer.startsWith(CARRIER_SIGNER_PREFIX);
1386
+ }
1387
+ function carrierIDMatchesSignOff(id, signOffs) {
1388
+ const signer = signOffs.find((s) => s.role === CARRIER_ROLE)?.signer ?? "";
1389
+ return signer === CARRIER_SIGNER_PREFIX + id;
1390
+ }
1391
+
1392
+ // src/verification-record/claims.ts
1393
+ var IAT_LEEWAY_SECONDS = 60;
1394
+ function checkRecordClaims(payload, want) {
1395
+ const obj = parseJsonObject(payload.toString("utf8"));
1396
+ if (!obj) {
1397
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "payload is not a JSON object");
1398
+ }
1399
+ if (member(obj, "ver") !== RECORD_VERSION) {
1400
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNSUPPORTED_VERSION, 'ver must be "1.0"');
1401
+ }
1402
+ const iss = member(obj, "iss");
1403
+ if (typeof iss !== "string" || iss !== want.issuer) {
1404
+ throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_ISSUER, `iss does not match ${want.issuer}`);
1405
+ }
1406
+ const aud = member(obj, "aud");
1407
+ if (typeof aud !== "string" || aud !== want.audience) {
1408
+ throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_AUDIENCE, "aud does not match the expected audience");
1409
+ }
1410
+ const { iat, exp } = checkRecordTimes(obj, want);
1411
+ const { signOffs, factors } = checkClaimShape(obj, iat, exp);
1412
+ const verified = member(obj, "verified");
1413
+ const r = new MemberReader(obj);
1414
+ const claims = {
1415
+ ver: RECORD_VERSION,
1416
+ iss,
1417
+ aud,
1418
+ iat,
1419
+ nbf: iat,
1420
+ exp,
1421
+ verified,
1422
+ sign_offs: signOffs,
1423
+ factors,
1424
+ jti: r.str("jti") ?? "",
1425
+ nonce: r.str("nonce") ?? "",
1426
+ use_case: r.str("use_case") ?? "",
1427
+ sub: r.str("sub") ?? "",
1428
+ origin: r.str("origin") ?? "",
1429
+ biometric_verification: r.str("biometric_verification") ?? ""
1430
+ };
1431
+ assignDefined(claims, "strategy", r.str("strategy"));
1432
+ assignDefined(claims, "action_hash", r.str("action_hash"));
1433
+ assignDefined(claims, "phone_number_details", readPhoneNumberDetails(r));
1434
+ assignDefined(claims, "carrier", readCarrier(r));
1435
+ assignDefined(claims, "sim_swap", readSwap(r, "sim_swap"));
1436
+ assignDefined(claims, "device_swap", readSwap(r, "device_swap"));
1437
+ assignDefined(claims, "live_call", readLiveCall(r, "live_call"));
1438
+ if (!r.ok) {
1439
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "claims have the wrong JSON types");
1440
+ }
1441
+ if (claims.carrier !== void 0 && !carrierIDMatchesSignOff(claims.carrier.id, signOffs)) {
1442
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "carrier.id must match the carrier sign-off signer");
1443
+ }
1444
+ if (want.nonce !== "" && claims.nonce !== want.nonce) {
1445
+ throw new VerificationRecordError(VerificationRecordErrorCode.NONCE_MISMATCH, "nonce does not match the expected nonce");
1446
+ }
1447
+ if (want.origins.length > 0 && !want.origins.includes(claims.origin)) {
1448
+ throw new VerificationRecordError(VerificationRecordErrorCode.ORIGIN_MISMATCH, "origin is not an expected origin");
1449
+ }
1450
+ return claims;
1451
+ }
1452
+ function checkRecordTimes(obj, want) {
1453
+ const iat = member(obj, "iat");
1454
+ const exp = member(obj, "exp");
1455
+ if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp)) {
1456
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "iat and exp must be integers");
1457
+ }
1458
+ const times = { iat, exp };
1459
+ const now = want.nowSeconds;
1460
+ if (times.iat > now + IAT_LEEWAY_SECONDS) {
1461
+ throw new VerificationRecordError(VerificationRecordErrorCode.NOT_YET_VALID, "iat is in the future");
1462
+ }
1463
+ if (times.exp > now) {
1464
+ return times;
1465
+ }
1466
+ if (!want.allowExpired) {
1467
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record has expired");
1468
+ }
1469
+ if (times.iat < now - want.maxAuditAgeSeconds) {
1470
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record is older than the maximum audit age");
1471
+ }
1472
+ return times;
1473
+ }
1474
+ function signOffResults(signOffs) {
1475
+ return signOffs.map((s) => {
1476
+ if (s.status === "unavailable") {
1477
+ const result = { role: s.role, signer: s.signer, result: "unavailable" };
1478
+ assignDefined(result, "reason", s.reason);
1479
+ return result;
1480
+ }
1481
+ return { role: s.role, signer: s.signer, result: "unverified" };
1482
+ });
1483
+ }
1484
+ function readCarrier(r) {
1485
+ const obj = r.object("carrier");
1486
+ if (!obj) return void 0;
1487
+ const s = new MemberReader(obj);
1488
+ const id = s.str("id");
1489
+ const carrier = { id: id ?? "" };
1490
+ assignDefined(carrier, "name", s.str("name"));
1491
+ assignDefined(carrier, "mvno", s.str("mvno"));
1492
+ r.ok = r.ok && s.ok && !!id;
1493
+ return carrier;
1494
+ }
1495
+ function readPhoneNumberDetails(r) {
1496
+ const obj = r.object("phone_number_details");
1497
+ if (!obj) return void 0;
1498
+ const s = new MemberReader(obj);
1499
+ const d = {
1500
+ country_code: s.int("country_code") ?? 0,
1501
+ national_number: s.str("national_number") ?? "",
1502
+ region_code: s.str("region_code") ?? ""
1503
+ };
1504
+ r.ok = r.ok && s.ok;
1505
+ return d;
1506
+ }
1507
+ function readLiveCall(r, name) {
1508
+ const obj = r.object(name);
1509
+ if (!obj) return void 0;
1510
+ const s = new MemberReader(obj);
1511
+ const status = s.str("status");
1512
+ const info = {
1513
+ status: status ?? ""
1514
+ };
1515
+ assignDefined(info, "carrier_name", s.str("carrier_name"));
1516
+ assignDefined(info, "reason", s.str("reason"));
1517
+ r.ok = r.ok && s.ok && !!status;
1518
+ return info;
1519
+ }
1520
+ function readSwap(r, name) {
1521
+ const obj = r.object(name);
1522
+ if (!obj) return void 0;
1523
+ const s = new MemberReader(obj);
1524
+ const info = { checked: s.bool("checked") ?? false };
1525
+ assignDefined(info, "risk_level", s.str("risk_level"));
1526
+ assignDefined(info, "carrier_name", s.str("carrier_name"));
1527
+ assignDefined(info, "reason", s.str("reason"));
1528
+ assignDefined(info, "swapped", s.bool("swapped"));
1529
+ assignDefined(info, "max_age_hours", s.int("max_age_hours"));
1530
+ const band = s.object("age_band");
1531
+ if (band) {
1532
+ const b = new MemberReader(band);
1533
+ info.age_band = { from: b.int("from") ?? -1, to: b.int("to") ?? -1 };
1534
+ s.ok = s.ok && b.ok;
1535
+ }
1536
+ r.ok = r.ok && s.ok;
1537
+ return info;
1538
+ }
1539
+ function assignDefined(target, key, value) {
1540
+ if (value !== void 0) {
1541
+ target[key] = value;
1542
+ }
1543
+ }
1544
+
1545
+ // src/verification-record/verify.ts
1546
+ var RECORD_TYP = "glide-verification+jwt";
1547
+ var DEFAULT_MAX_AUDIT_AGE_SECONDS = 90 * 24 * 60 * 60;
1548
+ var MAX_RECORD_BYTES = 16 * 1024;
1549
+ var RECORD_KIDS = [
1550
+ "glide-record-signing-key-ecdsa-es256-us-2026",
1551
+ "glide-record-signing-key-ecdsa-es256-eu-2026"
1552
+ ];
1553
+ var REVOKED_RECORD_KIDS = [];
1554
+ async function verifyVerificationRecord(record, options, ctx) {
1555
+ const opts = options ?? {};
1556
+ const nowMs = (opts.now ? opts.now() : /* @__PURE__ */ new Date()).getTime();
1557
+ if (!Number.isFinite(nowMs)) {
1558
+ throw new TypeError("options.now must return a valid Date");
1559
+ }
1560
+ const parsed = parseRecord(record);
1561
+ checkRecordKid(parsed.kid, opts.revokedKids ?? []);
1562
+ const key = await ctx.keys.key(parsed.kid);
1563
+ verifyRecordSignature(parsed, key);
1564
+ const maxAuditAge = opts.maxAuditAgeSeconds ?? 0;
1565
+ const claims = checkRecordClaims(parsed.payload, {
1566
+ issuer: opts.issuer ? opts.issuer : ctx.baseUrl.replace(/\/+$/, ""),
1567
+ audience: opts.expectedAudience ? opts.expectedAudience : ctx.clientId,
1568
+ nonce: opts.expectedNonce ?? "",
1569
+ origins: opts.expectedOrigin ?? [],
1570
+ allowExpired: opts.allowExpired === true,
1571
+ maxAuditAgeSeconds: Number.isFinite(maxAuditAge) && maxAuditAge > 0 ? maxAuditAge : DEFAULT_MAX_AUDIT_AGE_SECONDS,
1572
+ nowSeconds: Math.floor(nowMs / 1e3)
1573
+ });
1574
+ return { claims, signOffResults: signOffResults(claims.sign_offs) };
1575
+ }
1576
+ function parseRecord(record) {
1577
+ if (record === void 0 || record === null || record === "") {
1578
+ throw new VerificationRecordError(VerificationRecordErrorCode.RECORD_UNAVAILABLE, "no verification record");
1579
+ }
1580
+ if (typeof record === "string" && Buffer.byteLength(record, "utf8") > MAX_RECORD_BYTES) {
1581
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is larger than 16 KiB");
1582
+ }
1583
+ const segments = typeof record === "string" ? record.split(".") : [];
1584
+ if (segments.length !== 3) {
1585
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is not a compact JWS");
1586
+ }
1587
+ const decoded = segments.map(decodeBase64URL);
1588
+ const [header, payload, signature] = decoded;
1589
+ if (!header || !payload || !signature) {
1590
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record segment is not base64url");
1591
+ }
1592
+ const headerObj = parseJsonObject(header.toString("utf8"));
1593
+ if (!headerObj) {
1594
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "header is not a JSON object");
1595
+ }
1596
+ return {
1597
+ kid: checkRecordHeader(headerObj),
1598
+ signingInput: Buffer.from(`${segments[0]}.${segments[1]}`, "ascii"),
1599
+ payload,
1600
+ signature
1601
+ };
1602
+ }
1603
+ function checkRecordHeader(header) {
1604
+ const alg = member(header, "alg");
1605
+ const typ = member(header, "typ");
1606
+ const kid = member(header, "kid");
1607
+ if (Object.keys(header).length !== 3 || typeof alg !== "string" || typeof typ !== "string" || typeof kid !== "string") {
1608
+ throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header must contain exactly alg, typ and kid");
1609
+ }
1610
+ if (alg !== RECORD_ALG || typ !== RECORD_TYP) {
1611
+ throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header alg/typ not allowed");
1612
+ }
1613
+ return kid;
1614
+ }
1615
+ function checkRecordKid(kid, revoked) {
1616
+ if (REVOKED_RECORD_KIDS.includes(kid) || revoked.includes(kid)) {
1617
+ throw new VerificationRecordError(VerificationRecordErrorCode.REVOKED_KEY, `kid ${kid} is revoked`);
1618
+ }
1619
+ if (!RECORD_KIDS.includes(kid)) {
1620
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not a record signing key`);
1621
+ }
1622
+ }
1623
+ function verifyRecordSignature(record, key) {
1624
+ if (record.signature.length !== 64) {
1625
+ throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature is not 64 bytes");
1626
+ }
1627
+ let valid = false;
1628
+ try {
1629
+ valid = verify("sha256", record.signingInput, { key, dsaEncoding: "ieee-p1363" }, record.signature);
1630
+ } catch {
1631
+ valid = false;
1632
+ }
1633
+ if (!valid) {
1634
+ throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature does not verify");
1635
+ }
1636
+ }
1637
+
1638
+ // src/verification-record/action-hash.ts
1639
+ import { createHash as createHash2 } from "crypto";
1640
+ function actionHash(action) {
1641
+ const canonical = Object.keys(action).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))).map((k) => `${k}=${action[k]}`).join("|");
1642
+ return createHash2("sha256").update(canonical).digest("base64url");
1643
+ }
795
1644
 
796
1645
  // src/client.ts
797
1646
  var MagicalAuthClient = class {
798
1647
  config;
799
1648
  tokenManager;
1649
+ recordKeys;
800
1650
  /**
801
1651
  * Creates a new MagicalAuthClient instance.
802
1652
  *
@@ -818,6 +1668,11 @@ var MagicalAuthClient = class {
818
1668
  this.config.httpClient,
819
1669
  this.config.logger
820
1670
  );
1671
+ this.recordKeys = new RecordKeyCache(
1672
+ this.config.baseUrl.replace(/\/+$/, ""),
1673
+ this.config.httpClient,
1674
+ this.config.timeout
1675
+ );
821
1676
  }
822
1677
  /**
823
1678
  * Check authentication eligibility for a phone number or PLMN.
@@ -842,9 +1697,10 @@ var MagicalAuthClient = class {
842
1697
  /**
843
1698
  * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
844
1699
  *
845
- * Automatically generates `fe_code` / `fe_hash` for device binding. If the aggregator
846
- * selects the 'link' strategy, `feCode` is included in the result so the caller can
847
- * set it as an HttpOnly cookie via `buildSetBindingCookieHeader()`.
1700
+ * Automatically generates `fe_code` / `fe_hash` for device binding. If the strategy or
1701
+ * its fallback is 'link', `feCode` is included in the result so the caller can set it
1702
+ * as an HttpOnly cookie for the link session (`fallback.session` when the fallback is
1703
+ * link) via `buildSetBindingCookieHeader()`.
848
1704
  *
849
1705
  * @param request - Prepare request parameters
850
1706
  * @param options - Per-request options (e.g., correlationId)
@@ -859,7 +1715,11 @@ var MagicalAuthClient = class {
859
1715
  const nonce = request.nonce || generateNonce();
860
1716
  const feCode = generateFeCode();
861
1717
  const feHash = computeFeHash(feCode);
862
- const requestWithHash = { ...request, nonce, fe_hash: feHash };
1718
+ const requestWithHash = {
1719
+ ...request,
1720
+ nonce,
1721
+ fe_hash: feHash
1722
+ };
863
1723
  const response = await this.doRequest(
864
1724
  "POST",
865
1725
  "/magic-auth/v2/auth/prepare",
@@ -867,8 +1727,9 @@ var MagicalAuthClient = class {
867
1727
  options
868
1728
  );
869
1729
  const result = { ...response };
870
- if (response.authentication_strategy === AuthenticationStrategy.LINK) {
871
- const linkData = response.data;
1730
+ const link = response.authentication_strategy === AuthenticationStrategy.LINK ? response : response.fallback;
1731
+ if (link?.authentication_strategy === AuthenticationStrategy.LINK) {
1732
+ const linkData = link.data;
872
1733
  result.feCode = linkData.fe_code ?? feCode;
873
1734
  }
874
1735
  this.config.logger.debug("Auth prepared", {
@@ -877,6 +1738,39 @@ var MagicalAuthClient = class {
877
1738
  });
878
1739
  return result;
879
1740
  }
1741
+ /**
1742
+ * Prepares authentication for several phone numbers at once.
1743
+ *
1744
+ * Fans out one ordinary {@link prepare} call per number, so each number gets
1745
+ * its own carrier resolution, residency routing and session. Per-number
1746
+ * failures are returned as items rather than thrown; this only throws
1747
+ * {@link ValidationError}, and only before any request is issued.
1748
+ *
1749
+ * @param request - Shared prepare fields plus `phone_numbers` (1..10)
1750
+ * @param options - Per-request options (e.g., correlationId)
1751
+ * @returns One result per input number, in input order
1752
+ * @throws {ValidationError} If the list is empty, over the cap, has blank entries, or a shared prepare field is invalid
1753
+ */
1754
+ async prepareMultiple(request, options) {
1755
+ validatePrepareMultipleRequest(request);
1756
+ const { phone_numbers: phoneNumbers, nonce: _nonce, ...shared } = request;
1757
+ const derived = phoneNumbers.map(
1758
+ (phone_number) => ({ ...shared, phone_number })
1759
+ );
1760
+ for (const single of derived) {
1761
+ validatePrepareRequest(single);
1762
+ }
1763
+ this.config.logger.debug("Preparing auth for multiple numbers", {
1764
+ count: phoneNumbers.length
1765
+ });
1766
+ const settled = await Promise.allSettled(
1767
+ derived.map((single) => this.prepare(single, options))
1768
+ );
1769
+ return settled.map((outcome, index) => {
1770
+ const phone_number = phoneNumbers[index];
1771
+ return outcome.status === "fulfilled" ? { phone_number, ok: true, result: outcome.value } : { phone_number, ok: false, error: asMagicalAuthError(outcome.reason) };
1772
+ });
1773
+ }
880
1774
  /**
881
1775
  * Validates device binding codes and completes a link protocol session.
882
1776
  *
@@ -934,6 +1828,51 @@ var MagicalAuthClient = class {
934
1828
  this.config.logger.debug("Phone verification complete", { verified: response.verified });
935
1829
  return response;
936
1830
  }
1831
+ /**
1832
+ * Verifies a verification record returned by {@link verifyPhoneNumber}: the
1833
+ * ES256 signature against Glide's published record keys, then issuer,
1834
+ * the expected audience (default this client's ID), validity window, shape, nonce and origin.
1835
+ *
1836
+ * A missing or empty record fails with `RECORD_UNAVAILABLE`, so a caller
1837
+ * that requires records can pass `response.verification_record` straight in.
1838
+ *
1839
+ * @param record - Compact JWS from `VerifyPhoneNumberResponse.verification_record`
1840
+ * @param options - Expected nonce, expected audience, expected origins, audit mode, issuer override, extra revoked kids, clock
1841
+ * @returns The verified claims and how each sign-off was treated
1842
+ * @throws {VerificationRecordError} On any failed check; `code` is a {@link VerificationRecordErrorCode}
1843
+ */
1844
+ async verifyVerificationRecord(record, options) {
1845
+ return verifyVerificationRecord(record, options, {
1846
+ baseUrl: this.config.baseUrl,
1847
+ clientId: this.config.clientId,
1848
+ keys: this.recordKeys
1849
+ });
1850
+ }
1851
+ /**
1852
+ * Verifies a step-up verification record and requires that it is verified,
1853
+ * carries both the `passkey` and `carrier` factors, is bound to `action` and
1854
+ * is for `phoneNumber` (E.164). The record is accepted past `exp` while its
1855
+ * `iat` is within `maxAgeSeconds` (non-finite, zero or negative means 300).
1856
+ * `expectedAudience` is the record aud to require; unset means this client's ID.
1857
+ *
1858
+ * @throws {VerificationRecordError} `EXPIRED` when older than `maxAgeSeconds`, `STEP_UP_REJECTED` when a step-up check fails, or any record verification code
1859
+ */
1860
+ async verifyStepUp(record, action, phoneNumber, maxAgeSeconds = 300, expectedAudience) {
1861
+ const maxAge = Number.isFinite(maxAgeSeconds) && maxAgeSeconds > 0 ? maxAgeSeconds : 300;
1862
+ const rec = await this.verifyVerificationRecord(record, { allowExpired: true, maxAuditAgeSeconds: maxAge, expectedAudience });
1863
+ const c = rec.claims;
1864
+ const reject = (message) => new VerificationRecordError(VerificationRecordErrorCode.STEP_UP_REJECTED, message);
1865
+ if (Math.floor(Date.now() / 1e3) - c.iat > maxAge) {
1866
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record is older than maxAge");
1867
+ }
1868
+ if (!c.verified) throw reject("record is not verified");
1869
+ if (!c.factors.includes("passkey") || !c.factors.includes("carrier")) {
1870
+ throw reject("record lacks the passkey and carrier factors");
1871
+ }
1872
+ if (c.action_hash !== actionHash(action)) throw reject("action_hash does not match the action");
1873
+ if (c.sub !== `tel:${phoneNumber}`) throw reject("sub does not match the phone number");
1874
+ return rec;
1875
+ }
937
1876
  /**
938
1877
  * Retrieves the phone number associated with the device using digital credentials.
939
1878
  *
@@ -963,6 +1902,26 @@ var MagicalAuthClient = class {
963
1902
  });
964
1903
  return response;
965
1904
  }
1905
+ /**
1906
+ * Deletes every passkey Glide holds for the number on origin, a registered origin of this application.
1907
+ *
1908
+ * @param request - Phone number and origin whose passkeys are deleted
1909
+ * @param options - Per-request options (e.g., correlationId)
1910
+ * @returns The deleted credential ids; empty when there were none
1911
+ * @throws {ValidationError} If phone_number is not E.164 or origin is missing
1912
+ * @throws {ForbiddenError} If origin is not registered to this application
1913
+ * @throws {MagicalAuthError} For other API errors
1914
+ */
1915
+ async deletePasskeys(request, options) {
1916
+ validateDeletePasskeysRequest(request);
1917
+ const response = await this.doRequest(
1918
+ "POST",
1919
+ "/magic-auth/v2/auth/delete-passkeys",
1920
+ request,
1921
+ options
1922
+ );
1923
+ return { ...response, deleted_credential_ids: response?.deleted_credential_ids ?? [] };
1924
+ }
966
1925
  /**
967
1926
  * Reports when a user clicks the invoke/authenticate button.
968
1927
  *
@@ -1147,6 +2106,13 @@ function generateNonce(length = 32) {
1147
2106
  }
1148
2107
  return result;
1149
2108
  }
2109
+ function asMagicalAuthError(reason) {
2110
+ if (reason instanceof MagicalAuthError) {
2111
+ return reason;
2112
+ }
2113
+ const message = reason instanceof Error ? reason.message : "Prepare failed";
2114
+ return new MagicalAuthError(message, "UNKNOWN_ERROR", 0);
2115
+ }
1150
2116
 
1151
2117
  // src/logger.ts
1152
2118
  function createLogger(config = {}) {
@@ -1195,8 +2161,12 @@ export {
1195
2161
  BINDING_COOKIE_MAX_AGE,
1196
2162
  BINDING_COOKIE_PREFIX,
1197
2163
  BadRequestError,
2164
+ BiometricVerification,
1198
2165
  BrowserMismatchError,
2166
+ CarrierAppUnavailableError,
1199
2167
  CarrierNotEligibleError,
2168
+ CarrierRejectedError,
2169
+ CarrierTemporarilyUnavailableError,
1200
2170
  DEFAULT_BASE_URL,
1201
2171
  DEFAULT_TIMEOUT,
1202
2172
  DesktopWaitError,
@@ -1209,10 +2179,12 @@ export {
1209
2179
  MagicalAuthClient,
1210
2180
  MagicalAuthError,
1211
2181
  MissingBindingCookieError,
2182
+ PREPARE_MULTIPLE_MAX,
1212
2183
  PhoneNumberMismatchError,
1213
2184
  RateLimitError,
1214
2185
  SENSITIVE_KEYS,
1215
2186
  ServiceUnavailableError,
2187
+ SessionMetadataParentStrategy,
1216
2188
  SessionNotEligibleError,
1217
2189
  SessionNotFoundError,
1218
2190
  SessionStatus,
@@ -1222,6 +2194,9 @@ export {
1222
2194
  UseCase,
1223
2195
  VERSION,
1224
2196
  ValidationError,
2197
+ VerificationRecordError,
2198
+ VerificationRecordErrorCode,
2199
+ actionHash,
1225
2200
  assertValidFeCode,
1226
2201
  buildClearBindingCookieHeader,
1227
2202
  buildSetBindingCookieHeader,