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