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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -36,6 +36,8 @@ 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",
39
41
  UNSUPPORTED_PLATFORM: "UNSUPPORTED_PLATFORM",
40
42
  PHONE_NUMBER_MISMATCH: "PHONE_NUMBER_MISMATCH",
41
43
  INVALID_CREDENTIAL_FORMAT: "INVALID_CREDENTIAL_FORMAT",
@@ -61,9 +63,17 @@ var MagicalAuthError = class extends Error {
61
63
  */
62
64
  status;
63
65
  /**
64
- * Request ID for debugging/support.
66
+ * The id of this request, the same value as the `X-Request-ID` response
67
+ * header. Quote it to Glide support.
65
68
  */
66
69
  requestId;
70
+ /**
71
+ * The session the failed request was about, once the server had read it from
72
+ * the request. Undefined when the request failed before naming a session, on
73
+ * operations that have none (eligibility, prepare), and from servers older
74
+ * than the release that added it.
75
+ */
76
+ sessionKey;
67
77
  /**
68
78
  * Additional error details.
69
79
  */
@@ -132,6 +142,18 @@ var CarrierNotEligibleError = class extends MagicalAuthError {
132
142
  this.name = "CarrierNotEligibleError";
133
143
  }
134
144
  };
145
+ var CarrierRejectedError = class extends MagicalAuthError {
146
+ constructor(message = "The carrier rejected the authentication request", requestId, details) {
147
+ super(message, "CARRIER_REJECTED", 422, requestId, details);
148
+ this.name = "CarrierRejectedError";
149
+ }
150
+ };
151
+ var CarrierAppUnavailableError = class extends MagicalAuthError {
152
+ constructor(message = "Carrier app unavailable on the phone that scanned the QR code", requestId, details) {
153
+ super(message, "CARRIER_APP_UNAVAILABLE", 422, requestId, details);
154
+ this.name = "CarrierAppUnavailableError";
155
+ }
156
+ };
135
157
  var UnsupportedPlatformError = class extends MagicalAuthError {
136
158
  constructor(message = "Platform not supported", requestId) {
137
159
  super(message, "UNSUPPORTED_PLATFORM", 422, requestId);
@@ -212,9 +234,31 @@ var MissingBindingCookieError = class extends DeviceBindingError {
212
234
  var DesktopWaitError = class extends MagicalAuthError {
213
235
  waitResponse;
214
236
  constructor(waitResponse) {
215
- super(waitResponse.message, "DESKTOP_WAIT", 202);
237
+ super(waitResponse.message, "DESKTOP_WAIT", 202, waitResponse.request_id);
216
238
  this.name = "DesktopWaitError";
217
239
  this.waitResponse = waitResponse;
240
+ Object.assign(this, { sessionKey: waitResponse.session_key });
241
+ }
242
+ };
243
+ var VerificationRecordErrorCode = {
244
+ MALFORMED: "MALFORMED",
245
+ DISALLOWED_HEADER: "DISALLOWED_HEADER",
246
+ UNKNOWN_KEY: "UNKNOWN_KEY",
247
+ BAD_SIGNATURE: "BAD_SIGNATURE",
248
+ WRONG_ISSUER: "WRONG_ISSUER",
249
+ WRONG_AUDIENCE: "WRONG_AUDIENCE",
250
+ EXPIRED: "EXPIRED",
251
+ NOT_YET_VALID: "NOT_YET_VALID",
252
+ NONCE_MISMATCH: "NONCE_MISMATCH",
253
+ ORIGIN_MISMATCH: "ORIGIN_MISMATCH",
254
+ UNSUPPORTED_VERSION: "UNSUPPORTED_VERSION",
255
+ REVOKED_KEY: "REVOKED_KEY",
256
+ RECORD_UNAVAILABLE: "RECORD_UNAVAILABLE"
257
+ };
258
+ var VerificationRecordError = class extends MagicalAuthError {
259
+ constructor(code, message) {
260
+ super(`verification record: ${code}: ${message}`, code, 0);
261
+ this.name = "VerificationRecordError";
218
262
  }
219
263
  };
220
264
  function parseRetryAfter(headers) {
@@ -233,9 +277,10 @@ function parseRetryAfter(headers) {
233
277
  return void 0;
234
278
  }
235
279
  function createErrorFromResponse(response, headers) {
236
- const { code, message, request_id, details, status, trace_id, span_id, timestamp, service } = response;
280
+ const { code, message, request_id, session_key, details, status, trace_id, span_id, timestamp, service } = response;
237
281
  const error = createTypedError(code, message, request_id, details, status, headers);
238
282
  return Object.assign(error, {
283
+ sessionKey: session_key,
239
284
  traceId: trace_id,
240
285
  spanId: span_id,
241
286
  timestamp,
@@ -259,6 +304,18 @@ function createTypedError(code, message, request_id, details, status, headers) {
259
304
  return new SessionNotFoundError(message, request_id);
260
305
  case "CARRIER_NOT_ELIGIBLE":
261
306
  return new CarrierNotEligibleError(message, request_id);
307
+ case "CARRIER_REJECTED":
308
+ return new CarrierRejectedError(
309
+ message,
310
+ request_id,
311
+ details
312
+ );
313
+ case "CARRIER_APP_UNAVAILABLE":
314
+ return new CarrierAppUnavailableError(
315
+ message,
316
+ request_id,
317
+ details
318
+ );
262
319
  case "UNSUPPORTED_PLATFORM":
263
320
  return new UnsupportedPlatformError(message, request_id);
264
321
  case "INVALID_CREDENTIAL_FORMAT":
@@ -360,17 +417,17 @@ var TokenManager = class {
360
417
  body: "grant_type=client_credentials"
361
418
  });
362
419
  if (!response.ok) {
363
- let errorMessage = "Token request failed";
420
+ let errorMessage2 = "Token request failed";
364
421
  try {
365
422
  const errorBody = await response.json();
366
423
  if (errorBody.error_description) {
367
- errorMessage = errorBody.error_description;
424
+ errorMessage2 = errorBody.error_description;
368
425
  } else if (errorBody.error) {
369
- errorMessage = errorBody.error;
426
+ errorMessage2 = errorBody.error;
370
427
  }
371
428
  } catch {
372
429
  }
373
- throw new UnauthorizedError(errorMessage);
430
+ throw new UnauthorizedError(errorMessage2);
374
431
  }
375
432
  const data = await response.json();
376
433
  if (!data.access_token) {
@@ -626,12 +683,18 @@ function getCompletionPageHtml(completeEndpoint) {
626
683
 
627
684
  if (res.ok) {
628
685
  var signalKey = 'glide_signal_' + sessionKey;
686
+ var sigmetaKey = 'glide_sigmeta_' + sessionKey;
687
+ var signalStored = false;
629
688
  try {
630
689
  localStorage.setItem(signalKey, sessionKey);
631
- setTimeout(function() {
632
- try { localStorage.removeItem(signalKey); } catch(e) {}
633
- }, 5000);
690
+ signalStored = true;
691
+ localStorage.setItem(sigmetaKey, String(Date.now()));
634
692
  } catch(e) {}
693
+ if (signalStored) {
694
+ setTimeout(function() {
695
+ try { localStorage.removeItem(signalKey); localStorage.removeItem(sigmetaKey); } catch(e) {}
696
+ }, 600000);
697
+ }
635
698
  tryClose();
636
699
  } else {
637
700
  var code = '';
@@ -705,15 +768,26 @@ var SessionStatus = {
705
768
  COMPLETED: "completed",
706
769
  FAILED: "failed"
707
770
  };
771
+ var BiometricVerification = {
772
+ VERIFIED: "VERIFIED",
773
+ FAILED: "FAILED",
774
+ NOT_ENROLLED: "NOT_ENROLLED",
775
+ UNSUPPORTED: "UNSUPPORTED",
776
+ NOT_REQUESTED: "NOT_REQUESTED"
777
+ };
778
+
779
+ // src/models/prepare-multiple.ts
780
+ var PREPARE_MULTIPLE_MAX = 10;
708
781
 
709
782
  // src/validation.ts
710
783
  function validatePrepareRequest(request) {
711
784
  const errors = {};
712
785
  const hasParentSession = !!request.options?.parent_session_id?.trim();
786
+ const phoneNumber = request.phone_number?.trim();
713
787
  if (!request.use_case && !hasParentSession) {
714
788
  errors.use_case = "use_case is required";
715
789
  }
716
- if (request.use_case === UseCase.VERIFY_PHONE_NUMBER && !request.phone_number) {
790
+ if (request.use_case === UseCase.VERIFY_PHONE_NUMBER && !phoneNumber) {
717
791
  errors.phone_number = "phone_number is required for VerifyPhoneNumber";
718
792
  }
719
793
  if (Object.keys(errors).length > 0) {
@@ -778,11 +852,573 @@ function validateCompleteRequest(request) {
778
852
  throw new DeviceBindingError("Invalid device binding inputs");
779
853
  }
780
854
  }
855
+ function validateEligibilityRequest(request) {
856
+ const errors = {};
857
+ const phoneNumber = request.phone_number?.trim();
858
+ if (!phoneNumber && !request.plmn) {
859
+ errors.phone_number = "phone_number or plmn is required";
860
+ }
861
+ if (!request.client_info?.user_agent?.trim()) {
862
+ errors["client_info.user_agent"] = "client_info.user_agent is required";
863
+ }
864
+ if (Object.keys(errors).length > 0) {
865
+ throw new ValidationError("Request validation failed", errors);
866
+ }
867
+ }
868
+ function validatePrepareMultipleRequest(request) {
869
+ if (request == null) {
870
+ throw new ValidationError("Request validation failed", {
871
+ request: "request is required"
872
+ });
873
+ }
874
+ const numbers = request.phone_numbers;
875
+ let message = null;
876
+ if (!Array.isArray(numbers) || numbers.length === 0) {
877
+ message = "phone_numbers must contain at least one number";
878
+ } else if (numbers.length > PREPARE_MULTIPLE_MAX) {
879
+ message = `phone_numbers must contain at most ${PREPARE_MULTIPLE_MAX} numbers`;
880
+ } else if (Array.from(numbers).some((n) => typeof n !== "string" || !n.trim())) {
881
+ message = "phone_numbers must not contain blank entries";
882
+ }
883
+ if (message) {
884
+ throw new ValidationError("Request validation failed", { phone_numbers: message });
885
+ }
886
+ }
887
+
888
+ // src/verification-record/jwk.ts
889
+ import { createPublicKey } from "crypto";
890
+
891
+ // src/verification-record/decode.ts
892
+ var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]*$/;
893
+ function decodeBase64URL(segment) {
894
+ if (!BASE64URL_ALPHABET.test(segment) || segment.length % 4 === 1) {
895
+ return null;
896
+ }
897
+ const bytes = Buffer.from(segment, "base64url");
898
+ return bytes.toString("base64url") === segment ? bytes : null;
899
+ }
900
+ function isJsonObject(value) {
901
+ return typeof value === "object" && value !== null && !Array.isArray(value);
902
+ }
903
+ function parseJsonObject(text) {
904
+ try {
905
+ const value = JSON.parse(text);
906
+ return isJsonObject(value) ? value : null;
907
+ } catch {
908
+ return null;
909
+ }
910
+ }
911
+ function member(obj, name) {
912
+ return Object.hasOwn(obj, name) ? obj[name] : void 0;
913
+ }
914
+ var MemberReader = class {
915
+ constructor(obj) {
916
+ this.obj = obj;
917
+ }
918
+ obj;
919
+ ok = true;
920
+ str(name) {
921
+ return this.read(name, (v) => typeof v === "string");
922
+ }
923
+ bool(name) {
924
+ return this.read(name, (v) => typeof v === "boolean");
925
+ }
926
+ int(name) {
927
+ return this.read(name, (v) => Number.isSafeInteger(v));
928
+ }
929
+ /** A nested object member; absent yields undefined. Present null is a wrong type. */
930
+ object(name) {
931
+ return this.read(name, isJsonObject);
932
+ }
933
+ read(name, accept) {
934
+ if (!Object.hasOwn(this.obj, name)) return void 0;
935
+ const value = this.obj[name];
936
+ if (accept(value)) return value;
937
+ this.ok = false;
938
+ return void 0;
939
+ }
940
+ };
941
+
942
+ // src/verification-record/jwk.ts
943
+ var RECORD_ALG = "ES256";
944
+ function parseJWKS(body) {
945
+ const doc = parseJsonObject(body);
946
+ if (!doc) {
947
+ throw new Error("JWKS is not a JSON object");
948
+ }
949
+ const entries = member(doc, "keys");
950
+ if (!Array.isArray(entries)) {
951
+ throw new Error("JWKS keys is not an array");
952
+ }
953
+ const keys = [];
954
+ for (const entry of entries) {
955
+ if (!isJsonObject(entry)) continue;
956
+ const r = new MemberReader(entry);
957
+ const k = {
958
+ kty: r.str("kty") ?? "",
959
+ crv: r.str("crv") ?? "",
960
+ use: r.str("use") ?? "",
961
+ alg: r.str("alg") ?? "",
962
+ kid: r.str("kid") ?? "",
963
+ x: r.str("x") ?? "",
964
+ y: r.str("y") ?? ""
965
+ };
966
+ if (r.ok) keys.push(k);
967
+ }
968
+ return keys;
969
+ }
970
+ function recordPublicKey(k) {
971
+ if (k.kty !== "EC" || k.crv !== "P-256" || k.use !== "sig" || k.alg !== RECORD_ALG) {
972
+ throw new Error("JWK is not an EC P-256 ES256 signing key");
973
+ }
974
+ const x = decodeBase64URL(k.x);
975
+ const y = decodeBase64URL(k.y);
976
+ if (!x || !y || x.length !== 32 || y.length !== 32) {
977
+ throw new Error("JWK coordinates are not 32-byte base64url");
978
+ }
979
+ try {
980
+ return createPublicKey({ key: { kty: "EC", crv: "P-256", x: k.x, y: k.y }, format: "jwk" });
981
+ } catch {
982
+ throw new Error("JWK point is not on P-256");
983
+ }
984
+ }
985
+
986
+ // src/verification-record/jwks.ts
987
+ var DEFAULT_MAX_AGE_SECONDS = 300;
988
+ var REFRESH_INTERVAL_MS = 6e4;
989
+ var MAX_JWKS_BYTES = 1 << 20;
990
+ var JWKS_PATH = "/.well-known/us/jwks.json";
991
+ var RecordKeyCache = class {
992
+ constructor(baseUrl, httpClient, timeoutMs) {
993
+ this.baseUrl = baseUrl;
994
+ this.httpClient = httpClient;
995
+ this.timeoutMs = timeoutMs;
996
+ }
997
+ baseUrl;
998
+ httpClient;
999
+ timeoutMs;
1000
+ now = Date.now;
1001
+ keys = null;
1002
+ expiresAt = 0;
1003
+ lastRefresh = -Infinity;
1004
+ backoffUntil = -Infinity;
1005
+ queue = Promise.resolve();
1006
+ key(kid) {
1007
+ const run = this.queue.then(() => this.resolve(kid));
1008
+ this.queue = run.catch(() => void 0);
1009
+ return run;
1010
+ }
1011
+ /**
1012
+ * Refetches when the cache has expired, or when kid is missing and the last
1013
+ * refresh is at least 60 s old. After a failed refresh the previous keys are
1014
+ * kept and further refreshes are refused for 60 s.
1015
+ */
1016
+ async resolve(kid) {
1017
+ const now = this.now();
1018
+ const cached = this.keys?.has(kid) ?? false;
1019
+ const expired = this.keys === null || now >= this.expiresAt;
1020
+ if (expired || !cached && now - this.lastRefresh >= REFRESH_INTERVAL_MS) {
1021
+ if (now < this.backoffUntil) {
1022
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, "record key fetch is backing off after a failure");
1023
+ }
1024
+ try {
1025
+ await this.refresh(now);
1026
+ } catch (e) {
1027
+ this.backoffUntil = now + REFRESH_INTERVAL_MS;
1028
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `fetch record keys: ${errorMessage(e)}`);
1029
+ }
1030
+ }
1031
+ const jwk = this.keys?.get(kid);
1032
+ if (!jwk) {
1033
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not published`);
1034
+ }
1035
+ try {
1036
+ return recordPublicKey(jwk);
1037
+ } catch (e) {
1038
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid}: ${errorMessage(e)}`);
1039
+ }
1040
+ }
1041
+ async refresh(now) {
1042
+ this.lastRefresh = now;
1043
+ const doc = await this.fetch(`${this.baseUrl}${JWKS_PATH}`);
1044
+ const keys = /* @__PURE__ */ new Map();
1045
+ for (const k of doc.keys) {
1046
+ if (!keys.has(k.kid)) keys.set(k.kid, k);
1047
+ }
1048
+ this.keys = keys;
1049
+ this.expiresAt = now + doc.maxAgeSeconds * 1e3;
1050
+ }
1051
+ async fetch(url) {
1052
+ const controller = new AbortController();
1053
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
1054
+ try {
1055
+ const response = await this.httpClient.request({
1056
+ method: "GET",
1057
+ url,
1058
+ headers: { Accept: "application/json" },
1059
+ signal: controller.signal
1060
+ });
1061
+ if (response.status !== 200) {
1062
+ throw new Error(`${url}: HTTP ${response.status}`);
1063
+ }
1064
+ const body = await response.text();
1065
+ if (Buffer.byteLength(body, "utf8") > MAX_JWKS_BYTES) {
1066
+ throw new Error(`${url}: JWKS is larger than 1 MiB`);
1067
+ }
1068
+ const keys = prefixErrors(url, () => parseJWKS(body));
1069
+ return { keys, maxAgeSeconds: cacheMaxAge(response.headers?.get("cache-control") ?? null) };
1070
+ } catch (e) {
1071
+ if (controller.signal.aborted) {
1072
+ throw new Error(`${url}: timed out after ${this.timeoutMs}ms`);
1073
+ }
1074
+ throw e;
1075
+ } finally {
1076
+ clearTimeout(timer);
1077
+ }
1078
+ }
1079
+ };
1080
+ function cacheMaxAge(cacheControl) {
1081
+ for (const directive of (cacheControl ?? "").split(",")) {
1082
+ const trimmed = directive.trim();
1083
+ const eq = trimmed.indexOf("=");
1084
+ if (eq < 0 || trimmed.slice(0, eq).toLowerCase() !== "max-age") continue;
1085
+ const value = trimmed.slice(eq + 1);
1086
+ const seconds = /^[+-]?\d+$/.test(value) ? Number(value) : NaN;
1087
+ if (Number.isSafeInteger(seconds) && seconds >= 0) return seconds;
1088
+ }
1089
+ return DEFAULT_MAX_AGE_SECONDS;
1090
+ }
1091
+ function prefixErrors(url, fn) {
1092
+ try {
1093
+ return fn();
1094
+ } catch (e) {
1095
+ throw new Error(`${url}: ${errorMessage(e)}`);
1096
+ }
1097
+ }
1098
+ function errorMessage(e) {
1099
+ return e instanceof Error ? e.message : String(e);
1100
+ }
1101
+
1102
+ // src/verification-record/verify.ts
1103
+ import { verify } from "crypto";
1104
+
1105
+ // src/verification-record/shape.ts
1106
+ var USE_CASE = "VerifyPhoneNumber";
1107
+ var MAX_LIFETIME_SECONDS = 60;
1108
+ var RECORD_VERSION = "1.0";
1109
+ var CARRIER_ROLE = "carrier";
1110
+ var CARRIER_SIGNER_PREFIX = "carrier:";
1111
+ function malformed(message) {
1112
+ return new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, message);
1113
+ }
1114
+ function isNonEmptyString(value) {
1115
+ return typeof value === "string" && value !== "";
1116
+ }
1117
+ function checkClaimShape(obj, iat, exp) {
1118
+ if (typeof member(obj, "verified") !== "boolean") {
1119
+ throw malformed("verified must be a boolean");
1120
+ }
1121
+ for (const name of ["jti", "nonce", "sub"]) {
1122
+ if (!isNonEmptyString(member(obj, name))) {
1123
+ throw malformed(`${name} must be a non-empty string`);
1124
+ }
1125
+ }
1126
+ if (!member(obj, "sub").startsWith("tel:+")) {
1127
+ throw malformed("sub must be tel:+E164");
1128
+ }
1129
+ for (const name of ["origin", "biometric_verification"]) {
1130
+ if (typeof member(obj, name) !== "string") throw malformed(`${name} must be a string`);
1131
+ }
1132
+ if (member(obj, "nbf") !== iat) {
1133
+ throw malformed("nbf must equal iat");
1134
+ }
1135
+ if (member(obj, "use_case") !== USE_CASE) {
1136
+ throw malformed(`use_case must be ${USE_CASE}`);
1137
+ }
1138
+ if (exp < iat + 1 || exp > iat + MAX_LIFETIME_SECONDS) {
1139
+ throw malformed("exp must be 1 to 60 seconds after iat");
1140
+ }
1141
+ const signOffs = readSignOffs(member(obj, "sign_offs"));
1142
+ if (!signOffs) {
1143
+ throw malformed("sign_offs must be an array of well-formed entries");
1144
+ }
1145
+ if (!oneCarrierSignOff(signOffs)) {
1146
+ throw malformed("sign_offs must have exactly one carrier:<id> carrier entry");
1147
+ }
1148
+ return signOffs;
1149
+ }
1150
+ function readSignOffs(raw) {
1151
+ if (!Array.isArray(raw)) return null;
1152
+ const signOffs = [];
1153
+ for (const entry of raw) {
1154
+ const signOff = isJsonObject(entry) ? readSignOff(entry) : null;
1155
+ if (!signOff) return null;
1156
+ signOffs.push(signOff);
1157
+ }
1158
+ return signOffs;
1159
+ }
1160
+ function readSignOff(entry) {
1161
+ const r = new MemberReader(entry);
1162
+ const role = r.str("role");
1163
+ const signer = r.str("signer");
1164
+ const status = r.str("status");
1165
+ const reason = r.str("reason");
1166
+ const format = r.str("format");
1167
+ const token = r.str("token");
1168
+ if (!r.ok || !isNonEmptyString(role) || !isNonEmptyString(signer)) return null;
1169
+ const signOff = { role, signer, status };
1170
+ if (reason !== void 0) signOff.reason = reason;
1171
+ if (format !== void 0) signOff.format = format;
1172
+ if (token !== void 0) signOff.token = token;
1173
+ if (status === "unavailable") return isNonEmptyString(reason) ? signOff : null;
1174
+ if (status === "present") return isNonEmptyString(format) && isNonEmptyString(token) ? signOff : null;
1175
+ return null;
1176
+ }
1177
+ function oneCarrierSignOff(signOffs) {
1178
+ const carriers = signOffs.filter((s) => s.role === CARRIER_ROLE);
1179
+ const signer = carriers.length === 1 ? carriers[0]?.signer ?? "" : "";
1180
+ return signer.length > CARRIER_SIGNER_PREFIX.length && signer.startsWith(CARRIER_SIGNER_PREFIX);
1181
+ }
1182
+ function carrierIDMatchesSignOff(id, signOffs) {
1183
+ const signer = signOffs.find((s) => s.role === CARRIER_ROLE)?.signer ?? "";
1184
+ return signer === CARRIER_SIGNER_PREFIX + id;
1185
+ }
1186
+
1187
+ // src/verification-record/claims.ts
1188
+ var IAT_LEEWAY_SECONDS = 60;
1189
+ function checkRecordClaims(payload, want) {
1190
+ const obj = parseJsonObject(payload.toString("utf8"));
1191
+ if (!obj) {
1192
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "payload is not a JSON object");
1193
+ }
1194
+ if (member(obj, "ver") !== RECORD_VERSION) {
1195
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNSUPPORTED_VERSION, 'ver must be "1.0"');
1196
+ }
1197
+ const iss = member(obj, "iss");
1198
+ if (typeof iss !== "string" || iss !== want.issuer) {
1199
+ throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_ISSUER, `iss does not match ${want.issuer}`);
1200
+ }
1201
+ const aud = member(obj, "aud");
1202
+ if (typeof aud !== "string" || aud !== want.audience) {
1203
+ throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_AUDIENCE, "aud does not match the expected audience");
1204
+ }
1205
+ const { iat, exp } = checkRecordTimes(obj, want);
1206
+ const signOffs = checkClaimShape(obj, iat, exp);
1207
+ const verified = member(obj, "verified");
1208
+ const r = new MemberReader(obj);
1209
+ const claims = {
1210
+ ver: RECORD_VERSION,
1211
+ iss,
1212
+ aud,
1213
+ iat,
1214
+ nbf: iat,
1215
+ exp,
1216
+ verified,
1217
+ sign_offs: signOffs,
1218
+ jti: r.str("jti") ?? "",
1219
+ nonce: r.str("nonce") ?? "",
1220
+ use_case: r.str("use_case") ?? "",
1221
+ sub: r.str("sub") ?? "",
1222
+ origin: r.str("origin") ?? "",
1223
+ biometric_verification: r.str("biometric_verification") ?? ""
1224
+ };
1225
+ assignDefined(claims, "strategy", r.str("strategy"));
1226
+ assignDefined(claims, "phone_number_details", readPhoneNumberDetails(r));
1227
+ assignDefined(claims, "carrier", readCarrier(r));
1228
+ assignDefined(claims, "sim_swap", readSwap(r, "sim_swap"));
1229
+ assignDefined(claims, "device_swap", readSwap(r, "device_swap"));
1230
+ if (!r.ok) {
1231
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "claims have the wrong JSON types");
1232
+ }
1233
+ if (claims.carrier !== void 0 && !carrierIDMatchesSignOff(claims.carrier.id, signOffs)) {
1234
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "carrier.id must match the carrier sign-off signer");
1235
+ }
1236
+ if (want.nonce !== "" && claims.nonce !== want.nonce) {
1237
+ throw new VerificationRecordError(VerificationRecordErrorCode.NONCE_MISMATCH, "nonce does not match the expected nonce");
1238
+ }
1239
+ if (want.origins.length > 0 && !want.origins.includes(claims.origin)) {
1240
+ throw new VerificationRecordError(VerificationRecordErrorCode.ORIGIN_MISMATCH, "origin is not an expected origin");
1241
+ }
1242
+ return claims;
1243
+ }
1244
+ function checkRecordTimes(obj, want) {
1245
+ const iat = member(obj, "iat");
1246
+ const exp = member(obj, "exp");
1247
+ if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp)) {
1248
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "iat and exp must be integers");
1249
+ }
1250
+ const times = { iat, exp };
1251
+ const now = want.nowSeconds;
1252
+ if (times.iat > now + IAT_LEEWAY_SECONDS) {
1253
+ throw new VerificationRecordError(VerificationRecordErrorCode.NOT_YET_VALID, "iat is in the future");
1254
+ }
1255
+ if (times.exp > now) {
1256
+ return times;
1257
+ }
1258
+ if (!want.allowExpired) {
1259
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record has expired");
1260
+ }
1261
+ if (times.iat < now - want.maxAuditAgeSeconds) {
1262
+ throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record is older than the maximum audit age");
1263
+ }
1264
+ return times;
1265
+ }
1266
+ function signOffResults(signOffs) {
1267
+ return signOffs.map((s) => {
1268
+ if (s.status === "unavailable") {
1269
+ const result = { role: s.role, signer: s.signer, result: "unavailable" };
1270
+ assignDefined(result, "reason", s.reason);
1271
+ return result;
1272
+ }
1273
+ return { role: s.role, signer: s.signer, result: "unverified" };
1274
+ });
1275
+ }
1276
+ function readCarrier(r) {
1277
+ const obj = r.object("carrier");
1278
+ if (!obj) return void 0;
1279
+ const s = new MemberReader(obj);
1280
+ const id = s.str("id");
1281
+ const carrier = { id: id ?? "" };
1282
+ assignDefined(carrier, "name", s.str("name"));
1283
+ assignDefined(carrier, "mvno", s.str("mvno"));
1284
+ r.ok = r.ok && s.ok && !!id;
1285
+ return carrier;
1286
+ }
1287
+ function readPhoneNumberDetails(r) {
1288
+ const obj = r.object("phone_number_details");
1289
+ if (!obj) return void 0;
1290
+ const s = new MemberReader(obj);
1291
+ const d = {
1292
+ country_code: s.int("country_code") ?? 0,
1293
+ national_number: s.str("national_number") ?? "",
1294
+ region_code: s.str("region_code") ?? ""
1295
+ };
1296
+ r.ok = r.ok && s.ok;
1297
+ return d;
1298
+ }
1299
+ function readSwap(r, name) {
1300
+ const obj = r.object(name);
1301
+ if (!obj) return void 0;
1302
+ const s = new MemberReader(obj);
1303
+ const info = { checked: s.bool("checked") ?? false };
1304
+ assignDefined(info, "risk_level", s.str("risk_level"));
1305
+ assignDefined(info, "carrier_name", s.str("carrier_name"));
1306
+ assignDefined(info, "reason", s.str("reason"));
1307
+ assignDefined(info, "swapped", s.bool("swapped"));
1308
+ assignDefined(info, "max_age_hours", s.int("max_age_hours"));
1309
+ const band = s.object("age_band");
1310
+ if (band) {
1311
+ const b = new MemberReader(band);
1312
+ info.age_band = { from: b.int("from") ?? -1, to: b.int("to") ?? -1 };
1313
+ s.ok = s.ok && b.ok;
1314
+ }
1315
+ r.ok = r.ok && s.ok;
1316
+ return info;
1317
+ }
1318
+ function assignDefined(target, key, value) {
1319
+ if (value !== void 0) {
1320
+ target[key] = value;
1321
+ }
1322
+ }
1323
+
1324
+ // src/verification-record/verify.ts
1325
+ var RECORD_TYP = "glide-verification+jwt";
1326
+ var DEFAULT_MAX_AUDIT_AGE_SECONDS = 90 * 24 * 60 * 60;
1327
+ var MAX_RECORD_BYTES = 16 * 1024;
1328
+ var RECORD_KIDS = [
1329
+ "glide-record-signing-key-ecdsa-es256-us-2026",
1330
+ "glide-record-signing-key-ecdsa-es256-eu-2026"
1331
+ ];
1332
+ var REVOKED_RECORD_KIDS = [];
1333
+ async function verifyVerificationRecord(record, options, ctx) {
1334
+ const opts = options ?? {};
1335
+ const nowMs = (opts.now ? opts.now() : /* @__PURE__ */ new Date()).getTime();
1336
+ if (!Number.isFinite(nowMs)) {
1337
+ throw new TypeError("options.now must return a valid Date");
1338
+ }
1339
+ const parsed = parseRecord(record);
1340
+ checkRecordKid(parsed.kid, opts.revokedKids ?? []);
1341
+ const key = await ctx.keys.key(parsed.kid);
1342
+ verifyRecordSignature(parsed, key);
1343
+ const maxAuditAge = opts.maxAuditAgeSeconds ?? 0;
1344
+ const claims = checkRecordClaims(parsed.payload, {
1345
+ issuer: opts.issuer ? opts.issuer : ctx.baseUrl.replace(/\/+$/, ""),
1346
+ audience: opts.expectedAudience ? opts.expectedAudience : ctx.clientId,
1347
+ nonce: opts.expectedNonce ?? "",
1348
+ origins: opts.expectedOrigin ?? [],
1349
+ allowExpired: opts.allowExpired === true,
1350
+ maxAuditAgeSeconds: Number.isFinite(maxAuditAge) && maxAuditAge > 0 ? maxAuditAge : DEFAULT_MAX_AUDIT_AGE_SECONDS,
1351
+ nowSeconds: Math.floor(nowMs / 1e3)
1352
+ });
1353
+ return { claims, signOffResults: signOffResults(claims.sign_offs) };
1354
+ }
1355
+ function parseRecord(record) {
1356
+ if (record === void 0 || record === null || record === "") {
1357
+ throw new VerificationRecordError(VerificationRecordErrorCode.RECORD_UNAVAILABLE, "no verification record");
1358
+ }
1359
+ if (typeof record === "string" && Buffer.byteLength(record, "utf8") > MAX_RECORD_BYTES) {
1360
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is larger than 16 KiB");
1361
+ }
1362
+ const segments = typeof record === "string" ? record.split(".") : [];
1363
+ if (segments.length !== 3) {
1364
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is not a compact JWS");
1365
+ }
1366
+ const decoded = segments.map(decodeBase64URL);
1367
+ const [header, payload, signature] = decoded;
1368
+ if (!header || !payload || !signature) {
1369
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record segment is not base64url");
1370
+ }
1371
+ const headerObj = parseJsonObject(header.toString("utf8"));
1372
+ if (!headerObj) {
1373
+ throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "header is not a JSON object");
1374
+ }
1375
+ return {
1376
+ kid: checkRecordHeader(headerObj),
1377
+ signingInput: Buffer.from(`${segments[0]}.${segments[1]}`, "ascii"),
1378
+ payload,
1379
+ signature
1380
+ };
1381
+ }
1382
+ function checkRecordHeader(header) {
1383
+ const alg = member(header, "alg");
1384
+ const typ = member(header, "typ");
1385
+ const kid = member(header, "kid");
1386
+ if (Object.keys(header).length !== 3 || typeof alg !== "string" || typeof typ !== "string" || typeof kid !== "string") {
1387
+ throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header must contain exactly alg, typ and kid");
1388
+ }
1389
+ if (alg !== RECORD_ALG || typ !== RECORD_TYP) {
1390
+ throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header alg/typ not allowed");
1391
+ }
1392
+ return kid;
1393
+ }
1394
+ function checkRecordKid(kid, revoked) {
1395
+ if (REVOKED_RECORD_KIDS.includes(kid) || revoked.includes(kid)) {
1396
+ throw new VerificationRecordError(VerificationRecordErrorCode.REVOKED_KEY, `kid ${kid} is revoked`);
1397
+ }
1398
+ if (!RECORD_KIDS.includes(kid)) {
1399
+ throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not a record signing key`);
1400
+ }
1401
+ }
1402
+ function verifyRecordSignature(record, key) {
1403
+ if (record.signature.length !== 64) {
1404
+ throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature is not 64 bytes");
1405
+ }
1406
+ let valid = false;
1407
+ try {
1408
+ valid = verify("sha256", record.signingInput, { key, dsaEncoding: "ieee-p1363" }, record.signature);
1409
+ } catch {
1410
+ valid = false;
1411
+ }
1412
+ if (!valid) {
1413
+ throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature does not verify");
1414
+ }
1415
+ }
781
1416
 
782
1417
  // src/client.ts
783
1418
  var MagicalAuthClient = class {
784
1419
  config;
785
1420
  tokenManager;
1421
+ recordKeys;
786
1422
  /**
787
1423
  * Creates a new MagicalAuthClient instance.
788
1424
  *
@@ -804,6 +1440,31 @@ var MagicalAuthClient = class {
804
1440
  this.config.httpClient,
805
1441
  this.config.logger
806
1442
  );
1443
+ this.recordKeys = new RecordKeyCache(
1444
+ this.config.baseUrl.replace(/\/+$/, ""),
1445
+ this.config.httpClient,
1446
+ this.config.timeout
1447
+ );
1448
+ }
1449
+ /**
1450
+ * Check authentication eligibility for a phone number or PLMN.
1451
+ * Returns available authentication strategies with platform requirements.
1452
+ *
1453
+ * @param request - Eligibility request with phone_number or plmn. `client_info.user_agent` is required.
1454
+ * @param options - Per-request options (e.g., correlationId)
1455
+ * @returns Eligibility response with available options
1456
+ * @throws {ValidationError} If request validation fails (incl. missing/blank `client_info.user_agent`)
1457
+ * @throws {MagicalAuthError} For other API errors
1458
+ */
1459
+ async checkEligibility(request, options) {
1460
+ validateEligibilityRequest(request);
1461
+ const response = await this.doRequest(
1462
+ "POST",
1463
+ "/magic-auth/v2/auth/eligibility",
1464
+ request,
1465
+ options
1466
+ );
1467
+ return response;
807
1468
  }
808
1469
  /**
809
1470
  * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
@@ -825,7 +1486,11 @@ var MagicalAuthClient = class {
825
1486
  const nonce = request.nonce || generateNonce();
826
1487
  const feCode = generateFeCode();
827
1488
  const feHash = computeFeHash(feCode);
828
- const requestWithHash = { ...request, nonce, fe_hash: feHash };
1489
+ const requestWithHash = {
1490
+ ...request,
1491
+ nonce,
1492
+ fe_hash: feHash
1493
+ };
829
1494
  const response = await this.doRequest(
830
1495
  "POST",
831
1496
  "/magic-auth/v2/auth/prepare",
@@ -843,6 +1508,39 @@ var MagicalAuthClient = class {
843
1508
  });
844
1509
  return result;
845
1510
  }
1511
+ /**
1512
+ * Prepares authentication for several phone numbers at once.
1513
+ *
1514
+ * Fans out one ordinary {@link prepare} call per number, so each number gets
1515
+ * its own carrier resolution, residency routing and session. Per-number
1516
+ * failures are returned as items rather than thrown; this only throws
1517
+ * {@link ValidationError}, and only before any request is issued.
1518
+ *
1519
+ * @param request - Shared prepare fields plus `phone_numbers` (1..10)
1520
+ * @param options - Per-request options (e.g., correlationId)
1521
+ * @returns One result per input number, in input order
1522
+ * @throws {ValidationError} If the list is empty, over the cap, has blank entries, or a shared prepare field is invalid
1523
+ */
1524
+ async prepareMultiple(request, options) {
1525
+ validatePrepareMultipleRequest(request);
1526
+ const { phone_numbers: phoneNumbers, nonce: _nonce, ...shared } = request;
1527
+ const derived = phoneNumbers.map(
1528
+ (phone_number) => ({ ...shared, phone_number })
1529
+ );
1530
+ for (const single of derived) {
1531
+ validatePrepareRequest(single);
1532
+ }
1533
+ this.config.logger.debug("Preparing auth for multiple numbers", {
1534
+ count: phoneNumbers.length
1535
+ });
1536
+ const settled = await Promise.allSettled(
1537
+ derived.map((single) => this.prepare(single, options))
1538
+ );
1539
+ return settled.map((outcome, index) => {
1540
+ const phone_number = phoneNumbers[index];
1541
+ return outcome.status === "fulfilled" ? { phone_number, ok: true, result: outcome.value } : { phone_number, ok: false, error: asMagicalAuthError(outcome.reason) };
1542
+ });
1543
+ }
846
1544
  /**
847
1545
  * Validates device binding codes and completes a link protocol session.
848
1546
  *
@@ -900,6 +1598,26 @@ var MagicalAuthClient = class {
900
1598
  this.config.logger.debug("Phone verification complete", { verified: response.verified });
901
1599
  return response;
902
1600
  }
1601
+ /**
1602
+ * Verifies a verification record returned by {@link verifyPhoneNumber}: the
1603
+ * ES256 signature against Glide's published record keys, then issuer,
1604
+ * the expected audience (default this client's ID), validity window, shape, nonce and origin.
1605
+ *
1606
+ * A missing or empty record fails with `RECORD_UNAVAILABLE`, so a caller
1607
+ * that requires records can pass `response.verification_record` straight in.
1608
+ *
1609
+ * @param record - Compact JWS from `VerifyPhoneNumberResponse.verification_record`
1610
+ * @param options - Expected nonce, expected audience, expected origins, audit mode, issuer override, extra revoked kids, clock
1611
+ * @returns The verified claims and how each sign-off was treated
1612
+ * @throws {VerificationRecordError} On any failed check; `code` is a {@link VerificationRecordErrorCode}
1613
+ */
1614
+ async verifyVerificationRecord(record, options) {
1615
+ return verifyVerificationRecord(record, options, {
1616
+ baseUrl: this.config.baseUrl,
1617
+ clientId: this.config.clientId,
1618
+ keys: this.recordKeys
1619
+ });
1620
+ }
903
1621
  /**
904
1622
  * Retrieves the phone number associated with the device using digital credentials.
905
1623
  *
@@ -1113,6 +1831,13 @@ function generateNonce(length = 32) {
1113
1831
  }
1114
1832
  return result;
1115
1833
  }
1834
+ function asMagicalAuthError(reason) {
1835
+ if (reason instanceof MagicalAuthError) {
1836
+ return reason;
1837
+ }
1838
+ const message = reason instanceof Error ? reason.message : "Prepare failed";
1839
+ return new MagicalAuthError(message, "UNKNOWN_ERROR", 0);
1840
+ }
1116
1841
 
1117
1842
  // src/logger.ts
1118
1843
  function createLogger(config = {}) {
@@ -1135,19 +1860,22 @@ var JWT_RE = /(eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)/g;
1135
1860
  var SESSION_RE = /(session[_-]?key)(["']?\s*[:=]\s*["']?)([A-Za-z0-9_-]{16,})/gi;
1136
1861
  var SENSITIVE = ["phone_number", "phonenumber", "credential", "token", "password", "secret", "fe_code", "fecode"];
1137
1862
  function sanitize(data) {
1863
+ return sanitizeWith(data, /* @__PURE__ */ new WeakSet());
1864
+ }
1865
+ function sanitizeWith(data, seen) {
1138
1866
  if (data == null) return data;
1139
1867
  if (typeof data === "string") {
1140
- return data.replace(PHONE_RE, (m) => m.length < 8 ? m : `${m.slice(0, 4)}***${m.slice(-4)}`).replace(JWT_RE, "[JWT]").replace(SESSION_RE, (_, k, sep, v) => `${k}${sep}${v.slice(0, 4)}***${v.slice(-4)}`);
1868
+ return data.replace(JWT_RE, "[JWT]").replace(SESSION_RE, (_, k, sep, v) => `${k}${sep}${v.slice(0, 4)}***${v.slice(-4)}`).replace(PHONE_RE, (m) => m.length < 8 ? m : `${m.slice(0, 4)}***${m.slice(-4)}`);
1141
1869
  }
1142
- if (Array.isArray(data)) return data.map(sanitize);
1143
- if (typeof data === "object") {
1144
- const out = {};
1145
- for (const [k, v] of Object.entries(data)) {
1146
- out[k] = SENSITIVE.some((s) => k.toLowerCase().includes(s)) && typeof v === "string" ? "[REDACTED]" : sanitize(v);
1147
- }
1148
- return out;
1870
+ if (typeof data !== "object") return data;
1871
+ if (seen.has(data)) return "[Circular]";
1872
+ seen.add(data);
1873
+ if (Array.isArray(data)) return data.map((v) => sanitizeWith(v, seen));
1874
+ const out = {};
1875
+ for (const [k, v] of Object.entries(data)) {
1876
+ out[k] = SENSITIVE.some((s) => k.toLowerCase().includes(s)) ? "[REDACTED]" : sanitizeWith(v, seen);
1149
1877
  }
1150
- return data;
1878
+ return out;
1151
1879
  }
1152
1880
 
1153
1881
  // src/index.ts
@@ -1158,8 +1886,11 @@ export {
1158
1886
  BINDING_COOKIE_MAX_AGE,
1159
1887
  BINDING_COOKIE_PREFIX,
1160
1888
  BadRequestError,
1889
+ BiometricVerification,
1161
1890
  BrowserMismatchError,
1891
+ CarrierAppUnavailableError,
1162
1892
  CarrierNotEligibleError,
1893
+ CarrierRejectedError,
1163
1894
  DEFAULT_BASE_URL,
1164
1895
  DEFAULT_TIMEOUT,
1165
1896
  DesktopWaitError,
@@ -1172,6 +1903,7 @@ export {
1172
1903
  MagicalAuthClient,
1173
1904
  MagicalAuthError,
1174
1905
  MissingBindingCookieError,
1906
+ PREPARE_MULTIPLE_MAX,
1175
1907
  PhoneNumberMismatchError,
1176
1908
  RateLimitError,
1177
1909
  SENSITIVE_KEYS,
@@ -1185,6 +1917,8 @@ export {
1185
1917
  UseCase,
1186
1918
  VERSION,
1187
1919
  ValidationError,
1920
+ VerificationRecordError,
1921
+ VerificationRecordErrorCode,
1188
1922
  assertValidFeCode,
1189
1923
  buildClearBindingCookieHeader,
1190
1924
  buildSetBindingCookieHeader,