@glideidentity/glide-be-node-magical-auth 2.0.0 → 3.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/internal/http.ts","../src/errors.ts","../src/auth.ts","../src/config.ts","../src/device-binding.ts","../src/internal/mask.ts","../src/models/common.ts","../src/validation.ts","../src/logger.ts"],"sourcesContent":["/**\n * Glide Magical Auth SDK for Node.js\n *\n * Phone number authentication without SMS/OTP using carrier-based digital credentials.\n *\n * @packageDocumentation\n *\n * @example\n * ```typescript\n * import {\n * MagicalAuthClient,\n * UseCase,\n * AuthenticationStrategy,\n * buildSetBindingCookieHeader,\n * } from '@glideidentity/glide-be-node-magical-auth';\n *\n * const magicalAuth = new MagicalAuthClient({\n * clientId: process.env.GLIDE_CLIENT_ID!,\n * clientSecret: process.env.GLIDE_CLIENT_SECRET!,\n * });\n *\n * // Prepare authentication\n * const result = await magicalAuth.prepare({\n * phone_number: '+14155551234',\n * use_case: UseCase.VERIFY_PHONE_NUMBER,\n * client_info: { user_agent: req.headers['user-agent'] },\n * });\n *\n * // For link protocol, set the binding cookie\n * if (result.feCode) {\n * res.setHeader('Set-Cookie', buildSetBindingCookieHeader(result.feCode, result.session.session_key));\n * }\n *\n * // Handle based on strategy\n * switch (result.authentication_strategy) {\n * case AuthenticationStrategy.TS43:\n * // Direct carrier credential request\n * break;\n * case AuthenticationStrategy.LINK:\n * // OAuth redirect flow (device-bound)\n * break;\n * case AuthenticationStrategy.DESKTOP:\n * // QR code flow\n * break;\n * }\n * ```\n */\n\n// SDK version (read from package.json — always distributed with npm packages)\nimport { createRequire } from 'node:module';\nconst _require = createRequire(import.meta.url);\nexport const VERSION: string = _require('../package.json').version;\n\n// Main client\nexport { MagicalAuthClient } from './client.js';\nexport type { RequestOptions } from './client.js';\n\n// Configuration\nexport type { MagicalAuthConfig, ResolvedConfig } from './config.js';\nexport { DEFAULT_BASE_URL, DEFAULT_TIMEOUT, resolveConfig } from './config.js';\n\n// Token manager\nexport { TokenManager } from './auth.js';\n\n// HTTP interfaces (BYOC)\nexport type {\n HttpClient,\n HttpRequestOptions,\n HttpResponse,\n Logger,\n} from './internal/http.js';\nexport { defaultHttpClient } from './internal/http.js';\n\n// Logger factory (BYOL — bring your own, or use ours)\nexport type { LoggerConfig } from './logger.js';\nexport { createLogger, noopLogger, sanitize } from './logger.js';\n\n// Device binding utilities\nexport type { BindingCookieOptions } from './device-binding.js';\nexport {\n assertValidFeCode,\n BINDING_COOKIE_MAX_AGE,\n BINDING_COOKIE_PREFIX,\n buildClearBindingCookieHeader,\n buildSetBindingCookieHeader,\n clearStaleBindingCookies,\n computeFeHash,\n generateFeCode,\n getBindingCookieName,\n getCompletionPageHtml,\n HEX_64,\n parseBindingCookie,\n SENSITIVE_KEYS,\n} from './device-binding.js';\n\n// Errors (ErrorCode is both a const object and a type)\nexport type { ErrorResponse } from './errors.js';\nexport {\n BadRequestError,\n BrowserMismatchError,\n CarrierNotEligibleError,\n createErrorFromResponse,\n DesktopWaitError,\n DeviceBindingError,\n ErrorCode,\n MissingBindingCookieError,\n ForbiddenError,\n InternalServerError,\n InvalidCredentialError,\n MagicalAuthError,\n PhoneNumberMismatchError,\n RateLimitError,\n ServiceUnavailableError,\n SessionNotEligibleError,\n SessionNotFoundError,\n UnauthorizedError,\n UnsupportedPlatformError,\n ValidationError,\n} from './errors.js';\n\n// Constants (as const objects — use UseCase.GET_PHONE_NUMBER, AuthenticationStrategy.TS43, etc.)\nexport {\n AuthenticationStrategy,\n SessionStatus,\n UseCase,\n} from './models/index.js';\n\n// Model types\nexport type {\n Challenge,\n ClientInfo,\n ConsentData,\n DeviceInfo,\n DeviceSwapInfo,\n PLMN,\n ProtocolType,\n RiskLevel,\n SessionInfo,\n SimSwapFailureReason,\n SimSwapInfo,\n // Strategy-specific types\n DCQLCredential,\n DCQLCredentialMeta,\n DCQLQuery,\n DesktopQRData,\n DesktopStrategyData,\n LinkStrategyData,\n StrategyData,\n TS43RequestData,\n TS43StrategyData,\n // Prepare types\n PrepareOptions,\n PrepareRequest,\n PrepareResponse,\n PrepareResult,\n Theme,\n // Verify types\n VerifyPhoneNumberRequest,\n VerifyPhoneNumberResponse,\n // Phone types\n GetPhoneNumberRequest,\n GetPhoneNumberResponse,\n // Complete types\n CompleteRequest,\n CompleteResponse,\n DesktopWaitResponse,\n // Status types\n StatusResponse,\n // Report types\n ReportInvocationRequest,\n ReportInvocationResponse,\n} from './models/index.js';\n","import { randomBytes } from 'node:crypto';\nimport { TokenManager } from './auth.js';\nimport type { MagicalAuthConfig, ResolvedConfig } from './config.js';\nimport { resolveConfig } from './config.js';\nimport { computeFeHash, generateFeCode } from './device-binding.js';\nimport type { ErrorResponse } from './errors.js';\nimport {\n createErrorFromResponse,\n DesktopWaitError,\n MagicalAuthError,\n} from './errors.js';\nimport type { HttpResponse } from './internal/http.js';\nimport { maskPhoneNumber } from './internal/mask.js';\nimport { AuthenticationStrategy } from './models/index.js';\nimport type {\n CompleteRequest,\n CompleteResponse,\n DesktopWaitResponse,\n GetPhoneNumberRequest,\n GetPhoneNumberResponse,\n LinkStrategyData,\n PrepareRequest,\n PrepareResponse,\n PrepareResult,\n ReportInvocationResponse,\n StatusResponse,\n VerifyPhoneNumberRequest,\n VerifyPhoneNumberResponse,\n} from './models/index.js';\nimport {\n validateCompleteRequest,\n validateGetPhoneNumberRequest,\n validatePrepareRequest,\n validateSessionId,\n validateSessionKey,\n validateVerifyPhoneNumberRequest,\n} from './validation.js';\n\n/**\n * Per-request options for API calls.\n */\nexport interface RequestOptions {\n /** Correlation ID forwarded as X-Correlation-ID header for request tracing */\n correlationId?: string;\n}\n\n/**\n * Magical Auth SDK client for phone number authentication.\n *\n * @example\n * ```typescript\n * const client = new MagicalAuthClient({\n * clientId: 'your-client-id',\n * clientSecret: 'your-client-secret',\n * });\n *\n * // Prepare authentication (auto-generates device binding codes)\n * const result = await client.prepare({\n * phone_number: '+14155551234',\n * nonce: 'unique-nonce',\n * use_case: 'VerifyPhoneNumber',\n * client_info: { user_agent: req.headers['user-agent'] },\n * });\n *\n * // For link protocol, set the binding cookie\n * if (result.feCode) {\n * res.setHeader('Set-Cookie', buildSetBindingCookieHeader(result.feCode, result.session.session_key));\n * }\n * ```\n */\nexport class MagicalAuthClient {\n private readonly config: ResolvedConfig;\n private readonly tokenManager: TokenManager;\n\n /**\n * Creates a new MagicalAuthClient instance.\n *\n * @param config - Client configuration\n * @throws {Error} If clientId or clientSecret is missing\n */\n constructor(config: MagicalAuthConfig) {\n if (!config.clientId) {\n throw new Error('clientId is required');\n }\n if (!config.clientSecret) {\n throw new Error('clientSecret is required');\n }\n\n this.config = resolveConfig(config);\n this.tokenManager = new TokenManager(\n this.config.clientId,\n this.config.clientSecret,\n `${this.config.baseUrl}/oauth2-cc/token`,\n this.config.httpClient,\n this.config.logger,\n );\n }\n\n /**\n * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.\n *\n * Automatically generates `fe_code` / `fe_hash` for device binding. If the aggregator\n * selects the 'link' strategy, `feCode` is included in the result so the caller can\n * set it as an HttpOnly cookie via `buildSetBindingCookieHeader()`.\n *\n * @param request - Prepare request parameters\n * @param options - Per-request options (e.g., correlationId)\n * @returns Prepare result with authentication strategy, session info, and optional feCode\n * @throws {ValidationError} If request validation fails\n * @throws {CarrierNotEligibleError} If carrier is not eligible\n * @throws {MagicalAuthError} For other API errors\n */\n async prepare(\n request: PrepareRequest,\n options?: RequestOptions,\n ): Promise<PrepareResult> {\n validatePrepareRequest(request);\n this.config.logger.debug('Preparing auth', { use_case: request.use_case });\n\n const nonce = request.nonce || generateNonce();\n const feCode = generateFeCode();\n const feHash = computeFeHash(feCode);\n\n const requestWithHash: PrepareRequest = { ...request, nonce, fe_hash: feHash };\n\n const response = await this.doRequest<PrepareResponse>(\n 'POST',\n '/magic-auth/v2/auth/prepare',\n requestWithHash,\n options,\n );\n\n const result: PrepareResult = { ...response };\n\n if (response.authentication_strategy === AuthenticationStrategy.LINK) {\n const linkData = response.data as LinkStrategyData;\n result.feCode = linkData.fe_code ?? feCode;\n }\n\n this.config.logger.debug('Auth prepared', {\n strategy: response.authentication_strategy,\n session_key: response.session.session_key,\n });\n\n return result;\n }\n\n /**\n * Validates device binding codes and completes a link protocol session.\n *\n * Called after the carrier OAuth redirect lands on the developer's completion page.\n * The completion page extracts `agg_code` + `session_key` from the URL fragment\n * and the developer's handler reads `fe_code` from the `_glide_bind` cookie.\n *\n * @param request - Complete request with session_key, fe_code, and agg_code\n * @param options - Per-request options (e.g., correlationId)\n * @returns Complete response with status\n * @throws {DeviceBindingError} If binding code validation fails\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {SessionNotEligibleError} If session not in pending_completion status\n * @throws {BrowserMismatchError} If browser differs from the one used in prepare\n * @throws {MagicalAuthError} For other API errors\n */\n async complete(\n request: CompleteRequest,\n options?: RequestOptions,\n ): Promise<CompleteResponse> {\n validateCompleteRequest(request);\n this.config.logger.debug('Completing device-bound session', {\n session_key: request.session_key,\n });\n\n const response = await this.doRequest<CompleteResponse>(\n 'POST',\n '/magic-auth/v2/auth/complete',\n request,\n options,\n );\n\n this.config.logger.debug('Device binding validated', { status: response.status });\n return response;\n }\n\n /**\n * Verifies a phone number using digital credentials.\n *\n * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.\n *\n * @param request - Verify request with session and credential\n * @param options - Per-request options (e.g., correlationId)\n * @returns Verification result with phone number and verified status\n * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {InvalidCredentialError} If credential format is invalid\n * @throws {MagicalAuthError} For other API errors\n */\n async verifyPhoneNumber(\n request: VerifyPhoneNumberRequest,\n options?: RequestOptions,\n ): Promise<VerifyPhoneNumberResponse> {\n validateVerifyPhoneNumberRequest(request);\n this.config.logger.debug('Verifying phone number', {\n session_key: request.session.session_key,\n });\n\n const response = await this.doRequest<VerifyPhoneNumberResponse>(\n 'POST',\n '/magic-auth/v2/auth/verify-phone-number',\n request,\n options,\n );\n\n this.config.logger.debug('Phone verification complete', { verified: response.verified });\n return response;\n }\n\n /**\n * Retrieves the phone number associated with the device using digital credentials.\n *\n * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.\n *\n * @param request - Get phone number request with session and credential\n * @param options - Per-request options (e.g., correlationId)\n * @returns Response with the retrieved phone number\n * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {InvalidCredentialError} If credential format is invalid\n * @throws {MagicalAuthError} For other API errors\n */\n async getPhoneNumber(\n request: GetPhoneNumberRequest,\n options?: RequestOptions,\n ): Promise<GetPhoneNumberResponse> {\n validateGetPhoneNumberRequest(request);\n this.config.logger.debug('Getting phone number', {\n session_key: request.session.session_key,\n });\n\n const response = await this.doRequest<GetPhoneNumberResponse>(\n 'POST',\n '/magic-auth/v2/auth/get-phone-number',\n request,\n options,\n );\n\n this.config.logger.debug('Phone number retrieved', {\n phone: maskPhoneNumber(response.phone_number),\n });\n return response;\n }\n\n /**\n * Reports when a user clicks the invoke/authenticate button.\n *\n * Used for Authentication Success Rate (ASR) tracking and analytics.\n *\n * @param sessionId - The session identifier\n * @param options - Per-request options (e.g., correlationId)\n * @returns Report response with a boolean `success` flag\n * @throws {SessionNotFoundError} If session not found\n * @throws {MagicalAuthError} For other API errors\n */\n async reportInvocation(\n sessionId: string,\n options?: RequestOptions,\n ): Promise<ReportInvocationResponse> {\n validateSessionId(sessionId);\n this.config.logger.debug('Reporting invocation', { session_id: sessionId });\n\n return await this.doRequest<ReportInvocationResponse>(\n 'POST',\n '/magic-auth/v2/auth/report-invocation',\n { session_id: sessionId },\n options,\n );\n }\n\n /**\n * Polls for the status of an ongoing verification request (protected endpoint).\n *\n * @param sessionKey - The 64-character hex session key from prepare response\n * @param options - Per-request options (e.g., correlationId)\n * @returns Status response with current verification state\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {MagicalAuthError} For other API errors\n */\n async checkStatus(\n sessionKey: string,\n options?: RequestOptions,\n ): Promise<StatusResponse> {\n validateSessionKey(sessionKey);\n this.config.logger.debug('Checking status', { session_key: sessionKey });\n\n const response = await this.doRequest<StatusResponse>(\n 'GET',\n `/magic-auth/v2/auth/status/${encodeURIComponent(sessionKey)}`,\n undefined,\n options,\n );\n\n this.config.logger.debug('Status retrieved', { status: response.status });\n return response;\n }\n\n /**\n * Polls for the status of an ongoing verification request (public endpoint).\n *\n * This endpoint does not require authentication.\n *\n * @param sessionKey - The 64-character hex session key from prepare response\n * @param options - Per-request options (e.g., correlationId)\n * @returns Status response with current verification state\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {MagicalAuthError} For other API errors\n */\n async checkStatusPublic(\n sessionKey: string,\n options?: RequestOptions,\n ): Promise<StatusResponse> {\n validateSessionKey(sessionKey);\n this.config.logger.debug('Checking public status', { session_key: sessionKey });\n\n const response = await this.doRequestWithoutAuth<StatusResponse>(\n 'GET',\n `/public/status/${encodeURIComponent(sessionKey)}`,\n undefined,\n options,\n );\n\n this.config.logger.debug('Public status retrieved', { status: response.status });\n return response;\n }\n\n /**\n * Makes an authenticated API request.\n */\n private async doRequest<T>(\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n ): Promise<T> {\n const token = await this.tokenManager.getToken();\n\n this.config.logger.debug('Request', { method, path });\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n };\n if (options?.correlationId) {\n headers['X-Correlation-ID'] = options.correlationId;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n const response = await this.config.httpClient.request({\n method,\n url: `${this.config.baseUrl}${path}`,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n return this.handleResponse<T>(response);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new MagicalAuthError(\n 'Request timeout',\n 'TIMEOUT',\n 408,\n undefined,\n { timeout: this.config.timeout },\n );\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Makes an unauthenticated API request (for public endpoints).\n */\n private async doRequestWithoutAuth<T>(\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n ): Promise<T> {\n this.config.logger.debug('Request (no auth)', { method, path });\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n if (options?.correlationId) {\n headers['X-Correlation-ID'] = options.correlationId;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n const response = await this.config.httpClient.request({\n method,\n url: `${this.config.baseUrl}${path}`,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n return this.handleResponse<T>(response);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new MagicalAuthError(\n 'Request timeout',\n 'TIMEOUT',\n 408,\n undefined,\n { timeout: this.config.timeout },\n );\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Handles API response, parsing JSON and converting errors.\n * Throws DesktopWaitError for HTTP 202 responses.\n */\n private async handleResponse<T>(response: HttpResponse): Promise<T> {\n if (response.status === 202) {\n const waitBody = (await response.json()) as DesktopWaitResponse;\n throw new DesktopWaitError(waitBody);\n }\n\n if (!response.ok) {\n let errorBody: ErrorResponse;\n try {\n errorBody = (await response.json()) as ErrorResponse;\n if (!errorBody.status) {\n errorBody.status = response.status;\n }\n } catch {\n errorBody = {\n code: 'UNKNOWN_ERROR',\n message: `Request failed with status ${response.status}`,\n status: response.status,\n };\n }\n throw createErrorFromResponse(errorBody, response.headers);\n }\n\n return response.json() as Promise<T>;\n }\n\n /**\n * Invalidates the cached access token.\n */\n invalidateToken(): void {\n this.tokenManager.invalidate();\n }\n}\n\nconst ALPHANUMERIC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\nfunction generateNonce(length = 32): string {\n const bytes = randomBytes(length);\n let result = '';\n for (let i = 0; i < length; i++) {\n result += ALPHANUMERIC.charAt(bytes[i]! % ALPHANUMERIC.length);\n }\n return result;\n}\n","/**\n * HTTP client interface for custom implementations (BYOC - Bring Your Own Client).\n * Defaults to native fetch if not provided.\n */\nexport interface HttpClient {\n request(options: HttpRequestOptions): Promise<HttpResponse>;\n}\n\n/**\n * Options for making an HTTP request.\n */\nexport interface HttpRequestOptions {\n method: string;\n url: string;\n headers: Record<string, string>;\n body?: string;\n signal?: AbortSignal;\n}\n\n/**\n * HTTP response interface matching the native Response API.\n */\nexport interface HttpResponse {\n ok: boolean;\n status: number;\n headers: Headers;\n json(): Promise<unknown>;\n text(): Promise<string>;\n}\n\n/**\n * Logger interface for custom implementations (BYOL - Bring Your Own Logger).\n * Defaults to no-op if not provided.\n */\nexport interface Logger {\n debug(message: string, meta?: Record<string, unknown>): void;\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n error(message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Default HTTP client implementation using native fetch.\n */\nexport const defaultHttpClient: HttpClient = {\n async request(options: HttpRequestOptions): Promise<HttpResponse> {\n const response = await fetch(options.url, {\n method: options.method,\n headers: options.headers,\n body: options.body,\n signal: options.signal,\n });\n return response;\n },\n};\n\n/**\n * Default no-op logger implementation.\n */\nexport const noopLogger: Logger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n","/**\n * Error codes returned by the Magical Auth API.\n * Use `ErrorCode.SESSION_NOT_FOUND`, `ErrorCode.VALIDATION_ERROR`, etc. instead of raw strings.\n */\nexport const ErrorCode = {\n BAD_REQUEST: 'BAD_REQUEST',\n UNAUTHORIZED: 'UNAUTHORIZED',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n MISSING_PARAMETERS: 'MISSING_PARAMETERS',\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n INVALID_VERIFICATION: 'INVALID_VERIFICATION',\n CARRIER_NOT_ELIGIBLE: 'CARRIER_NOT_ELIGIBLE',\n UNSUPPORTED_PLATFORM: 'UNSUPPORTED_PLATFORM',\n PHONE_NUMBER_MISMATCH: 'PHONE_NUMBER_MISMATCH',\n INVALID_CREDENTIAL_FORMAT: 'INVALID_CREDENTIAL_FORMAT',\n FORBIDDEN: 'FORBIDDEN',\n AUDIENCE_VALIDATION_FAILED: 'AUDIENCE_VALIDATION_FAILED',\n BROWSER_MISMATCH: 'BROWSER_MISMATCH',\n QR_ALREADY_SCANNED: 'QR_ALREADY_SCANNED',\n SESSION_NOT_ELIGIBLE: 'SESSION_NOT_ELIGIBLE',\n SESSION_EXPIRED: 'SESSION_EXPIRED',\n DEVICE_BINDING_FAILED: 'DEVICE_BINDING_FAILED',\n MISSING_BINDING_COOKIE: 'MISSING_BINDING_COOKIE',\n RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',\n INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',\n SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',\n} as const;\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n/**\n * Error response structure from the API.\n */\nexport interface ErrorResponse {\n code: string;\n message: string;\n status?: number;\n request_id?: string;\n timestamp?: string;\n trace_id?: string;\n span_id?: string;\n service?: string;\n details?: {\n fields?: Record<string, string>;\n [key: string]: unknown;\n };\n}\n\n/**\n * Base error class for all Magical Auth SDK errors.\n */\nexport class MagicalAuthError extends Error {\n /**\n * Error code from the API.\n */\n public readonly code: string;\n\n /**\n * HTTP status code.\n */\n public readonly status: number;\n\n /**\n * Request ID for debugging/support.\n */\n public readonly requestId?: string;\n\n /**\n * Additional error details.\n */\n public readonly details?: Record<string, unknown>;\n\n /**\n * Distributed trace ID (from OpenTelemetry).\n */\n public readonly traceId?: string;\n\n /**\n * Span ID for tracing.\n */\n public readonly spanId?: string;\n\n /**\n * ISO 8601 timestamp of when the error occurred on the server.\n */\n public readonly timestamp?: string;\n\n /**\n * Name of the service that produced this error.\n */\n public readonly service?: string;\n\n constructor(\n message: string,\n code: string,\n status: number,\n requestId?: string,\n details?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'MagicalAuthError';\n this.code = code;\n this.status = status;\n this.requestId = requestId;\n this.details = details;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n // Ensure instanceof works correctly\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Bad request error (generic 400).\n */\nexport class BadRequestError extends MagicalAuthError {\n constructor(message = 'Bad request', requestId?: string) {\n super(message, 'BAD_REQUEST', 400, requestId);\n this.name = 'BadRequestError';\n }\n}\n\n/**\n * Validation error with field-level details.\n */\nexport class ValidationError extends MagicalAuthError {\n /**\n * Field-level validation errors.\n */\n public readonly fieldErrors: Record<string, string>;\n\n constructor(\n message: string,\n fieldErrors: Record<string, string>,\n requestId?: string,\n ) {\n super(message, 'VALIDATION_ERROR', 400, requestId, { fields: fieldErrors });\n this.name = 'ValidationError';\n this.fieldErrors = fieldErrors;\n }\n}\n\n/**\n * Authentication/authorization error.\n */\nexport class UnauthorizedError extends MagicalAuthError {\n constructor(message = 'Unauthorized', requestId?: string) {\n super(message, 'UNAUTHORIZED', 401, requestId);\n this.name = 'UnauthorizedError';\n }\n}\n\n/**\n * Session not found error.\n */\nexport class SessionNotFoundError extends MagicalAuthError {\n constructor(message = 'Session not found', requestId?: string) {\n super(message, 'SESSION_NOT_FOUND', 404, requestId);\n this.name = 'SessionNotFoundError';\n }\n}\n\n/**\n * Carrier not eligible for authentication.\n */\nexport class CarrierNotEligibleError extends MagicalAuthError {\n constructor(message = 'Carrier not eligible', requestId?: string) {\n super(message, 'CARRIER_NOT_ELIGIBLE', 422, requestId);\n this.name = 'CarrierNotEligibleError';\n }\n}\n\n/**\n * Platform not supported for authentication.\n */\nexport class UnsupportedPlatformError extends MagicalAuthError {\n constructor(message = 'Platform not supported', requestId?: string) {\n super(message, 'UNSUPPORTED_PLATFORM', 422, requestId);\n this.name = 'UnsupportedPlatformError';\n }\n}\n\n/**\n * Invalid credential format error.\n */\nexport class InvalidCredentialError extends MagicalAuthError {\n constructor(message = 'Invalid credential format', requestId?: string) {\n super(message, 'INVALID_CREDENTIAL_FORMAT', 422, requestId);\n this.name = 'InvalidCredentialError';\n }\n}\n\n/**\n * Phone number mismatch error.\n */\nexport class PhoneNumberMismatchError extends MagicalAuthError {\n constructor(message = 'Phone number does not match', requestId?: string) {\n super(message, 'PHONE_NUMBER_MISMATCH', 422, requestId);\n this.name = 'PhoneNumberMismatchError';\n }\n}\n\n/**\n * Rate limit exceeded error.\n */\nexport class RateLimitError extends MagicalAuthError {\n /**\n * Seconds until rate limit resets (if provided by API).\n */\n public readonly retryAfter?: number;\n\n constructor(message: string, retryAfter?: number, requestId?: string) {\n super(message, 'RATE_LIMIT_EXCEEDED', 429, requestId, \n retryAfter !== undefined ? { retryAfter } : undefined);\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Internal server error.\n */\nexport class InternalServerError extends MagicalAuthError {\n constructor(message = 'An internal error occurred', requestId?: string) {\n super(message, 'INTERNAL_SERVER_ERROR', 500, requestId);\n this.name = 'InternalServerError';\n }\n}\n\n/**\n * Service temporarily unavailable.\n */\nexport class ServiceUnavailableError extends MagicalAuthError {\n constructor(message = 'Service temporarily unavailable', requestId?: string) {\n super(message, 'SERVICE_UNAVAILABLE', 503, requestId);\n this.name = 'ServiceUnavailableError';\n }\n}\n\n/**\n * Forbidden error (device binding validation failed).\n */\nexport class ForbiddenError extends MagicalAuthError {\n constructor(message = 'Forbidden', requestId?: string) {\n super(message, 'FORBIDDEN', 403, requestId);\n this.name = 'ForbiddenError';\n }\n}\n\n/**\n * Browser mismatch error (completion page opened in a different browser than prepare).\n */\nexport class BrowserMismatchError extends MagicalAuthError {\n constructor(\n message = 'Browser mismatch detected',\n requestId?: string,\n details?: Record<string, unknown>,\n ) {\n super(message, 'BROWSER_MISMATCH', 422, requestId, details);\n this.name = 'BrowserMismatchError';\n }\n}\n\n/**\n * Session not eligible for the requested operation (e.g., wrong status for /complete).\n */\nexport class SessionNotEligibleError extends MagicalAuthError {\n constructor(message = 'Session is not eligible for completion', requestId?: string) {\n super(message, 'SESSION_NOT_ELIGIBLE', 409, requestId);\n this.name = 'SessionNotEligibleError';\n }\n}\n\n/**\n * Device binding validation failed (fe_code/agg_code format or aggregator rejection).\n */\nexport class DeviceBindingError extends MagicalAuthError {\n constructor(message = 'Device binding validation failed', code: string = 'DEVICE_BINDING_FAILED', requestId?: string) {\n super(message, code, 403, requestId);\n this.name = 'DeviceBindingError';\n }\n}\n\n/**\n * Binding cookie is missing — the session-scoped `_glide_bind_{sessionKey}` cookie\n * was not found. This typically means the user opened the completion URL in a\n * different browser than the one that initiated the flow.\n */\nexport class MissingBindingCookieError extends DeviceBindingError {\n constructor(message = 'Binding cookie missing or expired', requestId?: string) {\n super(message, 'MISSING_BINDING_COOKIE', requestId);\n this.name = 'MissingBindingCookieError';\n }\n}\n\n/**\n * Desktop wait response — thrown when the server returns HTTP 202\n * indicating the desktop QR session is still waiting for mobile completion.\n * Callers should inspect `waitResponse` to decide whether to retry.\n */\nexport class DesktopWaitError extends MagicalAuthError {\n public readonly waitResponse: {\n status: 'waiting';\n message: string;\n session_key: string;\n session_status: string;\n retry: boolean;\n session_expires_in_seconds: number;\n };\n\n constructor(waitResponse: {\n status: 'waiting';\n message: string;\n session_key: string;\n session_status: string;\n retry: boolean;\n session_expires_in_seconds: number;\n }) {\n super(waitResponse.message, 'DESKTOP_WAIT', 202);\n this.name = 'DesktopWaitError';\n this.waitResponse = waitResponse;\n }\n}\n\n/**\n * Parses the Retry-After header value.\n * @param headers - Response headers\n * @returns Retry-After value in seconds, or undefined if not present/invalid\n */\nfunction parseRetryAfter(headers?: Headers): number | undefined {\n if (!headers) return undefined;\n \n const retryAfter = headers.get('Retry-After');\n if (!retryAfter) return undefined;\n\n // Try parsing as seconds (integer)\n const seconds = parseInt(retryAfter, 10);\n if (!isNaN(seconds) && seconds >= 0) {\n return seconds;\n }\n\n // Try parsing as HTTP date\n const date = Date.parse(retryAfter);\n if (!isNaN(date)) {\n const diffMs = date - Date.now();\n return Math.max(0, Math.ceil(diffMs / 1000));\n }\n\n return undefined;\n}\n\n/**\n * Creates the appropriate error class instance from an API error response.\n * @param response - The error response from the API\n * @param headers - Optional response headers (for extracting Retry-After, etc.)\n * @returns The appropriate MagicalAuthError subclass instance\n */\nexport function createErrorFromResponse(\n response: ErrorResponse,\n headers?: Headers,\n): MagicalAuthError {\n const { code, message, request_id, details, status, trace_id, span_id, timestamp, service } = response;\n\n const error = createTypedError(code, message, request_id, details, status, headers);\n return Object.assign(error, {\n traceId: trace_id,\n spanId: span_id,\n timestamp,\n service,\n });\n}\n\nfunction createTypedError(\n code: string,\n message: string,\n request_id: string | undefined,\n details: ErrorResponse['details'],\n status: number | undefined,\n headers?: Headers,\n): MagicalAuthError {\n switch (code) {\n case 'BAD_REQUEST':\n return new BadRequestError(message, request_id);\n\n case 'VALIDATION_ERROR':\n case 'MISSING_PARAMETERS':\n return new ValidationError(\n message,\n (details?.fields as Record<string, string>) ?? {},\n request_id,\n );\n\n case 'UNAUTHORIZED':\n return new UnauthorizedError(message, request_id);\n\n case 'SESSION_NOT_FOUND':\n return new SessionNotFoundError(message, request_id);\n\n case 'CARRIER_NOT_ELIGIBLE':\n return new CarrierNotEligibleError(message, request_id);\n\n case 'UNSUPPORTED_PLATFORM':\n return new UnsupportedPlatformError(message, request_id);\n\n case 'INVALID_CREDENTIAL_FORMAT':\n case 'INVALID_VERIFICATION':\n return new InvalidCredentialError(message, request_id);\n\n case 'PHONE_NUMBER_MISMATCH':\n return new PhoneNumberMismatchError(message, request_id);\n\n case 'FORBIDDEN':\n return new ForbiddenError(message, request_id);\n\n case 'BROWSER_MISMATCH':\n return new BrowserMismatchError(\n message,\n request_id,\n details as Record<string, unknown> | undefined,\n );\n\n case 'SESSION_NOT_ELIGIBLE':\n return new SessionNotEligibleError(message, request_id);\n\n case 'DEVICE_BINDING_FAILED':\n return new DeviceBindingError(message, 'DEVICE_BINDING_FAILED', request_id);\n\n case 'MISSING_BINDING_COOKIE':\n return new MissingBindingCookieError(message, request_id);\n\n case 'RATE_LIMIT_EXCEEDED':\n return new RateLimitError(message, parseRetryAfter(headers), request_id);\n\n case 'INTERNAL_SERVER_ERROR':\n return new InternalServerError(message, request_id);\n\n case 'SERVICE_UNAVAILABLE':\n return new ServiceUnavailableError(message, request_id);\n\n default:\n return new MagicalAuthError(\n message,\n code,\n status ?? 500,\n request_id,\n details as Record<string, unknown> | undefined,\n );\n }\n}\n","import type { HttpClient, Logger } from './internal/http.js';\nimport { noopLogger } from './internal/http.js';\nimport { UnauthorizedError } from './errors.js';\n\n/**\n * Token response from OAuth2 token endpoint.\n */\ninterface TokenResponse {\n access_token: string;\n token_type: string;\n expires_in: number;\n}\n\n/**\n * Manages OAuth2 access tokens with automatic caching and refresh.\n *\n * Thread-safe through promise deduplication - concurrent calls to getToken()\n * will share the same in-flight request rather than making multiple requests.\n */\nexport class TokenManager {\n private token: string | null = null;\n private expiresAt = 0;\n private refreshPromise: Promise<string> | null = null;\n\n /** Buffer time in ms before expiry to refresh token (60 seconds) */\n private readonly bufferMs = 60_000;\n\n constructor(\n private readonly clientId: string,\n private readonly clientSecret: string,\n private readonly tokenUrl: string,\n private readonly httpClient: HttpClient,\n private readonly logger: Logger = noopLogger,\n ) {}\n\n /**\n * Gets a valid access token, refreshing if necessary.\n *\n * This method is safe for concurrent calls - if a refresh is already\n * in progress, subsequent calls will await the same promise.\n *\n * @returns A valid access token\n * @throws {UnauthorizedError} If token fetch fails\n */\n async getToken(): Promise<string> {\n if (this.token && Date.now() < this.expiresAt) {\n this.logger.debug('Using cached token', {\n expires_in_s: Math.max(0, Math.round((this.expiresAt - Date.now()) / 1000)),\n });\n return this.token;\n }\n\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n this.logger.debug('Refreshing access token');\n this.refreshPromise = this.fetchToken();\n\n try {\n return await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n /**\n * Fetches a new access token from the OAuth2 endpoint.\n */\n private async fetchToken(): Promise<string> {\n const credentials = Buffer.from(\n `${this.clientId}:${this.clientSecret}`,\n ).toString('base64');\n\n const response = await this.httpClient.request({\n method: 'POST',\n url: this.tokenUrl,\n headers: {\n Authorization: `Basic ${credentials}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: 'grant_type=client_credentials',\n });\n\n if (!response.ok) {\n // Try to get error details from response\n let errorMessage = 'Token request failed';\n try {\n const errorBody = (await response.json()) as {\n error?: string;\n error_description?: string;\n };\n if (errorBody.error_description) {\n errorMessage = errorBody.error_description;\n } else if (errorBody.error) {\n errorMessage = errorBody.error;\n }\n } catch {\n // Ignore JSON parse errors, use default message\n }\n throw new UnauthorizedError(errorMessage);\n }\n\n const data = (await response.json()) as TokenResponse;\n\n if (!data.access_token) {\n throw new UnauthorizedError('Invalid token response: missing access_token');\n }\n\n this.token = data.access_token;\n this.expiresAt = Date.now() + data.expires_in * 1000 - this.bufferMs;\n\n this.logger.debug('Access token refreshed', { expires_in_s: data.expires_in });\n\n return this.token;\n }\n\n /**\n * Invalidates the cached token, forcing a refresh on next getToken() call.\n * Useful when receiving a 401 response from the API.\n */\n invalidate(): void {\n this.token = null;\n this.expiresAt = 0;\n this.logger.debug('Token cache invalidated');\n }\n\n /**\n * Checks if there's a valid cached token.\n * @returns true if a valid token exists\n */\n hasValidToken(): boolean {\n return this.token !== null && Date.now() < this.expiresAt;\n }\n}\n","import type { HttpClient, Logger } from './internal/http.js';\nimport { defaultHttpClient, noopLogger } from './internal/http.js';\n\n/**\n * Configuration options for MagicalAuthClient.\n */\nexport interface MagicalAuthConfig {\n /** OAuth2 client ID (required) */\n clientId: string;\n /** OAuth2 client secret (required) */\n clientSecret: string;\n /** API base URL (default: https://api.glideidentity.app) */\n baseUrl?: string;\n /** Custom HTTP client (default: native fetch) */\n httpClient?: HttpClient;\n /** Custom logger (default: no-op) */\n logger?: Logger;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\n/**\n * Internal resolved configuration with all defaults applied.\n */\nexport interface ResolvedConfig {\n readonly clientId: string;\n readonly clientSecret: string;\n readonly baseUrl: string;\n readonly httpClient: HttpClient;\n readonly logger: Logger;\n readonly timeout: number;\n}\n\n/** Default API base URL */\nexport const DEFAULT_BASE_URL = 'https://api.glideidentity.app';\n\n/** Default request timeout in milliseconds */\nexport const DEFAULT_TIMEOUT = 30_000;\n\n/**\n * Resolves user-provided configuration with defaults.\n * @param config - User-provided configuration\n * @returns Fully resolved configuration with defaults applied\n */\nexport function resolveConfig(config: MagicalAuthConfig): ResolvedConfig {\n return {\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,\n httpClient: config.httpClient ?? defaultHttpClient,\n logger: config.logger ?? noopLogger,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n };\n}\n","import { createHash, randomBytes } from 'node:crypto';\n\n/**\n * Regex matching a valid 64-character hex string (case-insensitive).\n *\n * Accepts both lowercase and uppercase hex so that external inputs (URL\n * fragments, cookie values) still pass validation even if a proxy or\n * browser extension uppercases them. Internal code normalises to\n * lowercase before hashing or sending to the aggregator.\n */\nexport const HEX_64 = /^[0-9a-fA-F]{64}$/;\n\n/** Characters that must not appear in cookie attribute values. */\nconst UNSAFE_COOKIE_ATTR = /[;\\r\\n]/;\n\n/** Cookie name prefix for device binding codes. Append the session key for the full name. */\nexport const BINDING_COOKIE_PREFIX = '_glide_bind_';\n\n/**\n * Cookie max-age in seconds. Set to 5 minutes — sufficient for the carrier\n * authentication round-trip (typically under 2 minutes). The cookie auto-expires\n * after this period, so explicit clearing is optional.\n */\nexport const BINDING_COOKIE_MAX_AGE = 300;\n\n/**\n * Keys that MUST be redacted in logs to prevent leaking binding secrets.\n * Covers snake_case, camelCase, and collapsed forms.\n */\nexport const SENSITIVE_KEYS: readonly string[] = [\n 'fe_code',\n 'fecode',\n 'feCode',\n 'fe_hash',\n 'fehash',\n 'feHash',\n 'agg_code',\n 'aggcode',\n 'aggCode',\n '_glide_bind',\n 'glide_bind',\n];\n\n/**\n * Options for building binding cookie headers.\n */\nexport interface BindingCookieOptions {\n /** Cookie domain (must match the completion redirect URL domain) */\n domain?: string;\n /** Cookie path (default: \"/\") — must start with \"/\" */\n path?: string;\n /** Secure flag (default: true — set false for local HTTP dev only) */\n secure?: boolean;\n}\n\n/**\n * Returns the full cookie name for a given session key.\n *\n * Using a session-scoped name (`_glide_bind_{sessionKey}`) ensures that\n * parallel `prepare()` calls from the same browser don't overwrite each\n * other's cookies — each session gets its own cookie.\n */\nexport function getBindingCookieName(sessionKey: string): string {\n if (\n !sessionKey ||\n UNSAFE_COOKIE_ATTR.test(sessionKey) ||\n sessionKey.includes('=')\n ) {\n throw new Error(\n 'Invalid sessionKey for cookie name: must not be empty or contain \";\", \"=\", \"\\\\r\", or \"\\\\n\"',\n );\n }\n return `${BINDING_COOKIE_PREFIX}${sessionKey}`;\n}\n\n/**\n * Asserts that the given value is a valid 64-character hex string.\n * @throws {Error} If the value does not match.\n */\nexport function assertValidFeCode(feCode: string): void {\n if (!HEX_64.test(feCode)) {\n throw new Error('feCode must be a 64-character hex string');\n }\n}\n\n/**\n * Generates a cryptographically random fe_code (32 random bytes -> 64-char lowercase hex).\n */\nexport function generateFeCode(): string {\n return randomBytes(32).toString('hex');\n}\n\n/**\n * Computes SHA256(fe_code) -> 64-char lowercase hex hash.\n * Input is normalised to lowercase for deterministic hashing.\n *\n * @throws {Error} If feCode is not a valid 64-character hex string\n */\nexport function computeFeHash(feCode: string): string {\n assertValidFeCode(feCode);\n return createHash('sha256').update(feCode.toLowerCase()).digest('hex');\n}\n\n/**\n * Builds a Set-Cookie header value that sets the device binding cookie.\n *\n * @param feCode - The binding code to store (64-char hex, normalised to lowercase)\n * @param sessionKey - Session key used in the cookie name to avoid collisions between parallel sessions\n * @param options - Cookie options (domain, path, secure)\n * @returns Raw Set-Cookie header value string\n * @throws {Error} If feCode is invalid or options contain injection characters\n */\nexport function buildSetBindingCookieHeader(\n feCode: string,\n sessionKey: string,\n options?: BindingCookieOptions,\n): string {\n assertValidFeCode(feCode);\n validateCookieAttr('domain', options?.domain);\n validateCookieAttr('path', options?.path);\n\n const secure = options?.secure ?? true;\n const cookieName = getBindingCookieName(sessionKey);\n const parts = [\n `${cookieName}=${feCode.toLowerCase()}`,\n 'HttpOnly',\n 'SameSite=Lax',\n `Path=${options?.path ?? '/'}`,\n `Max-Age=${BINDING_COOKIE_MAX_AGE}`,\n ];\n if (secure) {\n parts.push('Secure');\n }\n if (options?.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n return parts.join('; ');\n}\n\n/**\n * Builds a Set-Cookie header value that clears the device binding cookie.\n *\n * @param sessionKey - Session key identifying which session's cookie to clear\n * @param options - Cookie options (must match the original cookie)\n * @returns Raw Set-Cookie header value string that expires the cookie\n * @throws {Error} If options contain injection characters\n */\nexport function buildClearBindingCookieHeader(\n sessionKey: string,\n options?: BindingCookieOptions,\n): string {\n validateCookieAttr('domain', options?.domain);\n validateCookieAttr('path', options?.path);\n\n const secure = options?.secure ?? true;\n const cookieName = getBindingCookieName(sessionKey);\n const parts = [\n `${cookieName}=`,\n 'HttpOnly',\n 'SameSite=Lax',\n `Path=${options?.path ?? '/'}`,\n 'Max-Age=0',\n 'Expires=Thu, 01 Jan 1970 00:00:00 GMT',\n ];\n if (secure) {\n parts.push('Secure');\n }\n if (options?.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n return parts.join('; ');\n}\n\n/**\n * Parses the fe_code from a raw Cookie header string for a specific session.\n *\n * Returns `undefined` if the cookie is not present or the value is not\n * a valid 64-character hex string. When found, the value is normalised\n * to lowercase for deterministic hashing downstream.\n *\n * @param cookieHeader - Raw Cookie header value (e.g., \"foo=bar; _glide_bind_abc123=...\")\n * @param sessionKey - Session key identifying which cookie to look for\n * @returns The fe_code value (lowercase), or undefined if missing/invalid\n */\nexport function parseBindingCookie(\n cookieHeader: string | undefined,\n sessionKey: string,\n): string | undefined {\n if (!cookieHeader) return undefined;\n const cookieName = getBindingCookieName(sessionKey);\n const prefix = `${cookieName}=`;\n const match = cookieHeader\n .split(';')\n .map((c) => c.trim())\n .find((c) => c.startsWith(prefix));\n if (!match) return undefined;\n const value = match.substring(prefix.length);\n return HEX_64.test(value) ? value.toLowerCase() : undefined;\n}\n\n/**\n * Builds Set-Cookie headers that expire every existing device binding cookie\n * (`_glide_bind_*`) found in the request.\n *\n * Binding cookies are session-scoped (`_glide_bind_{sessionKey}`) and\n * auto-expire after `BINDING_COOKIE_MAX_AGE` seconds, so cleanup is normally\n * handled by the TTL. This helper is a tidying utility for partners who want\n * to explicitly clear stale cookies (for example on logout, on session\n * cancellation, or before issuing a fresh `prepare()` from a long-lived\n * browser session) without waiting for the TTL.\n *\n * @param cookieHeader - Raw Cookie request header\n * @param options - Cookie options (must match the original set call)\n * @returns Array of Set-Cookie header values that expire stale binding cookies\n */\nexport function clearStaleBindingCookies(\n cookieHeader: string | undefined,\n options?: BindingCookieOptions,\n): string[] {\n if (!cookieHeader) return [];\n const headers: string[] = [];\n for (const pair of cookieHeader.split(';')) {\n const eqIdx = pair.indexOf('=');\n const name = (eqIdx === -1 ? pair : pair.slice(0, eqIdx)).trim();\n if (name.startsWith(BINDING_COOKIE_PREFIX)) {\n const sessionSuffix = name.substring(BINDING_COOKIE_PREFIX.length);\n if (!sessionSuffix) continue;\n try {\n headers.push(buildClearBindingCookieHeader(sessionSuffix, options));\n } catch {\n // Malformed session suffix (injection chars) — skip silently.\n }\n }\n }\n return headers;\n}\n\nfunction validateCookieAttr(\n name: string,\n value: string | undefined,\n): void {\n if (value === undefined) return;\n if (UNSAFE_COOKIE_ATTR.test(value)) {\n throw new Error(\n `Invalid cookie ${name}: must not contain ';', '\\\\r', or '\\\\n'`,\n );\n }\n if (name === 'path' && (value.length === 0 || !value.startsWith('/'))) {\n throw new Error(\"Invalid cookie path: must start with '/'\");\n }\n}\n\n/**\n * Returns the HTML for the completion redirect page.\n *\n * This page extracts `agg_code` and `session_key` from the URL fragment,\n * POSTs them to the developer's backend (which auto-includes the\n * `_glide_bind_{sessionKey}` HttpOnly cookie), and displays the result.\n *\n * On successful completion, a localStorage signal is written\n * (`glide_signal_{session_key}`) so the FE SDK in the original tab can\n * detect completion via `StorageEvent` without polling.\n *\n * @param completeEndpoint - Relative path to POST to (e.g., \"/api/glide/complete\")\n * @returns Complete HTML string ready to serve\n * @throws {Error} If completeEndpoint is not a relative path starting with \"/\"\n */\nexport function getCompletionPageHtml(completeEndpoint: string): string {\n if (!completeEndpoint.startsWith('/') || completeEndpoint.startsWith('//')) {\n throw new Error(\n 'completeEndpoint must be a relative path starting with \"/\" (e.g., \"/api/glide/complete\"). ' +\n 'Cross-origin and protocol-relative endpoints (e.g., \"//evil.com/...\") are not supported because ' +\n 'the page relies on credentials: \"include\" for cookie-based device binding, which requires same-origin requests.',\n );\n }\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'\">\n<title>Verifying</title>\n<style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n 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; }\n .spinner-wrap { text-align: center; }\n .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; }\n @keyframes spin { to { transform: rotate(360deg); } }\n .hidden { display: none; }\n .hint { margin-top: 1.5rem; font-size: 0.875rem; color: #999; }\n .err { display: none; text-align: center; padding: 2rem 1.5rem; max-width: 340px; }\n .err h2 { font-size: 1.25rem; font-weight: 600; color: #1a1a1a; margin-bottom: 1rem; letter-spacing: -0.02em; line-height: 1.3; }\n .err-points { text-align: left; margin: 0 auto 1.5rem; max-width: 280px; }\n .err-points li { font-size: 0.875rem; line-height: 1.6; color: #555; margin-bottom: 0.375rem; padding-left: 0.25rem; }\n .illust { margin: 0 auto 1.5rem; }\n .illust svg { color: #94a3b8; }\n .illust-browser { width: 140px; height: 90px; position: relative; }\n .illust-browser .b { position: absolute; width: 52px; height: 40px; border: 2px solid #cbd5e1; border-radius: 6px; background: #f8fafc; }\n .illust-browser .b .bar { height: 10px; border-bottom: 1.5px solid #e2e8f0; display: flex; align-items: center; padding: 0 4px; gap: 2px; }\n .illust-browser .b .bar i { width: 3px; height: 3px; border-radius: 50%; background: #cbd5e1; }\n .illust-browser .b1 { left: 10px; top: 16px; } .illust-browser .b2 { right: 10px; top: 16px; }\n .illust-browser .aw { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }\n .illust-browser .aw svg { width: 36px; height: 36px; animation: arrowSpin 2.5s ease-in-out infinite; }\n @keyframes arrowSpin { 0%,100% { transform: rotate(0); } 50% { transform: rotate(180deg); } }\n .illust-retry svg { width: 48px; height: 48px; animation: retryPulse 2s ease-in-out infinite; }\n @keyframes retryPulse { 0%,100% { transform: scale(1); opacity: 0.7; } 50% { transform: scale(1.1); opacity: 1; } }\n .illust-wifi svg { width: 48px; height: 48px; animation: wifiBlink 2s ease-in-out infinite; }\n @keyframes wifiBlink { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n .illust-link svg { width: 48px; height: 48px; animation: linkShake 2s ease-in-out infinite; }\n @keyframes linkShake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-5deg); } 75% { transform: rotate(5deg); } }\n .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; }\n @keyframes fadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }\n .err.show { display: block; animation: fadeUp 0.35s ease-out; }\n</style>\n</head>\n<body>\n<div class=\"spinner-wrap\" id=\"loading\" role=\"status\" aria-live=\"polite\">\n <div class=\"spinner\"></div>\n <p class=\"hint hidden\" id=\"hint\"></p>\n</div>\n<div class=\"err\" id=\"error\" role=\"alert\" aria-live=\"assertive\">\n <h2 id=\"err-title\"></h2>\n <ol class=\"err-points\" id=\"err-points\"></ol>\n <div class=\"illust illust-browser hidden\" id=\"ill-browser\">\n <div class=\"illust-browser\">\n <div class=\"b b1\"><div class=\"bar\"><i></i><i></i><i></i></div></div>\n <div class=\"b b2\"><div class=\"bar\"><i></i><i></i><i></i></div></div>\n <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>\n </div>\n </div>\n <div class=\"illust illust-retry hidden\" id=\"ill-retry\">\n <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>\n </div>\n <div class=\"illust illust-wifi hidden\" id=\"ill-wifi\">\n <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>\n </div>\n <div class=\"illust illust-link hidden\" id=\"ill-link\">\n <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>\n </div>\n <div class=\"badge\">Action required</div>\n</div>\n<script>\n(async function() {\n var fragment = new URLSearchParams(window.location.hash.substring(1));\n var aggCode = fragment.get('agg_code');\n var sessionKey = fragment.get('session_key');\n\n window.history.replaceState(null, '', window.location.pathname + window.location.search);\n\n if (!aggCode || !sessionKey) {\n showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');\n return;\n }\n\n try {\n var res = await fetch(${JSON.stringify(completeEndpoint)}, {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })\n });\n\n if (res.ok) {\n var signalKey = 'glide_signal_' + sessionKey;\n try {\n localStorage.setItem(signalKey, sessionKey);\n setTimeout(function() {\n try { localStorage.removeItem(signalKey); } catch(e) {}\n }, 5000);\n } catch(e) {}\n tryClose();\n } else {\n var code = '';\n try { var data = await res.json(); code = (data && (data.code || data.error)) || ''; } catch (_) {}\n var err = friendlyError(code);\n showError(err.title, err.points, err.illust);\n }\n } catch (e) {\n showError('Connection issue', ['We could not reach the server.', 'Check your internet connection and try again.'], 'wifi');\n }\n\n function friendlyError(code) {\n switch (code) {\n case 'MISSING_BINDING_COOKIE':\n case 'BROWSER_MISMATCH':\n 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' };\n default:\n return { title: 'Verification could not be completed', points: ['Something went wrong during verification.', 'Please go back and try again.'], illust: 'retry' };\n }\n }\n\n function tryClose() {\n document.querySelector('.spinner').classList.add('hidden');\n window.close();\n try { window.open('', '_self').close(); } catch(e) {}\n setTimeout(function() {\n document.getElementById('hint').textContent = 'You may close this tab.';\n document.getElementById('hint').classList.remove('hidden');\n }, 300);\n }\n\n function showError(title, points, illust) {\n document.getElementById('loading').classList.add('hidden');\n document.getElementById('err-title').textContent = title;\n var ol = document.getElementById('err-points');\n ol.innerHTML = '';\n (points || []).forEach(function(p) { var li = document.createElement('li'); li.textContent = p; ol.appendChild(li); });\n var ids = ['ill-browser','ill-retry','ill-wifi','ill-link'];\n ids.forEach(function(id) { document.getElementById(id).classList.add('hidden'); });\n var el = document.getElementById('ill-' + (illust || 'retry'));\n if (el) el.classList.remove('hidden');\n document.getElementById('error').classList.add('show');\n }\n})();\n</script>\n</body>\n</html>`;\n}\n","/**\n * Returns a redacted form of a phone number safe for logging.\n *\n * Mirrors the Java SDK's `maskPhone` for cross-SDK log consistency: keeps\n * the first 4 characters and the last 4, replacing the middle with `***`.\n * Inputs of length 8 or shorter are fully masked. The function never throws\n * — when the input is empty, null, or undefined, it returns `'***'`.\n *\n * @example\n * maskPhoneNumber('+14155551234') // '+141***1234'\n * maskPhoneNumber('14155551234') // '1415***1234'\n * maskPhoneNumber('12345678') // '***'\n * maskPhoneNumber(undefined) // '***'\n */\nexport function maskPhoneNumber(phone: string | null | undefined): string {\n if (!phone || phone.length <= 8) return '***';\n return `${phone.substring(0, 4)}***${phone.substring(phone.length - 4)}`;\n}\n","/**\n * Use case for authentication.\n * Use `UseCase.GET_PHONE_NUMBER` or `UseCase.VERIFY_PHONE_NUMBER` instead of raw strings.\n */\nexport const UseCase = {\n GET_PHONE_NUMBER: 'GetPhoneNumber',\n VERIFY_PHONE_NUMBER: 'VerifyPhoneNumber',\n} as const;\nexport type UseCase = (typeof UseCase)[keyof typeof UseCase];\n\n/**\n * Authentication strategy returned by prepare.\n * Use `AuthenticationStrategy.TS43`, `.LINK`, or `.DESKTOP` instead of raw strings.\n */\nexport const AuthenticationStrategy = {\n TS43: 'ts43',\n LINK: 'link',\n DESKTOP: 'desktop',\n NONE: '',\n} as const;\nexport type AuthenticationStrategy = (typeof AuthenticationStrategy)[keyof typeof AuthenticationStrategy];\n\n/**\n * Protocol type for authentication.\n */\nexport type ProtocolType = 'ts43' | 'link' | 'desktop';\n\n/**\n * Session status for polling.\n * Use `SessionStatus.PENDING`, `.SCANNED`, etc. instead of raw strings.\n */\nexport const SessionStatus = {\n PENDING: 'pending',\n SCANNED: 'scanned',\n PENDING_COMPLETION: 'pending_completion',\n COMPLETED: 'completed',\n FAILED: 'failed',\n} as const;\nexport type SessionStatus = (typeof SessionStatus)[keyof typeof SessionStatus];\n\n/**\n * SIM swap risk level.\n */\nexport type RiskLevel =\n | 'RISK_LEVEL_HIGH'\n | 'RISK_LEVEL_MEDIUM'\n | 'RISK_LEVEL_LOW'\n | 'RISK_LEVEL_UNKNOWN';\n\n/**\n * SIM swap check failure reason.\n */\nexport type SimSwapFailureReason =\n | 'timeout'\n | 'carrier_not_supported'\n | 'disabled'\n | 'error';\n\n/**\n * PLMN (Public Land Mobile Network) identifier.\n */\nexport interface PLMN {\n /** Mobile Country Code (3 digits) */\n mcc: string;\n /** Mobile Network Code (2-3 digits) */\n mnc: string;\n}\n\n/**\n * Client information for strategy selection.\n *\n * **IMPORTANT:** The `user_agent` field MUST be the actual browser's `navigator.userAgent`\n * from the end-user's device, NOT the server's user agent. The SDK runs on your backend,\n * but this value must come from your frontend (e.g., passed via your API).\n */\nexport interface ClientInfo {\n /**\n * End-user's browser user agent string (REQUIRED).\n * Must be captured from the frontend via `navigator.userAgent`.\n *\n * The backend uses the user agent (alongside other device/client signals) to\n * pick a strategy: `TS43` for clients with a Digital Credentials surface,\n * `LINK` for the mobile redirect flow, and `DESKTOP` when running on a\n * non-mobile browser.\n */\n user_agent: string;\n /** Platform identifier from the end-user's browser (e.g., navigator.platform) */\n platform?: string;\n}\n\n/**\n * User consent data for authentication.\n */\nexport interface ConsentData {\n /** User consent text */\n consent_text: string;\n /** Link to privacy policy */\n policy_link: string;\n /** Privacy policy text */\n policy_text?: string;\n}\n\n/**\n * Session information from prepare response.\n */\nexport interface SessionInfo {\n /** Hex string session key (16-char hex) */\n session_key: string;\n /** Session nonce for replay attack prevention */\n nonce?: string;\n /** Protocol type used for authentication */\n protocol_type?: ProtocolType;\n /** Additional session metadata (internal use) */\n metadata?: Record<string, string>;\n}\n\n/**\n * SIM swap check result.\n */\nexport interface SimSwapInfo {\n /** Whether the SIM swap check completed successfully */\n checked: boolean;\n /** Fraud risk level based on SIM swap recency */\n risk_level?: RiskLevel;\n /** Time band since last SIM change */\n age_band?: string;\n /** Carrier that performed the SIM swap check */\n carrier_name?: string;\n /** When the SIM swap check was performed (RFC3339) */\n checked_at?: string;\n /** Reason for check failure (only present when checked=false) */\n reason?: SimSwapFailureReason;\n}\n\n/**\n * Information about the device that scanned the QR code.\n * Only present when status is \"scanned\" or later.\n */\nexport interface DeviceInfo {\n /** Device type/model (e.g., \"iPhone 14\") */\n type: string;\n /** Operating system and version (e.g., \"iOS 17.1\") */\n os: string;\n /** Browser name and version (optional, may not be present for native apps) */\n browser?: string;\n}\n\n/**\n * Device swap (IMEI change) check result.\n * Present when the carrier supports device swap detection.\n * Parallel and independent signal alongside SimSwapInfo.\n */\nexport interface DeviceSwapInfo {\n /** Whether the device swap check completed successfully */\n checked: boolean;\n /** Fraud risk level based on device swap recency */\n risk_level?: RiskLevel;\n /** Time band since last device (IMEI) change */\n age_band?: string;\n /** Carrier that performed the device swap check */\n carrier_name?: string;\n /** When the device swap check was performed (RFC3339) */\n checked_at?: string;\n}\n\n/**\n * Parsed components of an E.164 phone number.\n */\nexport interface PhoneNumberDetails {\n /** ITU E.164 country calling code (1, 44, 972, etc.) */\n country_code: number;\n /** National significant number without trunk prefix or formatting */\n national_number: string;\n /** ISO 3166-1 alpha-2 country code (\"US\", \"GB\", \"IL\") */\n region_code: string;\n}\n\n/**\n * Visual verification code for desktop-mobile QR authentication.\n */\nexport interface Challenge {\n /** 4-character hex pattern displayed for visual verification */\n pattern?: string;\n /** Hex color code for the challenge display */\n color?: string;\n /** Associated session ID */\n session_id?: string;\n}\n","import { HEX_64 } from './device-binding.js';\nimport { DeviceBindingError, MissingBindingCookieError, ValidationError } from './errors.js';\nimport { UseCase } from './models/index.js';\nimport type {\n CompleteRequest,\n GetPhoneNumberRequest,\n PrepareRequest,\n VerifyPhoneNumberRequest,\n} from './models/index.js';\n\n/**\n * Validates prepare request.\n * @throws {ValidationError} If validation fails\n */\nexport function validatePrepareRequest(request: PrepareRequest): void {\n const errors: Record<string, string> = {};\n const hasParentSession = !!request.options?.parent_session_id?.trim();\n\n if (!request.use_case && !hasParentSession) {\n errors.use_case = 'use_case is required';\n }\n\n if (request.use_case === UseCase.VERIFY_PHONE_NUMBER && !request.phone_number) {\n errors.phone_number = 'phone_number is required for VerifyPhoneNumber';\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError('Request validation failed', errors);\n }\n}\n\n/**\n * Validates verifyPhoneNumber request.\n * @throws {ValidationError} If validation fails\n */\nexport function validateVerifyPhoneNumberRequest(request: VerifyPhoneNumberRequest): void {\n const errors: Record<string, string> = {};\n\n if (!request.session?.session_key) {\n errors['session.session_key'] = 'session.session_key is required';\n }\n\n if (!request.credential) {\n errors.credential = 'credential is required';\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError('Request validation failed', errors);\n }\n}\n\n/**\n * Validates getPhoneNumber request.\n * @throws {ValidationError} If validation fails\n */\nexport function validateGetPhoneNumberRequest(request: GetPhoneNumberRequest): void {\n const errors: Record<string, string> = {};\n\n if (!request.session?.session_key) {\n errors['session.session_key'] = 'session.session_key is required';\n }\n\n if (!request.credential) {\n errors.credential = 'credential is required';\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError('Request validation failed', errors);\n }\n}\n\n/**\n * Validates sessionId for reportInvocation.\n * @throws {ValidationError} If validation fails\n */\nexport function validateSessionId(sessionId: string): void {\n if (!sessionId) {\n throw new ValidationError('Request validation failed', {\n session_id: 'session_id is required',\n });\n }\n}\n\n/**\n * Validates sessionKey for checkStatus.\n * @throws {ValidationError} If validation fails\n */\nexport function validateSessionKey(sessionKey: string): void {\n if (!sessionKey) {\n throw new ValidationError('Request validation failed', {\n session_key: 'session_key is required',\n });\n }\n}\n\n/**\n * Validates complete request.\n *\n * Separate error codes per field:\n * - session_key missing → MISSING_REQUIRED_FIELD (400)\n * - fe_code missing → MISSING_BINDING_COOKIE (403)\n * - agg_code missing → MISSING_REQUIRED_FIELD (400)\n * - format invalid (either code) → DEVICE_BINDING_FAILED (403, generic message)\n */\nexport function validateCompleteRequest(request: CompleteRequest): void {\n if (!request.session_key) {\n throw new ValidationError('Request validation failed', {\n session_key: 'session_key is required',\n });\n }\n\n if (!request.fe_code) {\n throw new MissingBindingCookieError(\n 'fe_code is required (from _glide_bind cookie)',\n );\n }\n\n if (!request.agg_code) {\n throw new ValidationError('Request validation failed', {\n agg_code: 'agg_code is required',\n });\n }\n\n if (!HEX_64.test(request.fe_code) || !HEX_64.test(request.agg_code)) {\n throw new DeviceBindingError('Invalid device binding inputs');\n }\n}\n","import type { Logger } from './internal/http.js';\nimport { noopLogger } from './internal/http.js';\n\n/**\n * Configuration for {@link createLogger}.\n */\nexport interface LoggerConfig {\n /**\n * Enable logging. When `false` (default) the returned logger is silent at\n * every level. Set to `true` to route output through `console.*`. Partners\n * with their own structured logger (Pino, Winston, Bunyan, Datadog, etc.)\n * should pass it via `MagicalAuthConfig.logger` instead — this factory is\n * intended for local development and quick smoke tests.\n */\n debug?: boolean;\n /**\n * Prefix prepended to every log message. Default: `[GlideMagicalAuth]`.\n */\n prefix?: string;\n}\n\nexport { noopLogger };\n\n/**\n * Creates a console logger with PII sanitization and a configurable prefix.\n *\n * Default-silent — call with no args (or `debug: false`) and every level is\n * a no-op. Set `debug: true` to opt into console output. Phone numbers,\n * JWTs, and explicit `session_key=…` values are auto-masked; object fields\n * named `phone_number`, `credential`, `token`, `password`, `secret`, or\n * `fe_code` are redacted to `[REDACTED]`.\n *\n * @example\n * ```typescript\n * import { MagicalAuthClient, createLogger } from '@glideidentity/glide-be-node-magical-auth';\n *\n * const client = new MagicalAuthClient({\n * clientId: process.env.GLIDE_CLIENT_ID!,\n * clientSecret: process.env.GLIDE_CLIENT_SECRET!,\n * logger: createLogger({ debug: true }),\n * });\n * ```\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n const { debug = false, prefix = '[GlideMagicalAuth]' } = config;\n if (!debug) return noopLogger;\n const fmt = (msg: string, meta?: Record<string, unknown>): unknown[] => {\n const out: unknown[] = [`${prefix} ${sanitize(msg)}`];\n if (meta !== undefined) out.push(sanitize(meta));\n return out;\n };\n return {\n debug: (m, d) => console.log(...fmt(m, d)),\n info: (m, d) => console.info(...fmt(m, d)),\n warn: (m, d) => console.warn(...fmt(m, d)),\n error: (m, d) => console.error(...fmt(m, d)),\n };\n}\n\nconst PHONE_RE = /(\\+?[1-9]\\d{6,14})/g;\nconst JWT_RE = /(eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)/g;\nconst SESSION_RE = /(session[_-]?key)([\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9_-]{16,})/gi;\nconst SENSITIVE = ['phone_number', 'phonenumber', 'credential', 'token', 'password', 'secret', 'fe_code', 'fecode'];\n\n/**\n * Recursively redacts PII from a log payload (string, array, or object).\n * Exported for partners who want the same redaction in their own logger.\n */\nexport function sanitize(data: unknown): unknown {\n if (data == null) return data;\n if (typeof data === 'string') {\n return data\n .replace(PHONE_RE, (m) => (m.length < 8 ? m : `${m.slice(0, 4)}***${m.slice(-4)}`))\n .replace(JWT_RE, '[JWT]')\n .replace(SESSION_RE, (_, k, sep, v) => `${k}${sep}${v.slice(0, 4)}***${v.slice(-4)}`);\n }\n if (Array.isArray(data)) return data.map(sanitize);\n if (typeof data === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data as object)) {\n out[k] = SENSITIVE.some((s) => k.toLowerCase().includes(s)) && typeof v === 'string'\n ? '[REDACTED]'\n : sanitize(v);\n }\n return out;\n }\n return data;\n}\n"],"mappings":";AAiDA,SAAS,qBAAqB;;;ACjD9B,SAAS,eAAAA,oBAAmB;;;AC4CrB,IAAM,oBAAgC;AAAA,EAC3C,MAAM,QAAQ,SAAoD;AAChE,UAAM,WAAW,MAAM,MAAM,QAAQ,KAAK;AAAA,MACxC,QAAQ,QAAQ;AAAA,MAChB,SAAS,QAAQ;AAAA,MACjB,MAAM,QAAQ;AAAA,MACd,QAAQ,QAAQ;AAAA,IAClB,CAAC;AACD,WAAO;AAAA,EACT;AACF;AAKO,IAAM,aAAqB;AAAA,EAChC,QAAQ;AAAA,EAAC;AAAA,EACT,OAAO;AAAA,EAAC;AAAA,EACR,OAAO;AAAA,EAAC;AAAA,EACR,QAAQ;AAAA,EAAC;AACX;;;AC5DO,IAAM,YAAY;AAAA,EACvB,aAAa;AAAA,EACb,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,2BAA2B;AAAA,EAC3B,WAAW;AAAA,EACX,4BAA4B;AAAA,EAC5B,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,wBAAwB;AAAA,EACxB,qBAAqB;AAAA,EACrB,uBAAuB;AAAA,EACvB,qBAAqB;AACvB;AAwBO,IAAM,mBAAN,cAA+B,MAAM;AAAA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AAI,EAAG,QAAO,KAAK,IAAI,QAAQ;AACjD,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAM,MAA+B,CAAC;AACtC,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,IAAc,GAAG;AACnD,UAAI,CAAC,IAAI,UAAU,KAAK,CAAC,MAAM,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC,KAAK,OAAO,MAAM,WACxE,eACA,SAAS,CAAC;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;AVrCA,IAAM,WAAW,cAAc,YAAY,GAAG;AACvC,IAAM,UAAkB,SAAS,iBAAiB,EAAE;","names":["randomBytes","randomBytes"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/internal/http.ts","../src/errors.ts","../src/auth.ts","../src/config.ts","../src/device-binding.ts","../src/internal/mask.ts","../src/models/common.ts","../src/validation.ts","../src/logger.ts"],"sourcesContent":["/**\n * Glide Magical Auth SDK for Node.js\n *\n * Phone number authentication without SMS/OTP using carrier-based digital credentials.\n *\n * @packageDocumentation\n *\n * @example\n * ```typescript\n * import {\n * MagicalAuthClient,\n * UseCase,\n * AuthenticationStrategy,\n * buildSetBindingCookieHeader,\n * } from '@glideidentity/glide-be-node-magical-auth';\n *\n * const magicalAuth = new MagicalAuthClient({\n * clientId: process.env.GLIDE_CLIENT_ID!,\n * clientSecret: process.env.GLIDE_CLIENT_SECRET!,\n * });\n *\n * // Prepare authentication\n * const result = await magicalAuth.prepare({\n * phone_number: '+14155551234',\n * use_case: UseCase.VERIFY_PHONE_NUMBER,\n * client_info: { user_agent: req.headers['user-agent'] },\n * });\n *\n * // For link protocol, set the binding cookie\n * if (result.feCode) {\n * res.setHeader('Set-Cookie', buildSetBindingCookieHeader(result.feCode, result.session.session_key));\n * }\n *\n * // Handle based on strategy\n * switch (result.authentication_strategy) {\n * case AuthenticationStrategy.TS43:\n * // Direct carrier credential request\n * break;\n * case AuthenticationStrategy.LINK:\n * // OAuth redirect flow (device-bound)\n * break;\n * case AuthenticationStrategy.DESKTOP:\n * // QR code flow\n * break;\n * }\n * ```\n */\n\n// SDK version (read from package.json — always distributed with npm packages)\nimport { createRequire } from 'node:module';\nconst _require = createRequire(import.meta.url);\nexport const VERSION: string = _require('../package.json').version;\n\n// Main client\nexport { MagicalAuthClient } from './client.js';\nexport type { RequestOptions } from './client.js';\n\n// Configuration\nexport type { MagicalAuthConfig, ResolvedConfig } from './config.js';\nexport { DEFAULT_BASE_URL, DEFAULT_TIMEOUT, resolveConfig } from './config.js';\n\n// Token manager\nexport { TokenManager } from './auth.js';\n\n// HTTP interfaces (BYOC)\nexport type {\n HttpClient,\n HttpRequestOptions,\n HttpResponse,\n Logger,\n} from './internal/http.js';\nexport { defaultHttpClient } from './internal/http.js';\n\n// Logger factory (BYOL — bring your own, or use ours)\nexport type { LoggerConfig } from './logger.js';\nexport { createLogger, noopLogger, sanitize } from './logger.js';\n\n// Device binding utilities\nexport type { BindingCookieOptions } from './device-binding.js';\nexport {\n assertValidFeCode,\n BINDING_COOKIE_MAX_AGE,\n BINDING_COOKIE_PREFIX,\n buildClearBindingCookieHeader,\n buildSetBindingCookieHeader,\n clearStaleBindingCookies,\n computeFeHash,\n generateFeCode,\n getBindingCookieName,\n getCompletionPageHtml,\n HEX_64,\n parseBindingCookie,\n SENSITIVE_KEYS,\n} from './device-binding.js';\n\n// Errors (ErrorCode is both a const object and a type)\nexport type { ErrorResponse } from './errors.js';\nexport {\n BadRequestError,\n BrowserMismatchError,\n CarrierNotEligibleError,\n createErrorFromResponse,\n DesktopWaitError,\n DeviceBindingError,\n ErrorCode,\n MissingBindingCookieError,\n ForbiddenError,\n InternalServerError,\n InvalidCredentialError,\n MagicalAuthError,\n PhoneNumberMismatchError,\n RateLimitError,\n ServiceUnavailableError,\n SessionNotEligibleError,\n SessionNotFoundError,\n UnauthorizedError,\n UnsupportedPlatformError,\n ValidationError,\n} from './errors.js';\n\n// Constants (as const objects — use UseCase.GET_PHONE_NUMBER, AuthenticationStrategy.TS43, etc.)\nexport {\n AuthenticationStrategy,\n SessionStatus,\n UseCase,\n} from './models/index.js';\n\n// Model types\nexport type {\n Challenge,\n ClientInfo,\n ConsentData,\n DeviceInfo,\n DeviceSwapInfo,\n PLMN,\n ProtocolType,\n RiskLevel,\n SessionInfo,\n SimSwapFailureReason,\n SimSwapInfo,\n // Strategy-specific types\n DCQLCredential,\n DCQLCredentialMeta,\n DCQLQuery,\n DesktopQRData,\n DesktopStrategyData,\n LinkStrategyData,\n StrategyData,\n TS43RequestData,\n TS43StrategyData,\n // Prepare types\n PrepareOptions,\n PrepareRequest,\n PrepareResponse,\n PrepareResult,\n Theme,\n // Verify types\n VerifyPhoneNumberRequest,\n VerifyPhoneNumberResponse,\n // Phone types\n GetPhoneNumberRequest,\n GetPhoneNumberResponse,\n // Complete types\n CompleteRequest,\n CompleteResponse,\n DesktopWaitResponse,\n // Status types\n StatusResponse,\n // Report types\n ReportInvocationRequest,\n ReportInvocationResponse,\n // Eligibility types\n AvailableOption,\n EligibilityRequest,\n EligibilityResponse,\n Requirements,\n} from './models/index.js';\n","import { randomBytes } from 'node:crypto';\nimport { TokenManager } from './auth.js';\nimport type { MagicalAuthConfig, ResolvedConfig } from './config.js';\nimport { resolveConfig } from './config.js';\nimport { computeFeHash, generateFeCode } from './device-binding.js';\nimport type { ErrorResponse } from './errors.js';\nimport {\n createErrorFromResponse,\n DesktopWaitError,\n MagicalAuthError,\n} from './errors.js';\nimport type { HttpResponse } from './internal/http.js';\nimport { maskPhoneNumber } from './internal/mask.js';\nimport { AuthenticationStrategy } from './models/index.js';\nimport type {\n CompleteRequest,\n CompleteResponse,\n DesktopWaitResponse,\n EligibilityRequest,\n EligibilityResponse,\n GetPhoneNumberRequest,\n GetPhoneNumberResponse,\n LinkStrategyData,\n PrepareRequest,\n PrepareResponse,\n PrepareResult,\n ReportInvocationResponse,\n StatusResponse,\n VerifyPhoneNumberRequest,\n VerifyPhoneNumberResponse,\n} from './models/index.js';\nimport {\n validateCompleteRequest,\n validateEligibilityRequest,\n validateGetPhoneNumberRequest,\n validatePrepareRequest,\n validateSessionId,\n validateSessionKey,\n validateVerifyPhoneNumberRequest,\n} from './validation.js';\n\n/**\n * Per-request options for API calls.\n */\nexport interface RequestOptions {\n /** Correlation ID forwarded as X-Correlation-ID header for request tracing */\n correlationId?: string;\n}\n\n/**\n * Magical Auth SDK client for phone number authentication.\n *\n * @example\n * ```typescript\n * const client = new MagicalAuthClient({\n * clientId: 'your-client-id',\n * clientSecret: 'your-client-secret',\n * });\n *\n * // Prepare authentication (auto-generates device binding codes)\n * const result = await client.prepare({\n * phone_number: '+14155551234',\n * nonce: 'unique-nonce',\n * use_case: 'VerifyPhoneNumber',\n * client_info: { user_agent: req.headers['user-agent'] },\n * });\n *\n * // For link protocol, set the binding cookie\n * if (result.feCode) {\n * res.setHeader('Set-Cookie', buildSetBindingCookieHeader(result.feCode, result.session.session_key));\n * }\n * ```\n */\nexport class MagicalAuthClient {\n private readonly config: ResolvedConfig;\n private readonly tokenManager: TokenManager;\n\n /**\n * Creates a new MagicalAuthClient instance.\n *\n * @param config - Client configuration\n * @throws {Error} If clientId or clientSecret is missing\n */\n constructor(config: MagicalAuthConfig) {\n if (!config.clientId) {\n throw new Error('clientId is required');\n }\n if (!config.clientSecret) {\n throw new Error('clientSecret is required');\n }\n\n this.config = resolveConfig(config);\n this.tokenManager = new TokenManager(\n this.config.clientId,\n this.config.clientSecret,\n `${this.config.baseUrl}/oauth2-cc/token`,\n this.config.httpClient,\n this.config.logger,\n );\n }\n\n /**\n * Check authentication eligibility for a phone number or PLMN.\n * Returns available authentication strategies with platform requirements.\n *\n * @param request - Eligibility request with phone_number or plmn. `client_info.user_agent` is required.\n * @param options - Per-request options (e.g., correlationId)\n * @returns Eligibility response with available options\n * @throws {ValidationError} If request validation fails (incl. missing/blank `client_info.user_agent`)\n * @throws {MagicalAuthError} For other API errors\n */\n async checkEligibility(\n request: EligibilityRequest,\n options?: RequestOptions,\n ): Promise<EligibilityResponse> {\n validateEligibilityRequest(request);\n const response = await this.doRequest<EligibilityResponse>(\n 'POST',\n '/magic-auth/v2/auth/eligibility',\n request,\n options,\n );\n return response;\n }\n\n /**\n * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.\n *\n * Automatically generates `fe_code` / `fe_hash` for device binding. If the aggregator\n * selects the 'link' strategy, `feCode` is included in the result so the caller can\n * set it as an HttpOnly cookie via `buildSetBindingCookieHeader()`.\n *\n * @param request - Prepare request parameters\n * @param options - Per-request options (e.g., correlationId)\n * @returns Prepare result with authentication strategy, session info, and optional feCode\n * @throws {ValidationError} If request validation fails\n * @throws {CarrierNotEligibleError} If carrier is not eligible\n * @throws {MagicalAuthError} For other API errors\n */\n async prepare(\n request: PrepareRequest,\n options?: RequestOptions,\n ): Promise<PrepareResult> {\n validatePrepareRequest(request);\n this.config.logger.debug('Preparing auth', { use_case: request.use_case });\n\n const nonce = request.nonce || generateNonce();\n const feCode = generateFeCode();\n const feHash = computeFeHash(feCode);\n\n const requestWithHash: PrepareRequest = { ...request, nonce, fe_hash: feHash };\n\n const response = await this.doRequest<PrepareResponse>(\n 'POST',\n '/magic-auth/v2/auth/prepare',\n requestWithHash,\n options,\n );\n\n const result: PrepareResult = { ...response };\n\n if (response.authentication_strategy === AuthenticationStrategy.LINK) {\n const linkData = response.data as LinkStrategyData;\n result.feCode = linkData.fe_code ?? feCode;\n }\n\n this.config.logger.debug('Auth prepared', {\n strategy: response.authentication_strategy,\n session_key: response.session.session_key,\n });\n\n return result;\n }\n\n /**\n * Validates device binding codes and completes a link protocol session.\n *\n * Called after the carrier OAuth redirect lands on the developer's completion page.\n * The completion page extracts `agg_code` + `session_key` from the URL fragment\n * and the developer's handler reads `fe_code` from the `_glide_bind` cookie.\n *\n * @param request - Complete request with session_key, fe_code, and agg_code\n * @param options - Per-request options (e.g., correlationId)\n * @returns Complete response with status\n * @throws {DeviceBindingError} If binding code validation fails\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {SessionNotEligibleError} If session not in pending_completion status\n * @throws {BrowserMismatchError} If browser differs from the one used in prepare\n * @throws {MagicalAuthError} For other API errors\n */\n async complete(\n request: CompleteRequest,\n options?: RequestOptions,\n ): Promise<CompleteResponse> {\n validateCompleteRequest(request);\n this.config.logger.debug('Completing device-bound session', {\n session_key: request.session_key,\n });\n\n const response = await this.doRequest<CompleteResponse>(\n 'POST',\n '/magic-auth/v2/auth/complete',\n request,\n options,\n );\n\n this.config.logger.debug('Device binding validated', { status: response.status });\n return response;\n }\n\n /**\n * Verifies a phone number using digital credentials.\n *\n * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.\n *\n * @param request - Verify request with session and credential\n * @param options - Per-request options (e.g., correlationId)\n * @returns Verification result with phone number and verified status\n * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {InvalidCredentialError} If credential format is invalid\n * @throws {MagicalAuthError} For other API errors\n */\n async verifyPhoneNumber(\n request: VerifyPhoneNumberRequest,\n options?: RequestOptions,\n ): Promise<VerifyPhoneNumberResponse> {\n validateVerifyPhoneNumberRequest(request);\n this.config.logger.debug('Verifying phone number', {\n session_key: request.session.session_key,\n });\n\n const response = await this.doRequest<VerifyPhoneNumberResponse>(\n 'POST',\n '/magic-auth/v2/auth/verify-phone-number',\n request,\n options,\n );\n\n this.config.logger.debug('Phone verification complete', { verified: response.verified });\n return response;\n }\n\n /**\n * Retrieves the phone number associated with the device using digital credentials.\n *\n * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.\n *\n * @param request - Get phone number request with session and credential\n * @param options - Per-request options (e.g., correlationId)\n * @returns Response with the retrieved phone number\n * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {InvalidCredentialError} If credential format is invalid\n * @throws {MagicalAuthError} For other API errors\n */\n async getPhoneNumber(\n request: GetPhoneNumberRequest,\n options?: RequestOptions,\n ): Promise<GetPhoneNumberResponse> {\n validateGetPhoneNumberRequest(request);\n this.config.logger.debug('Getting phone number', {\n session_key: request.session.session_key,\n });\n\n const response = await this.doRequest<GetPhoneNumberResponse>(\n 'POST',\n '/magic-auth/v2/auth/get-phone-number',\n request,\n options,\n );\n\n this.config.logger.debug('Phone number retrieved', {\n phone: maskPhoneNumber(response.phone_number),\n });\n return response;\n }\n\n /**\n * Reports when a user clicks the invoke/authenticate button.\n *\n * Used for Authentication Success Rate (ASR) tracking and analytics.\n *\n * @param sessionId - The session identifier\n * @param options - Per-request options (e.g., correlationId)\n * @returns Report response with a boolean `success` flag\n * @throws {SessionNotFoundError} If session not found\n * @throws {MagicalAuthError} For other API errors\n */\n async reportInvocation(\n sessionId: string,\n options?: RequestOptions,\n ): Promise<ReportInvocationResponse> {\n validateSessionId(sessionId);\n this.config.logger.debug('Reporting invocation', { session_id: sessionId });\n\n return await this.doRequest<ReportInvocationResponse>(\n 'POST',\n '/magic-auth/v2/auth/report-invocation',\n { session_id: sessionId },\n options,\n );\n }\n\n /**\n * Polls for the status of an ongoing verification request (protected endpoint).\n *\n * @param sessionKey - The 64-character hex session key from prepare response\n * @param options - Per-request options (e.g., correlationId)\n * @returns Status response with current verification state\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {MagicalAuthError} For other API errors\n */\n async checkStatus(\n sessionKey: string,\n options?: RequestOptions,\n ): Promise<StatusResponse> {\n validateSessionKey(sessionKey);\n this.config.logger.debug('Checking status', { session_key: sessionKey });\n\n const response = await this.doRequest<StatusResponse>(\n 'GET',\n `/magic-auth/v2/auth/status/${encodeURIComponent(sessionKey)}`,\n undefined,\n options,\n );\n\n this.config.logger.debug('Status retrieved', { status: response.status });\n return response;\n }\n\n /**\n * Polls for the status of an ongoing verification request (public endpoint).\n *\n * This endpoint does not require authentication.\n *\n * @param sessionKey - The 64-character hex session key from prepare response\n * @param options - Per-request options (e.g., correlationId)\n * @returns Status response with current verification state\n * @throws {SessionNotFoundError} If session not found or expired\n * @throws {MagicalAuthError} For other API errors\n */\n async checkStatusPublic(\n sessionKey: string,\n options?: RequestOptions,\n ): Promise<StatusResponse> {\n validateSessionKey(sessionKey);\n this.config.logger.debug('Checking public status', { session_key: sessionKey });\n\n const response = await this.doRequestWithoutAuth<StatusResponse>(\n 'GET',\n `/public/status/${encodeURIComponent(sessionKey)}`,\n undefined,\n options,\n );\n\n this.config.logger.debug('Public status retrieved', { status: response.status });\n return response;\n }\n\n /**\n * Makes an authenticated API request.\n */\n private async doRequest<T>(\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n ): Promise<T> {\n const token = await this.tokenManager.getToken();\n\n this.config.logger.debug('Request', { method, path });\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n };\n if (options?.correlationId) {\n headers['X-Correlation-ID'] = options.correlationId;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n const response = await this.config.httpClient.request({\n method,\n url: `${this.config.baseUrl}${path}`,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n return this.handleResponse<T>(response);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new MagicalAuthError(\n 'Request timeout',\n 'TIMEOUT',\n 408,\n undefined,\n { timeout: this.config.timeout },\n );\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Makes an unauthenticated API request (for public endpoints).\n */\n private async doRequestWithoutAuth<T>(\n method: string,\n path: string,\n body?: unknown,\n options?: RequestOptions,\n ): Promise<T> {\n this.config.logger.debug('Request (no auth)', { method, path });\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n if (options?.correlationId) {\n headers['X-Correlation-ID'] = options.correlationId;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n\n try {\n const response = await this.config.httpClient.request({\n method,\n url: `${this.config.baseUrl}${path}`,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n return this.handleResponse<T>(response);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new MagicalAuthError(\n 'Request timeout',\n 'TIMEOUT',\n 408,\n undefined,\n { timeout: this.config.timeout },\n );\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n /**\n * Handles API response, parsing JSON and converting errors.\n * Throws DesktopWaitError for HTTP 202 responses.\n */\n private async handleResponse<T>(response: HttpResponse): Promise<T> {\n if (response.status === 202) {\n const waitBody = (await response.json()) as DesktopWaitResponse;\n throw new DesktopWaitError(waitBody);\n }\n\n if (!response.ok) {\n let errorBody: ErrorResponse;\n try {\n errorBody = (await response.json()) as ErrorResponse;\n if (!errorBody.status) {\n errorBody.status = response.status;\n }\n } catch {\n errorBody = {\n code: 'UNKNOWN_ERROR',\n message: `Request failed with status ${response.status}`,\n status: response.status,\n };\n }\n throw createErrorFromResponse(errorBody, response.headers);\n }\n\n return response.json() as Promise<T>;\n }\n\n /**\n * Invalidates the cached access token.\n */\n invalidateToken(): void {\n this.tokenManager.invalidate();\n }\n}\n\nconst ALPHANUMERIC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\nfunction generateNonce(length = 32): string {\n const bytes = randomBytes(length);\n let result = '';\n for (let i = 0; i < length; i++) {\n result += ALPHANUMERIC.charAt(bytes[i]! % ALPHANUMERIC.length);\n }\n return result;\n}\n","/**\n * HTTP client interface for custom implementations (BYOC - Bring Your Own Client).\n * Defaults to native fetch if not provided.\n */\nexport interface HttpClient {\n request(options: HttpRequestOptions): Promise<HttpResponse>;\n}\n\n/**\n * Options for making an HTTP request.\n */\nexport interface HttpRequestOptions {\n method: string;\n url: string;\n headers: Record<string, string>;\n body?: string;\n signal?: AbortSignal;\n}\n\n/**\n * HTTP response interface matching the native Response API.\n */\nexport interface HttpResponse {\n ok: boolean;\n status: number;\n headers: Headers;\n json(): Promise<unknown>;\n text(): Promise<string>;\n}\n\n/**\n * Logger interface for custom implementations (BYOL - Bring Your Own Logger).\n * Defaults to no-op if not provided.\n */\nexport interface Logger {\n debug(message: string, meta?: Record<string, unknown>): void;\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n error(message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Default HTTP client implementation using native fetch.\n */\nexport const defaultHttpClient: HttpClient = {\n async request(options: HttpRequestOptions): Promise<HttpResponse> {\n const response = await fetch(options.url, {\n method: options.method,\n headers: options.headers,\n body: options.body,\n signal: options.signal,\n });\n return response;\n },\n};\n\n/**\n * Default no-op logger implementation.\n */\nexport const noopLogger: Logger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n","/**\n * Error codes returned by the Magical Auth API.\n * Use `ErrorCode.SESSION_NOT_FOUND`, `ErrorCode.VALIDATION_ERROR`, etc. instead of raw strings.\n */\nexport const ErrorCode = {\n BAD_REQUEST: 'BAD_REQUEST',\n UNAUTHORIZED: 'UNAUTHORIZED',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n MISSING_PARAMETERS: 'MISSING_PARAMETERS',\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n INVALID_VERIFICATION: 'INVALID_VERIFICATION',\n CARRIER_NOT_ELIGIBLE: 'CARRIER_NOT_ELIGIBLE',\n UNSUPPORTED_PLATFORM: 'UNSUPPORTED_PLATFORM',\n PHONE_NUMBER_MISMATCH: 'PHONE_NUMBER_MISMATCH',\n INVALID_CREDENTIAL_FORMAT: 'INVALID_CREDENTIAL_FORMAT',\n FORBIDDEN: 'FORBIDDEN',\n AUDIENCE_VALIDATION_FAILED: 'AUDIENCE_VALIDATION_FAILED',\n BROWSER_MISMATCH: 'BROWSER_MISMATCH',\n QR_ALREADY_SCANNED: 'QR_ALREADY_SCANNED',\n SESSION_NOT_ELIGIBLE: 'SESSION_NOT_ELIGIBLE',\n SESSION_EXPIRED: 'SESSION_EXPIRED',\n DEVICE_BINDING_FAILED: 'DEVICE_BINDING_FAILED',\n MISSING_BINDING_COOKIE: 'MISSING_BINDING_COOKIE',\n RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',\n INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',\n SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',\n} as const;\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n/**\n * Error response structure from the API.\n */\nexport interface ErrorResponse {\n code: string;\n message: string;\n status?: number;\n request_id?: string;\n timestamp?: string;\n trace_id?: string;\n span_id?: string;\n service?: string;\n details?: {\n fields?: Record<string, string>;\n [key: string]: unknown;\n };\n}\n\n/**\n * Base error class for all Magical Auth SDK errors.\n */\nexport class MagicalAuthError extends Error {\n /**\n * Error code from the API.\n */\n public readonly code: string;\n\n /**\n * HTTP status code.\n */\n public readonly status: number;\n\n /**\n * Request ID for debugging/support.\n */\n public readonly requestId?: string;\n\n /**\n * Additional error details.\n */\n public readonly details?: Record<string, unknown>;\n\n /**\n * Distributed trace ID (from OpenTelemetry).\n */\n public readonly traceId?: string;\n\n /**\n * Span ID for tracing.\n */\n public readonly spanId?: string;\n\n /**\n * ISO 8601 timestamp of when the error occurred on the server.\n */\n public readonly timestamp?: string;\n\n /**\n * Name of the service that produced this error.\n */\n public readonly service?: string;\n\n constructor(\n message: string,\n code: string,\n status: number,\n requestId?: string,\n details?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'MagicalAuthError';\n this.code = code;\n this.status = status;\n this.requestId = requestId;\n this.details = details;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n // Ensure instanceof works correctly\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Bad request error (generic 400).\n */\nexport class BadRequestError extends MagicalAuthError {\n constructor(message = 'Bad request', requestId?: string) {\n super(message, 'BAD_REQUEST', 400, requestId);\n this.name = 'BadRequestError';\n }\n}\n\n/**\n * Validation error with field-level details.\n */\nexport class ValidationError extends MagicalAuthError {\n /**\n * Field-level validation errors.\n */\n public readonly fieldErrors: Record<string, string>;\n\n constructor(\n message: string,\n fieldErrors: Record<string, string>,\n requestId?: string,\n ) {\n super(message, 'VALIDATION_ERROR', 400, requestId, { fields: fieldErrors });\n this.name = 'ValidationError';\n this.fieldErrors = fieldErrors;\n }\n}\n\n/**\n * Authentication/authorization error.\n */\nexport class UnauthorizedError extends MagicalAuthError {\n constructor(message = 'Unauthorized', requestId?: string) {\n super(message, 'UNAUTHORIZED', 401, requestId);\n this.name = 'UnauthorizedError';\n }\n}\n\n/**\n * Session not found error.\n */\nexport class SessionNotFoundError extends MagicalAuthError {\n constructor(message = 'Session not found', requestId?: string) {\n super(message, 'SESSION_NOT_FOUND', 404, requestId);\n this.name = 'SessionNotFoundError';\n }\n}\n\n/**\n * Carrier not eligible for authentication.\n */\nexport class CarrierNotEligibleError extends MagicalAuthError {\n constructor(message = 'Carrier not eligible', requestId?: string) {\n super(message, 'CARRIER_NOT_ELIGIBLE', 422, requestId);\n this.name = 'CarrierNotEligibleError';\n }\n}\n\n/**\n * Platform not supported for authentication.\n */\nexport class UnsupportedPlatformError extends MagicalAuthError {\n constructor(message = 'Platform not supported', requestId?: string) {\n super(message, 'UNSUPPORTED_PLATFORM', 422, requestId);\n this.name = 'UnsupportedPlatformError';\n }\n}\n\n/**\n * Invalid credential format error.\n */\nexport class InvalidCredentialError extends MagicalAuthError {\n constructor(message = 'Invalid credential format', requestId?: string) {\n super(message, 'INVALID_CREDENTIAL_FORMAT', 422, requestId);\n this.name = 'InvalidCredentialError';\n }\n}\n\n/**\n * Phone number mismatch error.\n */\nexport class PhoneNumberMismatchError extends MagicalAuthError {\n constructor(message = 'Phone number does not match', requestId?: string) {\n super(message, 'PHONE_NUMBER_MISMATCH', 422, requestId);\n this.name = 'PhoneNumberMismatchError';\n }\n}\n\n/**\n * Rate limit exceeded error.\n */\nexport class RateLimitError extends MagicalAuthError {\n /**\n * Seconds until rate limit resets (if provided by API).\n */\n public readonly retryAfter?: number;\n\n constructor(message: string, retryAfter?: number, requestId?: string) {\n super(message, 'RATE_LIMIT_EXCEEDED', 429, requestId, \n retryAfter !== undefined ? { retryAfter } : undefined);\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Internal server error.\n */\nexport class InternalServerError extends MagicalAuthError {\n constructor(message = 'An internal error occurred', requestId?: string) {\n super(message, 'INTERNAL_SERVER_ERROR', 500, requestId);\n this.name = 'InternalServerError';\n }\n}\n\n/**\n * Service temporarily unavailable.\n */\nexport class ServiceUnavailableError extends MagicalAuthError {\n constructor(message = 'Service temporarily unavailable', requestId?: string) {\n super(message, 'SERVICE_UNAVAILABLE', 503, requestId);\n this.name = 'ServiceUnavailableError';\n }\n}\n\n/**\n * Forbidden error (device binding validation failed).\n */\nexport class ForbiddenError extends MagicalAuthError {\n constructor(message = 'Forbidden', requestId?: string) {\n super(message, 'FORBIDDEN', 403, requestId);\n this.name = 'ForbiddenError';\n }\n}\n\n/**\n * Browser mismatch error (completion page opened in a different browser than prepare).\n */\nexport class BrowserMismatchError extends MagicalAuthError {\n constructor(\n message = 'Browser mismatch detected',\n requestId?: string,\n details?: Record<string, unknown>,\n ) {\n super(message, 'BROWSER_MISMATCH', 422, requestId, details);\n this.name = 'BrowserMismatchError';\n }\n}\n\n/**\n * Session not eligible for the requested operation (e.g., wrong status for /complete).\n */\nexport class SessionNotEligibleError extends MagicalAuthError {\n constructor(message = 'Session is not eligible for completion', requestId?: string) {\n super(message, 'SESSION_NOT_ELIGIBLE', 409, requestId);\n this.name = 'SessionNotEligibleError';\n }\n}\n\n/**\n * Device binding validation failed (fe_code/agg_code format or aggregator rejection).\n */\nexport class DeviceBindingError extends MagicalAuthError {\n constructor(message = 'Device binding validation failed', code: string = 'DEVICE_BINDING_FAILED', requestId?: string) {\n super(message, code, 403, requestId);\n this.name = 'DeviceBindingError';\n }\n}\n\n/**\n * Binding cookie is missing — the session-scoped `_glide_bind_{sessionKey}` cookie\n * was not found. This typically means the user opened the completion URL in a\n * different browser than the one that initiated the flow.\n */\nexport class MissingBindingCookieError extends DeviceBindingError {\n constructor(message = 'Binding cookie missing or expired', requestId?: string) {\n super(message, 'MISSING_BINDING_COOKIE', requestId);\n this.name = 'MissingBindingCookieError';\n }\n}\n\n/**\n * Desktop wait response — thrown when the server returns HTTP 202\n * indicating the desktop QR session is still waiting for mobile completion.\n * Callers should inspect `waitResponse` to decide whether to retry.\n */\nexport class DesktopWaitError extends MagicalAuthError {\n public readonly waitResponse: {\n status: 'waiting';\n message: string;\n session_key: string;\n session_status: string;\n retry: boolean;\n session_expires_in_seconds: number;\n };\n\n constructor(waitResponse: {\n status: 'waiting';\n message: string;\n session_key: string;\n session_status: string;\n retry: boolean;\n session_expires_in_seconds: number;\n }) {\n super(waitResponse.message, 'DESKTOP_WAIT', 202);\n this.name = 'DesktopWaitError';\n this.waitResponse = waitResponse;\n }\n}\n\n/**\n * Parses the Retry-After header value.\n * @param headers - Response headers\n * @returns Retry-After value in seconds, or undefined if not present/invalid\n */\nfunction parseRetryAfter(headers?: Headers): number | undefined {\n if (!headers) return undefined;\n \n const retryAfter = headers.get('Retry-After');\n if (!retryAfter) return undefined;\n\n // Try parsing as seconds (integer)\n const seconds = parseInt(retryAfter, 10);\n if (!isNaN(seconds) && seconds >= 0) {\n return seconds;\n }\n\n // Try parsing as HTTP date\n const date = Date.parse(retryAfter);\n if (!isNaN(date)) {\n const diffMs = date - Date.now();\n return Math.max(0, Math.ceil(diffMs / 1000));\n }\n\n return undefined;\n}\n\n/**\n * Creates the appropriate error class instance from an API error response.\n * @param response - The error response from the API\n * @param headers - Optional response headers (for extracting Retry-After, etc.)\n * @returns The appropriate MagicalAuthError subclass instance\n */\nexport function createErrorFromResponse(\n response: ErrorResponse,\n headers?: Headers,\n): MagicalAuthError {\n const { code, message, request_id, details, status, trace_id, span_id, timestamp, service } = response;\n\n const error = createTypedError(code, message, request_id, details, status, headers);\n return Object.assign(error, {\n traceId: trace_id,\n spanId: span_id,\n timestamp,\n service,\n });\n}\n\nfunction createTypedError(\n code: string,\n message: string,\n request_id: string | undefined,\n details: ErrorResponse['details'],\n status: number | undefined,\n headers?: Headers,\n): MagicalAuthError {\n switch (code) {\n case 'BAD_REQUEST':\n return new BadRequestError(message, request_id);\n\n case 'VALIDATION_ERROR':\n case 'MISSING_PARAMETERS':\n return new ValidationError(\n message,\n (details?.fields as Record<string, string>) ?? {},\n request_id,\n );\n\n case 'UNAUTHORIZED':\n return new UnauthorizedError(message, request_id);\n\n case 'SESSION_NOT_FOUND':\n return new SessionNotFoundError(message, request_id);\n\n case 'CARRIER_NOT_ELIGIBLE':\n return new CarrierNotEligibleError(message, request_id);\n\n case 'UNSUPPORTED_PLATFORM':\n return new UnsupportedPlatformError(message, request_id);\n\n case 'INVALID_CREDENTIAL_FORMAT':\n case 'INVALID_VERIFICATION':\n return new InvalidCredentialError(message, request_id);\n\n case 'PHONE_NUMBER_MISMATCH':\n return new PhoneNumberMismatchError(message, request_id);\n\n case 'FORBIDDEN':\n return new ForbiddenError(message, request_id);\n\n case 'BROWSER_MISMATCH':\n return new BrowserMismatchError(\n message,\n request_id,\n details as Record<string, unknown> | undefined,\n );\n\n case 'SESSION_NOT_ELIGIBLE':\n return new SessionNotEligibleError(message, request_id);\n\n case 'DEVICE_BINDING_FAILED':\n return new DeviceBindingError(message, 'DEVICE_BINDING_FAILED', request_id);\n\n case 'MISSING_BINDING_COOKIE':\n return new MissingBindingCookieError(message, request_id);\n\n case 'RATE_LIMIT_EXCEEDED':\n return new RateLimitError(message, parseRetryAfter(headers), request_id);\n\n case 'INTERNAL_SERVER_ERROR':\n return new InternalServerError(message, request_id);\n\n case 'SERVICE_UNAVAILABLE':\n return new ServiceUnavailableError(message, request_id);\n\n default:\n return new MagicalAuthError(\n message,\n code,\n status ?? 500,\n request_id,\n details as Record<string, unknown> | undefined,\n );\n }\n}\n","import type { HttpClient, Logger } from './internal/http.js';\nimport { noopLogger } from './internal/http.js';\nimport { UnauthorizedError } from './errors.js';\n\n/**\n * Token response from OAuth2 token endpoint.\n */\ninterface TokenResponse {\n access_token: string;\n token_type: string;\n expires_in: number;\n}\n\n/**\n * Manages OAuth2 access tokens with automatic caching and refresh.\n *\n * Thread-safe through promise deduplication - concurrent calls to getToken()\n * will share the same in-flight request rather than making multiple requests.\n */\nexport class TokenManager {\n private token: string | null = null;\n private expiresAt = 0;\n private refreshPromise: Promise<string> | null = null;\n\n /** Buffer time in ms before expiry to refresh token (60 seconds) */\n private readonly bufferMs = 60_000;\n\n constructor(\n private readonly clientId: string,\n private readonly clientSecret: string,\n private readonly tokenUrl: string,\n private readonly httpClient: HttpClient,\n private readonly logger: Logger = noopLogger,\n ) {}\n\n /**\n * Gets a valid access token, refreshing if necessary.\n *\n * This method is safe for concurrent calls - if a refresh is already\n * in progress, subsequent calls will await the same promise.\n *\n * @returns A valid access token\n * @throws {UnauthorizedError} If token fetch fails\n */\n async getToken(): Promise<string> {\n if (this.token && Date.now() < this.expiresAt) {\n this.logger.debug('Using cached token', {\n expires_in_s: Math.max(0, Math.round((this.expiresAt - Date.now()) / 1000)),\n });\n return this.token;\n }\n\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n this.logger.debug('Refreshing access token');\n this.refreshPromise = this.fetchToken();\n\n try {\n return await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n /**\n * Fetches a new access token from the OAuth2 endpoint.\n */\n private async fetchToken(): Promise<string> {\n const credentials = Buffer.from(\n `${this.clientId}:${this.clientSecret}`,\n ).toString('base64');\n\n const response = await this.httpClient.request({\n method: 'POST',\n url: this.tokenUrl,\n headers: {\n Authorization: `Basic ${credentials}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: 'grant_type=client_credentials',\n });\n\n if (!response.ok) {\n // Try to get error details from response\n let errorMessage = 'Token request failed';\n try {\n const errorBody = (await response.json()) as {\n error?: string;\n error_description?: string;\n };\n if (errorBody.error_description) {\n errorMessage = errorBody.error_description;\n } else if (errorBody.error) {\n errorMessage = errorBody.error;\n }\n } catch {\n // Ignore JSON parse errors, use default message\n }\n throw new UnauthorizedError(errorMessage);\n }\n\n const data = (await response.json()) as TokenResponse;\n\n if (!data.access_token) {\n throw new UnauthorizedError('Invalid token response: missing access_token');\n }\n\n this.token = data.access_token;\n this.expiresAt = Date.now() + data.expires_in * 1000 - this.bufferMs;\n\n this.logger.debug('Access token refreshed', { expires_in_s: data.expires_in });\n\n return this.token;\n }\n\n /**\n * Invalidates the cached token, forcing a refresh on next getToken() call.\n * Useful when receiving a 401 response from the API.\n */\n invalidate(): void {\n this.token = null;\n this.expiresAt = 0;\n this.logger.debug('Token cache invalidated');\n }\n\n /**\n * Checks if there's a valid cached token.\n * @returns true if a valid token exists\n */\n hasValidToken(): boolean {\n return this.token !== null && Date.now() < this.expiresAt;\n }\n}\n","import type { HttpClient, Logger } from './internal/http.js';\nimport { defaultHttpClient, noopLogger } from './internal/http.js';\n\n/**\n * Configuration options for MagicalAuthClient.\n */\nexport interface MagicalAuthConfig {\n /** OAuth2 client ID (required) */\n clientId: string;\n /** OAuth2 client secret (required) */\n clientSecret: string;\n /** API base URL (default: https://api.glideidentity.app) */\n baseUrl?: string;\n /** Custom HTTP client (default: native fetch) */\n httpClient?: HttpClient;\n /** Custom logger (default: no-op) */\n logger?: Logger;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n}\n\n/**\n * Internal resolved configuration with all defaults applied.\n */\nexport interface ResolvedConfig {\n readonly clientId: string;\n readonly clientSecret: string;\n readonly baseUrl: string;\n readonly httpClient: HttpClient;\n readonly logger: Logger;\n readonly timeout: number;\n}\n\n/** Default API base URL */\nexport const DEFAULT_BASE_URL = 'https://api.glideidentity.app';\n\n/** Default request timeout in milliseconds */\nexport const DEFAULT_TIMEOUT = 30_000;\n\n/**\n * Resolves user-provided configuration with defaults.\n * @param config - User-provided configuration\n * @returns Fully resolved configuration with defaults applied\n */\nexport function resolveConfig(config: MagicalAuthConfig): ResolvedConfig {\n return {\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,\n httpClient: config.httpClient ?? defaultHttpClient,\n logger: config.logger ?? noopLogger,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n };\n}\n","import { createHash, randomBytes } from 'node:crypto';\n\n/**\n * Regex matching a valid 64-character hex string (case-insensitive).\n *\n * Accepts both lowercase and uppercase hex so that external inputs (URL\n * fragments, cookie values) still pass validation even if a proxy or\n * browser extension uppercases them. Internal code normalises to\n * lowercase before hashing or sending to the aggregator.\n */\nexport const HEX_64 = /^[0-9a-fA-F]{64}$/;\n\n/** Characters that must not appear in cookie attribute values. */\nconst UNSAFE_COOKIE_ATTR = /[;\\r\\n]/;\n\n/** Cookie name prefix for device binding codes. Append the session key for the full name. */\nexport const BINDING_COOKIE_PREFIX = '_glide_bind_';\n\n/**\n * Cookie max-age in seconds. Set to 5 minutes — sufficient for the carrier\n * authentication round-trip (typically under 2 minutes). The cookie auto-expires\n * after this period, so explicit clearing is optional.\n */\nexport const BINDING_COOKIE_MAX_AGE = 300;\n\n/**\n * Keys that MUST be redacted in logs to prevent leaking binding secrets.\n * Covers snake_case, camelCase, and collapsed forms.\n */\nexport const SENSITIVE_KEYS: readonly string[] = [\n 'fe_code',\n 'fecode',\n 'feCode',\n 'fe_hash',\n 'fehash',\n 'feHash',\n 'agg_code',\n 'aggcode',\n 'aggCode',\n '_glide_bind',\n 'glide_bind',\n];\n\n/**\n * Options for building binding cookie headers.\n */\nexport interface BindingCookieOptions {\n /** Cookie domain (must match the completion redirect URL domain) */\n domain?: string;\n /** Cookie path (default: \"/\") — must start with \"/\" */\n path?: string;\n /** Secure flag (default: true — set false for local HTTP dev only) */\n secure?: boolean;\n}\n\n/**\n * Returns the full cookie name for a given session key.\n *\n * Using a session-scoped name (`_glide_bind_{sessionKey}`) ensures that\n * parallel `prepare()` calls from the same browser don't overwrite each\n * other's cookies — each session gets its own cookie.\n */\nexport function getBindingCookieName(sessionKey: string): string {\n if (\n !sessionKey ||\n UNSAFE_COOKIE_ATTR.test(sessionKey) ||\n sessionKey.includes('=')\n ) {\n throw new Error(\n 'Invalid sessionKey for cookie name: must not be empty or contain \";\", \"=\", \"\\\\r\", or \"\\\\n\"',\n );\n }\n return `${BINDING_COOKIE_PREFIX}${sessionKey}`;\n}\n\n/**\n * Asserts that the given value is a valid 64-character hex string.\n * @throws {Error} If the value does not match.\n */\nexport function assertValidFeCode(feCode: string): void {\n if (!HEX_64.test(feCode)) {\n throw new Error('feCode must be a 64-character hex string');\n }\n}\n\n/**\n * Generates a cryptographically random fe_code (32 random bytes -> 64-char lowercase hex).\n */\nexport function generateFeCode(): string {\n return randomBytes(32).toString('hex');\n}\n\n/**\n * Computes SHA256(fe_code) -> 64-char lowercase hex hash.\n * Input is normalised to lowercase for deterministic hashing.\n *\n * @throws {Error} If feCode is not a valid 64-character hex string\n */\nexport function computeFeHash(feCode: string): string {\n assertValidFeCode(feCode);\n return createHash('sha256').update(feCode.toLowerCase()).digest('hex');\n}\n\n/**\n * Builds a Set-Cookie header value that sets the device binding cookie.\n *\n * @param feCode - The binding code to store (64-char hex, normalised to lowercase)\n * @param sessionKey - Session key used in the cookie name to avoid collisions between parallel sessions\n * @param options - Cookie options (domain, path, secure)\n * @returns Raw Set-Cookie header value string\n * @throws {Error} If feCode is invalid or options contain injection characters\n */\nexport function buildSetBindingCookieHeader(\n feCode: string,\n sessionKey: string,\n options?: BindingCookieOptions,\n): string {\n assertValidFeCode(feCode);\n validateCookieAttr('domain', options?.domain);\n validateCookieAttr('path', options?.path);\n\n const secure = options?.secure ?? true;\n const cookieName = getBindingCookieName(sessionKey);\n const parts = [\n `${cookieName}=${feCode.toLowerCase()}`,\n 'HttpOnly',\n 'SameSite=Lax',\n `Path=${options?.path ?? '/'}`,\n `Max-Age=${BINDING_COOKIE_MAX_AGE}`,\n ];\n if (secure) {\n parts.push('Secure');\n }\n if (options?.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n return parts.join('; ');\n}\n\n/**\n * Builds a Set-Cookie header value that clears the device binding cookie.\n *\n * @param sessionKey - Session key identifying which session's cookie to clear\n * @param options - Cookie options (must match the original cookie)\n * @returns Raw Set-Cookie header value string that expires the cookie\n * @throws {Error} If options contain injection characters\n */\nexport function buildClearBindingCookieHeader(\n sessionKey: string,\n options?: BindingCookieOptions,\n): string {\n validateCookieAttr('domain', options?.domain);\n validateCookieAttr('path', options?.path);\n\n const secure = options?.secure ?? true;\n const cookieName = getBindingCookieName(sessionKey);\n const parts = [\n `${cookieName}=`,\n 'HttpOnly',\n 'SameSite=Lax',\n `Path=${options?.path ?? '/'}`,\n 'Max-Age=0',\n 'Expires=Thu, 01 Jan 1970 00:00:00 GMT',\n ];\n if (secure) {\n parts.push('Secure');\n }\n if (options?.domain) {\n parts.push(`Domain=${options.domain}`);\n }\n return parts.join('; ');\n}\n\n/**\n * Parses the fe_code from a raw Cookie header string for a specific session.\n *\n * Returns `undefined` if the cookie is not present or the value is not\n * a valid 64-character hex string. When found, the value is normalised\n * to lowercase for deterministic hashing downstream.\n *\n * @param cookieHeader - Raw Cookie header value (e.g., \"foo=bar; _glide_bind_abc123=...\")\n * @param sessionKey - Session key identifying which cookie to look for\n * @returns The fe_code value (lowercase), or undefined if missing/invalid\n */\nexport function parseBindingCookie(\n cookieHeader: string | undefined,\n sessionKey: string,\n): string | undefined {\n if (!cookieHeader) return undefined;\n const cookieName = getBindingCookieName(sessionKey);\n const prefix = `${cookieName}=`;\n const match = cookieHeader\n .split(';')\n .map((c) => c.trim())\n .find((c) => c.startsWith(prefix));\n if (!match) return undefined;\n const value = match.substring(prefix.length);\n return HEX_64.test(value) ? value.toLowerCase() : undefined;\n}\n\n/**\n * Builds Set-Cookie headers that expire every existing device binding cookie\n * (`_glide_bind_*`) found in the request.\n *\n * Binding cookies are session-scoped (`_glide_bind_{sessionKey}`) and\n * auto-expire after `BINDING_COOKIE_MAX_AGE` seconds, so cleanup is normally\n * handled by the TTL. This helper is a tidying utility for partners who want\n * to explicitly clear stale cookies (for example on logout, on session\n * cancellation, or before issuing a fresh `prepare()` from a long-lived\n * browser session) without waiting for the TTL.\n *\n * @param cookieHeader - Raw Cookie request header\n * @param options - Cookie options (must match the original set call)\n * @returns Array of Set-Cookie header values that expire stale binding cookies\n */\nexport function clearStaleBindingCookies(\n cookieHeader: string | undefined,\n options?: BindingCookieOptions,\n): string[] {\n if (!cookieHeader) return [];\n const headers: string[] = [];\n for (const pair of cookieHeader.split(';')) {\n const eqIdx = pair.indexOf('=');\n const name = (eqIdx === -1 ? pair : pair.slice(0, eqIdx)).trim();\n if (name.startsWith(BINDING_COOKIE_PREFIX)) {\n const sessionSuffix = name.substring(BINDING_COOKIE_PREFIX.length);\n if (!sessionSuffix) continue;\n try {\n headers.push(buildClearBindingCookieHeader(sessionSuffix, options));\n } catch {\n // Malformed session suffix (injection chars) — skip silently.\n }\n }\n }\n return headers;\n}\n\nfunction validateCookieAttr(\n name: string,\n value: string | undefined,\n): void {\n if (value === undefined) return;\n if (UNSAFE_COOKIE_ATTR.test(value)) {\n throw new Error(\n `Invalid cookie ${name}: must not contain ';', '\\\\r', or '\\\\n'`,\n );\n }\n if (name === 'path' && (value.length === 0 || !value.startsWith('/'))) {\n throw new Error(\"Invalid cookie path: must start with '/'\");\n }\n}\n\n/**\n * Returns the HTML for the completion redirect page.\n *\n * This page extracts `agg_code` and `session_key` from the URL fragment,\n * POSTs them to the developer's backend (which auto-includes the\n * `_glide_bind_{sessionKey}` HttpOnly cookie), and displays the result.\n *\n * On successful completion, a localStorage signal is written\n * (`glide_signal_{session_key}`) so the FE SDK in the original tab can\n * detect completion via `StorageEvent` without polling.\n *\n * @param completeEndpoint - Relative path to POST to (e.g., \"/api/glide/complete\")\n * @returns Complete HTML string ready to serve\n * @throws {Error} If completeEndpoint is not a relative path starting with \"/\"\n */\nexport function getCompletionPageHtml(completeEndpoint: string): string {\n if (!completeEndpoint.startsWith('/') || completeEndpoint.startsWith('//')) {\n throw new Error(\n 'completeEndpoint must be a relative path starting with \"/\" (e.g., \"/api/glide/complete\"). ' +\n 'Cross-origin and protocol-relative endpoints (e.g., \"//evil.com/...\") are not supported because ' +\n 'the page relies on credentials: \"include\" for cookie-based device binding, which requires same-origin requests.',\n );\n }\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'\">\n<title>Verifying</title>\n<style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n 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; }\n .spinner-wrap { text-align: center; }\n .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; }\n @keyframes spin { to { transform: rotate(360deg); } }\n .hidden { display: none; }\n .hint { margin-top: 1.5rem; font-size: 0.875rem; color: #999; }\n .err { display: none; text-align: center; padding: 2rem 1.5rem; max-width: 340px; }\n .err h2 { font-size: 1.25rem; font-weight: 600; color: #1a1a1a; margin-bottom: 1rem; letter-spacing: -0.02em; line-height: 1.3; }\n .err-points { text-align: left; margin: 0 auto 1.5rem; max-width: 280px; }\n .err-points li { font-size: 0.875rem; line-height: 1.6; color: #555; margin-bottom: 0.375rem; padding-left: 0.25rem; }\n .illust { margin: 0 auto 1.5rem; }\n .illust svg { color: #94a3b8; }\n .illust-browser { width: 140px; height: 90px; position: relative; }\n .illust-browser .b { position: absolute; width: 52px; height: 40px; border: 2px solid #cbd5e1; border-radius: 6px; background: #f8fafc; }\n .illust-browser .b .bar { height: 10px; border-bottom: 1.5px solid #e2e8f0; display: flex; align-items: center; padding: 0 4px; gap: 2px; }\n .illust-browser .b .bar i { width: 3px; height: 3px; border-radius: 50%; background: #cbd5e1; }\n .illust-browser .b1 { left: 10px; top: 16px; } .illust-browser .b2 { right: 10px; top: 16px; }\n .illust-browser .aw { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }\n .illust-browser .aw svg { width: 36px; height: 36px; animation: arrowSpin 2.5s ease-in-out infinite; }\n @keyframes arrowSpin { 0%,100% { transform: rotate(0); } 50% { transform: rotate(180deg); } }\n .illust-retry svg { width: 48px; height: 48px; animation: retryPulse 2s ease-in-out infinite; }\n @keyframes retryPulse { 0%,100% { transform: scale(1); opacity: 0.7; } 50% { transform: scale(1.1); opacity: 1; } }\n .illust-wifi svg { width: 48px; height: 48px; animation: wifiBlink 2s ease-in-out infinite; }\n @keyframes wifiBlink { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n .illust-link svg { width: 48px; height: 48px; animation: linkShake 2s ease-in-out infinite; }\n @keyframes linkShake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-5deg); } 75% { transform: rotate(5deg); } }\n .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; }\n @keyframes fadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }\n .err.show { display: block; animation: fadeUp 0.35s ease-out; }\n</style>\n</head>\n<body>\n<div class=\"spinner-wrap\" id=\"loading\" role=\"status\" aria-live=\"polite\">\n <div class=\"spinner\"></div>\n <p class=\"hint hidden\" id=\"hint\"></p>\n</div>\n<div class=\"err\" id=\"error\" role=\"alert\" aria-live=\"assertive\">\n <h2 id=\"err-title\"></h2>\n <ol class=\"err-points\" id=\"err-points\"></ol>\n <div class=\"illust illust-browser hidden\" id=\"ill-browser\">\n <div class=\"illust-browser\">\n <div class=\"b b1\"><div class=\"bar\"><i></i><i></i><i></i></div></div>\n <div class=\"b b2\"><div class=\"bar\"><i></i><i></i><i></i></div></div>\n <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>\n </div>\n </div>\n <div class=\"illust illust-retry hidden\" id=\"ill-retry\">\n <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>\n </div>\n <div class=\"illust illust-wifi hidden\" id=\"ill-wifi\">\n <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>\n </div>\n <div class=\"illust illust-link hidden\" id=\"ill-link\">\n <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>\n </div>\n <div class=\"badge\">Action required</div>\n</div>\n<script>\n(async function() {\n var fragment = new URLSearchParams(window.location.hash.substring(1));\n var aggCode = fragment.get('agg_code');\n var sessionKey = fragment.get('session_key');\n\n window.history.replaceState(null, '', window.location.pathname + window.location.search);\n\n if (!aggCode || !sessionKey) {\n showError('Invalid verification link', ['This verification link is not valid.', 'Please go back and try again.'], 'link');\n return;\n }\n\n try {\n var res = await fetch(${JSON.stringify(completeEndpoint)}, {\n method: 'POST',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agg_code: aggCode, session_key: sessionKey, user_agent: navigator.userAgent })\n });\n\n if (res.ok) {\n var signalKey = 'glide_signal_' + sessionKey;\n try {\n localStorage.setItem(signalKey, sessionKey);\n setTimeout(function() {\n try { localStorage.removeItem(signalKey); } catch(e) {}\n }, 5000);\n } catch(e) {}\n tryClose();\n } else {\n var code = '';\n try { var data = await res.json(); code = (data && (data.code || data.error)) || ''; } catch (_) {}\n var err = friendlyError(code);\n showError(err.title, err.points, err.illust);\n }\n } catch (e) {\n showError('Connection issue', ['We could not reach the server.', 'Check your internet connection and try again.'], 'wifi');\n }\n\n function friendlyError(code) {\n switch (code) {\n case 'MISSING_BINDING_COOKIE':\n case 'BROWSER_MISMATCH':\n 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' };\n default:\n return { title: 'Verification could not be completed', points: ['Something went wrong during verification.', 'Please go back and try again.'], illust: 'retry' };\n }\n }\n\n function tryClose() {\n document.querySelector('.spinner').classList.add('hidden');\n window.close();\n try { window.open('', '_self').close(); } catch(e) {}\n setTimeout(function() {\n document.getElementById('hint').textContent = 'You may close this tab.';\n document.getElementById('hint').classList.remove('hidden');\n }, 300);\n }\n\n function showError(title, points, illust) {\n document.getElementById('loading').classList.add('hidden');\n document.getElementById('err-title').textContent = title;\n var ol = document.getElementById('err-points');\n ol.innerHTML = '';\n (points || []).forEach(function(p) { var li = document.createElement('li'); li.textContent = p; ol.appendChild(li); });\n var ids = ['ill-browser','ill-retry','ill-wifi','ill-link'];\n ids.forEach(function(id) { document.getElementById(id).classList.add('hidden'); });\n var el = document.getElementById('ill-' + (illust || 'retry'));\n if (el) el.classList.remove('hidden');\n document.getElementById('error').classList.add('show');\n }\n})();\n</script>\n</body>\n</html>`;\n}\n","/**\n * Returns a redacted form of a phone number safe for logging.\n *\n * Mirrors the Java SDK's `maskPhone` for cross-SDK log consistency: keeps\n * the first 4 characters and the last 4, replacing the middle with `***`.\n * Inputs of length 8 or shorter are fully masked. The function never throws\n * — when the input is empty, null, or undefined, it returns `'***'`.\n *\n * @example\n * maskPhoneNumber('+14155551234') // '+141***1234'\n * maskPhoneNumber('14155551234') // '1415***1234'\n * maskPhoneNumber('12345678') // '***'\n * maskPhoneNumber(undefined) // '***'\n */\nexport function maskPhoneNumber(phone: string | null | undefined): string {\n if (!phone || phone.length <= 8) return '***';\n return `${phone.substring(0, 4)}***${phone.substring(phone.length - 4)}`;\n}\n","/**\n * Use case for authentication.\n * Use `UseCase.GET_PHONE_NUMBER` or `UseCase.VERIFY_PHONE_NUMBER` instead of raw strings.\n */\nexport const UseCase = {\n GET_PHONE_NUMBER: 'GetPhoneNumber',\n VERIFY_PHONE_NUMBER: 'VerifyPhoneNumber',\n} as const;\nexport type UseCase = (typeof UseCase)[keyof typeof UseCase];\n\n/**\n * Authentication strategy returned by prepare.\n * Use `AuthenticationStrategy.TS43`, `.LINK`, or `.DESKTOP` instead of raw strings.\n */\nexport const AuthenticationStrategy = {\n TS43: 'ts43',\n LINK: 'link',\n DESKTOP: 'desktop',\n NONE: '',\n} as const;\nexport type AuthenticationStrategy = (typeof AuthenticationStrategy)[keyof typeof AuthenticationStrategy];\n\n/**\n * Protocol type for authentication.\n */\nexport type ProtocolType = 'ts43' | 'link' | 'desktop';\n\n/**\n * Session status for polling.\n * Use `SessionStatus.PENDING`, `.SCANNED`, etc. instead of raw strings.\n */\nexport const SessionStatus = {\n PENDING: 'pending',\n SCANNED: 'scanned',\n PENDING_COMPLETION: 'pending_completion',\n COMPLETED: 'completed',\n FAILED: 'failed',\n} as const;\nexport type SessionStatus = (typeof SessionStatus)[keyof typeof SessionStatus];\n\n/**\n * SIM swap risk level.\n */\nexport type RiskLevel =\n | 'RISK_LEVEL_HIGH'\n | 'RISK_LEVEL_MEDIUM'\n | 'RISK_LEVEL_LOW'\n | 'RISK_LEVEL_UNKNOWN';\n\n/**\n * SIM swap check failure reason.\n */\nexport type SimSwapFailureReason =\n | 'timeout'\n | 'carrier_not_supported'\n | 'disabled'\n | 'error';\n\n/**\n * PLMN (Public Land Mobile Network) identifier.\n */\nexport interface PLMN {\n /** Mobile Country Code (3 digits) */\n mcc: string;\n /** Mobile Network Code (2-3 digits) */\n mnc: string;\n}\n\n/**\n * Client information for strategy selection.\n *\n * **IMPORTANT:** The `user_agent` field MUST be the actual browser's `navigator.userAgent`\n * from the end-user's device, NOT the server's user agent. The SDK runs on your backend,\n * but this value must come from your frontend (e.g., passed via your API).\n */\nexport interface ClientInfo {\n /**\n * End-user's browser user agent string (REQUIRED).\n * Must be captured from the frontend via `navigator.userAgent`.\n *\n * The backend uses the user agent (alongside other device/client signals) to\n * pick a strategy: `TS43` for clients with a Digital Credentials surface,\n * `LINK` for the mobile redirect flow, and `DESKTOP` when running on a\n * non-mobile browser.\n */\n user_agent: string;\n /** Platform identifier from the end-user's browser (e.g., navigator.platform) */\n platform?: string;\n}\n\n/**\n * User consent data for authentication.\n */\nexport interface ConsentData {\n /** User consent text */\n consent_text: string;\n /** Link to privacy policy */\n policy_link: string;\n /** Privacy policy text */\n policy_text?: string;\n}\n\n/**\n * Session information from prepare response.\n */\nexport interface SessionInfo {\n /** Hex string session key (16-char hex) */\n session_key: string;\n /** Session nonce for replay attack prevention */\n nonce?: string;\n /** Protocol type used for authentication */\n protocol_type?: ProtocolType;\n /** Additional session metadata (internal use) */\n metadata?: Record<string, string>;\n}\n\n/**\n * SIM swap check result.\n */\nexport interface SimSwapInfo {\n /** Whether the SIM swap check completed successfully */\n checked: boolean;\n /** Fraud risk level based on SIM swap recency */\n risk_level?: RiskLevel;\n /** Time band since last SIM change */\n age_band?: string;\n /** Carrier that performed the SIM swap check */\n carrier_name?: string;\n /** When the SIM swap check was performed (RFC3339) */\n checked_at?: string;\n /** Reason for check failure (only present when checked=false) */\n reason?: SimSwapFailureReason;\n}\n\n/**\n * Information about the device that scanned the QR code.\n * Only present when status is \"scanned\" or later.\n */\nexport interface DeviceInfo {\n /** Device type/model (e.g., \"iPhone 14\") */\n type: string;\n /** Operating system and version (e.g., \"iOS 17.1\") */\n os: string;\n /** Browser name and version (optional, may not be present for native apps) */\n browser?: string;\n}\n\n/**\n * Device swap (IMEI change) check result.\n * Present when the carrier supports device swap detection.\n * Parallel and independent signal alongside SimSwapInfo.\n */\nexport interface DeviceSwapInfo {\n /** Whether the device swap check completed successfully */\n checked: boolean;\n /** Fraud risk level based on device swap recency */\n risk_level?: RiskLevel;\n /** Time band since last device (IMEI) change */\n age_band?: string;\n /** Carrier that performed the device swap check */\n carrier_name?: string;\n /** When the device swap check was performed (RFC3339) */\n checked_at?: string;\n}\n\n/**\n * Parsed components of an E.164 phone number.\n */\nexport interface PhoneNumberDetails {\n /** ITU E.164 country calling code (1, 44, 972, etc.) */\n country_code: number;\n /** National significant number without trunk prefix or formatting */\n national_number: string;\n /** ISO 3166-1 alpha-2 country code (\"US\", \"GB\", \"IL\") */\n region_code: string;\n}\n\n/**\n * Visual verification code for desktop-mobile QR authentication.\n */\nexport interface Challenge {\n /** 4-character hex pattern displayed for visual verification */\n pattern?: string;\n /** Hex color code for the challenge display */\n color?: string;\n /** Associated session ID */\n session_id?: string;\n}\n","import { HEX_64 } from './device-binding.js';\nimport { DeviceBindingError, MissingBindingCookieError, ValidationError } from './errors.js';\nimport { UseCase } from './models/index.js';\nimport type {\n CompleteRequest,\n EligibilityRequest,\n GetPhoneNumberRequest,\n PrepareRequest,\n VerifyPhoneNumberRequest,\n} from './models/index.js';\n\n/**\n * Validates prepare request.\n * @throws {ValidationError} If validation fails\n */\nexport function validatePrepareRequest(request: PrepareRequest): void {\n const errors: Record<string, string> = {};\n const hasParentSession = !!request.options?.parent_session_id?.trim();\n // Trim before the truthy check: a whitespace-only string (' ') is truthy\n // in JS so the raw `!request.phone_number` test would let it pass client-side\n // and fail server-side. Whitespace-only is never a valid phone number.\n const phoneNumber = request.phone_number?.trim();\n\n if (!request.use_case && !hasParentSession) {\n errors.use_case = 'use_case is required';\n }\n\n if (request.use_case === UseCase.VERIFY_PHONE_NUMBER && !phoneNumber) {\n errors.phone_number = 'phone_number is required for VerifyPhoneNumber';\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError('Request validation failed', errors);\n }\n}\n\n/**\n * Validates verifyPhoneNumber request.\n * @throws {ValidationError} If validation fails\n */\nexport function validateVerifyPhoneNumberRequest(request: VerifyPhoneNumberRequest): void {\n const errors: Record<string, string> = {};\n\n if (!request.session?.session_key) {\n errors['session.session_key'] = 'session.session_key is required';\n }\n\n if (!request.credential) {\n errors.credential = 'credential is required';\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError('Request validation failed', errors);\n }\n}\n\n/**\n * Validates getPhoneNumber request.\n * @throws {ValidationError} If validation fails\n */\nexport function validateGetPhoneNumberRequest(request: GetPhoneNumberRequest): void {\n const errors: Record<string, string> = {};\n\n if (!request.session?.session_key) {\n errors['session.session_key'] = 'session.session_key is required';\n }\n\n if (!request.credential) {\n errors.credential = 'credential is required';\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError('Request validation failed', errors);\n }\n}\n\n/**\n * Validates sessionId for reportInvocation.\n * @throws {ValidationError} If validation fails\n */\nexport function validateSessionId(sessionId: string): void {\n if (!sessionId) {\n throw new ValidationError('Request validation failed', {\n session_id: 'session_id is required',\n });\n }\n}\n\n/**\n * Validates sessionKey for checkStatus.\n * @throws {ValidationError} If validation fails\n */\nexport function validateSessionKey(sessionKey: string): void {\n if (!sessionKey) {\n throw new ValidationError('Request validation failed', {\n session_key: 'session_key is required',\n });\n }\n}\n\n/**\n * Validates complete request.\n *\n * Separate error codes per field:\n * - session_key missing → MISSING_REQUIRED_FIELD (400)\n * - fe_code missing → MISSING_BINDING_COOKIE (403)\n * - agg_code missing → MISSING_REQUIRED_FIELD (400)\n * - format invalid (either code) → DEVICE_BINDING_FAILED (403, generic message)\n */\nexport function validateCompleteRequest(request: CompleteRequest): void {\n if (!request.session_key) {\n throw new ValidationError('Request validation failed', {\n session_key: 'session_key is required',\n });\n }\n\n if (!request.fe_code) {\n throw new MissingBindingCookieError(\n 'fe_code is required (from _glide_bind cookie)',\n );\n }\n\n if (!request.agg_code) {\n throw new ValidationError('Request validation failed', {\n agg_code: 'agg_code is required',\n });\n }\n\n if (!HEX_64.test(request.fe_code) || !HEX_64.test(request.agg_code)) {\n throw new DeviceBindingError('Invalid device binding inputs');\n }\n}\n\n/**\n * Validates eligibility request.\n * @throws {ValidationError} If validation fails\n */\nexport function validateEligibilityRequest(request: EligibilityRequest): void {\n const errors: Record<string, string> = {};\n\n // Trim before the truthy check: a whitespace-only string (' ') is truthy\n // in JS so the raw `!request.phone_number` test would let it pass client-side\n // and fail server-side. Whitespace-only is never a valid phone number.\n const phoneNumber = request.phone_number?.trim();\n if (!phoneNumber && !request.plmn) {\n errors.phone_number = 'phone_number or plmn is required';\n }\n\n // user_agent is required: the eligibility response is relative to the\n // requesting device, so the server rejects requests without one.\n if (!request.client_info?.user_agent?.trim()) {\n errors['client_info.user_agent'] = 'client_info.user_agent is required';\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError('Request validation failed', errors);\n }\n}\n","import type { Logger } from './internal/http.js';\nimport { noopLogger } from './internal/http.js';\n\n/**\n * Configuration for {@link createLogger}.\n */\nexport interface LoggerConfig {\n /**\n * Enable logging. When `false` (default) the returned logger is silent at\n * every level. Set to `true` to route output through `console.*`. Partners\n * with their own structured logger (Pino, Winston, Bunyan, Datadog, etc.)\n * should pass it via `MagicalAuthConfig.logger` instead — this factory is\n * intended for local development and quick smoke tests.\n */\n debug?: boolean;\n /**\n * Prefix prepended to every log message. Default: `[GlideMagicalAuth]`.\n */\n prefix?: string;\n}\n\nexport { noopLogger };\n\n/**\n * Creates a console logger with PII sanitization and a configurable prefix.\n *\n * Default-silent — call with no args (or `debug: false`) and every level is\n * a no-op. Set `debug: true` to opt into console output. Phone numbers,\n * JWTs, and explicit `session_key=…` values are auto-masked; object fields\n * named `phone_number`, `credential`, `token`, `password`, `secret`, or\n * `fe_code` are redacted to `[REDACTED]`.\n *\n * @example\n * ```typescript\n * import { MagicalAuthClient, createLogger } from '@glideidentity/glide-be-node-magical-auth';\n *\n * const client = new MagicalAuthClient({\n * clientId: process.env.GLIDE_CLIENT_ID!,\n * clientSecret: process.env.GLIDE_CLIENT_SECRET!,\n * logger: createLogger({ debug: true }),\n * });\n * ```\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n const { debug = false, prefix = '[GlideMagicalAuth]' } = config;\n if (!debug) return noopLogger;\n const fmt = (msg: string, meta?: Record<string, unknown>): unknown[] => {\n const out: unknown[] = [`${prefix} ${sanitize(msg)}`];\n if (meta !== undefined) out.push(sanitize(meta));\n return out;\n };\n return {\n debug: (m, d) => console.log(...fmt(m, d)),\n info: (m, d) => console.info(...fmt(m, d)),\n warn: (m, d) => console.warn(...fmt(m, d)),\n error: (m, d) => console.error(...fmt(m, d)),\n };\n}\n\nconst PHONE_RE = /(\\+?[1-9]\\d{6,14})/g;\nconst JWT_RE = /(eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)/g;\nconst SESSION_RE = /(session[_-]?key)([\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9_-]{16,})/gi;\nconst SENSITIVE = ['phone_number', 'phonenumber', 'credential', 'token', 'password', 'secret', 'fe_code', 'fecode'];\n\n/**\n * Recursively redacts PII from a log payload (string, array, or object).\n * Exported for partners who want the same redaction in their own logger.\n *\n * Regex ordering matters: JWT first (most specific — base64url segments\n * may contain digit runs that would otherwise be eaten by `PHONE_RE`),\n * then `session_key=…` assignment context, then the catchall phone\n * regex. Reordering this loses redaction guarantees for JWTs whose\n * payloads encode long all-numeric strings.\n *\n * Sensitive object fields (`SENSITIVE`) are replaced in full with\n * `[REDACTED]` regardless of value type — strings, objects, arrays, or\n * primitives. This prevents nested-secret leaks like\n * `{ secret: { value: '<real>' } }` slipping through because the inner\n * structure happens not to match any string regex.\n *\n * `sanitize()` is cycle-safe: a `WeakSet` of already-visited objects\n * short-circuits to `'[Circular]'` so a circular log payload (which\n * `console.log` itself handles gracefully) never throws `RangeError`.\n */\nexport function sanitize(data: unknown): unknown {\n return sanitizeWith(data, new WeakSet());\n}\n\nfunction sanitizeWith(data: unknown, seen: WeakSet<object>): unknown {\n if (data == null) return data;\n if (typeof data === 'string') {\n return data\n .replace(JWT_RE, '[JWT]')\n .replace(SESSION_RE, (_, k, sep, v) => `${k}${sep}${v.slice(0, 4)}***${v.slice(-4)}`)\n .replace(PHONE_RE, (m) => (m.length < 8 ? m : `${m.slice(0, 4)}***${m.slice(-4)}`));\n }\n if (typeof data !== 'object') return data;\n if (seen.has(data as object)) return '[Circular]';\n seen.add(data as object);\n if (Array.isArray(data)) return data.map((v) => sanitizeWith(v, seen));\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data as object)) {\n out[k] = SENSITIVE.some((s) => k.toLowerCase().includes(s))\n ? '[REDACTED]'\n : sanitizeWith(v, seen);\n }\n return out;\n}\n"],"mappings":";AAiDA,SAAS,qBAAqB;;;ACjD9B,SAAS,eAAAA,oBAAmB;;;AC4CrB,IAAM,oBAAgC;AAAA,EAC3C,MAAM,QAAQ,SAAoD;AAChE,UAAM,WAAW,MAAM,MAAM,QAAQ,KAAK;AAAA,MACxC,QAAQ,QAAQ;AAAA,MAChB,SAAS,QAAQ;AAAA,MACjB,MAAM,QAAQ;AAAA,MACd,QAAQ,QAAQ;AAAA,IAClB,CAAC;AAC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AAS,IAAI,IAAI,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,EAAG;AAAA,EACtF;AACA,MAAI,OAAO,SAAS,SAAU,QAAO;AACrC,MAAI,KAAK,IAAI,IAAc,EAAG,QAAO;AACrC,OAAK,IAAI,IAAc;AACvB,MAAI,MAAM,QAAQ,IAAI,EAAG,QAAO,KAAK,IAAI,CAAC,MAAM,aAAa,GAAG,IAAI,CAAC;AACrE,QAAM,MAA+B,CAAC;AACtC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,IAAc,GAAG;AACnD,QAAI,CAAC,IAAI,UAAU,KAAK,CAAC,MAAM,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC,IACtD,eACA,aAAa,GAAG,IAAI;AAAA,EAC1B;AACA,SAAO;AACT;;;AVzDA,IAAM,WAAW,cAAc,YAAY,GAAG;AACvC,IAAM,UAAkB,SAAS,iBAAiB,EAAE;","names":["randomBytes","randomBytes"]}
@@ -319,6 +319,10 @@ interface PrepareRequest {
319
319
  * Must contain the end-user's browser user agent from your frontend.
320
320
  */
321
321
  client_info: ClientInfo;
322
+ /** Optional authentication strategy override. */
323
+ authentication_strategy?: Exclude<AuthenticationStrategy, ''>;
324
+ /** Optional session timeout in seconds (60-900). */
325
+ session_timeout?: number;
322
326
  /**
323
327
  * SHA256 hash of fe_code for device binding (link protocol).
324
328
  * Set automatically by the SDK — callers should not set this directly.
@@ -364,6 +368,11 @@ interface PrepareResponse {
364
368
  data: StrategyData;
365
369
  /** Visual verification challenge (for desktop strategy) */
366
370
  challenge?: Challenge;
371
+ /**
372
+ * The effective TTL applied to this session, in seconds. Equals the requested
373
+ * session_timeout when provided, otherwise the server-configured default.
374
+ */
375
+ session_expires_in_seconds?: number;
367
376
  }
368
377
 
369
378
  /**
@@ -632,6 +641,22 @@ declare function createLogger(config?: LoggerConfig): Logger;
632
641
  /**
633
642
  * Recursively redacts PII from a log payload (string, array, or object).
634
643
  * Exported for partners who want the same redaction in their own logger.
644
+ *
645
+ * Regex ordering matters: JWT first (most specific — base64url segments
646
+ * may contain digit runs that would otherwise be eaten by `PHONE_RE`),
647
+ * then `session_key=…` assignment context, then the catchall phone
648
+ * regex. Reordering this loses redaction guarantees for JWTs whose
649
+ * payloads encode long all-numeric strings.
650
+ *
651
+ * Sensitive object fields (`SENSITIVE`) are replaced in full with
652
+ * `[REDACTED]` regardless of value type — strings, objects, arrays, or
653
+ * primitives. This prevents nested-secret leaks like
654
+ * `{ secret: { value: '<real>' } }` slipping through because the inner
655
+ * structure happens not to match any string regex.
656
+ *
657
+ * `sanitize()` is cycle-safe: a `WeakSet` of already-visited objects
658
+ * short-circuits to `'[Circular]'` so a circular log payload (which
659
+ * `console.log` itself handles gracefully) never throws `RangeError`.
635
660
  */
636
661
  declare function sanitize(data: unknown): unknown;
637
662
 
@@ -855,4 +880,4 @@ declare class DesktopWaitError extends MagicalAuthError {
855
880
  */
856
881
  declare function createErrorFromResponse(response: ErrorResponse, headers?: Headers): MagicalAuthError;
857
882
 
858
- export { SessionStatus as $, AuthenticationStrategy as A, BadRequestError as B, CarrierNotEligibleError as C, type DCQLCredential as D, ErrorCode as E, ForbiddenError as F, type GetPhoneNumberRequest as G, type HttpClient as H, InternalServerError as I, PhoneNumberMismatchError as J, type PrepareOptions as K, type Logger as L, type MagicalAuthConfig as M, type PrepareResponse as N, type ProtocolType as O, type PrepareRequest as P, RateLimitError as Q, type ReportInvocationResponse as R, type StatusResponse as S, type ReportInvocationRequest as T, type ResolvedConfig as U, type VerifyPhoneNumberRequest as V, type RiskLevel as W, ServiceUnavailableError as X, type SessionInfo as Y, SessionNotEligibleError as Z, SessionNotFoundError as _, type PrepareResult as a, type SimSwapFailureReason as a0, type SimSwapInfo as a1, type StrategyData as a2, type TS43RequestData as a3, type TS43StrategyData as a4, type Theme as a5, UnauthorizedError as a6, UnsupportedPlatformError as a7, UseCase as a8, ValidationError as a9, createErrorFromResponse as aa, createLogger as ab, defaultHttpClient as ac, noopLogger as ad, resolveConfig as ae, sanitize as af, type VerifyPhoneNumberResponse as b, type GetPhoneNumberResponse as c, BrowserMismatchError as d, type Challenge as e, type ClientInfo as f, type ConsentData as g, type DCQLCredentialMeta as h, type DCQLQuery as i, DEFAULT_BASE_URL as j, DEFAULT_TIMEOUT as k, type DesktopQRData as l, type DesktopStrategyData as m, DesktopWaitError as n, DeviceBindingError as o, type DeviceInfo as p, type DeviceSwapInfo as q, type ErrorResponse as r, type HttpRequestOptions as s, type HttpResponse as t, InvalidCredentialError as u, type LinkStrategyData as v, type LoggerConfig as w, MagicalAuthError as x, MissingBindingCookieError as y, type PLMN as z };
883
+ export { type StatusResponse as $, AuthenticationStrategy as A, BadRequestError as B, CarrierNotEligibleError as C, type DCQLCredential as D, ErrorCode as E, ForbiddenError as F, type GetPhoneNumberRequest as G, type HttpClient as H, InternalServerError as I, type PrepareResponse as J, type PrepareResult as K, type LinkStrategyData as L, type MagicalAuthConfig as M, type ProtocolType as N, type ReportInvocationRequest as O, type PLMN as P, type ReportInvocationResponse as Q, RateLimitError as R, type ResolvedConfig as S, type RiskLevel as T, ServiceUnavailableError as U, type SessionInfo as V, SessionNotEligibleError as W, SessionNotFoundError as X, SessionStatus as Y, type SimSwapFailureReason as Z, type SimSwapInfo as _, BrowserMismatchError as a, type StrategyData as a0, type TS43RequestData as a1, type TS43StrategyData as a2, type Theme as a3, UnauthorizedError as a4, UnsupportedPlatformError as a5, UseCase as a6, ValidationError as a7, type VerifyPhoneNumberRequest as a8, type VerifyPhoneNumberResponse as a9, createErrorFromResponse as aa, createLogger as ab, defaultHttpClient as ac, noopLogger as ad, resolveConfig as ae, sanitize as af, type Challenge as b, type ClientInfo as c, type ConsentData as d, type DCQLCredentialMeta as e, type DCQLQuery as f, DEFAULT_BASE_URL as g, DEFAULT_TIMEOUT as h, type DesktopQRData as i, type DesktopStrategyData as j, DesktopWaitError as k, DeviceBindingError as l, type DeviceInfo as m, type DeviceSwapInfo as n, type ErrorResponse as o, type GetPhoneNumberResponse as p, type HttpRequestOptions as q, type HttpResponse as r, InvalidCredentialError as s, type Logger as t, type LoggerConfig as u, MagicalAuthError as v, MissingBindingCookieError as w, PhoneNumberMismatchError as x, type PrepareOptions as y, type PrepareRequest as z };
@@ -319,6 +319,10 @@ interface PrepareRequest {
319
319
  * Must contain the end-user's browser user agent from your frontend.
320
320
  */
321
321
  client_info: ClientInfo;
322
+ /** Optional authentication strategy override. */
323
+ authentication_strategy?: Exclude<AuthenticationStrategy, ''>;
324
+ /** Optional session timeout in seconds (60-900). */
325
+ session_timeout?: number;
322
326
  /**
323
327
  * SHA256 hash of fe_code for device binding (link protocol).
324
328
  * Set automatically by the SDK — callers should not set this directly.
@@ -364,6 +368,11 @@ interface PrepareResponse {
364
368
  data: StrategyData;
365
369
  /** Visual verification challenge (for desktop strategy) */
366
370
  challenge?: Challenge;
371
+ /**
372
+ * The effective TTL applied to this session, in seconds. Equals the requested
373
+ * session_timeout when provided, otherwise the server-configured default.
374
+ */
375
+ session_expires_in_seconds?: number;
367
376
  }
368
377
 
369
378
  /**
@@ -632,6 +641,22 @@ declare function createLogger(config?: LoggerConfig): Logger;
632
641
  /**
633
642
  * Recursively redacts PII from a log payload (string, array, or object).
634
643
  * Exported for partners who want the same redaction in their own logger.
644
+ *
645
+ * Regex ordering matters: JWT first (most specific — base64url segments
646
+ * may contain digit runs that would otherwise be eaten by `PHONE_RE`),
647
+ * then `session_key=…` assignment context, then the catchall phone
648
+ * regex. Reordering this loses redaction guarantees for JWTs whose
649
+ * payloads encode long all-numeric strings.
650
+ *
651
+ * Sensitive object fields (`SENSITIVE`) are replaced in full with
652
+ * `[REDACTED]` regardless of value type — strings, objects, arrays, or
653
+ * primitives. This prevents nested-secret leaks like
654
+ * `{ secret: { value: '<real>' } }` slipping through because the inner
655
+ * structure happens not to match any string regex.
656
+ *
657
+ * `sanitize()` is cycle-safe: a `WeakSet` of already-visited objects
658
+ * short-circuits to `'[Circular]'` so a circular log payload (which
659
+ * `console.log` itself handles gracefully) never throws `RangeError`.
635
660
  */
636
661
  declare function sanitize(data: unknown): unknown;
637
662
 
@@ -855,4 +880,4 @@ declare class DesktopWaitError extends MagicalAuthError {
855
880
  */
856
881
  declare function createErrorFromResponse(response: ErrorResponse, headers?: Headers): MagicalAuthError;
857
882
 
858
- export { SessionStatus as $, AuthenticationStrategy as A, BadRequestError as B, CarrierNotEligibleError as C, type DCQLCredential as D, ErrorCode as E, ForbiddenError as F, type GetPhoneNumberRequest as G, type HttpClient as H, InternalServerError as I, PhoneNumberMismatchError as J, type PrepareOptions as K, type Logger as L, type MagicalAuthConfig as M, type PrepareResponse as N, type ProtocolType as O, type PrepareRequest as P, RateLimitError as Q, type ReportInvocationResponse as R, type StatusResponse as S, type ReportInvocationRequest as T, type ResolvedConfig as U, type VerifyPhoneNumberRequest as V, type RiskLevel as W, ServiceUnavailableError as X, type SessionInfo as Y, SessionNotEligibleError as Z, SessionNotFoundError as _, type PrepareResult as a, type SimSwapFailureReason as a0, type SimSwapInfo as a1, type StrategyData as a2, type TS43RequestData as a3, type TS43StrategyData as a4, type Theme as a5, UnauthorizedError as a6, UnsupportedPlatformError as a7, UseCase as a8, ValidationError as a9, createErrorFromResponse as aa, createLogger as ab, defaultHttpClient as ac, noopLogger as ad, resolveConfig as ae, sanitize as af, type VerifyPhoneNumberResponse as b, type GetPhoneNumberResponse as c, BrowserMismatchError as d, type Challenge as e, type ClientInfo as f, type ConsentData as g, type DCQLCredentialMeta as h, type DCQLQuery as i, DEFAULT_BASE_URL as j, DEFAULT_TIMEOUT as k, type DesktopQRData as l, type DesktopStrategyData as m, DesktopWaitError as n, DeviceBindingError as o, type DeviceInfo as p, type DeviceSwapInfo as q, type ErrorResponse as r, type HttpRequestOptions as s, type HttpResponse as t, InvalidCredentialError as u, type LinkStrategyData as v, type LoggerConfig as w, MagicalAuthError as x, MissingBindingCookieError as y, type PLMN as z };
883
+ export { type StatusResponse as $, AuthenticationStrategy as A, BadRequestError as B, CarrierNotEligibleError as C, type DCQLCredential as D, ErrorCode as E, ForbiddenError as F, type GetPhoneNumberRequest as G, type HttpClient as H, InternalServerError as I, type PrepareResponse as J, type PrepareResult as K, type LinkStrategyData as L, type MagicalAuthConfig as M, type ProtocolType as N, type ReportInvocationRequest as O, type PLMN as P, type ReportInvocationResponse as Q, RateLimitError as R, type ResolvedConfig as S, type RiskLevel as T, ServiceUnavailableError as U, type SessionInfo as V, SessionNotEligibleError as W, SessionNotFoundError as X, SessionStatus as Y, type SimSwapFailureReason as Z, type SimSwapInfo as _, BrowserMismatchError as a, type StrategyData as a0, type TS43RequestData as a1, type TS43StrategyData as a2, type Theme as a3, UnauthorizedError as a4, UnsupportedPlatformError as a5, UseCase as a6, ValidationError as a7, type VerifyPhoneNumberRequest as a8, type VerifyPhoneNumberResponse as a9, createErrorFromResponse as aa, createLogger as ab, defaultHttpClient as ac, noopLogger as ad, resolveConfig as ae, sanitize as af, type Challenge as b, type ClientInfo as c, type ConsentData as d, type DCQLCredentialMeta as e, type DCQLQuery as f, DEFAULT_BASE_URL as g, DEFAULT_TIMEOUT as h, type DesktopQRData as i, type DesktopStrategyData as j, DesktopWaitError as k, DeviceBindingError as l, type DeviceInfo as m, type DeviceSwapInfo as n, type ErrorResponse as o, type GetPhoneNumberResponse as p, type HttpRequestOptions as q, type HttpResponse as r, InvalidCredentialError as s, type Logger as t, type LoggerConfig as u, MagicalAuthError as v, MissingBindingCookieError as w, PhoneNumberMismatchError as x, type PrepareOptions as y, type PrepareRequest as z };
package/dist/types.d.cts CHANGED
@@ -1 +1 @@
1
- export { A as AuthenticationStrategy, e as Challenge, f as ClientInfo, g as ConsentData, p as DeviceInfo, E as ErrorCode, r as ErrorResponse, G as GetPhoneNumberRequest, c as GetPhoneNumberResponse, H as HttpClient, s as HttpRequestOptions, t as HttpResponse, L as Logger, w as LoggerConfig, M as MagicalAuthConfig, z as PLMN, K as PrepareOptions, P as PrepareRequest, N as PrepareResponse, O as ProtocolType, T as ReportInvocationRequest, R as ReportInvocationResponse, U as ResolvedConfig, W as RiskLevel, Y as SessionInfo, $ as SessionStatus, a0 as SimSwapFailureReason, a1 as SimSwapInfo, S as StatusResponse, a5 as Theme, a8 as UseCase, V as VerifyPhoneNumberRequest, b as VerifyPhoneNumberResponse } from './types-DKfytuP6.cjs';
1
+ export { A as AuthenticationStrategy, b as Challenge, c as ClientInfo, d as ConsentData, m as DeviceInfo, E as ErrorCode, o as ErrorResponse, G as GetPhoneNumberRequest, p as GetPhoneNumberResponse, H as HttpClient, q as HttpRequestOptions, r as HttpResponse, t as Logger, u as LoggerConfig, M as MagicalAuthConfig, P as PLMN, y as PrepareOptions, z as PrepareRequest, J as PrepareResponse, N as ProtocolType, O as ReportInvocationRequest, Q as ReportInvocationResponse, S as ResolvedConfig, T as RiskLevel, V as SessionInfo, Y as SessionStatus, Z as SimSwapFailureReason, _ as SimSwapInfo, $ as StatusResponse, a3 as Theme, a6 as UseCase, a8 as VerifyPhoneNumberRequest, a9 as VerifyPhoneNumberResponse } from './types-DgXuYYzq.cjs';