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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiDA,yBAA8B;;;ACjD9B,IAAAA,sBAA4B;;;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;AA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G,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,EAAG,EACjF,QAAQ,QAAQ,OAAO,EACvB,QAAQ,YAAY,CAAC,GAAG,GAAG,KAAK,MAAM,GAAG,CAAC,GAAG,GAAG,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE;AAAA,EACxF;AACA,MAAI,MAAM,QAAQ,IAAI,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;;;AVvFA;AAkDA,IAAM,eAAW,kCAAc,YAAY,GAAG;AACvC,IAAM,UAAkB,SAAS,iBAAiB,EAAE;","names":["import_node_crypto"]}
@@ -0,0 +1,419 @@
1
+ import { M as MagicalAuthConfig, P as PrepareRequest, a as PrepareResult, V as VerifyPhoneNumberRequest, b as VerifyPhoneNumberResponse, G as GetPhoneNumberRequest, c as GetPhoneNumberResponse, R as ReportInvocationResponse, S as StatusResponse, H as HttpClient, L as Logger } from './types-DKfytuP6.cjs';
2
+ export { A as AuthenticationStrategy, B as BadRequestError, d as BrowserMismatchError, C as CarrierNotEligibleError, e as Challenge, f as ClientInfo, g as ConsentData, D as DCQLCredential, h as DCQLCredentialMeta, i as DCQLQuery, j as DEFAULT_BASE_URL, k as DEFAULT_TIMEOUT, l as DesktopQRData, m as DesktopStrategyData, n as DesktopWaitError, o as DeviceBindingError, p as DeviceInfo, q as DeviceSwapInfo, E as ErrorCode, r as ErrorResponse, F as ForbiddenError, s as HttpRequestOptions, t as HttpResponse, I as InternalServerError, u as InvalidCredentialError, v as LinkStrategyData, w as LoggerConfig, x as MagicalAuthError, y as MissingBindingCookieError, z as PLMN, J as PhoneNumberMismatchError, K as PrepareOptions, N as PrepareResponse, O as ProtocolType, Q as RateLimitError, T as ReportInvocationRequest, U as ResolvedConfig, W as RiskLevel, X as ServiceUnavailableError, Y as SessionInfo, Z as SessionNotEligibleError, _ as SessionNotFoundError, $ as SessionStatus, a0 as SimSwapFailureReason, a1 as SimSwapInfo, a2 as StrategyData, a3 as TS43RequestData, a4 as TS43StrategyData, a5 as Theme, a6 as UnauthorizedError, a7 as UnsupportedPlatformError, a8 as UseCase, a9 as ValidationError, aa as createErrorFromResponse, ab as createLogger, ac as defaultHttpClient, ad as noopLogger, ae as resolveConfig, af as sanitize } from './types-DKfytuP6.cjs';
3
+
4
+ /**
5
+ * Request body for device-bound session completion (link protocol only).
6
+ *
7
+ * Both codes prove device binding:
8
+ * - `fe_code`: proves same browser (HttpOnly cookie set by developer backend)
9
+ * - `agg_code`: proves same device received the carrier redirect (URL fragment)
10
+ */
11
+ interface CompleteRequest {
12
+ /** The 16-character hex session key from the prepare response */
13
+ session_key: string;
14
+ /** Frontend binding code from the _glide_bind HttpOnly cookie */
15
+ fe_code: string;
16
+ /** Aggregator binding code from the carrier redirect URL fragment */
17
+ agg_code: string;
18
+ /** Browser User-Agent from the completion page (optional, enables browser mismatch detection) */
19
+ user_agent?: string;
20
+ }
21
+ /**
22
+ * Response from the `/complete` endpoint.
23
+ * Returned after successful device binding validation.
24
+ */
25
+ interface CompleteResponse {
26
+ /** Session status after successful device binding validation (always "completed") */
27
+ status: 'completed';
28
+ }
29
+ /**
30
+ * Returned with HTTP 202 when a desktop (QR) session's wait timer expires
31
+ * before the mobile device completes authentication.
32
+ *
33
+ * The SDK throws a `DesktopWaitError` carrying this response.
34
+ * Callers implement their own retry loop based on `retry` and `session_expires_in_seconds`.
35
+ */
36
+ interface DesktopWaitResponse {
37
+ /** Always "waiting" for this response type */
38
+ status: 'waiting';
39
+ /** Human-readable explanation */
40
+ message: string;
41
+ /** The session key (same as the one sent in the request) */
42
+ session_key: string;
43
+ /** Current session status at the time of the timeout */
44
+ session_status: string;
45
+ /** Whether the SDK should retry the request */
46
+ retry: boolean;
47
+ /** Approximate seconds until the session expires */
48
+ session_expires_in_seconds: number;
49
+ }
50
+
51
+ /**
52
+ * Per-request options for API calls.
53
+ */
54
+ interface RequestOptions {
55
+ /** Correlation ID forwarded as X-Correlation-ID header for request tracing */
56
+ correlationId?: string;
57
+ }
58
+ /**
59
+ * Magical Auth SDK client for phone number authentication.
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const client = new MagicalAuthClient({
64
+ * clientId: 'your-client-id',
65
+ * clientSecret: 'your-client-secret',
66
+ * });
67
+ *
68
+ * // Prepare authentication (auto-generates device binding codes)
69
+ * const result = await client.prepare({
70
+ * phone_number: '+14155551234',
71
+ * nonce: 'unique-nonce',
72
+ * use_case: 'VerifyPhoneNumber',
73
+ * client_info: { user_agent: req.headers['user-agent'] },
74
+ * });
75
+ *
76
+ * // For link protocol, set the binding cookie
77
+ * if (result.feCode) {
78
+ * res.setHeader('Set-Cookie', buildSetBindingCookieHeader(result.feCode, result.session.session_key));
79
+ * }
80
+ * ```
81
+ */
82
+ declare class MagicalAuthClient {
83
+ private readonly config;
84
+ private readonly tokenManager;
85
+ /**
86
+ * Creates a new MagicalAuthClient instance.
87
+ *
88
+ * @param config - Client configuration
89
+ * @throws {Error} If clientId or clientSecret is missing
90
+ */
91
+ constructor(config: MagicalAuthConfig);
92
+ /**
93
+ * Prepares authentication by checking carrier eligibility and generating protocol-specific requests.
94
+ *
95
+ * Automatically generates `fe_code` / `fe_hash` for device binding. If the aggregator
96
+ * selects the 'link' strategy, `feCode` is included in the result so the caller can
97
+ * set it as an HttpOnly cookie via `buildSetBindingCookieHeader()`.
98
+ *
99
+ * @param request - Prepare request parameters
100
+ * @param options - Per-request options (e.g., correlationId)
101
+ * @returns Prepare result with authentication strategy, session info, and optional feCode
102
+ * @throws {ValidationError} If request validation fails
103
+ * @throws {CarrierNotEligibleError} If carrier is not eligible
104
+ * @throws {MagicalAuthError} For other API errors
105
+ */
106
+ prepare(request: PrepareRequest, options?: RequestOptions): Promise<PrepareResult>;
107
+ /**
108
+ * Validates device binding codes and completes a link protocol session.
109
+ *
110
+ * Called after the carrier OAuth redirect lands on the developer's completion page.
111
+ * The completion page extracts `agg_code` + `session_key` from the URL fragment
112
+ * and the developer's handler reads `fe_code` from the `_glide_bind` cookie.
113
+ *
114
+ * @param request - Complete request with session_key, fe_code, and agg_code
115
+ * @param options - Per-request options (e.g., correlationId)
116
+ * @returns Complete response with status
117
+ * @throws {DeviceBindingError} If binding code validation fails
118
+ * @throws {SessionNotFoundError} If session not found or expired
119
+ * @throws {SessionNotEligibleError} If session not in pending_completion status
120
+ * @throws {BrowserMismatchError} If browser differs from the one used in prepare
121
+ * @throws {MagicalAuthError} For other API errors
122
+ */
123
+ complete(request: CompleteRequest, options?: RequestOptions): Promise<CompleteResponse>;
124
+ /**
125
+ * Verifies a phone number using digital credentials.
126
+ *
127
+ * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.
128
+ *
129
+ * @param request - Verify request with session and credential
130
+ * @param options - Per-request options (e.g., correlationId)
131
+ * @returns Verification result with phone number and verified status
132
+ * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info
133
+ * @throws {SessionNotFoundError} If session not found or expired
134
+ * @throws {InvalidCredentialError} If credential format is invalid
135
+ * @throws {MagicalAuthError} For other API errors
136
+ */
137
+ verifyPhoneNumber(request: VerifyPhoneNumberRequest, options?: RequestOptions): Promise<VerifyPhoneNumberResponse>;
138
+ /**
139
+ * Retrieves the phone number associated with the device using digital credentials.
140
+ *
141
+ * For device-bound link sessions, include `fe_code` from the `_glide_bind` cookie.
142
+ *
143
+ * @param request - Get phone number request with session and credential
144
+ * @param options - Per-request options (e.g., correlationId)
145
+ * @returns Response with the retrieved phone number
146
+ * @throws {DesktopWaitError} If the desktop session is still waiting (HTTP 202) — inspect `waitResponse` for retry info
147
+ * @throws {SessionNotFoundError} If session not found or expired
148
+ * @throws {InvalidCredentialError} If credential format is invalid
149
+ * @throws {MagicalAuthError} For other API errors
150
+ */
151
+ getPhoneNumber(request: GetPhoneNumberRequest, options?: RequestOptions): Promise<GetPhoneNumberResponse>;
152
+ /**
153
+ * Reports when a user clicks the invoke/authenticate button.
154
+ *
155
+ * Used for Authentication Success Rate (ASR) tracking and analytics.
156
+ *
157
+ * @param sessionId - The session identifier
158
+ * @param options - Per-request options (e.g., correlationId)
159
+ * @returns Report response with a boolean `success` flag
160
+ * @throws {SessionNotFoundError} If session not found
161
+ * @throws {MagicalAuthError} For other API errors
162
+ */
163
+ reportInvocation(sessionId: string, options?: RequestOptions): Promise<ReportInvocationResponse>;
164
+ /**
165
+ * Polls for the status of an ongoing verification request (protected endpoint).
166
+ *
167
+ * @param sessionKey - The 64-character hex session key from prepare response
168
+ * @param options - Per-request options (e.g., correlationId)
169
+ * @returns Status response with current verification state
170
+ * @throws {SessionNotFoundError} If session not found or expired
171
+ * @throws {MagicalAuthError} For other API errors
172
+ */
173
+ checkStatus(sessionKey: string, options?: RequestOptions): Promise<StatusResponse>;
174
+ /**
175
+ * Polls for the status of an ongoing verification request (public endpoint).
176
+ *
177
+ * This endpoint does not require authentication.
178
+ *
179
+ * @param sessionKey - The 64-character hex session key from prepare response
180
+ * @param options - Per-request options (e.g., correlationId)
181
+ * @returns Status response with current verification state
182
+ * @throws {SessionNotFoundError} If session not found or expired
183
+ * @throws {MagicalAuthError} For other API errors
184
+ */
185
+ checkStatusPublic(sessionKey: string, options?: RequestOptions): Promise<StatusResponse>;
186
+ /**
187
+ * Makes an authenticated API request.
188
+ */
189
+ private doRequest;
190
+ /**
191
+ * Makes an unauthenticated API request (for public endpoints).
192
+ */
193
+ private doRequestWithoutAuth;
194
+ /**
195
+ * Handles API response, parsing JSON and converting errors.
196
+ * Throws DesktopWaitError for HTTP 202 responses.
197
+ */
198
+ private handleResponse;
199
+ /**
200
+ * Invalidates the cached access token.
201
+ */
202
+ invalidateToken(): void;
203
+ }
204
+
205
+ /**
206
+ * Manages OAuth2 access tokens with automatic caching and refresh.
207
+ *
208
+ * Thread-safe through promise deduplication - concurrent calls to getToken()
209
+ * will share the same in-flight request rather than making multiple requests.
210
+ */
211
+ declare class TokenManager {
212
+ private readonly clientId;
213
+ private readonly clientSecret;
214
+ private readonly tokenUrl;
215
+ private readonly httpClient;
216
+ private readonly logger;
217
+ private token;
218
+ private expiresAt;
219
+ private refreshPromise;
220
+ /** Buffer time in ms before expiry to refresh token (60 seconds) */
221
+ private readonly bufferMs;
222
+ constructor(clientId: string, clientSecret: string, tokenUrl: string, httpClient: HttpClient, logger?: Logger);
223
+ /**
224
+ * Gets a valid access token, refreshing if necessary.
225
+ *
226
+ * This method is safe for concurrent calls - if a refresh is already
227
+ * in progress, subsequent calls will await the same promise.
228
+ *
229
+ * @returns A valid access token
230
+ * @throws {UnauthorizedError} If token fetch fails
231
+ */
232
+ getToken(): Promise<string>;
233
+ /**
234
+ * Fetches a new access token from the OAuth2 endpoint.
235
+ */
236
+ private fetchToken;
237
+ /**
238
+ * Invalidates the cached token, forcing a refresh on next getToken() call.
239
+ * Useful when receiving a 401 response from the API.
240
+ */
241
+ invalidate(): void;
242
+ /**
243
+ * Checks if there's a valid cached token.
244
+ * @returns true if a valid token exists
245
+ */
246
+ hasValidToken(): boolean;
247
+ }
248
+
249
+ /**
250
+ * Regex matching a valid 64-character hex string (case-insensitive).
251
+ *
252
+ * Accepts both lowercase and uppercase hex so that external inputs (URL
253
+ * fragments, cookie values) still pass validation even if a proxy or
254
+ * browser extension uppercases them. Internal code normalises to
255
+ * lowercase before hashing or sending to the aggregator.
256
+ */
257
+ declare const HEX_64: RegExp;
258
+ /** Cookie name prefix for device binding codes. Append the session key for the full name. */
259
+ declare const BINDING_COOKIE_PREFIX = "_glide_bind_";
260
+ /**
261
+ * Cookie max-age in seconds. Set to 5 minutes — sufficient for the carrier
262
+ * authentication round-trip (typically under 2 minutes). The cookie auto-expires
263
+ * after this period, so explicit clearing is optional.
264
+ */
265
+ declare const BINDING_COOKIE_MAX_AGE = 300;
266
+ /**
267
+ * Keys that MUST be redacted in logs to prevent leaking binding secrets.
268
+ * Covers snake_case, camelCase, and collapsed forms.
269
+ */
270
+ declare const SENSITIVE_KEYS: readonly string[];
271
+ /**
272
+ * Options for building binding cookie headers.
273
+ */
274
+ interface BindingCookieOptions {
275
+ /** Cookie domain (must match the completion redirect URL domain) */
276
+ domain?: string;
277
+ /** Cookie path (default: "/") — must start with "/" */
278
+ path?: string;
279
+ /** Secure flag (default: true — set false for local HTTP dev only) */
280
+ secure?: boolean;
281
+ }
282
+ /**
283
+ * Returns the full cookie name for a given session key.
284
+ *
285
+ * Using a session-scoped name (`_glide_bind_{sessionKey}`) ensures that
286
+ * parallel `prepare()` calls from the same browser don't overwrite each
287
+ * other's cookies — each session gets its own cookie.
288
+ */
289
+ declare function getBindingCookieName(sessionKey: string): string;
290
+ /**
291
+ * Asserts that the given value is a valid 64-character hex string.
292
+ * @throws {Error} If the value does not match.
293
+ */
294
+ declare function assertValidFeCode(feCode: string): void;
295
+ /**
296
+ * Generates a cryptographically random fe_code (32 random bytes -> 64-char lowercase hex).
297
+ */
298
+ declare function generateFeCode(): string;
299
+ /**
300
+ * Computes SHA256(fe_code) -> 64-char lowercase hex hash.
301
+ * Input is normalised to lowercase for deterministic hashing.
302
+ *
303
+ * @throws {Error} If feCode is not a valid 64-character hex string
304
+ */
305
+ declare function computeFeHash(feCode: string): string;
306
+ /**
307
+ * Builds a Set-Cookie header value that sets the device binding cookie.
308
+ *
309
+ * @param feCode - The binding code to store (64-char hex, normalised to lowercase)
310
+ * @param sessionKey - Session key used in the cookie name to avoid collisions between parallel sessions
311
+ * @param options - Cookie options (domain, path, secure)
312
+ * @returns Raw Set-Cookie header value string
313
+ * @throws {Error} If feCode is invalid or options contain injection characters
314
+ */
315
+ declare function buildSetBindingCookieHeader(feCode: string, sessionKey: string, options?: BindingCookieOptions): string;
316
+ /**
317
+ * Builds a Set-Cookie header value that clears the device binding cookie.
318
+ *
319
+ * @param sessionKey - Session key identifying which session's cookie to clear
320
+ * @param options - Cookie options (must match the original cookie)
321
+ * @returns Raw Set-Cookie header value string that expires the cookie
322
+ * @throws {Error} If options contain injection characters
323
+ */
324
+ declare function buildClearBindingCookieHeader(sessionKey: string, options?: BindingCookieOptions): string;
325
+ /**
326
+ * Parses the fe_code from a raw Cookie header string for a specific session.
327
+ *
328
+ * Returns `undefined` if the cookie is not present or the value is not
329
+ * a valid 64-character hex string. When found, the value is normalised
330
+ * to lowercase for deterministic hashing downstream.
331
+ *
332
+ * @param cookieHeader - Raw Cookie header value (e.g., "foo=bar; _glide_bind_abc123=...")
333
+ * @param sessionKey - Session key identifying which cookie to look for
334
+ * @returns The fe_code value (lowercase), or undefined if missing/invalid
335
+ */
336
+ declare function parseBindingCookie(cookieHeader: string | undefined, sessionKey: string): string | undefined;
337
+ /**
338
+ * Builds Set-Cookie headers that expire every existing device binding cookie
339
+ * (`_glide_bind_*`) found in the request.
340
+ *
341
+ * Binding cookies are session-scoped (`_glide_bind_{sessionKey}`) and
342
+ * auto-expire after `BINDING_COOKIE_MAX_AGE` seconds, so cleanup is normally
343
+ * handled by the TTL. This helper is a tidying utility for partners who want
344
+ * to explicitly clear stale cookies (for example on logout, on session
345
+ * cancellation, or before issuing a fresh `prepare()` from a long-lived
346
+ * browser session) without waiting for the TTL.
347
+ *
348
+ * @param cookieHeader - Raw Cookie request header
349
+ * @param options - Cookie options (must match the original set call)
350
+ * @returns Array of Set-Cookie header values that expire stale binding cookies
351
+ */
352
+ declare function clearStaleBindingCookies(cookieHeader: string | undefined, options?: BindingCookieOptions): string[];
353
+ /**
354
+ * Returns the HTML for the completion redirect page.
355
+ *
356
+ * This page extracts `agg_code` and `session_key` from the URL fragment,
357
+ * POSTs them to the developer's backend (which auto-includes the
358
+ * `_glide_bind_{sessionKey}` HttpOnly cookie), and displays the result.
359
+ *
360
+ * On successful completion, a localStorage signal is written
361
+ * (`glide_signal_{session_key}`) so the FE SDK in the original tab can
362
+ * detect completion via `StorageEvent` without polling.
363
+ *
364
+ * @param completeEndpoint - Relative path to POST to (e.g., "/api/glide/complete")
365
+ * @returns Complete HTML string ready to serve
366
+ * @throws {Error} If completeEndpoint is not a relative path starting with "/"
367
+ */
368
+ declare function getCompletionPageHtml(completeEndpoint: string): string;
369
+
370
+ /**
371
+ * Glide Magical Auth SDK for Node.js
372
+ *
373
+ * Phone number authentication without SMS/OTP using carrier-based digital credentials.
374
+ *
375
+ * @packageDocumentation
376
+ *
377
+ * @example
378
+ * ```typescript
379
+ * import {
380
+ * MagicalAuthClient,
381
+ * UseCase,
382
+ * AuthenticationStrategy,
383
+ * buildSetBindingCookieHeader,
384
+ * } from '@glideidentity/glide-be-node-magical-auth';
385
+ *
386
+ * const magicalAuth = new MagicalAuthClient({
387
+ * clientId: process.env.GLIDE_CLIENT_ID!,
388
+ * clientSecret: process.env.GLIDE_CLIENT_SECRET!,
389
+ * });
390
+ *
391
+ * // Prepare authentication
392
+ * const result = await magicalAuth.prepare({
393
+ * phone_number: '+14155551234',
394
+ * use_case: UseCase.VERIFY_PHONE_NUMBER,
395
+ * client_info: { user_agent: req.headers['user-agent'] },
396
+ * });
397
+ *
398
+ * // For link protocol, set the binding cookie
399
+ * if (result.feCode) {
400
+ * res.setHeader('Set-Cookie', buildSetBindingCookieHeader(result.feCode, result.session.session_key));
401
+ * }
402
+ *
403
+ * // Handle based on strategy
404
+ * switch (result.authentication_strategy) {
405
+ * case AuthenticationStrategy.TS43:
406
+ * // Direct carrier credential request
407
+ * break;
408
+ * case AuthenticationStrategy.LINK:
409
+ * // OAuth redirect flow (device-bound)
410
+ * break;
411
+ * case AuthenticationStrategy.DESKTOP:
412
+ * // QR code flow
413
+ * break;
414
+ * }
415
+ * ```
416
+ */
417
+ declare const VERSION: string;
418
+
419
+ export { BINDING_COOKIE_MAX_AGE, BINDING_COOKIE_PREFIX, type BindingCookieOptions, type CompleteRequest, type CompleteResponse, type DesktopWaitResponse, GetPhoneNumberRequest, GetPhoneNumberResponse, HEX_64, HttpClient, Logger, MagicalAuthClient, MagicalAuthConfig, PrepareRequest, PrepareResult, ReportInvocationResponse, type RequestOptions, SENSITIVE_KEYS, StatusResponse, TokenManager, VERSION, VerifyPhoneNumberRequest, VerifyPhoneNumberResponse, assertValidFeCode, buildClearBindingCookieHeader, buildSetBindingCookieHeader, clearStaleBindingCookies, computeFeHash, generateFeCode, getBindingCookieName, getCompletionPageHtml, parseBindingCookie };