@glideidentity/glide-be-node-magical-auth 2.0.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 ADDED
@@ -0,0 +1,1204 @@
1
+ // src/index.ts
2
+ import { createRequire } from "module";
3
+
4
+ // src/client.ts
5
+ import { randomBytes as randomBytes2 } from "crypto";
6
+
7
+ // src/internal/http.ts
8
+ var defaultHttpClient = {
9
+ async request(options) {
10
+ const response = await fetch(options.url, {
11
+ method: options.method,
12
+ headers: options.headers,
13
+ body: options.body,
14
+ signal: options.signal
15
+ });
16
+ return response;
17
+ }
18
+ };
19
+ var noopLogger = {
20
+ debug() {
21
+ },
22
+ info() {
23
+ },
24
+ warn() {
25
+ },
26
+ error() {
27
+ }
28
+ };
29
+
30
+ // src/errors.ts
31
+ var ErrorCode = {
32
+ BAD_REQUEST: "BAD_REQUEST",
33
+ UNAUTHORIZED: "UNAUTHORIZED",
34
+ VALIDATION_ERROR: "VALIDATION_ERROR",
35
+ MISSING_PARAMETERS: "MISSING_PARAMETERS",
36
+ SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
37
+ INVALID_VERIFICATION: "INVALID_VERIFICATION",
38
+ CARRIER_NOT_ELIGIBLE: "CARRIER_NOT_ELIGIBLE",
39
+ UNSUPPORTED_PLATFORM: "UNSUPPORTED_PLATFORM",
40
+ PHONE_NUMBER_MISMATCH: "PHONE_NUMBER_MISMATCH",
41
+ INVALID_CREDENTIAL_FORMAT: "INVALID_CREDENTIAL_FORMAT",
42
+ FORBIDDEN: "FORBIDDEN",
43
+ AUDIENCE_VALIDATION_FAILED: "AUDIENCE_VALIDATION_FAILED",
44
+ BROWSER_MISMATCH: "BROWSER_MISMATCH",
45
+ QR_ALREADY_SCANNED: "QR_ALREADY_SCANNED",
46
+ SESSION_NOT_ELIGIBLE: "SESSION_NOT_ELIGIBLE",
47
+ SESSION_EXPIRED: "SESSION_EXPIRED",
48
+ DEVICE_BINDING_FAILED: "DEVICE_BINDING_FAILED",
49
+ MISSING_BINDING_COOKIE: "MISSING_BINDING_COOKIE",
50
+ RATE_LIMIT_EXCEEDED: "RATE_LIMIT_EXCEEDED",
51
+ INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR",
52
+ SERVICE_UNAVAILABLE: "SERVICE_UNAVAILABLE"
53
+ };
54
+ var MagicalAuthError = class extends Error {
55
+ /**
56
+ * Error code from the API.
57
+ */
58
+ code;
59
+ /**
60
+ * HTTP status code.
61
+ */
62
+ status;
63
+ /**
64
+ * Request ID for debugging/support.
65
+ */
66
+ requestId;
67
+ /**
68
+ * Additional error details.
69
+ */
70
+ details;
71
+ /**
72
+ * Distributed trace ID (from OpenTelemetry).
73
+ */
74
+ traceId;
75
+ /**
76
+ * Span ID for tracing.
77
+ */
78
+ spanId;
79
+ /**
80
+ * ISO 8601 timestamp of when the error occurred on the server.
81
+ */
82
+ timestamp;
83
+ /**
84
+ * Name of the service that produced this error.
85
+ */
86
+ service;
87
+ constructor(message, code, status, requestId, details) {
88
+ super(message);
89
+ this.name = "MagicalAuthError";
90
+ this.code = code;
91
+ this.status = status;
92
+ this.requestId = requestId;
93
+ this.details = details;
94
+ if (Error.captureStackTrace) {
95
+ Error.captureStackTrace(this, this.constructor);
96
+ }
97
+ Object.setPrototypeOf(this, new.target.prototype);
98
+ }
99
+ };
100
+ var BadRequestError = class extends MagicalAuthError {
101
+ constructor(message = "Bad request", requestId) {
102
+ super(message, "BAD_REQUEST", 400, requestId);
103
+ this.name = "BadRequestError";
104
+ }
105
+ };
106
+ var ValidationError = class extends MagicalAuthError {
107
+ /**
108
+ * Field-level validation errors.
109
+ */
110
+ fieldErrors;
111
+ constructor(message, fieldErrors, requestId) {
112
+ super(message, "VALIDATION_ERROR", 400, requestId, { fields: fieldErrors });
113
+ this.name = "ValidationError";
114
+ this.fieldErrors = fieldErrors;
115
+ }
116
+ };
117
+ var UnauthorizedError = class extends MagicalAuthError {
118
+ constructor(message = "Unauthorized", requestId) {
119
+ super(message, "UNAUTHORIZED", 401, requestId);
120
+ this.name = "UnauthorizedError";
121
+ }
122
+ };
123
+ var SessionNotFoundError = class extends MagicalAuthError {
124
+ constructor(message = "Session not found", requestId) {
125
+ super(message, "SESSION_NOT_FOUND", 404, requestId);
126
+ this.name = "SessionNotFoundError";
127
+ }
128
+ };
129
+ var CarrierNotEligibleError = class extends MagicalAuthError {
130
+ constructor(message = "Carrier not eligible", requestId) {
131
+ super(message, "CARRIER_NOT_ELIGIBLE", 422, requestId);
132
+ this.name = "CarrierNotEligibleError";
133
+ }
134
+ };
135
+ var UnsupportedPlatformError = class extends MagicalAuthError {
136
+ constructor(message = "Platform not supported", requestId) {
137
+ super(message, "UNSUPPORTED_PLATFORM", 422, requestId);
138
+ this.name = "UnsupportedPlatformError";
139
+ }
140
+ };
141
+ var InvalidCredentialError = class extends MagicalAuthError {
142
+ constructor(message = "Invalid credential format", requestId) {
143
+ super(message, "INVALID_CREDENTIAL_FORMAT", 422, requestId);
144
+ this.name = "InvalidCredentialError";
145
+ }
146
+ };
147
+ var PhoneNumberMismatchError = class extends MagicalAuthError {
148
+ constructor(message = "Phone number does not match", requestId) {
149
+ super(message, "PHONE_NUMBER_MISMATCH", 422, requestId);
150
+ this.name = "PhoneNumberMismatchError";
151
+ }
152
+ };
153
+ var RateLimitError = class extends MagicalAuthError {
154
+ /**
155
+ * Seconds until rate limit resets (if provided by API).
156
+ */
157
+ retryAfter;
158
+ constructor(message, retryAfter, requestId) {
159
+ super(
160
+ message,
161
+ "RATE_LIMIT_EXCEEDED",
162
+ 429,
163
+ requestId,
164
+ retryAfter !== void 0 ? { retryAfter } : void 0
165
+ );
166
+ this.name = "RateLimitError";
167
+ this.retryAfter = retryAfter;
168
+ }
169
+ };
170
+ var InternalServerError = class extends MagicalAuthError {
171
+ constructor(message = "An internal error occurred", requestId) {
172
+ super(message, "INTERNAL_SERVER_ERROR", 500, requestId);
173
+ this.name = "InternalServerError";
174
+ }
175
+ };
176
+ var ServiceUnavailableError = class extends MagicalAuthError {
177
+ constructor(message = "Service temporarily unavailable", requestId) {
178
+ super(message, "SERVICE_UNAVAILABLE", 503, requestId);
179
+ this.name = "ServiceUnavailableError";
180
+ }
181
+ };
182
+ var ForbiddenError = class extends MagicalAuthError {
183
+ constructor(message = "Forbidden", requestId) {
184
+ super(message, "FORBIDDEN", 403, requestId);
185
+ this.name = "ForbiddenError";
186
+ }
187
+ };
188
+ var BrowserMismatchError = class extends MagicalAuthError {
189
+ constructor(message = "Browser mismatch detected", requestId, details) {
190
+ super(message, "BROWSER_MISMATCH", 422, requestId, details);
191
+ this.name = "BrowserMismatchError";
192
+ }
193
+ };
194
+ var SessionNotEligibleError = class extends MagicalAuthError {
195
+ constructor(message = "Session is not eligible for completion", requestId) {
196
+ super(message, "SESSION_NOT_ELIGIBLE", 409, requestId);
197
+ this.name = "SessionNotEligibleError";
198
+ }
199
+ };
200
+ var DeviceBindingError = class extends MagicalAuthError {
201
+ constructor(message = "Device binding validation failed", code = "DEVICE_BINDING_FAILED", requestId) {
202
+ super(message, code, 403, requestId);
203
+ this.name = "DeviceBindingError";
204
+ }
205
+ };
206
+ var MissingBindingCookieError = class extends DeviceBindingError {
207
+ constructor(message = "Binding cookie missing or expired", requestId) {
208
+ super(message, "MISSING_BINDING_COOKIE", requestId);
209
+ this.name = "MissingBindingCookieError";
210
+ }
211
+ };
212
+ var DesktopWaitError = class extends MagicalAuthError {
213
+ waitResponse;
214
+ constructor(waitResponse) {
215
+ super(waitResponse.message, "DESKTOP_WAIT", 202);
216
+ this.name = "DesktopWaitError";
217
+ this.waitResponse = waitResponse;
218
+ }
219
+ };
220
+ function parseRetryAfter(headers) {
221
+ if (!headers) return void 0;
222
+ const retryAfter = headers.get("Retry-After");
223
+ if (!retryAfter) return void 0;
224
+ const seconds = parseInt(retryAfter, 10);
225
+ if (!isNaN(seconds) && seconds >= 0) {
226
+ return seconds;
227
+ }
228
+ const date = Date.parse(retryAfter);
229
+ if (!isNaN(date)) {
230
+ const diffMs = date - Date.now();
231
+ return Math.max(0, Math.ceil(diffMs / 1e3));
232
+ }
233
+ return void 0;
234
+ }
235
+ function createErrorFromResponse(response, headers) {
236
+ const { code, message, request_id, details, status, trace_id, span_id, timestamp, service } = response;
237
+ const error = createTypedError(code, message, request_id, details, status, headers);
238
+ return Object.assign(error, {
239
+ traceId: trace_id,
240
+ spanId: span_id,
241
+ timestamp,
242
+ service
243
+ });
244
+ }
245
+ function createTypedError(code, message, request_id, details, status, headers) {
246
+ switch (code) {
247
+ case "BAD_REQUEST":
248
+ return new BadRequestError(message, request_id);
249
+ case "VALIDATION_ERROR":
250
+ case "MISSING_PARAMETERS":
251
+ return new ValidationError(
252
+ message,
253
+ details?.fields ?? {},
254
+ request_id
255
+ );
256
+ case "UNAUTHORIZED":
257
+ return new UnauthorizedError(message, request_id);
258
+ case "SESSION_NOT_FOUND":
259
+ return new SessionNotFoundError(message, request_id);
260
+ case "CARRIER_NOT_ELIGIBLE":
261
+ return new CarrierNotEligibleError(message, request_id);
262
+ case "UNSUPPORTED_PLATFORM":
263
+ return new UnsupportedPlatformError(message, request_id);
264
+ case "INVALID_CREDENTIAL_FORMAT":
265
+ case "INVALID_VERIFICATION":
266
+ return new InvalidCredentialError(message, request_id);
267
+ case "PHONE_NUMBER_MISMATCH":
268
+ return new PhoneNumberMismatchError(message, request_id);
269
+ case "FORBIDDEN":
270
+ return new ForbiddenError(message, request_id);
271
+ case "BROWSER_MISMATCH":
272
+ return new BrowserMismatchError(
273
+ message,
274
+ request_id,
275
+ details
276
+ );
277
+ case "SESSION_NOT_ELIGIBLE":
278
+ return new SessionNotEligibleError(message, request_id);
279
+ case "DEVICE_BINDING_FAILED":
280
+ return new DeviceBindingError(message, "DEVICE_BINDING_FAILED", request_id);
281
+ case "MISSING_BINDING_COOKIE":
282
+ return new MissingBindingCookieError(message, request_id);
283
+ case "RATE_LIMIT_EXCEEDED":
284
+ return new RateLimitError(message, parseRetryAfter(headers), request_id);
285
+ case "INTERNAL_SERVER_ERROR":
286
+ return new InternalServerError(message, request_id);
287
+ case "SERVICE_UNAVAILABLE":
288
+ return new ServiceUnavailableError(message, request_id);
289
+ default:
290
+ return new MagicalAuthError(
291
+ message,
292
+ code,
293
+ status ?? 500,
294
+ request_id,
295
+ details
296
+ );
297
+ }
298
+ }
299
+
300
+ // src/auth.ts
301
+ var TokenManager = class {
302
+ constructor(clientId, clientSecret, tokenUrl, httpClient, logger = noopLogger) {
303
+ this.clientId = clientId;
304
+ this.clientSecret = clientSecret;
305
+ this.tokenUrl = tokenUrl;
306
+ this.httpClient = httpClient;
307
+ this.logger = logger;
308
+ }
309
+ clientId;
310
+ clientSecret;
311
+ tokenUrl;
312
+ httpClient;
313
+ logger;
314
+ token = null;
315
+ expiresAt = 0;
316
+ refreshPromise = null;
317
+ /** Buffer time in ms before expiry to refresh token (60 seconds) */
318
+ bufferMs = 6e4;
319
+ /**
320
+ * Gets a valid access token, refreshing if necessary.
321
+ *
322
+ * This method is safe for concurrent calls - if a refresh is already
323
+ * in progress, subsequent calls will await the same promise.
324
+ *
325
+ * @returns A valid access token
326
+ * @throws {UnauthorizedError} If token fetch fails
327
+ */
328
+ async getToken() {
329
+ if (this.token && Date.now() < this.expiresAt) {
330
+ this.logger.debug("Using cached token", {
331
+ expires_in_s: Math.max(0, Math.round((this.expiresAt - Date.now()) / 1e3))
332
+ });
333
+ return this.token;
334
+ }
335
+ if (this.refreshPromise) {
336
+ return this.refreshPromise;
337
+ }
338
+ this.logger.debug("Refreshing access token");
339
+ this.refreshPromise = this.fetchToken();
340
+ try {
341
+ return await this.refreshPromise;
342
+ } finally {
343
+ this.refreshPromise = null;
344
+ }
345
+ }
346
+ /**
347
+ * Fetches a new access token from the OAuth2 endpoint.
348
+ */
349
+ async fetchToken() {
350
+ const credentials = Buffer.from(
351
+ `${this.clientId}:${this.clientSecret}`
352
+ ).toString("base64");
353
+ const response = await this.httpClient.request({
354
+ method: "POST",
355
+ url: this.tokenUrl,
356
+ headers: {
357
+ Authorization: `Basic ${credentials}`,
358
+ "Content-Type": "application/x-www-form-urlencoded"
359
+ },
360
+ body: "grant_type=client_credentials"
361
+ });
362
+ if (!response.ok) {
363
+ let errorMessage = "Token request failed";
364
+ try {
365
+ const errorBody = await response.json();
366
+ if (errorBody.error_description) {
367
+ errorMessage = errorBody.error_description;
368
+ } else if (errorBody.error) {
369
+ errorMessage = errorBody.error;
370
+ }
371
+ } catch {
372
+ }
373
+ throw new UnauthorizedError(errorMessage);
374
+ }
375
+ const data = await response.json();
376
+ if (!data.access_token) {
377
+ throw new UnauthorizedError("Invalid token response: missing access_token");
378
+ }
379
+ this.token = data.access_token;
380
+ this.expiresAt = Date.now() + data.expires_in * 1e3 - this.bufferMs;
381
+ this.logger.debug("Access token refreshed", { expires_in_s: data.expires_in });
382
+ return this.token;
383
+ }
384
+ /**
385
+ * Invalidates the cached token, forcing a refresh on next getToken() call.
386
+ * Useful when receiving a 401 response from the API.
387
+ */
388
+ invalidate() {
389
+ this.token = null;
390
+ this.expiresAt = 0;
391
+ this.logger.debug("Token cache invalidated");
392
+ }
393
+ /**
394
+ * Checks if there's a valid cached token.
395
+ * @returns true if a valid token exists
396
+ */
397
+ hasValidToken() {
398
+ return this.token !== null && Date.now() < this.expiresAt;
399
+ }
400
+ };
401
+
402
+ // src/config.ts
403
+ var DEFAULT_BASE_URL = "https://api.glideidentity.app";
404
+ var DEFAULT_TIMEOUT = 3e4;
405
+ function resolveConfig(config) {
406
+ return {
407
+ clientId: config.clientId,
408
+ clientSecret: config.clientSecret,
409
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
410
+ httpClient: config.httpClient ?? defaultHttpClient,
411
+ logger: config.logger ?? noopLogger,
412
+ timeout: config.timeout ?? DEFAULT_TIMEOUT
413
+ };
414
+ }
415
+
416
+ // src/device-binding.ts
417
+ import { createHash, randomBytes } from "crypto";
418
+ var HEX_64 = /^[0-9a-fA-F]{64}$/;
419
+ var UNSAFE_COOKIE_ATTR = /[;\r\n]/;
420
+ var BINDING_COOKIE_PREFIX = "_glide_bind_";
421
+ var BINDING_COOKIE_MAX_AGE = 300;
422
+ var SENSITIVE_KEYS = [
423
+ "fe_code",
424
+ "fecode",
425
+ "feCode",
426
+ "fe_hash",
427
+ "fehash",
428
+ "feHash",
429
+ "agg_code",
430
+ "aggcode",
431
+ "aggCode",
432
+ "_glide_bind",
433
+ "glide_bind"
434
+ ];
435
+ function getBindingCookieName(sessionKey) {
436
+ if (!sessionKey || UNSAFE_COOKIE_ATTR.test(sessionKey) || sessionKey.includes("=")) {
437
+ throw new Error(
438
+ 'Invalid sessionKey for cookie name: must not be empty or contain ";", "=", "\\r", or "\\n"'
439
+ );
440
+ }
441
+ return `${BINDING_COOKIE_PREFIX}${sessionKey}`;
442
+ }
443
+ function assertValidFeCode(feCode) {
444
+ if (!HEX_64.test(feCode)) {
445
+ throw new Error("feCode must be a 64-character hex string");
446
+ }
447
+ }
448
+ function generateFeCode() {
449
+ return randomBytes(32).toString("hex");
450
+ }
451
+ function computeFeHash(feCode) {
452
+ assertValidFeCode(feCode);
453
+ return createHash("sha256").update(feCode.toLowerCase()).digest("hex");
454
+ }
455
+ function buildSetBindingCookieHeader(feCode, sessionKey, options) {
456
+ assertValidFeCode(feCode);
457
+ validateCookieAttr("domain", options?.domain);
458
+ validateCookieAttr("path", options?.path);
459
+ const secure = options?.secure ?? true;
460
+ const cookieName = getBindingCookieName(sessionKey);
461
+ const parts = [
462
+ `${cookieName}=${feCode.toLowerCase()}`,
463
+ "HttpOnly",
464
+ "SameSite=Lax",
465
+ `Path=${options?.path ?? "/"}`,
466
+ `Max-Age=${BINDING_COOKIE_MAX_AGE}`
467
+ ];
468
+ if (secure) {
469
+ parts.push("Secure");
470
+ }
471
+ if (options?.domain) {
472
+ parts.push(`Domain=${options.domain}`);
473
+ }
474
+ return parts.join("; ");
475
+ }
476
+ function buildClearBindingCookieHeader(sessionKey, options) {
477
+ validateCookieAttr("domain", options?.domain);
478
+ validateCookieAttr("path", options?.path);
479
+ const secure = options?.secure ?? true;
480
+ const cookieName = getBindingCookieName(sessionKey);
481
+ const parts = [
482
+ `${cookieName}=`,
483
+ "HttpOnly",
484
+ "SameSite=Lax",
485
+ `Path=${options?.path ?? "/"}`,
486
+ "Max-Age=0",
487
+ "Expires=Thu, 01 Jan 1970 00:00:00 GMT"
488
+ ];
489
+ if (secure) {
490
+ parts.push("Secure");
491
+ }
492
+ if (options?.domain) {
493
+ parts.push(`Domain=${options.domain}`);
494
+ }
495
+ return parts.join("; ");
496
+ }
497
+ function parseBindingCookie(cookieHeader, sessionKey) {
498
+ if (!cookieHeader) return void 0;
499
+ const cookieName = getBindingCookieName(sessionKey);
500
+ const prefix = `${cookieName}=`;
501
+ const match = cookieHeader.split(";").map((c) => c.trim()).find((c) => c.startsWith(prefix));
502
+ if (!match) return void 0;
503
+ const value = match.substring(prefix.length);
504
+ return HEX_64.test(value) ? value.toLowerCase() : void 0;
505
+ }
506
+ function clearStaleBindingCookies(cookieHeader, options) {
507
+ if (!cookieHeader) return [];
508
+ const headers = [];
509
+ for (const pair of cookieHeader.split(";")) {
510
+ const eqIdx = pair.indexOf("=");
511
+ const name = (eqIdx === -1 ? pair : pair.slice(0, eqIdx)).trim();
512
+ if (name.startsWith(BINDING_COOKIE_PREFIX)) {
513
+ const sessionSuffix = name.substring(BINDING_COOKIE_PREFIX.length);
514
+ if (!sessionSuffix) continue;
515
+ try {
516
+ headers.push(buildClearBindingCookieHeader(sessionSuffix, options));
517
+ } catch {
518
+ }
519
+ }
520
+ }
521
+ return headers;
522
+ }
523
+ function validateCookieAttr(name, value) {
524
+ if (value === void 0) return;
525
+ if (UNSAFE_COOKIE_ATTR.test(value)) {
526
+ throw new Error(
527
+ `Invalid cookie ${name}: must not contain ';', '\\r', or '\\n'`
528
+ );
529
+ }
530
+ if (name === "path" && (value.length === 0 || !value.startsWith("/"))) {
531
+ throw new Error("Invalid cookie path: must start with '/'");
532
+ }
533
+ }
534
+ function getCompletionPageHtml(completeEndpoint) {
535
+ if (!completeEndpoint.startsWith("/") || completeEndpoint.startsWith("//")) {
536
+ throw new Error(
537
+ '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
+ );
539
+ }
540
+ return `<!DOCTYPE html>
541
+ <html lang="en">
542
+ <head>
543
+ <meta charset="utf-8">
544
+ <meta name="viewport" content="width=device-width, initial-scale=1">
545
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'">
546
+ <title>Verifying</title>
547
+ <style>
548
+ * { box-sizing: border-box; margin: 0; padding: 0; }
549
+ body { font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; min-height: 100dvh; background: #fff; color: #1a1a1a; -webkit-font-smoothing: antialiased; }
550
+ .spinner-wrap { text-align: center; }
551
+ .spinner { width: 44px; height: 44px; border: 3px solid transparent; border-top-color: #222; border-radius: 50%; animation: spin 0.7s linear infinite; margin: 0 auto; }
552
+ @keyframes spin { to { transform: rotate(360deg); } }
553
+ .hidden { display: none; }
554
+ .hint { margin-top: 1.5rem; font-size: 0.875rem; color: #999; }
555
+ .err { display: none; text-align: center; padding: 2rem 1.5rem; max-width: 340px; }
556
+ .err h2 { font-size: 1.25rem; font-weight: 600; color: #1a1a1a; margin-bottom: 1rem; letter-spacing: -0.02em; line-height: 1.3; }
557
+ .err-points { text-align: left; margin: 0 auto 1.5rem; max-width: 280px; }
558
+ .err-points li { font-size: 0.875rem; line-height: 1.6; color: #555; margin-bottom: 0.375rem; padding-left: 0.25rem; }
559
+ .illust { margin: 0 auto 1.5rem; }
560
+ .illust svg { color: #94a3b8; }
561
+ .illust-browser { width: 140px; height: 90px; position: relative; }
562
+ .illust-browser .b { position: absolute; width: 52px; height: 40px; border: 2px solid #cbd5e1; border-radius: 6px; background: #f8fafc; }
563
+ .illust-browser .b .bar { height: 10px; border-bottom: 1.5px solid #e2e8f0; display: flex; align-items: center; padding: 0 4px; gap: 2px; }
564
+ .illust-browser .b .bar i { width: 3px; height: 3px; border-radius: 50%; background: #cbd5e1; }
565
+ .illust-browser .b1 { left: 10px; top: 16px; } .illust-browser .b2 { right: 10px; top: 16px; }
566
+ .illust-browser .aw { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
567
+ .illust-browser .aw svg { width: 36px; height: 36px; animation: arrowSpin 2.5s ease-in-out infinite; }
568
+ @keyframes arrowSpin { 0%,100% { transform: rotate(0); } 50% { transform: rotate(180deg); } }
569
+ .illust-retry svg { width: 48px; height: 48px; animation: retryPulse 2s ease-in-out infinite; }
570
+ @keyframes retryPulse { 0%,100% { transform: scale(1); opacity: 0.7; } 50% { transform: scale(1.1); opacity: 1; } }
571
+ .illust-wifi svg { width: 48px; height: 48px; animation: wifiBlink 2s ease-in-out infinite; }
572
+ @keyframes wifiBlink { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
573
+ .illust-link svg { width: 48px; height: 48px; animation: linkShake 2s ease-in-out infinite; }
574
+ @keyframes linkShake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-5deg); } 75% { transform: rotate(5deg); } }
575
+ .badge { display: inline-flex; align-items: center; background: #fff4e6; border: 1px solid #ffd8a8; border-radius: 100px; padding: 5px 14px; font-size: 0.6875rem; font-weight: 600; color: #e67700; text-transform: uppercase; letter-spacing: 0.06em; margin-top: 0.25rem; }
576
+ @keyframes fadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
577
+ .err.show { display: block; animation: fadeUp 0.35s ease-out; }
578
+ </style>
579
+ </head>
580
+ <body>
581
+ <div class="spinner-wrap" id="loading" role="status" aria-live="polite">
582
+ <div class="spinner"></div>
583
+ <p class="hint hidden" id="hint"></p>
584
+ </div>
585
+ <div class="err" id="error" role="alert" aria-live="assertive">
586
+ <h2 id="err-title"></h2>
587
+ <ol class="err-points" id="err-points"></ol>
588
+ <div class="illust illust-browser hidden" id="ill-browser">
589
+ <div class="illust-browser">
590
+ <div class="b b1"><div class="bar"><i></i><i></i><i></i></div></div>
591
+ <div class="b b2"><div class="bar"><i></i><i></i><i></i></div></div>
592
+ <div class="aw"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"/></svg></div>
593
+ </div>
594
+ </div>
595
+ <div class="illust illust-retry hidden" id="ill-retry">
596
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>
597
+ </div>
598
+ <div class="illust illust-wifi hidden" id="ill-wifi">
599
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M1 1l22 22M16.72 11.06A10.94 10.94 0 0119 12.55M5 12.55a10.94 10.94 0 015.17-2.39M10.71 5.05A16 16 0 0122.56 9M1.42 9a15.91 15.91 0 014.7-2.88M8.53 16.11a6 6 0 016.95 0M12 20h.01"/></svg>
600
+ </div>
601
+ <div class="illust illust-link hidden" id="ill-link">
602
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M15 7h3a5 5 0 010 10h-3m-6 0H6a5 5 0 010-10h3"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
603
+ </div>
604
+ <div class="badge">Action required</div>
605
+ </div>
606
+ <script>
607
+ (async function() {
608
+ var fragment = new URLSearchParams(window.location.hash.substring(1));
609
+ var aggCode = fragment.get('agg_code');
610
+ var sessionKey = fragment.get('session_key');
611
+
612
+ window.history.replaceState(null, '', window.location.pathname + window.location.search);
613
+
614
+ if (!aggCode || !sessionKey) {
615
+ showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');
616
+ return;
617
+ }
618
+
619
+ try {
620
+ var res = await fetch(${JSON.stringify(completeEndpoint)}, {
621
+ method: 'POST',
622
+ credentials: 'include',
623
+ headers: { 'Content-Type': 'application/json' },
624
+ body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })
625
+ });
626
+
627
+ if (res.ok) {
628
+ var signalKey = 'glide_signal_' + sessionKey;
629
+ try {
630
+ localStorage.setItem(signalKey, sessionKey);
631
+ setTimeout(function() {
632
+ try { localStorage.removeItem(signalKey); } catch(e) {}
633
+ }, 5000);
634
+ } catch(e) {}
635
+ tryClose();
636
+ } else {
637
+ var code = '';
638
+ try { var data = await res.json(); code = (data && (data.code || data.error)) || ''; } catch (_) {}
639
+ var err = friendlyError(code);
640
+ showError(err.title, err.points, err.illust);
641
+ }
642
+ } catch (e) {
643
+ showError('Connection issue', ['We could not reach the server.', 'Check your internet connection and try again.'], 'wifi');
644
+ }
645
+
646
+ function friendlyError(code) {
647
+ switch (code) {
648
+ case 'MISSING_BINDING_COOKIE':
649
+ case 'BROWSER_MISMATCH':
650
+ 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' };
651
+ default:
652
+ return { title: 'Verification could not be completed', points: ['Something went wrong during verification.', 'Please go back and try again.'], illust: 'retry' };
653
+ }
654
+ }
655
+
656
+ function tryClose() {
657
+ document.querySelector('.spinner').classList.add('hidden');
658
+ window.close();
659
+ try { window.open('', '_self').close(); } catch(e) {}
660
+ setTimeout(function() {
661
+ document.getElementById('hint').textContent = 'You may close this tab.';
662
+ document.getElementById('hint').classList.remove('hidden');
663
+ }, 300);
664
+ }
665
+
666
+ function showError(title, points, illust) {
667
+ document.getElementById('loading').classList.add('hidden');
668
+ document.getElementById('err-title').textContent = title;
669
+ var ol = document.getElementById('err-points');
670
+ ol.innerHTML = '';
671
+ (points || []).forEach(function(p) { var li = document.createElement('li'); li.textContent = p; ol.appendChild(li); });
672
+ var ids = ['ill-browser','ill-retry','ill-wifi','ill-link'];
673
+ ids.forEach(function(id) { document.getElementById(id).classList.add('hidden'); });
674
+ var el = document.getElementById('ill-' + (illust || 'retry'));
675
+ if (el) el.classList.remove('hidden');
676
+ document.getElementById('error').classList.add('show');
677
+ }
678
+ })();
679
+ </script>
680
+ </body>
681
+ </html>`;
682
+ }
683
+
684
+ // src/internal/mask.ts
685
+ function maskPhoneNumber(phone) {
686
+ if (!phone || phone.length <= 8) return "***";
687
+ return `${phone.substring(0, 4)}***${phone.substring(phone.length - 4)}`;
688
+ }
689
+
690
+ // src/models/common.ts
691
+ var UseCase = {
692
+ GET_PHONE_NUMBER: "GetPhoneNumber",
693
+ VERIFY_PHONE_NUMBER: "VerifyPhoneNumber"
694
+ };
695
+ var AuthenticationStrategy = {
696
+ TS43: "ts43",
697
+ LINK: "link",
698
+ DESKTOP: "desktop",
699
+ NONE: ""
700
+ };
701
+ var SessionStatus = {
702
+ PENDING: "pending",
703
+ SCANNED: "scanned",
704
+ PENDING_COMPLETION: "pending_completion",
705
+ COMPLETED: "completed",
706
+ FAILED: "failed"
707
+ };
708
+
709
+ // src/validation.ts
710
+ function validatePrepareRequest(request) {
711
+ const errors = {};
712
+ const hasParentSession = !!request.options?.parent_session_id?.trim();
713
+ if (!request.use_case && !hasParentSession) {
714
+ errors.use_case = "use_case is required";
715
+ }
716
+ if (request.use_case === UseCase.VERIFY_PHONE_NUMBER && !request.phone_number) {
717
+ errors.phone_number = "phone_number is required for VerifyPhoneNumber";
718
+ }
719
+ if (Object.keys(errors).length > 0) {
720
+ throw new ValidationError("Request validation failed", errors);
721
+ }
722
+ }
723
+ function validateVerifyPhoneNumberRequest(request) {
724
+ const errors = {};
725
+ if (!request.session?.session_key) {
726
+ errors["session.session_key"] = "session.session_key is required";
727
+ }
728
+ if (!request.credential) {
729
+ errors.credential = "credential is required";
730
+ }
731
+ if (Object.keys(errors).length > 0) {
732
+ throw new ValidationError("Request validation failed", errors);
733
+ }
734
+ }
735
+ function validateGetPhoneNumberRequest(request) {
736
+ const errors = {};
737
+ if (!request.session?.session_key) {
738
+ errors["session.session_key"] = "session.session_key is required";
739
+ }
740
+ if (!request.credential) {
741
+ errors.credential = "credential is required";
742
+ }
743
+ if (Object.keys(errors).length > 0) {
744
+ throw new ValidationError("Request validation failed", errors);
745
+ }
746
+ }
747
+ function validateSessionId(sessionId) {
748
+ if (!sessionId) {
749
+ throw new ValidationError("Request validation failed", {
750
+ session_id: "session_id is required"
751
+ });
752
+ }
753
+ }
754
+ function validateSessionKey(sessionKey) {
755
+ if (!sessionKey) {
756
+ throw new ValidationError("Request validation failed", {
757
+ session_key: "session_key is required"
758
+ });
759
+ }
760
+ }
761
+ function validateCompleteRequest(request) {
762
+ if (!request.session_key) {
763
+ throw new ValidationError("Request validation failed", {
764
+ session_key: "session_key is required"
765
+ });
766
+ }
767
+ if (!request.fe_code) {
768
+ throw new MissingBindingCookieError(
769
+ "fe_code is required (from _glide_bind cookie)"
770
+ );
771
+ }
772
+ if (!request.agg_code) {
773
+ throw new ValidationError("Request validation failed", {
774
+ agg_code: "agg_code is required"
775
+ });
776
+ }
777
+ if (!HEX_64.test(request.fe_code) || !HEX_64.test(request.agg_code)) {
778
+ throw new DeviceBindingError("Invalid device binding inputs");
779
+ }
780
+ }
781
+
782
+ // src/client.ts
783
+ var MagicalAuthClient = class {
784
+ config;
785
+ tokenManager;
786
+ /**
787
+ * Creates a new MagicalAuthClient instance.
788
+ *
789
+ * @param config - Client configuration
790
+ * @throws {Error} If clientId or clientSecret is missing
791
+ */
792
+ constructor(config) {
793
+ if (!config.clientId) {
794
+ throw new Error("clientId is required");
795
+ }
796
+ if (!config.clientSecret) {
797
+ throw new Error("clientSecret is required");
798
+ }
799
+ this.config = resolveConfig(config);
800
+ this.tokenManager = new TokenManager(
801
+ this.config.clientId,
802
+ this.config.clientSecret,
803
+ `${this.config.baseUrl}/oauth2-cc/token`,
804
+ this.config.httpClient,
805
+ this.config.logger
806
+ );
807
+ }
808
+ /**
809
+ * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
810
+ *
811
+ * Automatically generates `fe_code` / `fe_hash` for device binding. If the aggregator
812
+ * selects the 'link' strategy, `feCode` is included in the result so the caller can
813
+ * set it as an HttpOnly cookie via `buildSetBindingCookieHeader()`.
814
+ *
815
+ * @param request - Prepare request parameters
816
+ * @param options - Per-request options (e.g., correlationId)
817
+ * @returns Prepare result with authentication strategy, session info, and optional feCode
818
+ * @throws {ValidationError} If request validation fails
819
+ * @throws {CarrierNotEligibleError} If carrier is not eligible
820
+ * @throws {MagicalAuthError} For other API errors
821
+ */
822
+ async prepare(request, options) {
823
+ validatePrepareRequest(request);
824
+ this.config.logger.debug("Preparing auth", { use_case: request.use_case });
825
+ const nonce = request.nonce || generateNonce();
826
+ const feCode = generateFeCode();
827
+ const feHash = computeFeHash(feCode);
828
+ const requestWithHash = { ...request, nonce, fe_hash: feHash };
829
+ const response = await this.doRequest(
830
+ "POST",
831
+ "/magic-auth/v2/auth/prepare",
832
+ requestWithHash,
833
+ options
834
+ );
835
+ const result = { ...response };
836
+ if (response.authentication_strategy === AuthenticationStrategy.LINK) {
837
+ const linkData = response.data;
838
+ result.feCode = linkData.fe_code ?? feCode;
839
+ }
840
+ this.config.logger.debug("Auth prepared", {
841
+ strategy: response.authentication_strategy,
842
+ session_key: response.session.session_key
843
+ });
844
+ return result;
845
+ }
846
+ /**
847
+ * Validates device binding codes and completes a link protocol session.
848
+ *
849
+ * Called after the carrier OAuth redirect lands on the developer's completion page.
850
+ * The completion page extracts `agg_code` + `session_key` from the URL fragment
851
+ * and the developer's handler reads `fe_code` from the `_glide_bind` cookie.
852
+ *
853
+ * @param request - Complete request with session_key, fe_code, and agg_code
854
+ * @param options - Per-request options (e.g., correlationId)
855
+ * @returns Complete response with status
856
+ * @throws {DeviceBindingError} If binding code validation fails
857
+ * @throws {SessionNotFoundError} If session not found or expired
858
+ * @throws {SessionNotEligibleError} If session not in pending_completion status
859
+ * @throws {BrowserMismatchError} If browser differs from the one used in prepare
860
+ * @throws {MagicalAuthError} For other API errors
861
+ */
862
+ async complete(request, options) {
863
+ validateCompleteRequest(request);
864
+ this.config.logger.debug("Completing device-bound session", {
865
+ session_key: request.session_key
866
+ });
867
+ const response = await this.doRequest(
868
+ "POST",
869
+ "/magic-auth/v2/auth/complete",
870
+ request,
871
+ options
872
+ );
873
+ this.config.logger.debug("Device binding validated", { status: response.status });
874
+ return response;
875
+ }
876
+ /**
877
+ * Verifies a phone number using digital credentials.
878
+ *
879
+ * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.
880
+ *
881
+ * @param request - Verify request with session and credential
882
+ * @param options - Per-request options (e.g., correlationId)
883
+ * @returns Verification result with phone number and verified status
884
+ * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info
885
+ * @throws {SessionNotFoundError} If session not found or expired
886
+ * @throws {InvalidCredentialError} If credential format is invalid
887
+ * @throws {MagicalAuthError} For other API errors
888
+ */
889
+ async verifyPhoneNumber(request, options) {
890
+ validateVerifyPhoneNumberRequest(request);
891
+ this.config.logger.debug("Verifying phone number", {
892
+ session_key: request.session.session_key
893
+ });
894
+ const response = await this.doRequest(
895
+ "POST",
896
+ "/magic-auth/v2/auth/verify-phone-number",
897
+ request,
898
+ options
899
+ );
900
+ this.config.logger.debug("Phone verification complete", { verified: response.verified });
901
+ return response;
902
+ }
903
+ /**
904
+ * Retrieves the phone number associated with the device using digital credentials.
905
+ *
906
+ * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.
907
+ *
908
+ * @param request - Get phone number request with session and credential
909
+ * @param options - Per-request options (e.g., correlationId)
910
+ * @returns Response with the retrieved phone number
911
+ * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info
912
+ * @throws {SessionNotFoundError} If session not found or expired
913
+ * @throws {InvalidCredentialError} If credential format is invalid
914
+ * @throws {MagicalAuthError} For other API errors
915
+ */
916
+ async getPhoneNumber(request, options) {
917
+ validateGetPhoneNumberRequest(request);
918
+ this.config.logger.debug("Getting phone number", {
919
+ session_key: request.session.session_key
920
+ });
921
+ const response = await this.doRequest(
922
+ "POST",
923
+ "/magic-auth/v2/auth/get-phone-number",
924
+ request,
925
+ options
926
+ );
927
+ this.config.logger.debug("Phone number retrieved", {
928
+ phone: maskPhoneNumber(response.phone_number)
929
+ });
930
+ return response;
931
+ }
932
+ /**
933
+ * Reports when a user clicks the invoke/authenticate button.
934
+ *
935
+ * Used for Authentication Success Rate (ASR) tracking and analytics.
936
+ *
937
+ * @param sessionId - The session identifier
938
+ * @param options - Per-request options (e.g., correlationId)
939
+ * @returns Report response with a boolean `success` flag
940
+ * @throws {SessionNotFoundError} If session not found
941
+ * @throws {MagicalAuthError} For other API errors
942
+ */
943
+ async reportInvocation(sessionId, options) {
944
+ validateSessionId(sessionId);
945
+ this.config.logger.debug("Reporting invocation", { session_id: sessionId });
946
+ return await this.doRequest(
947
+ "POST",
948
+ "/magic-auth/v2/auth/report-invocation",
949
+ { session_id: sessionId },
950
+ options
951
+ );
952
+ }
953
+ /**
954
+ * Polls for the status of an ongoing verification request (protected endpoint).
955
+ *
956
+ * @param sessionKey - The 64-character hex session key from prepare response
957
+ * @param options - Per-request options (e.g., correlationId)
958
+ * @returns Status response with current verification state
959
+ * @throws {SessionNotFoundError} If session not found or expired
960
+ * @throws {MagicalAuthError} For other API errors
961
+ */
962
+ async checkStatus(sessionKey, options) {
963
+ validateSessionKey(sessionKey);
964
+ this.config.logger.debug("Checking status", { session_key: sessionKey });
965
+ const response = await this.doRequest(
966
+ "GET",
967
+ `/magic-auth/v2/auth/status/${encodeURIComponent(sessionKey)}`,
968
+ void 0,
969
+ options
970
+ );
971
+ this.config.logger.debug("Status retrieved", { status: response.status });
972
+ return response;
973
+ }
974
+ /**
975
+ * Polls for the status of an ongoing verification request (public endpoint).
976
+ *
977
+ * This endpoint does not require authentication.
978
+ *
979
+ * @param sessionKey - The 64-character hex session key from prepare response
980
+ * @param options - Per-request options (e.g., correlationId)
981
+ * @returns Status response with current verification state
982
+ * @throws {SessionNotFoundError} If session not found or expired
983
+ * @throws {MagicalAuthError} For other API errors
984
+ */
985
+ async checkStatusPublic(sessionKey, options) {
986
+ validateSessionKey(sessionKey);
987
+ this.config.logger.debug("Checking public status", { session_key: sessionKey });
988
+ const response = await this.doRequestWithoutAuth(
989
+ "GET",
990
+ `/public/status/${encodeURIComponent(sessionKey)}`,
991
+ void 0,
992
+ options
993
+ );
994
+ this.config.logger.debug("Public status retrieved", { status: response.status });
995
+ return response;
996
+ }
997
+ /**
998
+ * Makes an authenticated API request.
999
+ */
1000
+ async doRequest(method, path, body, options) {
1001
+ const token = await this.tokenManager.getToken();
1002
+ this.config.logger.debug("Request", { method, path });
1003
+ const headers = {
1004
+ "Content-Type": "application/json",
1005
+ Authorization: `Bearer ${token}`
1006
+ };
1007
+ if (options?.correlationId) {
1008
+ headers["X-Correlation-ID"] = options.correlationId;
1009
+ }
1010
+ const controller = new AbortController();
1011
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1012
+ try {
1013
+ const response = await this.config.httpClient.request({
1014
+ method,
1015
+ url: `${this.config.baseUrl}${path}`,
1016
+ headers,
1017
+ body: body ? JSON.stringify(body) : void 0,
1018
+ signal: controller.signal
1019
+ });
1020
+ return this.handleResponse(response);
1021
+ } catch (error) {
1022
+ if (error instanceof Error && error.name === "AbortError") {
1023
+ throw new MagicalAuthError(
1024
+ "Request timeout",
1025
+ "TIMEOUT",
1026
+ 408,
1027
+ void 0,
1028
+ { timeout: this.config.timeout }
1029
+ );
1030
+ }
1031
+ throw error;
1032
+ } finally {
1033
+ clearTimeout(timeoutId);
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Makes an unauthenticated API request (for public endpoints).
1038
+ */
1039
+ async doRequestWithoutAuth(method, path, body, options) {
1040
+ this.config.logger.debug("Request (no auth)", { method, path });
1041
+ const headers = {
1042
+ "Content-Type": "application/json"
1043
+ };
1044
+ if (options?.correlationId) {
1045
+ headers["X-Correlation-ID"] = options.correlationId;
1046
+ }
1047
+ const controller = new AbortController();
1048
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1049
+ try {
1050
+ const response = await this.config.httpClient.request({
1051
+ method,
1052
+ url: `${this.config.baseUrl}${path}`,
1053
+ headers,
1054
+ body: body ? JSON.stringify(body) : void 0,
1055
+ signal: controller.signal
1056
+ });
1057
+ return this.handleResponse(response);
1058
+ } catch (error) {
1059
+ if (error instanceof Error && error.name === "AbortError") {
1060
+ throw new MagicalAuthError(
1061
+ "Request timeout",
1062
+ "TIMEOUT",
1063
+ 408,
1064
+ void 0,
1065
+ { timeout: this.config.timeout }
1066
+ );
1067
+ }
1068
+ throw error;
1069
+ } finally {
1070
+ clearTimeout(timeoutId);
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Handles API response, parsing JSON and converting errors.
1075
+ * Throws DesktopWaitError for HTTP 202 responses.
1076
+ */
1077
+ async handleResponse(response) {
1078
+ if (response.status === 202) {
1079
+ const waitBody = await response.json();
1080
+ throw new DesktopWaitError(waitBody);
1081
+ }
1082
+ if (!response.ok) {
1083
+ let errorBody;
1084
+ try {
1085
+ errorBody = await response.json();
1086
+ if (!errorBody.status) {
1087
+ errorBody.status = response.status;
1088
+ }
1089
+ } catch {
1090
+ errorBody = {
1091
+ code: "UNKNOWN_ERROR",
1092
+ message: `Request failed with status ${response.status}`,
1093
+ status: response.status
1094
+ };
1095
+ }
1096
+ throw createErrorFromResponse(errorBody, response.headers);
1097
+ }
1098
+ return response.json();
1099
+ }
1100
+ /**
1101
+ * Invalidates the cached access token.
1102
+ */
1103
+ invalidateToken() {
1104
+ this.tokenManager.invalidate();
1105
+ }
1106
+ };
1107
+ var ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1108
+ function generateNonce(length = 32) {
1109
+ const bytes = randomBytes2(length);
1110
+ let result = "";
1111
+ for (let i = 0; i < length; i++) {
1112
+ result += ALPHANUMERIC.charAt(bytes[i] % ALPHANUMERIC.length);
1113
+ }
1114
+ return result;
1115
+ }
1116
+
1117
+ // src/logger.ts
1118
+ function createLogger(config = {}) {
1119
+ const { debug = false, prefix = "[GlideMagicalAuth]" } = config;
1120
+ if (!debug) return noopLogger;
1121
+ const fmt = (msg, meta) => {
1122
+ const out = [`${prefix} ${sanitize(msg)}`];
1123
+ if (meta !== void 0) out.push(sanitize(meta));
1124
+ return out;
1125
+ };
1126
+ return {
1127
+ debug: (m, d) => console.log(...fmt(m, d)),
1128
+ info: (m, d) => console.info(...fmt(m, d)),
1129
+ warn: (m, d) => console.warn(...fmt(m, d)),
1130
+ error: (m, d) => console.error(...fmt(m, d))
1131
+ };
1132
+ }
1133
+ var PHONE_RE = /(\+?[1-9]\d{6,14})/g;
1134
+ var JWT_RE = /(eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)/g;
1135
+ var SESSION_RE = /(session[_-]?key)(["']?\s*[:=]\s*["']?)([A-Za-z0-9_-]{16,})/gi;
1136
+ var SENSITIVE = ["phone_number", "phonenumber", "credential", "token", "password", "secret", "fe_code", "fecode"];
1137
+ function sanitize(data) {
1138
+ if (data == null) return data;
1139
+ 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)}`);
1141
+ }
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;
1149
+ }
1150
+ return data;
1151
+ }
1152
+
1153
+ // src/index.ts
1154
+ var _require = createRequire(import.meta.url);
1155
+ var VERSION = _require("../package.json").version;
1156
+ export {
1157
+ AuthenticationStrategy,
1158
+ BINDING_COOKIE_MAX_AGE,
1159
+ BINDING_COOKIE_PREFIX,
1160
+ BadRequestError,
1161
+ BrowserMismatchError,
1162
+ CarrierNotEligibleError,
1163
+ DEFAULT_BASE_URL,
1164
+ DEFAULT_TIMEOUT,
1165
+ DesktopWaitError,
1166
+ DeviceBindingError,
1167
+ ErrorCode,
1168
+ ForbiddenError,
1169
+ HEX_64,
1170
+ InternalServerError,
1171
+ InvalidCredentialError,
1172
+ MagicalAuthClient,
1173
+ MagicalAuthError,
1174
+ MissingBindingCookieError,
1175
+ PhoneNumberMismatchError,
1176
+ RateLimitError,
1177
+ SENSITIVE_KEYS,
1178
+ ServiceUnavailableError,
1179
+ SessionNotEligibleError,
1180
+ SessionNotFoundError,
1181
+ SessionStatus,
1182
+ TokenManager,
1183
+ UnauthorizedError,
1184
+ UnsupportedPlatformError,
1185
+ UseCase,
1186
+ VERSION,
1187
+ ValidationError,
1188
+ assertValidFeCode,
1189
+ buildClearBindingCookieHeader,
1190
+ buildSetBindingCookieHeader,
1191
+ clearStaleBindingCookies,
1192
+ computeFeHash,
1193
+ createErrorFromResponse,
1194
+ createLogger,
1195
+ defaultHttpClient,
1196
+ generateFeCode,
1197
+ getBindingCookieName,
1198
+ getCompletionPageHtml,
1199
+ noopLogger,
1200
+ parseBindingCookie,
1201
+ resolveConfig,
1202
+ sanitize
1203
+ };
1204
+ //# sourceMappingURL=index.js.map