@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,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.js';
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.js';
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 };