@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/LICENSE +190 -23
- package/README.md +167 -1
- package/dist/index.cjs +763 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +220 -5
- package/dist/index.d.ts +220 -5
- package/dist/index.js +755 -21
- package/dist/index.js.map +1 -1
- package/dist/{types-DKfytuP6.d.cts → types-BPuPzIcL.d.cts} +465 -162
- package/dist/{types-DKfytuP6.d.ts → types-BPuPzIcL.d.ts} +465 -162
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +10 -3
package/dist/index.cjs
CHANGED
|
@@ -24,8 +24,11 @@ __export(index_exports, {
|
|
|
24
24
|
BINDING_COOKIE_MAX_AGE: () => BINDING_COOKIE_MAX_AGE,
|
|
25
25
|
BINDING_COOKIE_PREFIX: () => BINDING_COOKIE_PREFIX,
|
|
26
26
|
BadRequestError: () => BadRequestError,
|
|
27
|
+
BiometricVerification: () => BiometricVerification,
|
|
27
28
|
BrowserMismatchError: () => BrowserMismatchError,
|
|
29
|
+
CarrierAppUnavailableError: () => CarrierAppUnavailableError,
|
|
28
30
|
CarrierNotEligibleError: () => CarrierNotEligibleError,
|
|
31
|
+
CarrierRejectedError: () => CarrierRejectedError,
|
|
29
32
|
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
30
33
|
DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
|
|
31
34
|
DesktopWaitError: () => DesktopWaitError,
|
|
@@ -38,6 +41,7 @@ __export(index_exports, {
|
|
|
38
41
|
MagicalAuthClient: () => MagicalAuthClient,
|
|
39
42
|
MagicalAuthError: () => MagicalAuthError,
|
|
40
43
|
MissingBindingCookieError: () => MissingBindingCookieError,
|
|
44
|
+
PREPARE_MULTIPLE_MAX: () => PREPARE_MULTIPLE_MAX,
|
|
41
45
|
PhoneNumberMismatchError: () => PhoneNumberMismatchError,
|
|
42
46
|
RateLimitError: () => RateLimitError,
|
|
43
47
|
SENSITIVE_KEYS: () => SENSITIVE_KEYS,
|
|
@@ -51,6 +55,8 @@ __export(index_exports, {
|
|
|
51
55
|
UseCase: () => UseCase,
|
|
52
56
|
VERSION: () => VERSION,
|
|
53
57
|
ValidationError: () => ValidationError,
|
|
58
|
+
VerificationRecordError: () => VerificationRecordError,
|
|
59
|
+
VerificationRecordErrorCode: () => VerificationRecordErrorCode,
|
|
54
60
|
assertValidFeCode: () => assertValidFeCode,
|
|
55
61
|
buildClearBindingCookieHeader: () => buildClearBindingCookieHeader,
|
|
56
62
|
buildSetBindingCookieHeader: () => buildSetBindingCookieHeader,
|
|
@@ -71,7 +77,7 @@ module.exports = __toCommonJS(index_exports);
|
|
|
71
77
|
var import_node_module = require("module");
|
|
72
78
|
|
|
73
79
|
// src/client.ts
|
|
74
|
-
var
|
|
80
|
+
var import_node_crypto4 = require("crypto");
|
|
75
81
|
|
|
76
82
|
// src/internal/http.ts
|
|
77
83
|
var defaultHttpClient = {
|
|
@@ -105,6 +111,8 @@ var ErrorCode = {
|
|
|
105
111
|
SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
|
|
106
112
|
INVALID_VERIFICATION: "INVALID_VERIFICATION",
|
|
107
113
|
CARRIER_NOT_ELIGIBLE: "CARRIER_NOT_ELIGIBLE",
|
|
114
|
+
CARRIER_REJECTED: "CARRIER_REJECTED",
|
|
115
|
+
CARRIER_APP_UNAVAILABLE: "CARRIER_APP_UNAVAILABLE",
|
|
108
116
|
UNSUPPORTED_PLATFORM: "UNSUPPORTED_PLATFORM",
|
|
109
117
|
PHONE_NUMBER_MISMATCH: "PHONE_NUMBER_MISMATCH",
|
|
110
118
|
INVALID_CREDENTIAL_FORMAT: "INVALID_CREDENTIAL_FORMAT",
|
|
@@ -130,9 +138,17 @@ var MagicalAuthError = class extends Error {
|
|
|
130
138
|
*/
|
|
131
139
|
status;
|
|
132
140
|
/**
|
|
133
|
-
* Request
|
|
141
|
+
* The id of this request, the same value as the `X-Request-ID` response
|
|
142
|
+
* header. Quote it to Glide support.
|
|
134
143
|
*/
|
|
135
144
|
requestId;
|
|
145
|
+
/**
|
|
146
|
+
* The session the failed request was about, once the server had read it from
|
|
147
|
+
* the request. Undefined when the request failed before naming a session, on
|
|
148
|
+
* operations that have none (eligibility, prepare), and from servers older
|
|
149
|
+
* than the release that added it.
|
|
150
|
+
*/
|
|
151
|
+
sessionKey;
|
|
136
152
|
/**
|
|
137
153
|
* Additional error details.
|
|
138
154
|
*/
|
|
@@ -201,6 +217,18 @@ var CarrierNotEligibleError = class extends MagicalAuthError {
|
|
|
201
217
|
this.name = "CarrierNotEligibleError";
|
|
202
218
|
}
|
|
203
219
|
};
|
|
220
|
+
var CarrierRejectedError = class extends MagicalAuthError {
|
|
221
|
+
constructor(message = "The carrier rejected the authentication request", requestId, details) {
|
|
222
|
+
super(message, "CARRIER_REJECTED", 422, requestId, details);
|
|
223
|
+
this.name = "CarrierRejectedError";
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
var CarrierAppUnavailableError = class extends MagicalAuthError {
|
|
227
|
+
constructor(message = "Carrier app unavailable on the phone that scanned the QR code", requestId, details) {
|
|
228
|
+
super(message, "CARRIER_APP_UNAVAILABLE", 422, requestId, details);
|
|
229
|
+
this.name = "CarrierAppUnavailableError";
|
|
230
|
+
}
|
|
231
|
+
};
|
|
204
232
|
var UnsupportedPlatformError = class extends MagicalAuthError {
|
|
205
233
|
constructor(message = "Platform not supported", requestId) {
|
|
206
234
|
super(message, "UNSUPPORTED_PLATFORM", 422, requestId);
|
|
@@ -281,9 +309,31 @@ var MissingBindingCookieError = class extends DeviceBindingError {
|
|
|
281
309
|
var DesktopWaitError = class extends MagicalAuthError {
|
|
282
310
|
waitResponse;
|
|
283
311
|
constructor(waitResponse) {
|
|
284
|
-
super(waitResponse.message, "DESKTOP_WAIT", 202);
|
|
312
|
+
super(waitResponse.message, "DESKTOP_WAIT", 202, waitResponse.request_id);
|
|
285
313
|
this.name = "DesktopWaitError";
|
|
286
314
|
this.waitResponse = waitResponse;
|
|
315
|
+
Object.assign(this, { sessionKey: waitResponse.session_key });
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
var VerificationRecordErrorCode = {
|
|
319
|
+
MALFORMED: "MALFORMED",
|
|
320
|
+
DISALLOWED_HEADER: "DISALLOWED_HEADER",
|
|
321
|
+
UNKNOWN_KEY: "UNKNOWN_KEY",
|
|
322
|
+
BAD_SIGNATURE: "BAD_SIGNATURE",
|
|
323
|
+
WRONG_ISSUER: "WRONG_ISSUER",
|
|
324
|
+
WRONG_AUDIENCE: "WRONG_AUDIENCE",
|
|
325
|
+
EXPIRED: "EXPIRED",
|
|
326
|
+
NOT_YET_VALID: "NOT_YET_VALID",
|
|
327
|
+
NONCE_MISMATCH: "NONCE_MISMATCH",
|
|
328
|
+
ORIGIN_MISMATCH: "ORIGIN_MISMATCH",
|
|
329
|
+
UNSUPPORTED_VERSION: "UNSUPPORTED_VERSION",
|
|
330
|
+
REVOKED_KEY: "REVOKED_KEY",
|
|
331
|
+
RECORD_UNAVAILABLE: "RECORD_UNAVAILABLE"
|
|
332
|
+
};
|
|
333
|
+
var VerificationRecordError = class extends MagicalAuthError {
|
|
334
|
+
constructor(code, message) {
|
|
335
|
+
super(`verification record: ${code}: ${message}`, code, 0);
|
|
336
|
+
this.name = "VerificationRecordError";
|
|
287
337
|
}
|
|
288
338
|
};
|
|
289
339
|
function parseRetryAfter(headers) {
|
|
@@ -302,9 +352,10 @@ function parseRetryAfter(headers) {
|
|
|
302
352
|
return void 0;
|
|
303
353
|
}
|
|
304
354
|
function createErrorFromResponse(response, headers) {
|
|
305
|
-
const { code, message, request_id, details, status, trace_id, span_id, timestamp, service } = response;
|
|
355
|
+
const { code, message, request_id, session_key, details, status, trace_id, span_id, timestamp, service } = response;
|
|
306
356
|
const error = createTypedError(code, message, request_id, details, status, headers);
|
|
307
357
|
return Object.assign(error, {
|
|
358
|
+
sessionKey: session_key,
|
|
308
359
|
traceId: trace_id,
|
|
309
360
|
spanId: span_id,
|
|
310
361
|
timestamp,
|
|
@@ -328,6 +379,18 @@ function createTypedError(code, message, request_id, details, status, headers) {
|
|
|
328
379
|
return new SessionNotFoundError(message, request_id);
|
|
329
380
|
case "CARRIER_NOT_ELIGIBLE":
|
|
330
381
|
return new CarrierNotEligibleError(message, request_id);
|
|
382
|
+
case "CARRIER_REJECTED":
|
|
383
|
+
return new CarrierRejectedError(
|
|
384
|
+
message,
|
|
385
|
+
request_id,
|
|
386
|
+
details
|
|
387
|
+
);
|
|
388
|
+
case "CARRIER_APP_UNAVAILABLE":
|
|
389
|
+
return new CarrierAppUnavailableError(
|
|
390
|
+
message,
|
|
391
|
+
request_id,
|
|
392
|
+
details
|
|
393
|
+
);
|
|
331
394
|
case "UNSUPPORTED_PLATFORM":
|
|
332
395
|
return new UnsupportedPlatformError(message, request_id);
|
|
333
396
|
case "INVALID_CREDENTIAL_FORMAT":
|
|
@@ -429,17 +492,17 @@ var TokenManager = class {
|
|
|
429
492
|
body: "grant_type=client_credentials"
|
|
430
493
|
});
|
|
431
494
|
if (!response.ok) {
|
|
432
|
-
let
|
|
495
|
+
let errorMessage2 = "Token request failed";
|
|
433
496
|
try {
|
|
434
497
|
const errorBody = await response.json();
|
|
435
498
|
if (errorBody.error_description) {
|
|
436
|
-
|
|
499
|
+
errorMessage2 = errorBody.error_description;
|
|
437
500
|
} else if (errorBody.error) {
|
|
438
|
-
|
|
501
|
+
errorMessage2 = errorBody.error;
|
|
439
502
|
}
|
|
440
503
|
} catch {
|
|
441
504
|
}
|
|
442
|
-
throw new UnauthorizedError(
|
|
505
|
+
throw new UnauthorizedError(errorMessage2);
|
|
443
506
|
}
|
|
444
507
|
const data = await response.json();
|
|
445
508
|
if (!data.access_token) {
|
|
@@ -695,12 +758,18 @@ function getCompletionPageHtml(completeEndpoint) {
|
|
|
695
758
|
|
|
696
759
|
if (res.ok) {
|
|
697
760
|
var signalKey = 'glide_signal_' + sessionKey;
|
|
761
|
+
var sigmetaKey = 'glide_sigmeta_' + sessionKey;
|
|
762
|
+
var signalStored = false;
|
|
698
763
|
try {
|
|
699
764
|
localStorage.setItem(signalKey, sessionKey);
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
}, 5000);
|
|
765
|
+
signalStored = true;
|
|
766
|
+
localStorage.setItem(sigmetaKey, String(Date.now()));
|
|
703
767
|
} catch(e) {}
|
|
768
|
+
if (signalStored) {
|
|
769
|
+
setTimeout(function() {
|
|
770
|
+
try { localStorage.removeItem(signalKey); localStorage.removeItem(sigmetaKey); } catch(e) {}
|
|
771
|
+
}, 600000);
|
|
772
|
+
}
|
|
704
773
|
tryClose();
|
|
705
774
|
} else {
|
|
706
775
|
var code = '';
|
|
@@ -774,15 +843,26 @@ var SessionStatus = {
|
|
|
774
843
|
COMPLETED: "completed",
|
|
775
844
|
FAILED: "failed"
|
|
776
845
|
};
|
|
846
|
+
var BiometricVerification = {
|
|
847
|
+
VERIFIED: "VERIFIED",
|
|
848
|
+
FAILED: "FAILED",
|
|
849
|
+
NOT_ENROLLED: "NOT_ENROLLED",
|
|
850
|
+
UNSUPPORTED: "UNSUPPORTED",
|
|
851
|
+
NOT_REQUESTED: "NOT_REQUESTED"
|
|
852
|
+
};
|
|
853
|
+
|
|
854
|
+
// src/models/prepare-multiple.ts
|
|
855
|
+
var PREPARE_MULTIPLE_MAX = 10;
|
|
777
856
|
|
|
778
857
|
// src/validation.ts
|
|
779
858
|
function validatePrepareRequest(request) {
|
|
780
859
|
const errors = {};
|
|
781
860
|
const hasParentSession = !!request.options?.parent_session_id?.trim();
|
|
861
|
+
const phoneNumber = request.phone_number?.trim();
|
|
782
862
|
if (!request.use_case && !hasParentSession) {
|
|
783
863
|
errors.use_case = "use_case is required";
|
|
784
864
|
}
|
|
785
|
-
if (request.use_case === UseCase.VERIFY_PHONE_NUMBER && !
|
|
865
|
+
if (request.use_case === UseCase.VERIFY_PHONE_NUMBER && !phoneNumber) {
|
|
786
866
|
errors.phone_number = "phone_number is required for VerifyPhoneNumber";
|
|
787
867
|
}
|
|
788
868
|
if (Object.keys(errors).length > 0) {
|
|
@@ -847,11 +927,573 @@ function validateCompleteRequest(request) {
|
|
|
847
927
|
throw new DeviceBindingError("Invalid device binding inputs");
|
|
848
928
|
}
|
|
849
929
|
}
|
|
930
|
+
function validateEligibilityRequest(request) {
|
|
931
|
+
const errors = {};
|
|
932
|
+
const phoneNumber = request.phone_number?.trim();
|
|
933
|
+
if (!phoneNumber && !request.plmn) {
|
|
934
|
+
errors.phone_number = "phone_number or plmn is required";
|
|
935
|
+
}
|
|
936
|
+
if (!request.client_info?.user_agent?.trim()) {
|
|
937
|
+
errors["client_info.user_agent"] = "client_info.user_agent is required";
|
|
938
|
+
}
|
|
939
|
+
if (Object.keys(errors).length > 0) {
|
|
940
|
+
throw new ValidationError("Request validation failed", errors);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
function validatePrepareMultipleRequest(request) {
|
|
944
|
+
if (request == null) {
|
|
945
|
+
throw new ValidationError("Request validation failed", {
|
|
946
|
+
request: "request is required"
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
const numbers = request.phone_numbers;
|
|
950
|
+
let message = null;
|
|
951
|
+
if (!Array.isArray(numbers) || numbers.length === 0) {
|
|
952
|
+
message = "phone_numbers must contain at least one number";
|
|
953
|
+
} else if (numbers.length > PREPARE_MULTIPLE_MAX) {
|
|
954
|
+
message = `phone_numbers must contain at most ${PREPARE_MULTIPLE_MAX} numbers`;
|
|
955
|
+
} else if (Array.from(numbers).some((n) => typeof n !== "string" || !n.trim())) {
|
|
956
|
+
message = "phone_numbers must not contain blank entries";
|
|
957
|
+
}
|
|
958
|
+
if (message) {
|
|
959
|
+
throw new ValidationError("Request validation failed", { phone_numbers: message });
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// src/verification-record/jwk.ts
|
|
964
|
+
var import_node_crypto2 = require("crypto");
|
|
965
|
+
|
|
966
|
+
// src/verification-record/decode.ts
|
|
967
|
+
var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]*$/;
|
|
968
|
+
function decodeBase64URL(segment) {
|
|
969
|
+
if (!BASE64URL_ALPHABET.test(segment) || segment.length % 4 === 1) {
|
|
970
|
+
return null;
|
|
971
|
+
}
|
|
972
|
+
const bytes = Buffer.from(segment, "base64url");
|
|
973
|
+
return bytes.toString("base64url") === segment ? bytes : null;
|
|
974
|
+
}
|
|
975
|
+
function isJsonObject(value) {
|
|
976
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
977
|
+
}
|
|
978
|
+
function parseJsonObject(text) {
|
|
979
|
+
try {
|
|
980
|
+
const value = JSON.parse(text);
|
|
981
|
+
return isJsonObject(value) ? value : null;
|
|
982
|
+
} catch {
|
|
983
|
+
return null;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
function member(obj, name) {
|
|
987
|
+
return Object.hasOwn(obj, name) ? obj[name] : void 0;
|
|
988
|
+
}
|
|
989
|
+
var MemberReader = class {
|
|
990
|
+
constructor(obj) {
|
|
991
|
+
this.obj = obj;
|
|
992
|
+
}
|
|
993
|
+
obj;
|
|
994
|
+
ok = true;
|
|
995
|
+
str(name) {
|
|
996
|
+
return this.read(name, (v) => typeof v === "string");
|
|
997
|
+
}
|
|
998
|
+
bool(name) {
|
|
999
|
+
return this.read(name, (v) => typeof v === "boolean");
|
|
1000
|
+
}
|
|
1001
|
+
int(name) {
|
|
1002
|
+
return this.read(name, (v) => Number.isSafeInteger(v));
|
|
1003
|
+
}
|
|
1004
|
+
/** A nested object member; absent yields undefined. Present null is a wrong type. */
|
|
1005
|
+
object(name) {
|
|
1006
|
+
return this.read(name, isJsonObject);
|
|
1007
|
+
}
|
|
1008
|
+
read(name, accept) {
|
|
1009
|
+
if (!Object.hasOwn(this.obj, name)) return void 0;
|
|
1010
|
+
const value = this.obj[name];
|
|
1011
|
+
if (accept(value)) return value;
|
|
1012
|
+
this.ok = false;
|
|
1013
|
+
return void 0;
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1016
|
+
|
|
1017
|
+
// src/verification-record/jwk.ts
|
|
1018
|
+
var RECORD_ALG = "ES256";
|
|
1019
|
+
function parseJWKS(body) {
|
|
1020
|
+
const doc = parseJsonObject(body);
|
|
1021
|
+
if (!doc) {
|
|
1022
|
+
throw new Error("JWKS is not a JSON object");
|
|
1023
|
+
}
|
|
1024
|
+
const entries = member(doc, "keys");
|
|
1025
|
+
if (!Array.isArray(entries)) {
|
|
1026
|
+
throw new Error("JWKS keys is not an array");
|
|
1027
|
+
}
|
|
1028
|
+
const keys = [];
|
|
1029
|
+
for (const entry of entries) {
|
|
1030
|
+
if (!isJsonObject(entry)) continue;
|
|
1031
|
+
const r = new MemberReader(entry);
|
|
1032
|
+
const k = {
|
|
1033
|
+
kty: r.str("kty") ?? "",
|
|
1034
|
+
crv: r.str("crv") ?? "",
|
|
1035
|
+
use: r.str("use") ?? "",
|
|
1036
|
+
alg: r.str("alg") ?? "",
|
|
1037
|
+
kid: r.str("kid") ?? "",
|
|
1038
|
+
x: r.str("x") ?? "",
|
|
1039
|
+
y: r.str("y") ?? ""
|
|
1040
|
+
};
|
|
1041
|
+
if (r.ok) keys.push(k);
|
|
1042
|
+
}
|
|
1043
|
+
return keys;
|
|
1044
|
+
}
|
|
1045
|
+
function recordPublicKey(k) {
|
|
1046
|
+
if (k.kty !== "EC" || k.crv !== "P-256" || k.use !== "sig" || k.alg !== RECORD_ALG) {
|
|
1047
|
+
throw new Error("JWK is not an EC P-256 ES256 signing key");
|
|
1048
|
+
}
|
|
1049
|
+
const x = decodeBase64URL(k.x);
|
|
1050
|
+
const y = decodeBase64URL(k.y);
|
|
1051
|
+
if (!x || !y || x.length !== 32 || y.length !== 32) {
|
|
1052
|
+
throw new Error("JWK coordinates are not 32-byte base64url");
|
|
1053
|
+
}
|
|
1054
|
+
try {
|
|
1055
|
+
return (0, import_node_crypto2.createPublicKey)({ key: { kty: "EC", crv: "P-256", x: k.x, y: k.y }, format: "jwk" });
|
|
1056
|
+
} catch {
|
|
1057
|
+
throw new Error("JWK point is not on P-256");
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// src/verification-record/jwks.ts
|
|
1062
|
+
var DEFAULT_MAX_AGE_SECONDS = 300;
|
|
1063
|
+
var REFRESH_INTERVAL_MS = 6e4;
|
|
1064
|
+
var MAX_JWKS_BYTES = 1 << 20;
|
|
1065
|
+
var JWKS_PATH = "/.well-known/us/jwks.json";
|
|
1066
|
+
var RecordKeyCache = class {
|
|
1067
|
+
constructor(baseUrl, httpClient, timeoutMs) {
|
|
1068
|
+
this.baseUrl = baseUrl;
|
|
1069
|
+
this.httpClient = httpClient;
|
|
1070
|
+
this.timeoutMs = timeoutMs;
|
|
1071
|
+
}
|
|
1072
|
+
baseUrl;
|
|
1073
|
+
httpClient;
|
|
1074
|
+
timeoutMs;
|
|
1075
|
+
now = Date.now;
|
|
1076
|
+
keys = null;
|
|
1077
|
+
expiresAt = 0;
|
|
1078
|
+
lastRefresh = -Infinity;
|
|
1079
|
+
backoffUntil = -Infinity;
|
|
1080
|
+
queue = Promise.resolve();
|
|
1081
|
+
key(kid) {
|
|
1082
|
+
const run = this.queue.then(() => this.resolve(kid));
|
|
1083
|
+
this.queue = run.catch(() => void 0);
|
|
1084
|
+
return run;
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Refetches when the cache has expired, or when kid is missing and the last
|
|
1088
|
+
* refresh is at least 60 s old. After a failed refresh the previous keys are
|
|
1089
|
+
* kept and further refreshes are refused for 60 s.
|
|
1090
|
+
*/
|
|
1091
|
+
async resolve(kid) {
|
|
1092
|
+
const now = this.now();
|
|
1093
|
+
const cached = this.keys?.has(kid) ?? false;
|
|
1094
|
+
const expired = this.keys === null || now >= this.expiresAt;
|
|
1095
|
+
if (expired || !cached && now - this.lastRefresh >= REFRESH_INTERVAL_MS) {
|
|
1096
|
+
if (now < this.backoffUntil) {
|
|
1097
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, "record key fetch is backing off after a failure");
|
|
1098
|
+
}
|
|
1099
|
+
try {
|
|
1100
|
+
await this.refresh(now);
|
|
1101
|
+
} catch (e) {
|
|
1102
|
+
this.backoffUntil = now + REFRESH_INTERVAL_MS;
|
|
1103
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `fetch record keys: ${errorMessage(e)}`);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
const jwk = this.keys?.get(kid);
|
|
1107
|
+
if (!jwk) {
|
|
1108
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not published`);
|
|
1109
|
+
}
|
|
1110
|
+
try {
|
|
1111
|
+
return recordPublicKey(jwk);
|
|
1112
|
+
} catch (e) {
|
|
1113
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid}: ${errorMessage(e)}`);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
async refresh(now) {
|
|
1117
|
+
this.lastRefresh = now;
|
|
1118
|
+
const doc = await this.fetch(`${this.baseUrl}${JWKS_PATH}`);
|
|
1119
|
+
const keys = /* @__PURE__ */ new Map();
|
|
1120
|
+
for (const k of doc.keys) {
|
|
1121
|
+
if (!keys.has(k.kid)) keys.set(k.kid, k);
|
|
1122
|
+
}
|
|
1123
|
+
this.keys = keys;
|
|
1124
|
+
this.expiresAt = now + doc.maxAgeSeconds * 1e3;
|
|
1125
|
+
}
|
|
1126
|
+
async fetch(url) {
|
|
1127
|
+
const controller = new AbortController();
|
|
1128
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
1129
|
+
try {
|
|
1130
|
+
const response = await this.httpClient.request({
|
|
1131
|
+
method: "GET",
|
|
1132
|
+
url,
|
|
1133
|
+
headers: { Accept: "application/json" },
|
|
1134
|
+
signal: controller.signal
|
|
1135
|
+
});
|
|
1136
|
+
if (response.status !== 200) {
|
|
1137
|
+
throw new Error(`${url}: HTTP ${response.status}`);
|
|
1138
|
+
}
|
|
1139
|
+
const body = await response.text();
|
|
1140
|
+
if (Buffer.byteLength(body, "utf8") > MAX_JWKS_BYTES) {
|
|
1141
|
+
throw new Error(`${url}: JWKS is larger than 1 MiB`);
|
|
1142
|
+
}
|
|
1143
|
+
const keys = prefixErrors(url, () => parseJWKS(body));
|
|
1144
|
+
return { keys, maxAgeSeconds: cacheMaxAge(response.headers?.get("cache-control") ?? null) };
|
|
1145
|
+
} catch (e) {
|
|
1146
|
+
if (controller.signal.aborted) {
|
|
1147
|
+
throw new Error(`${url}: timed out after ${this.timeoutMs}ms`);
|
|
1148
|
+
}
|
|
1149
|
+
throw e;
|
|
1150
|
+
} finally {
|
|
1151
|
+
clearTimeout(timer);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
};
|
|
1155
|
+
function cacheMaxAge(cacheControl) {
|
|
1156
|
+
for (const directive of (cacheControl ?? "").split(",")) {
|
|
1157
|
+
const trimmed = directive.trim();
|
|
1158
|
+
const eq = trimmed.indexOf("=");
|
|
1159
|
+
if (eq < 0 || trimmed.slice(0, eq).toLowerCase() !== "max-age") continue;
|
|
1160
|
+
const value = trimmed.slice(eq + 1);
|
|
1161
|
+
const seconds = /^[+-]?\d+$/.test(value) ? Number(value) : NaN;
|
|
1162
|
+
if (Number.isSafeInteger(seconds) && seconds >= 0) return seconds;
|
|
1163
|
+
}
|
|
1164
|
+
return DEFAULT_MAX_AGE_SECONDS;
|
|
1165
|
+
}
|
|
1166
|
+
function prefixErrors(url, fn) {
|
|
1167
|
+
try {
|
|
1168
|
+
return fn();
|
|
1169
|
+
} catch (e) {
|
|
1170
|
+
throw new Error(`${url}: ${errorMessage(e)}`);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
function errorMessage(e) {
|
|
1174
|
+
return e instanceof Error ? e.message : String(e);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// src/verification-record/verify.ts
|
|
1178
|
+
var import_node_crypto3 = require("crypto");
|
|
1179
|
+
|
|
1180
|
+
// src/verification-record/shape.ts
|
|
1181
|
+
var USE_CASE = "VerifyPhoneNumber";
|
|
1182
|
+
var MAX_LIFETIME_SECONDS = 60;
|
|
1183
|
+
var RECORD_VERSION = "1.0";
|
|
1184
|
+
var CARRIER_ROLE = "carrier";
|
|
1185
|
+
var CARRIER_SIGNER_PREFIX = "carrier:";
|
|
1186
|
+
function malformed(message) {
|
|
1187
|
+
return new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, message);
|
|
1188
|
+
}
|
|
1189
|
+
function isNonEmptyString(value) {
|
|
1190
|
+
return typeof value === "string" && value !== "";
|
|
1191
|
+
}
|
|
1192
|
+
function checkClaimShape(obj, iat, exp) {
|
|
1193
|
+
if (typeof member(obj, "verified") !== "boolean") {
|
|
1194
|
+
throw malformed("verified must be a boolean");
|
|
1195
|
+
}
|
|
1196
|
+
for (const name of ["jti", "nonce", "sub"]) {
|
|
1197
|
+
if (!isNonEmptyString(member(obj, name))) {
|
|
1198
|
+
throw malformed(`${name} must be a non-empty string`);
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
if (!member(obj, "sub").startsWith("tel:+")) {
|
|
1202
|
+
throw malformed("sub must be tel:+E164");
|
|
1203
|
+
}
|
|
1204
|
+
for (const name of ["origin", "biometric_verification"]) {
|
|
1205
|
+
if (typeof member(obj, name) !== "string") throw malformed(`${name} must be a string`);
|
|
1206
|
+
}
|
|
1207
|
+
if (member(obj, "nbf") !== iat) {
|
|
1208
|
+
throw malformed("nbf must equal iat");
|
|
1209
|
+
}
|
|
1210
|
+
if (member(obj, "use_case") !== USE_CASE) {
|
|
1211
|
+
throw malformed(`use_case must be ${USE_CASE}`);
|
|
1212
|
+
}
|
|
1213
|
+
if (exp < iat + 1 || exp > iat + MAX_LIFETIME_SECONDS) {
|
|
1214
|
+
throw malformed("exp must be 1 to 60 seconds after iat");
|
|
1215
|
+
}
|
|
1216
|
+
const signOffs = readSignOffs(member(obj, "sign_offs"));
|
|
1217
|
+
if (!signOffs) {
|
|
1218
|
+
throw malformed("sign_offs must be an array of well-formed entries");
|
|
1219
|
+
}
|
|
1220
|
+
if (!oneCarrierSignOff(signOffs)) {
|
|
1221
|
+
throw malformed("sign_offs must have exactly one carrier:<id> carrier entry");
|
|
1222
|
+
}
|
|
1223
|
+
return signOffs;
|
|
1224
|
+
}
|
|
1225
|
+
function readSignOffs(raw) {
|
|
1226
|
+
if (!Array.isArray(raw)) return null;
|
|
1227
|
+
const signOffs = [];
|
|
1228
|
+
for (const entry of raw) {
|
|
1229
|
+
const signOff = isJsonObject(entry) ? readSignOff(entry) : null;
|
|
1230
|
+
if (!signOff) return null;
|
|
1231
|
+
signOffs.push(signOff);
|
|
1232
|
+
}
|
|
1233
|
+
return signOffs;
|
|
1234
|
+
}
|
|
1235
|
+
function readSignOff(entry) {
|
|
1236
|
+
const r = new MemberReader(entry);
|
|
1237
|
+
const role = r.str("role");
|
|
1238
|
+
const signer = r.str("signer");
|
|
1239
|
+
const status = r.str("status");
|
|
1240
|
+
const reason = r.str("reason");
|
|
1241
|
+
const format = r.str("format");
|
|
1242
|
+
const token = r.str("token");
|
|
1243
|
+
if (!r.ok || !isNonEmptyString(role) || !isNonEmptyString(signer)) return null;
|
|
1244
|
+
const signOff = { role, signer, status };
|
|
1245
|
+
if (reason !== void 0) signOff.reason = reason;
|
|
1246
|
+
if (format !== void 0) signOff.format = format;
|
|
1247
|
+
if (token !== void 0) signOff.token = token;
|
|
1248
|
+
if (status === "unavailable") return isNonEmptyString(reason) ? signOff : null;
|
|
1249
|
+
if (status === "present") return isNonEmptyString(format) && isNonEmptyString(token) ? signOff : null;
|
|
1250
|
+
return null;
|
|
1251
|
+
}
|
|
1252
|
+
function oneCarrierSignOff(signOffs) {
|
|
1253
|
+
const carriers = signOffs.filter((s) => s.role === CARRIER_ROLE);
|
|
1254
|
+
const signer = carriers.length === 1 ? carriers[0]?.signer ?? "" : "";
|
|
1255
|
+
return signer.length > CARRIER_SIGNER_PREFIX.length && signer.startsWith(CARRIER_SIGNER_PREFIX);
|
|
1256
|
+
}
|
|
1257
|
+
function carrierIDMatchesSignOff(id, signOffs) {
|
|
1258
|
+
const signer = signOffs.find((s) => s.role === CARRIER_ROLE)?.signer ?? "";
|
|
1259
|
+
return signer === CARRIER_SIGNER_PREFIX + id;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// src/verification-record/claims.ts
|
|
1263
|
+
var IAT_LEEWAY_SECONDS = 60;
|
|
1264
|
+
function checkRecordClaims(payload, want) {
|
|
1265
|
+
const obj = parseJsonObject(payload.toString("utf8"));
|
|
1266
|
+
if (!obj) {
|
|
1267
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "payload is not a JSON object");
|
|
1268
|
+
}
|
|
1269
|
+
if (member(obj, "ver") !== RECORD_VERSION) {
|
|
1270
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.UNSUPPORTED_VERSION, 'ver must be "1.0"');
|
|
1271
|
+
}
|
|
1272
|
+
const iss = member(obj, "iss");
|
|
1273
|
+
if (typeof iss !== "string" || iss !== want.issuer) {
|
|
1274
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_ISSUER, `iss does not match ${want.issuer}`);
|
|
1275
|
+
}
|
|
1276
|
+
const aud = member(obj, "aud");
|
|
1277
|
+
if (typeof aud !== "string" || aud !== want.audience) {
|
|
1278
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.WRONG_AUDIENCE, "aud does not match the expected audience");
|
|
1279
|
+
}
|
|
1280
|
+
const { iat, exp } = checkRecordTimes(obj, want);
|
|
1281
|
+
const signOffs = checkClaimShape(obj, iat, exp);
|
|
1282
|
+
const verified = member(obj, "verified");
|
|
1283
|
+
const r = new MemberReader(obj);
|
|
1284
|
+
const claims = {
|
|
1285
|
+
ver: RECORD_VERSION,
|
|
1286
|
+
iss,
|
|
1287
|
+
aud,
|
|
1288
|
+
iat,
|
|
1289
|
+
nbf: iat,
|
|
1290
|
+
exp,
|
|
1291
|
+
verified,
|
|
1292
|
+
sign_offs: signOffs,
|
|
1293
|
+
jti: r.str("jti") ?? "",
|
|
1294
|
+
nonce: r.str("nonce") ?? "",
|
|
1295
|
+
use_case: r.str("use_case") ?? "",
|
|
1296
|
+
sub: r.str("sub") ?? "",
|
|
1297
|
+
origin: r.str("origin") ?? "",
|
|
1298
|
+
biometric_verification: r.str("biometric_verification") ?? ""
|
|
1299
|
+
};
|
|
1300
|
+
assignDefined(claims, "strategy", r.str("strategy"));
|
|
1301
|
+
assignDefined(claims, "phone_number_details", readPhoneNumberDetails(r));
|
|
1302
|
+
assignDefined(claims, "carrier", readCarrier(r));
|
|
1303
|
+
assignDefined(claims, "sim_swap", readSwap(r, "sim_swap"));
|
|
1304
|
+
assignDefined(claims, "device_swap", readSwap(r, "device_swap"));
|
|
1305
|
+
if (!r.ok) {
|
|
1306
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "claims have the wrong JSON types");
|
|
1307
|
+
}
|
|
1308
|
+
if (claims.carrier !== void 0 && !carrierIDMatchesSignOff(claims.carrier.id, signOffs)) {
|
|
1309
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "carrier.id must match the carrier sign-off signer");
|
|
1310
|
+
}
|
|
1311
|
+
if (want.nonce !== "" && claims.nonce !== want.nonce) {
|
|
1312
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.NONCE_MISMATCH, "nonce does not match the expected nonce");
|
|
1313
|
+
}
|
|
1314
|
+
if (want.origins.length > 0 && !want.origins.includes(claims.origin)) {
|
|
1315
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.ORIGIN_MISMATCH, "origin is not an expected origin");
|
|
1316
|
+
}
|
|
1317
|
+
return claims;
|
|
1318
|
+
}
|
|
1319
|
+
function checkRecordTimes(obj, want) {
|
|
1320
|
+
const iat = member(obj, "iat");
|
|
1321
|
+
const exp = member(obj, "exp");
|
|
1322
|
+
if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp)) {
|
|
1323
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "iat and exp must be integers");
|
|
1324
|
+
}
|
|
1325
|
+
const times = { iat, exp };
|
|
1326
|
+
const now = want.nowSeconds;
|
|
1327
|
+
if (times.iat > now + IAT_LEEWAY_SECONDS) {
|
|
1328
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.NOT_YET_VALID, "iat is in the future");
|
|
1329
|
+
}
|
|
1330
|
+
if (times.exp > now) {
|
|
1331
|
+
return times;
|
|
1332
|
+
}
|
|
1333
|
+
if (!want.allowExpired) {
|
|
1334
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record has expired");
|
|
1335
|
+
}
|
|
1336
|
+
if (times.iat < now - want.maxAuditAgeSeconds) {
|
|
1337
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.EXPIRED, "record is older than the maximum audit age");
|
|
1338
|
+
}
|
|
1339
|
+
return times;
|
|
1340
|
+
}
|
|
1341
|
+
function signOffResults(signOffs) {
|
|
1342
|
+
return signOffs.map((s) => {
|
|
1343
|
+
if (s.status === "unavailable") {
|
|
1344
|
+
const result = { role: s.role, signer: s.signer, result: "unavailable" };
|
|
1345
|
+
assignDefined(result, "reason", s.reason);
|
|
1346
|
+
return result;
|
|
1347
|
+
}
|
|
1348
|
+
return { role: s.role, signer: s.signer, result: "unverified" };
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
function readCarrier(r) {
|
|
1352
|
+
const obj = r.object("carrier");
|
|
1353
|
+
if (!obj) return void 0;
|
|
1354
|
+
const s = new MemberReader(obj);
|
|
1355
|
+
const id = s.str("id");
|
|
1356
|
+
const carrier = { id: id ?? "" };
|
|
1357
|
+
assignDefined(carrier, "name", s.str("name"));
|
|
1358
|
+
assignDefined(carrier, "mvno", s.str("mvno"));
|
|
1359
|
+
r.ok = r.ok && s.ok && !!id;
|
|
1360
|
+
return carrier;
|
|
1361
|
+
}
|
|
1362
|
+
function readPhoneNumberDetails(r) {
|
|
1363
|
+
const obj = r.object("phone_number_details");
|
|
1364
|
+
if (!obj) return void 0;
|
|
1365
|
+
const s = new MemberReader(obj);
|
|
1366
|
+
const d = {
|
|
1367
|
+
country_code: s.int("country_code") ?? 0,
|
|
1368
|
+
national_number: s.str("national_number") ?? "",
|
|
1369
|
+
region_code: s.str("region_code") ?? ""
|
|
1370
|
+
};
|
|
1371
|
+
r.ok = r.ok && s.ok;
|
|
1372
|
+
return d;
|
|
1373
|
+
}
|
|
1374
|
+
function readSwap(r, name) {
|
|
1375
|
+
const obj = r.object(name);
|
|
1376
|
+
if (!obj) return void 0;
|
|
1377
|
+
const s = new MemberReader(obj);
|
|
1378
|
+
const info = { checked: s.bool("checked") ?? false };
|
|
1379
|
+
assignDefined(info, "risk_level", s.str("risk_level"));
|
|
1380
|
+
assignDefined(info, "carrier_name", s.str("carrier_name"));
|
|
1381
|
+
assignDefined(info, "reason", s.str("reason"));
|
|
1382
|
+
assignDefined(info, "swapped", s.bool("swapped"));
|
|
1383
|
+
assignDefined(info, "max_age_hours", s.int("max_age_hours"));
|
|
1384
|
+
const band = s.object("age_band");
|
|
1385
|
+
if (band) {
|
|
1386
|
+
const b = new MemberReader(band);
|
|
1387
|
+
info.age_band = { from: b.int("from") ?? -1, to: b.int("to") ?? -1 };
|
|
1388
|
+
s.ok = s.ok && b.ok;
|
|
1389
|
+
}
|
|
1390
|
+
r.ok = r.ok && s.ok;
|
|
1391
|
+
return info;
|
|
1392
|
+
}
|
|
1393
|
+
function assignDefined(target, key, value) {
|
|
1394
|
+
if (value !== void 0) {
|
|
1395
|
+
target[key] = value;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
// src/verification-record/verify.ts
|
|
1400
|
+
var RECORD_TYP = "glide-verification+jwt";
|
|
1401
|
+
var DEFAULT_MAX_AUDIT_AGE_SECONDS = 90 * 24 * 60 * 60;
|
|
1402
|
+
var MAX_RECORD_BYTES = 16 * 1024;
|
|
1403
|
+
var RECORD_KIDS = [
|
|
1404
|
+
"glide-record-signing-key-ecdsa-es256-us-2026",
|
|
1405
|
+
"glide-record-signing-key-ecdsa-es256-eu-2026"
|
|
1406
|
+
];
|
|
1407
|
+
var REVOKED_RECORD_KIDS = [];
|
|
1408
|
+
async function verifyVerificationRecord(record, options, ctx) {
|
|
1409
|
+
const opts = options ?? {};
|
|
1410
|
+
const nowMs = (opts.now ? opts.now() : /* @__PURE__ */ new Date()).getTime();
|
|
1411
|
+
if (!Number.isFinite(nowMs)) {
|
|
1412
|
+
throw new TypeError("options.now must return a valid Date");
|
|
1413
|
+
}
|
|
1414
|
+
const parsed = parseRecord(record);
|
|
1415
|
+
checkRecordKid(parsed.kid, opts.revokedKids ?? []);
|
|
1416
|
+
const key = await ctx.keys.key(parsed.kid);
|
|
1417
|
+
verifyRecordSignature(parsed, key);
|
|
1418
|
+
const maxAuditAge = opts.maxAuditAgeSeconds ?? 0;
|
|
1419
|
+
const claims = checkRecordClaims(parsed.payload, {
|
|
1420
|
+
issuer: opts.issuer ? opts.issuer : ctx.baseUrl.replace(/\/+$/, ""),
|
|
1421
|
+
audience: opts.expectedAudience ? opts.expectedAudience : ctx.clientId,
|
|
1422
|
+
nonce: opts.expectedNonce ?? "",
|
|
1423
|
+
origins: opts.expectedOrigin ?? [],
|
|
1424
|
+
allowExpired: opts.allowExpired === true,
|
|
1425
|
+
maxAuditAgeSeconds: Number.isFinite(maxAuditAge) && maxAuditAge > 0 ? maxAuditAge : DEFAULT_MAX_AUDIT_AGE_SECONDS,
|
|
1426
|
+
nowSeconds: Math.floor(nowMs / 1e3)
|
|
1427
|
+
});
|
|
1428
|
+
return { claims, signOffResults: signOffResults(claims.sign_offs) };
|
|
1429
|
+
}
|
|
1430
|
+
function parseRecord(record) {
|
|
1431
|
+
if (record === void 0 || record === null || record === "") {
|
|
1432
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.RECORD_UNAVAILABLE, "no verification record");
|
|
1433
|
+
}
|
|
1434
|
+
if (typeof record === "string" && Buffer.byteLength(record, "utf8") > MAX_RECORD_BYTES) {
|
|
1435
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is larger than 16 KiB");
|
|
1436
|
+
}
|
|
1437
|
+
const segments = typeof record === "string" ? record.split(".") : [];
|
|
1438
|
+
if (segments.length !== 3) {
|
|
1439
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record is not a compact JWS");
|
|
1440
|
+
}
|
|
1441
|
+
const decoded = segments.map(decodeBase64URL);
|
|
1442
|
+
const [header, payload, signature] = decoded;
|
|
1443
|
+
if (!header || !payload || !signature) {
|
|
1444
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "record segment is not base64url");
|
|
1445
|
+
}
|
|
1446
|
+
const headerObj = parseJsonObject(header.toString("utf8"));
|
|
1447
|
+
if (!headerObj) {
|
|
1448
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.MALFORMED, "header is not a JSON object");
|
|
1449
|
+
}
|
|
1450
|
+
return {
|
|
1451
|
+
kid: checkRecordHeader(headerObj),
|
|
1452
|
+
signingInput: Buffer.from(`${segments[0]}.${segments[1]}`, "ascii"),
|
|
1453
|
+
payload,
|
|
1454
|
+
signature
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
function checkRecordHeader(header) {
|
|
1458
|
+
const alg = member(header, "alg");
|
|
1459
|
+
const typ = member(header, "typ");
|
|
1460
|
+
const kid = member(header, "kid");
|
|
1461
|
+
if (Object.keys(header).length !== 3 || typeof alg !== "string" || typeof typ !== "string" || typeof kid !== "string") {
|
|
1462
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header must contain exactly alg, typ and kid");
|
|
1463
|
+
}
|
|
1464
|
+
if (alg !== RECORD_ALG || typ !== RECORD_TYP) {
|
|
1465
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.DISALLOWED_HEADER, "header alg/typ not allowed");
|
|
1466
|
+
}
|
|
1467
|
+
return kid;
|
|
1468
|
+
}
|
|
1469
|
+
function checkRecordKid(kid, revoked) {
|
|
1470
|
+
if (REVOKED_RECORD_KIDS.includes(kid) || revoked.includes(kid)) {
|
|
1471
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.REVOKED_KEY, `kid ${kid} is revoked`);
|
|
1472
|
+
}
|
|
1473
|
+
if (!RECORD_KIDS.includes(kid)) {
|
|
1474
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.UNKNOWN_KEY, `kid ${kid} is not a record signing key`);
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
function verifyRecordSignature(record, key) {
|
|
1478
|
+
if (record.signature.length !== 64) {
|
|
1479
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature is not 64 bytes");
|
|
1480
|
+
}
|
|
1481
|
+
let valid = false;
|
|
1482
|
+
try {
|
|
1483
|
+
valid = (0, import_node_crypto3.verify)("sha256", record.signingInput, { key, dsaEncoding: "ieee-p1363" }, record.signature);
|
|
1484
|
+
} catch {
|
|
1485
|
+
valid = false;
|
|
1486
|
+
}
|
|
1487
|
+
if (!valid) {
|
|
1488
|
+
throw new VerificationRecordError(VerificationRecordErrorCode.BAD_SIGNATURE, "signature does not verify");
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
850
1491
|
|
|
851
1492
|
// src/client.ts
|
|
852
1493
|
var MagicalAuthClient = class {
|
|
853
1494
|
config;
|
|
854
1495
|
tokenManager;
|
|
1496
|
+
recordKeys;
|
|
855
1497
|
/**
|
|
856
1498
|
* Creates a new MagicalAuthClient instance.
|
|
857
1499
|
*
|
|
@@ -873,6 +1515,31 @@ var MagicalAuthClient = class {
|
|
|
873
1515
|
this.config.httpClient,
|
|
874
1516
|
this.config.logger
|
|
875
1517
|
);
|
|
1518
|
+
this.recordKeys = new RecordKeyCache(
|
|
1519
|
+
this.config.baseUrl.replace(/\/+$/, ""),
|
|
1520
|
+
this.config.httpClient,
|
|
1521
|
+
this.config.timeout
|
|
1522
|
+
);
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Check authentication eligibility for a phone number or PLMN.
|
|
1526
|
+
* Returns available authentication strategies with platform requirements.
|
|
1527
|
+
*
|
|
1528
|
+
* @param request - Eligibility request with phone_number or plmn. `client_info.user_agent` is required.
|
|
1529
|
+
* @param options - Per-request options (e.g., correlationId)
|
|
1530
|
+
* @returns Eligibility response with available options
|
|
1531
|
+
* @throws {ValidationError} If request validation fails (incl. missing/blank `client_info.user_agent`)
|
|
1532
|
+
* @throws {MagicalAuthError} For other API errors
|
|
1533
|
+
*/
|
|
1534
|
+
async checkEligibility(request, options) {
|
|
1535
|
+
validateEligibilityRequest(request);
|
|
1536
|
+
const response = await this.doRequest(
|
|
1537
|
+
"POST",
|
|
1538
|
+
"/magic-auth/v2/auth/eligibility",
|
|
1539
|
+
request,
|
|
1540
|
+
options
|
|
1541
|
+
);
|
|
1542
|
+
return response;
|
|
876
1543
|
}
|
|
877
1544
|
/**
|
|
878
1545
|
* Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
|
|
@@ -894,7 +1561,11 @@ var MagicalAuthClient = class {
|
|
|
894
1561
|
const nonce = request.nonce || generateNonce();
|
|
895
1562
|
const feCode = generateFeCode();
|
|
896
1563
|
const feHash = computeFeHash(feCode);
|
|
897
|
-
const requestWithHash = {
|
|
1564
|
+
const requestWithHash = {
|
|
1565
|
+
...request,
|
|
1566
|
+
nonce,
|
|
1567
|
+
fe_hash: feHash
|
|
1568
|
+
};
|
|
898
1569
|
const response = await this.doRequest(
|
|
899
1570
|
"POST",
|
|
900
1571
|
"/magic-auth/v2/auth/prepare",
|
|
@@ -912,6 +1583,39 @@ var MagicalAuthClient = class {
|
|
|
912
1583
|
});
|
|
913
1584
|
return result;
|
|
914
1585
|
}
|
|
1586
|
+
/**
|
|
1587
|
+
* Prepares authentication for several phone numbers at once.
|
|
1588
|
+
*
|
|
1589
|
+
* Fans out one ordinary {@link prepare} call per number, so each number gets
|
|
1590
|
+
* its own carrier resolution, residency routing and session. Per-number
|
|
1591
|
+
* failures are returned as items rather than thrown; this only throws
|
|
1592
|
+
* {@link ValidationError}, and only before any request is issued.
|
|
1593
|
+
*
|
|
1594
|
+
* @param request - Shared prepare fields plus `phone_numbers` (1..10)
|
|
1595
|
+
* @param options - Per-request options (e.g., correlationId)
|
|
1596
|
+
* @returns One result per input number, in input order
|
|
1597
|
+
* @throws {ValidationError} If the list is empty, over the cap, has blank entries, or a shared prepare field is invalid
|
|
1598
|
+
*/
|
|
1599
|
+
async prepareMultiple(request, options) {
|
|
1600
|
+
validatePrepareMultipleRequest(request);
|
|
1601
|
+
const { phone_numbers: phoneNumbers, nonce: _nonce, ...shared } = request;
|
|
1602
|
+
const derived = phoneNumbers.map(
|
|
1603
|
+
(phone_number) => ({ ...shared, phone_number })
|
|
1604
|
+
);
|
|
1605
|
+
for (const single of derived) {
|
|
1606
|
+
validatePrepareRequest(single);
|
|
1607
|
+
}
|
|
1608
|
+
this.config.logger.debug("Preparing auth for multiple numbers", {
|
|
1609
|
+
count: phoneNumbers.length
|
|
1610
|
+
});
|
|
1611
|
+
const settled = await Promise.allSettled(
|
|
1612
|
+
derived.map((single) => this.prepare(single, options))
|
|
1613
|
+
);
|
|
1614
|
+
return settled.map((outcome, index) => {
|
|
1615
|
+
const phone_number = phoneNumbers[index];
|
|
1616
|
+
return outcome.status === "fulfilled" ? { phone_number, ok: true, result: outcome.value } : { phone_number, ok: false, error: asMagicalAuthError(outcome.reason) };
|
|
1617
|
+
});
|
|
1618
|
+
}
|
|
915
1619
|
/**
|
|
916
1620
|
* Validates device binding codes and completes a link protocol session.
|
|
917
1621
|
*
|
|
@@ -969,6 +1673,26 @@ var MagicalAuthClient = class {
|
|
|
969
1673
|
this.config.logger.debug("Phone verification complete", { verified: response.verified });
|
|
970
1674
|
return response;
|
|
971
1675
|
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Verifies a verification record returned by {@link verifyPhoneNumber}: the
|
|
1678
|
+
* ES256 signature against Glide's published record keys, then issuer,
|
|
1679
|
+
* the expected audience (default this client's ID), validity window, shape, nonce and origin.
|
|
1680
|
+
*
|
|
1681
|
+
* A missing or empty record fails with `RECORD_UNAVAILABLE`, so a caller
|
|
1682
|
+
* that requires records can pass `response.verification_record` straight in.
|
|
1683
|
+
*
|
|
1684
|
+
* @param record - Compact JWS from `VerifyPhoneNumberResponse.verification_record`
|
|
1685
|
+
* @param options - Expected nonce, expected audience, expected origins, audit mode, issuer override, extra revoked kids, clock
|
|
1686
|
+
* @returns The verified claims and how each sign-off was treated
|
|
1687
|
+
* @throws {VerificationRecordError} On any failed check; `code` is a {@link VerificationRecordErrorCode}
|
|
1688
|
+
*/
|
|
1689
|
+
async verifyVerificationRecord(record, options) {
|
|
1690
|
+
return verifyVerificationRecord(record, options, {
|
|
1691
|
+
baseUrl: this.config.baseUrl,
|
|
1692
|
+
clientId: this.config.clientId,
|
|
1693
|
+
keys: this.recordKeys
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
972
1696
|
/**
|
|
973
1697
|
* Retrieves the phone number associated with the device using digital credentials.
|
|
974
1698
|
*
|
|
@@ -1175,13 +1899,20 @@ var MagicalAuthClient = class {
|
|
|
1175
1899
|
};
|
|
1176
1900
|
var ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
1177
1901
|
function generateNonce(length = 32) {
|
|
1178
|
-
const bytes = (0,
|
|
1902
|
+
const bytes = (0, import_node_crypto4.randomBytes)(length);
|
|
1179
1903
|
let result = "";
|
|
1180
1904
|
for (let i = 0; i < length; i++) {
|
|
1181
1905
|
result += ALPHANUMERIC.charAt(bytes[i] % ALPHANUMERIC.length);
|
|
1182
1906
|
}
|
|
1183
1907
|
return result;
|
|
1184
1908
|
}
|
|
1909
|
+
function asMagicalAuthError(reason) {
|
|
1910
|
+
if (reason instanceof MagicalAuthError) {
|
|
1911
|
+
return reason;
|
|
1912
|
+
}
|
|
1913
|
+
const message = reason instanceof Error ? reason.message : "Prepare failed";
|
|
1914
|
+
return new MagicalAuthError(message, "UNKNOWN_ERROR", 0);
|
|
1915
|
+
}
|
|
1185
1916
|
|
|
1186
1917
|
// src/logger.ts
|
|
1187
1918
|
function createLogger(config = {}) {
|
|
@@ -1204,19 +1935,22 @@ var JWT_RE = /(eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)/g;
|
|
|
1204
1935
|
var SESSION_RE = /(session[_-]?key)(["']?\s*[:=]\s*["']?)([A-Za-z0-9_-]{16,})/gi;
|
|
1205
1936
|
var SENSITIVE = ["phone_number", "phonenumber", "credential", "token", "password", "secret", "fe_code", "fecode"];
|
|
1206
1937
|
function sanitize(data) {
|
|
1938
|
+
return sanitizeWith(data, /* @__PURE__ */ new WeakSet());
|
|
1939
|
+
}
|
|
1940
|
+
function sanitizeWith(data, seen) {
|
|
1207
1941
|
if (data == null) return data;
|
|
1208
1942
|
if (typeof data === "string") {
|
|
1209
|
-
return data.replace(
|
|
1943
|
+
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)}`);
|
|
1210
1944
|
}
|
|
1211
|
-
if (
|
|
1212
|
-
if (
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1945
|
+
if (typeof data !== "object") return data;
|
|
1946
|
+
if (seen.has(data)) return "[Circular]";
|
|
1947
|
+
seen.add(data);
|
|
1948
|
+
if (Array.isArray(data)) return data.map((v) => sanitizeWith(v, seen));
|
|
1949
|
+
const out = {};
|
|
1950
|
+
for (const [k, v] of Object.entries(data)) {
|
|
1951
|
+
out[k] = SENSITIVE.some((s) => k.toLowerCase().includes(s)) ? "[REDACTED]" : sanitizeWith(v, seen);
|
|
1218
1952
|
}
|
|
1219
|
-
return
|
|
1953
|
+
return out;
|
|
1220
1954
|
}
|
|
1221
1955
|
|
|
1222
1956
|
// src/index.ts
|
|
@@ -1229,8 +1963,11 @@ var VERSION = _require("../package.json").version;
|
|
|
1229
1963
|
BINDING_COOKIE_MAX_AGE,
|
|
1230
1964
|
BINDING_COOKIE_PREFIX,
|
|
1231
1965
|
BadRequestError,
|
|
1966
|
+
BiometricVerification,
|
|
1232
1967
|
BrowserMismatchError,
|
|
1968
|
+
CarrierAppUnavailableError,
|
|
1233
1969
|
CarrierNotEligibleError,
|
|
1970
|
+
CarrierRejectedError,
|
|
1234
1971
|
DEFAULT_BASE_URL,
|
|
1235
1972
|
DEFAULT_TIMEOUT,
|
|
1236
1973
|
DesktopWaitError,
|
|
@@ -1243,6 +1980,7 @@ var VERSION = _require("../package.json").version;
|
|
|
1243
1980
|
MagicalAuthClient,
|
|
1244
1981
|
MagicalAuthError,
|
|
1245
1982
|
MissingBindingCookieError,
|
|
1983
|
+
PREPARE_MULTIPLE_MAX,
|
|
1246
1984
|
PhoneNumberMismatchError,
|
|
1247
1985
|
RateLimitError,
|
|
1248
1986
|
SENSITIVE_KEYS,
|
|
@@ -1256,6 +1994,8 @@ var VERSION = _require("../package.json").version;
|
|
|
1256
1994
|
UseCase,
|
|
1257
1995
|
VERSION,
|
|
1258
1996
|
ValidationError,
|
|
1997
|
+
VerificationRecordError,
|
|
1998
|
+
VerificationRecordErrorCode,
|
|
1259
1999
|
assertValidFeCode,
|
|
1260
2000
|
buildClearBindingCookieHeader,
|
|
1261
2001
|
buildSetBindingCookieHeader,
|