@nauth-toolkit/client 0.1.49 → 0.1.53

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.
@@ -1,2316 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
5
- var __decorateClass = (decorators, target, key, kind) => {
6
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
7
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
8
- if (decorator = decorators[i])
9
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
10
- if (kind && result) __defProp(target, key, result);
11
- return result;
12
- };
13
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
14
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
15
-
16
- // src/angular/tokens.ts
17
- import { InjectionToken } from "@angular/core";
18
- var NAUTH_CLIENT_CONFIG = new InjectionToken("NAUTH_CLIENT_CONFIG");
19
-
20
- // src/angular/auth.service.ts
21
- import { Inject, Injectable as Injectable2, Optional } from "@angular/core";
22
- import { BehaviorSubject, Subject } from "rxjs";
23
- import { filter } from "rxjs/operators";
24
-
25
- // src/angular/http-adapter.ts
26
- import { Injectable, inject } from "@angular/core";
27
- import { HttpClient, HttpErrorResponse } from "@angular/common/http";
28
- import { firstValueFrom } from "rxjs";
29
-
30
- // src/core/errors.ts
31
- var _NAuthClientError = class _NAuthClientError extends Error {
32
- /**
33
- * Create a new client error.
34
- *
35
- * @param code - Error code from NAuthErrorCode enum
36
- * @param message - Human-readable error message
37
- * @param options - Optional metadata including details, statusCode, timestamp, and network error flag
38
- */
39
- constructor(code, message, options) {
40
- super(message);
41
- __publicField(this, "code");
42
- __publicField(this, "details");
43
- __publicField(this, "statusCode");
44
- __publicField(this, "timestamp");
45
- __publicField(this, "isNetworkError");
46
- this.code = code;
47
- this.details = options?.details;
48
- this.statusCode = options?.statusCode;
49
- this.timestamp = options?.timestamp || (/* @__PURE__ */ new Date()).toISOString();
50
- this.isNetworkError = options?.isNetworkError ?? false;
51
- this.name = "NAuthClientError";
52
- Object.setPrototypeOf(this, _NAuthClientError.prototype);
53
- }
54
- /**
55
- * Check if error matches a specific error code.
56
- *
57
- * @param code - Error code to check against
58
- * @returns True if the error code matches
59
- *
60
- * @example
61
- * ```typescript
62
- * if (error.isCode(NAuthErrorCode.RATE_LIMIT_SMS)) {
63
- * // Handle SMS rate limit
64
- * }
65
- * ```
66
- */
67
- isCode(code) {
68
- return this.code === code;
69
- }
70
- /**
71
- * Get error details/metadata.
72
- *
73
- * @returns Error details object or undefined
74
- *
75
- * @example
76
- * ```typescript
77
- * const details = error.getDetails();
78
- * if (details?.retryAfter) {
79
- * console.log(`Retry after ${details.retryAfter} seconds`);
80
- * }
81
- * ```
82
- */
83
- getDetails() {
84
- return this.details;
85
- }
86
- /**
87
- * Get the error code.
88
- *
89
- * @returns The error code enum value
90
- */
91
- getCode() {
92
- return this.code;
93
- }
94
- /**
95
- * Serialize error to JSON object.
96
- *
97
- * @returns Plain object representation
98
- *
99
- * @example
100
- * ```typescript
101
- * const errorJson = error.toJSON();
102
- * // { code: 'AUTH_INVALID_CREDENTIALS', message: '...', timestamp: '...', details: {...} }
103
- * ```
104
- */
105
- toJSON() {
106
- return {
107
- code: this.code,
108
- message: this.message,
109
- timestamp: this.timestamp,
110
- details: this.details,
111
- statusCode: this.statusCode
112
- };
113
- }
114
- };
115
- __name(_NAuthClientError, "NAuthClientError");
116
- var NAuthClientError = _NAuthClientError;
117
-
118
- // src/angular/http-adapter.ts
119
- var AngularHttpAdapter = class {
120
- constructor() {
121
- __publicField(this, "http", inject(HttpClient));
122
- }
123
- /**
124
- * Execute HTTP request using Angular's HttpClient.
125
- *
126
- * @param config - Request configuration
127
- * @returns Response with parsed data
128
- * @throws NAuthClientError if request fails
129
- */
130
- async request(config) {
131
- try {
132
- const data = await firstValueFrom(
133
- this.http.request(config.method, config.url, {
134
- body: config.body,
135
- headers: config.headers,
136
- withCredentials: config.credentials === "include",
137
- observe: "body"
138
- // Only return body data
139
- })
140
- );
141
- return {
142
- data,
143
- status: 200,
144
- // HttpClient only returns data on success
145
- headers: {}
146
- // Can extract from observe: 'response' if needed
147
- };
148
- } catch (error) {
149
- if (error instanceof HttpErrorResponse) {
150
- const errorData = error.error || {};
151
- const code = typeof errorData["code"] === "string" ? errorData.code : "INTERNAL_ERROR" /* INTERNAL_ERROR */;
152
- const message = typeof errorData["message"] === "string" ? errorData.message : error.message || `Request failed with status ${error.status}`;
153
- const timestamp = typeof errorData["timestamp"] === "string" ? errorData.timestamp : void 0;
154
- const details = errorData["details"];
155
- throw new NAuthClientError(code, message, {
156
- statusCode: error.status,
157
- timestamp,
158
- details,
159
- isNetworkError: error.status === 0
160
- // Network error (no response from server)
161
- });
162
- }
163
- throw error;
164
- }
165
- }
166
- };
167
- __name(AngularHttpAdapter, "AngularHttpAdapter");
168
- AngularHttpAdapter = __decorateClass([
169
- Injectable({ providedIn: "root" })
170
- ], AngularHttpAdapter);
171
-
172
- // src/core/config.ts
173
- var defaultEndpoints = {
174
- login: "/login",
175
- signup: "/signup",
176
- logout: "/logout",
177
- logoutAll: "/logout/all",
178
- refresh: "/refresh",
179
- respondChallenge: "/respond-challenge",
180
- resendCode: "/challenge/resend",
181
- getSetupData: "/challenge/setup-data",
182
- getChallengeData: "/challenge/challenge-data",
183
- profile: "/profile",
184
- changePassword: "/change-password",
185
- requestPasswordChange: "/request-password-change",
186
- forgotPassword: "/forgot-password",
187
- confirmForgotPassword: "/forgot-password/confirm",
188
- mfaStatus: "/mfa/status",
189
- mfaDevices: "/mfa/devices",
190
- mfaSetupData: "/mfa/setup-data",
191
- mfaVerifySetup: "/mfa/verify-setup",
192
- mfaRemove: "/mfa/method",
193
- mfaPreferred: "/mfa/preferred-method",
194
- mfaBackupCodes: "/mfa/backup-codes/generate",
195
- mfaExemption: "/mfa/exemption",
196
- socialLinked: "/social/linked",
197
- socialLink: "/social/link",
198
- socialUnlink: "/social/unlink",
199
- socialVerify: "/social/:provider/verify",
200
- socialRedirectStart: "/social/:provider/redirect",
201
- socialExchange: "/social/exchange",
202
- trustDevice: "/trust-device",
203
- isTrustedDevice: "/is-trusted-device",
204
- auditHistory: "/audit/history",
205
- updateProfile: "/profile"
206
- };
207
- var resolveConfig = /* @__PURE__ */ __name((config, defaultAdapter) => {
208
- const resolvedEndpoints = {
209
- ...defaultEndpoints,
210
- ...config.endpoints ?? {}
211
- };
212
- return {
213
- ...config,
214
- csrf: {
215
- cookieName: config.csrf?.cookieName ?? "nauth_csrf_token",
216
- headerName: config.csrf?.headerName ?? "x-csrf-token"
217
- },
218
- deviceTrust: {
219
- headerName: config.deviceTrust?.headerName ?? "X-Device-Token",
220
- storageKey: config.deviceTrust?.storageKey ?? "nauth_device_token"
221
- },
222
- headers: config.headers ?? {},
223
- timeout: config.timeout ?? 3e4,
224
- endpoints: resolvedEndpoints,
225
- storage: config.storage,
226
- httpAdapter: config.httpAdapter ?? defaultAdapter
227
- };
228
- }, "resolveConfig");
229
-
230
- // src/core/refresh.ts
231
- var ACCESS_TOKEN_KEY = "nauth_access_token";
232
- var REFRESH_TOKEN_KEY = "nauth_refresh_token";
233
- var ACCESS_EXPIRES_AT_KEY = "nauth_access_token_expires_at";
234
- var REFRESH_EXPIRES_AT_KEY = "nauth_refresh_token_expires_at";
235
- var USER_KEY = "nauth_user";
236
- var CHALLENGE_KEY = "nauth_challenge_session";
237
- var _TokenManager = class _TokenManager {
238
- /**
239
- * @param storage - storage adapter
240
- */
241
- constructor(storage) {
242
- __publicField(this, "storage");
243
- __publicField(this, "refreshPromise", null);
244
- __publicField(this, "isBrowser", typeof window !== "undefined");
245
- this.storage = storage;
246
- }
247
- /**
248
- * Load tokens from storage.
249
- */
250
- async getTokens() {
251
- const [accessToken, refreshToken, accessExpRaw, refreshExpRaw] = await Promise.all([
252
- this.storage.getItem(ACCESS_TOKEN_KEY),
253
- this.storage.getItem(REFRESH_TOKEN_KEY),
254
- this.storage.getItem(ACCESS_EXPIRES_AT_KEY),
255
- this.storage.getItem(REFRESH_EXPIRES_AT_KEY)
256
- ]);
257
- return {
258
- accessToken,
259
- refreshToken,
260
- accessTokenExpiresAt: accessExpRaw ? Number(accessExpRaw) : null,
261
- refreshTokenExpiresAt: refreshExpRaw ? Number(refreshExpRaw) : null
262
- };
263
- }
264
- /**
265
- * Persist tokens.
266
- *
267
- * @param tokens - new token pair
268
- */
269
- async setTokens(tokens) {
270
- await Promise.all([
271
- this.storage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken),
272
- this.storage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken),
273
- this.storage.setItem(ACCESS_EXPIRES_AT_KEY, tokens.accessTokenExpiresAt.toString()),
274
- this.storage.setItem(REFRESH_EXPIRES_AT_KEY, tokens.refreshTokenExpiresAt.toString())
275
- ]);
276
- this.broadcastStorage();
277
- }
278
- /**
279
- * Clear tokens and related auth state.
280
- */
281
- async clearTokens() {
282
- await Promise.all([
283
- this.storage.removeItem(ACCESS_TOKEN_KEY),
284
- this.storage.removeItem(REFRESH_TOKEN_KEY),
285
- this.storage.removeItem(ACCESS_EXPIRES_AT_KEY),
286
- this.storage.removeItem(REFRESH_EXPIRES_AT_KEY),
287
- this.storage.removeItem(USER_KEY),
288
- this.storage.removeItem(CHALLENGE_KEY)
289
- ]);
290
- this.broadcastStorage();
291
- }
292
- /**
293
- * Ensure only one refresh in flight.
294
- *
295
- * @param refreshFn - function performing refresh request
296
- */
297
- async refreshOnce(refreshFn) {
298
- if (!this.refreshPromise) {
299
- this.refreshPromise = refreshFn().then(async (tokens) => {
300
- await this.setTokens(tokens);
301
- return tokens;
302
- }).catch((error) => {
303
- throw error;
304
- }).finally(() => {
305
- this.refreshPromise = null;
306
- });
307
- }
308
- return this.refreshPromise;
309
- }
310
- /**
311
- * Validate that a refresh token exists before attempting refresh.
312
- */
313
- async assertHasRefreshToken() {
314
- const state = await this.getTokens();
315
- if (!state.refreshToken) {
316
- throw new NAuthClientError("AUTH_SESSION_NOT_FOUND" /* AUTH_SESSION_NOT_FOUND */, "No refresh token available");
317
- }
318
- }
319
- /**
320
- * Broadcast a no-op write to trigger storage listeners in other tabs.
321
- */
322
- broadcastStorage() {
323
- if (!this.isBrowser) return;
324
- try {
325
- window.localStorage.setItem("nauth_sync", Date.now().toString());
326
- } catch {
327
- }
328
- }
329
- };
330
- __name(_TokenManager, "TokenManager");
331
- var TokenManager = _TokenManager;
332
-
333
- // src/storage/browser.ts
334
- var _BrowserStorage = class _BrowserStorage {
335
- /**
336
- * Create a browser storage adapter.
337
- *
338
- * @param storage - Storage implementation (localStorage by default)
339
- */
340
- constructor(storage = window.localStorage) {
341
- __publicField(this, "storage");
342
- this.storage = storage;
343
- }
344
- async getItem(key) {
345
- return this.storage.getItem(key);
346
- }
347
- async setItem(key, value) {
348
- this.storage.setItem(key, value);
349
- }
350
- async removeItem(key) {
351
- this.storage.removeItem(key);
352
- }
353
- async clear() {
354
- this.storage.clear();
355
- }
356
- };
357
- __name(_BrowserStorage, "BrowserStorage");
358
- var BrowserStorage = _BrowserStorage;
359
-
360
- // src/storage/memory.ts
361
- var _InMemoryStorage = class _InMemoryStorage {
362
- constructor() {
363
- __publicField(this, "store", /* @__PURE__ */ new Map());
364
- }
365
- async getItem(key) {
366
- return this.store.has(key) ? this.store.get(key) : null;
367
- }
368
- async setItem(key, value) {
369
- this.store.set(key, value);
370
- }
371
- async removeItem(key) {
372
- this.store.delete(key);
373
- }
374
- async clear() {
375
- this.store.clear();
376
- }
377
- };
378
- __name(_InMemoryStorage, "InMemoryStorage");
379
- var InMemoryStorage = _InMemoryStorage;
380
-
381
- // src/core/events.ts
382
- var _EventEmitter = class _EventEmitter {
383
- constructor() {
384
- __publicField(this, "listeners", /* @__PURE__ */ new Map());
385
- }
386
- /**
387
- * Subscribe to an authentication event
388
- *
389
- * @param event - Event type or '*' for all events
390
- * @param listener - Callback function
391
- * @returns Unsubscribe function
392
- *
393
- * @example
394
- * ```typescript
395
- * const unsubscribe = emitter.on('auth:success', (event) => {
396
- * console.log('User logged in:', event.data);
397
- * });
398
- *
399
- * // Later
400
- * unsubscribe();
401
- * ```
402
- */
403
- on(event, listener) {
404
- if (!this.listeners.has(event)) {
405
- this.listeners.set(event, /* @__PURE__ */ new Set());
406
- }
407
- this.listeners.get(event).add(listener);
408
- return () => this.off(event, listener);
409
- }
410
- /**
411
- * Unsubscribe from an authentication event
412
- *
413
- * @param event - Event type or '*'
414
- * @param listener - Callback function to remove
415
- */
416
- off(event, listener) {
417
- this.listeners.get(event)?.delete(listener);
418
- }
419
- /**
420
- * Emit an authentication event
421
- *
422
- * Notifies all listeners for the specific event type and wildcard listeners.
423
- *
424
- * @param event - Event to emit
425
- * @internal
426
- */
427
- emit(event) {
428
- const specificListeners = this.listeners.get(event.type);
429
- const wildcardListeners = this.listeners.get("*");
430
- specificListeners?.forEach((listener) => {
431
- try {
432
- listener(event);
433
- } catch (error) {
434
- console.error(`Error in ${event.type} event listener:`, error);
435
- }
436
- });
437
- wildcardListeners?.forEach((listener) => {
438
- try {
439
- listener(event);
440
- } catch (error) {
441
- console.error(`Error in wildcard event listener:`, error);
442
- }
443
- });
444
- }
445
- /**
446
- * Remove all listeners
447
- *
448
- * @internal
449
- */
450
- clear() {
451
- this.listeners.clear();
452
- }
453
- };
454
- __name(_EventEmitter, "EventEmitter");
455
- var EventEmitter = _EventEmitter;
456
-
457
- // src/adapters/fetch-adapter.ts
458
- var _FetchAdapter = class _FetchAdapter {
459
- /**
460
- * Execute HTTP request using native fetch.
461
- *
462
- * @param config - Request configuration
463
- * @returns Response with parsed data
464
- * @throws NAuthClientError if request fails
465
- */
466
- async request(config) {
467
- const fetchOptions = {
468
- method: config.method,
469
- headers: config.headers,
470
- signal: config.signal,
471
- credentials: config.credentials
472
- };
473
- if (config.body !== void 0) {
474
- fetchOptions.body = JSON.stringify(config.body);
475
- }
476
- let response;
477
- try {
478
- response = await fetch(config.url, fetchOptions);
479
- } catch (error) {
480
- throw new NAuthClientError("INTERNAL_ERROR" /* INTERNAL_ERROR */, "Network request failed", {
481
- isNetworkError: true,
482
- details: { url: config.url, message: error.message }
483
- });
484
- }
485
- const status = response.status;
486
- let data = null;
487
- const text = await response.text();
488
- if (text) {
489
- try {
490
- data = JSON.parse(text);
491
- } catch {
492
- data = text;
493
- }
494
- }
495
- const headers = {};
496
- response.headers.forEach((value, key) => {
497
- headers[key] = value;
498
- });
499
- if (!response.ok) {
500
- const errorData = typeof data === "object" && data !== null ? data : {};
501
- const code = typeof errorData["code"] === "string" ? errorData["code"] : "INTERNAL_ERROR" /* INTERNAL_ERROR */;
502
- const message = typeof errorData["message"] === "string" ? errorData["message"] : `Request failed with status ${status}`;
503
- const timestamp = typeof errorData["timestamp"] === "string" ? errorData["timestamp"] : void 0;
504
- const details = errorData["details"];
505
- throw new NAuthClientError(code, message, {
506
- statusCode: status,
507
- timestamp,
508
- details
509
- });
510
- }
511
- return { data, status, headers };
512
- }
513
- };
514
- __name(_FetchAdapter, "FetchAdapter");
515
- var FetchAdapter = _FetchAdapter;
516
-
517
- // src/core/client.ts
518
- var USER_KEY2 = "nauth_user";
519
- var CHALLENGE_KEY2 = "nauth_challenge_session";
520
- var hasWindow = /* @__PURE__ */ __name(() => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined", "hasWindow");
521
- var defaultStorage = /* @__PURE__ */ __name(() => {
522
- if (hasWindow() && typeof window.localStorage !== "undefined") {
523
- return new BrowserStorage();
524
- }
525
- return new InMemoryStorage();
526
- }, "defaultStorage");
527
- var _NAuthClient = class _NAuthClient {
528
- /**
529
- * Create a new client instance.
530
- *
531
- * @param userConfig - Client configuration
532
- */
533
- constructor(userConfig) {
534
- __publicField(this, "config");
535
- __publicField(this, "tokenManager");
536
- __publicField(this, "eventEmitter");
537
- __publicField(this, "currentUser", null);
538
- /**
539
- * Handle cross-tab storage updates.
540
- */
541
- __publicField(this, "handleStorageEvent", /* @__PURE__ */ __name((event) => {
542
- if (event.key === "nauth_sync") {
543
- this.config.storage.getItem(USER_KEY2).then((value) => value ? JSON.parse(value) : null).then((user) => {
544
- this.currentUser = user;
545
- this.config.onAuthStateChange?.(user);
546
- }).catch(() => {
547
- });
548
- }
549
- }, "handleStorageEvent"));
550
- const storage = userConfig.storage ?? defaultStorage();
551
- const defaultAdapter = userConfig.httpAdapter ?? new FetchAdapter();
552
- this.config = resolveConfig({ ...userConfig, storage }, defaultAdapter);
553
- this.tokenManager = new TokenManager(storage);
554
- this.eventEmitter = new EventEmitter();
555
- if (hasWindow()) {
556
- window.addEventListener("storage", this.handleStorageEvent);
557
- }
558
- }
559
- /**
560
- * Clean up resources.
561
- */
562
- dispose() {
563
- if (hasWindow()) {
564
- window.removeEventListener("storage", this.handleStorageEvent);
565
- }
566
- }
567
- /**
568
- * Login with identifier and password.
569
- */
570
- async login(identifier, password) {
571
- const loginEvent = { type: "auth:login", data: { identifier }, timestamp: Date.now() };
572
- this.eventEmitter.emit(loginEvent);
573
- try {
574
- const body = { identifier, password };
575
- const response = await this.post(this.config.endpoints.login, body);
576
- await this.handleAuthResponse(response);
577
- if (response.challengeName) {
578
- const challengeEvent = { type: "auth:challenge", data: response, timestamp: Date.now() };
579
- this.eventEmitter.emit(challengeEvent);
580
- } else {
581
- const successEvent = { type: "auth:success", data: response, timestamp: Date.now() };
582
- this.eventEmitter.emit(successEvent);
583
- }
584
- return response;
585
- } catch (error) {
586
- const authError = error instanceof NAuthClientError ? error : new NAuthClientError("AUTH_INVALID_CREDENTIALS" /* AUTH_INVALID_CREDENTIALS */, error.message || "Login failed");
587
- const errorEvent = { type: "auth:error", data: authError, timestamp: Date.now() };
588
- this.eventEmitter.emit(errorEvent);
589
- throw authError;
590
- }
591
- }
592
- /**
593
- * Signup with credentials.
594
- */
595
- async signup(payload) {
596
- this.eventEmitter.emit({ type: "auth:signup", data: { email: payload.email }, timestamp: Date.now() });
597
- try {
598
- const response = await this.post(this.config.endpoints.signup, payload);
599
- await this.handleAuthResponse(response);
600
- if (response.challengeName) {
601
- this.eventEmitter.emit({ type: "auth:challenge", data: response, timestamp: Date.now() });
602
- } else {
603
- this.eventEmitter.emit({ type: "auth:success", data: response, timestamp: Date.now() });
604
- }
605
- return response;
606
- } catch (error) {
607
- const authError = error instanceof NAuthClientError ? error : new NAuthClientError("AUTH_INVALID_CREDENTIALS" /* AUTH_INVALID_CREDENTIALS */, error.message || "Signup failed");
608
- this.eventEmitter.emit({ type: "auth:error", data: authError, timestamp: Date.now() });
609
- throw authError;
610
- }
611
- }
612
- /**
613
- * Refresh tokens manually.
614
- */
615
- async refreshTokens() {
616
- const tokenDelivery = this.getTokenDeliveryMode();
617
- if (tokenDelivery === "json") {
618
- await this.tokenManager.assertHasRefreshToken();
619
- }
620
- const body = tokenDelivery === "json" ? { refreshToken: (await this.tokenManager.getTokens()).refreshToken } : { refreshToken: "" };
621
- const refreshFn = /* @__PURE__ */ __name(async () => {
622
- return this.post(this.config.endpoints.refresh, body, false);
623
- }, "refreshFn");
624
- const tokens = await this.tokenManager.refreshOnce(refreshFn);
625
- this.config.onTokenRefresh?.();
626
- this.eventEmitter.emit({ type: "auth:refresh", data: { success: true }, timestamp: Date.now() });
627
- return tokens;
628
- }
629
- /**
630
- * Logout current session.
631
- *
632
- * Uses GET request to avoid CSRF token issues.
633
- *
634
- * @param forgetDevice - If true, also untrust the device (require MFA on next login)
635
- */
636
- async logout(forgetDevice) {
637
- const queryParams = forgetDevice ? "?forgetMe=true" : "";
638
- try {
639
- await this.get(this.config.endpoints.logout + queryParams, true);
640
- } catch (error) {
641
- console.warn("[nauth] Logout request failed (session may already be invalid):", error);
642
- } finally {
643
- await this.clearAuthState(forgetDevice);
644
- this.eventEmitter.emit({
645
- type: "auth:logout",
646
- data: { forgetDevice: !!forgetDevice, global: false },
647
- timestamp: Date.now()
648
- });
649
- }
650
- }
651
- /**
652
- * Logout all sessions.
653
- *
654
- * Revokes all active sessions for the current user across all devices.
655
- * Optionally revokes all trusted devices if forgetDevices is true.
656
- *
657
- * @param forgetDevices - If true, also revokes all trusted devices (default: false)
658
- * @returns Number of sessions revoked
659
- */
660
- async logoutAll(forgetDevices) {
661
- try {
662
- const payload = {
663
- forgetDevices: forgetDevices ?? false
664
- };
665
- const result = await this.post(
666
- this.config.endpoints.logoutAll,
667
- payload,
668
- true
669
- );
670
- await this.clearAuthState(forgetDevices);
671
- this.eventEmitter.emit({
672
- type: "auth:logout",
673
- data: { forgetDevice: !!forgetDevices, global: true },
674
- timestamp: Date.now()
675
- });
676
- return { revokedCount: result.revokedCount };
677
- } catch (error) {
678
- await this.clearAuthState(forgetDevices);
679
- this.eventEmitter.emit({
680
- type: "auth:logout",
681
- data: { forgetDevice: !!forgetDevices, global: true },
682
- timestamp: Date.now()
683
- });
684
- throw error;
685
- }
686
- }
687
- /**
688
- * Respond to a challenge.
689
- *
690
- * Validates challenge response data before sending to backend.
691
- * Provides helpful error messages for common validation issues.
692
- *
693
- * @param response - Challenge response data
694
- * @returns Auth response from backend
695
- * @throws {NAuthClientError} If validation fails
696
- */
697
- async respondToChallenge(response) {
698
- if (response.type === "MFA_SETUP_REQUIRED" /* MFA_SETUP_REQUIRED */ && response.method === "totp") {
699
- const setupData = response.setupData;
700
- if (!setupData || typeof setupData !== "object") {
701
- throw new NAuthClientError(
702
- "VALIDATION_FAILED" /* VALIDATION_FAILED */,
703
- "TOTP setup requires setupData with both secret and code",
704
- { details: { field: "setupData" } }
705
- );
706
- }
707
- const secret = setupData["secret"];
708
- const code = setupData["code"];
709
- if (!secret || typeof secret !== "string") {
710
- throw new NAuthClientError(
711
- "VALIDATION_FAILED" /* VALIDATION_FAILED */,
712
- "TOTP setup requires secret in setupData. Make sure to include the secret from getSetupData() response.",
713
- { details: { field: "secret" } }
714
- );
715
- }
716
- if (!code || typeof code !== "string") {
717
- throw new NAuthClientError(
718
- "VALIDATION_FAILED" /* VALIDATION_FAILED */,
719
- "TOTP setup requires code in setupData. Please enter the verification code from your authenticator app.",
720
- { details: { field: "code" } }
721
- );
722
- }
723
- }
724
- try {
725
- const result = await this.post(this.config.endpoints.respondChallenge, response);
726
- await this.handleAuthResponse(result);
727
- if (result.challengeName) {
728
- const challengeEvent = { type: "auth:challenge", data: result, timestamp: Date.now() };
729
- this.eventEmitter.emit(challengeEvent);
730
- } else {
731
- const successEvent = { type: "auth:success", data: result, timestamp: Date.now() };
732
- this.eventEmitter.emit(successEvent);
733
- }
734
- return result;
735
- } catch (error) {
736
- const authError = error instanceof NAuthClientError ? error : new NAuthClientError(
737
- "CHALLENGE_INVALID" /* CHALLENGE_INVALID */,
738
- error.message || "Challenge response failed"
739
- );
740
- const errorEvent = { type: "auth:error", data: authError, timestamp: Date.now() };
741
- this.eventEmitter.emit(errorEvent);
742
- throw authError;
743
- }
744
- }
745
- /**
746
- * Resend a challenge code.
747
- */
748
- async resendCode(session) {
749
- const payload = { session };
750
- return this.post(this.config.endpoints.resendCode, payload);
751
- }
752
- /**
753
- * Get setup data for MFA.
754
- *
755
- * Returns method-specific setup information:
756
- * - TOTP: { secret, qrCode, manualEntryKey }
757
- * - SMS: { maskedPhone }
758
- * - Email: { maskedEmail }
759
- * - Passkey: WebAuthn registration options
760
- *
761
- * @param session - Challenge session token
762
- * @param method - MFA method to set up
763
- * @returns Setup data wrapped in GetSetupDataResponse
764
- */
765
- async getSetupData(session, method) {
766
- const payload = { session, method };
767
- return this.post(this.config.endpoints.getSetupData, payload);
768
- }
769
- /**
770
- * Get challenge data (e.g., WebAuthn options).
771
- *
772
- * Returns challenge-specific data for verification flows.
773
- *
774
- * @param session - Challenge session token
775
- * @param method - Challenge method to get data for
776
- * @returns Challenge data wrapped in GetChallengeDataResponse
777
- */
778
- async getChallengeData(session, method) {
779
- const payload = { session, method };
780
- return this.post(this.config.endpoints.getChallengeData, payload);
781
- }
782
- /**
783
- * Get current user profile.
784
- */
785
- async getProfile() {
786
- const profile = await this.get(this.config.endpoints.profile, true);
787
- await this.setUser(profile);
788
- return profile;
789
- }
790
- /**
791
- * Update user profile.
792
- */
793
- async updateProfile(updates) {
794
- const updated = await this.put(this.config.endpoints.updateProfile, updates, true);
795
- await this.setUser(updated);
796
- return updated;
797
- }
798
- /**
799
- * Change user password.
800
- */
801
- async changePassword(oldPassword, newPassword) {
802
- const payload = { currentPassword: oldPassword, newPassword };
803
- await this.post(this.config.endpoints.changePassword, payload, true);
804
- }
805
- /**
806
- * Request a password reset code (forgot password).
807
- */
808
- async forgotPassword(identifier) {
809
- const payload = { identifier };
810
- return this.post(this.config.endpoints.forgotPassword, payload);
811
- }
812
- /**
813
- * Confirm a password reset code and set a new password.
814
- */
815
- async confirmForgotPassword(identifier, code, newPassword) {
816
- const payload = { identifier, code, newPassword };
817
- const result = await this.post(this.config.endpoints.confirmForgotPassword, payload);
818
- await this.clearAuthState(false);
819
- return result;
820
- }
821
- /**
822
- * Request password change (must change on next login).
823
- */
824
- async requestPasswordChange() {
825
- await this.post(this.config.endpoints.requestPasswordChange, {}, true);
826
- }
827
- /**
828
- * Get MFA status.
829
- */
830
- async getMfaStatus() {
831
- return this.get(this.config.endpoints.mfaStatus, true);
832
- }
833
- /**
834
- * Get MFA devices.
835
- */
836
- async getMfaDevices() {
837
- return this.get(this.config.endpoints.mfaDevices, true);
838
- }
839
- /**
840
- * Setup MFA device (authenticated user).
841
- */
842
- async setupMfaDevice(method) {
843
- return this.post(this.config.endpoints.mfaSetupData, { method }, true);
844
- }
845
- /**
846
- * Verify MFA setup (authenticated user).
847
- */
848
- async verifyMfaSetup(method, setupData, deviceName) {
849
- return this.post(
850
- this.config.endpoints.mfaVerifySetup,
851
- { method, setupData, deviceName },
852
- true
853
- );
854
- }
855
- /**
856
- * Remove MFA method.
857
- */
858
- async removeMfaDevice(method) {
859
- const path = `${this.config.endpoints.mfaRemove}/${method}`;
860
- return this.delete(path, true);
861
- }
862
- /**
863
- * Set preferred MFA method.
864
- *
865
- * @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey'). Cannot be 'backup'.
866
- * @returns Success message
867
- */
868
- async setPreferredMfaMethod(method) {
869
- return this.post(this.config.endpoints.mfaPreferred, { method }, true);
870
- }
871
- /**
872
- * Generate backup codes.
873
- */
874
- async generateBackupCodes() {
875
- const result = await this.post(this.config.endpoints.mfaBackupCodes, {}, true);
876
- return result.codes;
877
- }
878
- /**
879
- * Set MFA exemption (admin/test scenarios).
880
- */
881
- async setMfaExemption(exempt, reason) {
882
- await this.post(this.config.endpoints.mfaExemption, { exempt, reason }, true);
883
- }
884
- // ============================================================================
885
- // Event System
886
- // ============================================================================
887
- /**
888
- * Subscribe to authentication events.
889
- *
890
- * Emits events throughout the auth lifecycle for custom logic, analytics, or UI updates.
891
- *
892
- * @param event - Event type to listen for, or '*' for all events
893
- * @param listener - Callback function to handle the event
894
- * @returns Unsubscribe function
895
- *
896
- * @example
897
- * ```typescript
898
- * // Listen to successful authentication
899
- * const unsubscribe = client.on('auth:success', (event) => {
900
- * console.log('User logged in:', event.data.user);
901
- * analytics.track('login_success');
902
- * });
903
- *
904
- * // Listen to all events
905
- * client.on('*', (event) => {
906
- * console.log('Auth event:', event.type, event.data);
907
- * });
908
- *
909
- * // Unsubscribe when done
910
- * unsubscribe();
911
- * ```
912
- */
913
- on(event, listener) {
914
- return this.eventEmitter.on(event, listener);
915
- }
916
- /**
917
- * Unsubscribe from authentication events.
918
- *
919
- * @param event - Event type
920
- * @param listener - Callback function to remove
921
- */
922
- off(event, listener) {
923
- this.eventEmitter.off(event, listener);
924
- }
925
- // ============================================================================
926
- // Social Authentication
927
- // ============================================================================
928
- /**
929
- * Start redirect-first social OAuth flow (web).
930
- *
931
- * This performs a browser navigation to:
932
- * `GET {baseUrl}/social/:provider/redirect?returnTo=...&appState=...`
933
- *
934
- * The backend:
935
- * - generates and stores CSRF state (cluster-safe)
936
- * - redirects the user to the provider
937
- * - completes OAuth on callback and sets cookies (or issues an exchange token)
938
- * - redirects back to `returnTo` with `appState` (and `exchangeToken` for json/hybrid)
939
- *
940
- * @param provider - OAuth provider ('google', 'apple', 'facebook')
941
- * @param options - Optional redirect options
942
- *
943
- * @example
944
- * ```typescript
945
- * await client.loginWithSocial('google', { returnTo: '/auth/callback', appState: '12345' });
946
- * ```
947
- */
948
- async loginWithSocial(provider, options) {
949
- this.eventEmitter.emit({ type: "oauth:started", data: { provider }, timestamp: Date.now() });
950
- if (hasWindow()) {
951
- const startPath = this.config.endpoints.socialRedirectStart.replace(":provider", provider);
952
- const base = this.config.baseUrl.replace(/\/$/, "");
953
- const startUrl = new URL(`${base}${startPath}`);
954
- const returnTo = options?.returnTo ?? this.config.redirects?.success ?? "/";
955
- startUrl.searchParams.set("returnTo", returnTo);
956
- if (options?.action === "link") {
957
- startUrl.searchParams.set("action", "link");
958
- }
959
- if (typeof options?.appState === "string" && options.appState.trim() !== "") {
960
- startUrl.searchParams.set("appState", options.appState);
961
- }
962
- window.location.href = startUrl.toString();
963
- }
964
- }
965
- /**
966
- * Exchange an `exchangeToken` (from redirect callback URL) into an AuthResponse.
967
- *
968
- * Used for `tokenDelivery: 'json'` or hybrid flows where the backend redirects back
969
- * with `exchangeToken` instead of setting cookies.
970
- *
971
- * @param exchangeToken - One-time exchange token from the callback URL
972
- * @returns AuthResponse
973
- */
974
- async exchangeSocialRedirect(exchangeToken) {
975
- const token = exchangeToken?.trim();
976
- if (!token) {
977
- throw new NAuthClientError("CHALLENGE_INVALID" /* CHALLENGE_INVALID */, "Missing exchangeToken");
978
- }
979
- const result = await this.post(this.config.endpoints.socialExchange, { exchangeToken: token });
980
- await this.handleAuthResponse(result);
981
- return result;
982
- }
983
- /**
984
- * Verify native social token (mobile).
985
- */
986
- async verifyNativeSocial(request) {
987
- try {
988
- const path = this.config.endpoints.socialVerify.replace(":provider", request.provider);
989
- const result = await this.post(path, request);
990
- await this.handleAuthResponse(result);
991
- if (result.challengeName) {
992
- const challengeEvent = { type: "auth:challenge", data: result, timestamp: Date.now() };
993
- this.eventEmitter.emit(challengeEvent);
994
- } else {
995
- const successEvent = { type: "auth:success", data: result, timestamp: Date.now() };
996
- this.eventEmitter.emit(successEvent);
997
- }
998
- return result;
999
- } catch (error) {
1000
- const authError = error instanceof NAuthClientError ? error : new NAuthClientError(
1001
- "SOCIAL_TOKEN_INVALID" /* SOCIAL_TOKEN_INVALID */,
1002
- error.message || "Social verification failed"
1003
- );
1004
- const errorEvent = { type: "auth:error", data: authError, timestamp: Date.now() };
1005
- this.eventEmitter.emit(errorEvent);
1006
- throw authError;
1007
- }
1008
- }
1009
- /**
1010
- * Get linked accounts.
1011
- */
1012
- async getLinkedAccounts() {
1013
- return this.get(this.config.endpoints.socialLinked, true);
1014
- }
1015
- /**
1016
- * Link social account.
1017
- */
1018
- async linkSocialAccount(provider, code, state) {
1019
- return this.post(this.config.endpoints.socialLink, { provider, code, state }, true);
1020
- }
1021
- /**
1022
- * Unlink social account.
1023
- */
1024
- async unlinkSocialAccount(provider) {
1025
- return this.post(this.config.endpoints.socialUnlink, { provider }, true);
1026
- }
1027
- /**
1028
- * Trust current device.
1029
- */
1030
- async trustDevice() {
1031
- const result = await this.post(this.config.endpoints.trustDevice, {}, true);
1032
- await this.setDeviceToken(result.deviceToken);
1033
- return result;
1034
- }
1035
- /**
1036
- * Check if the current device is trusted.
1037
- *
1038
- * Returns whether the current device is trusted based on the device token
1039
- * (from cookie in cookies mode, or header in JSON mode).
1040
- *
1041
- * This performs a server-side validation of the device token and checks:
1042
- * - Device token exists and is valid
1043
- * - Device token matches a trusted device record in the database
1044
- * - Trust has not expired
1045
- *
1046
- * @returns Object with trusted status
1047
- *
1048
- * @example
1049
- * ```typescript
1050
- * const result = await client.isTrustedDevice();
1051
- * if (result.trusted) {
1052
- * console.log('This device is trusted');
1053
- * }
1054
- * ```
1055
- */
1056
- async isTrustedDevice() {
1057
- return this.get(this.config.endpoints.isTrustedDevice, true);
1058
- }
1059
- /**
1060
- * Get paginated audit history for the current user.
1061
- *
1062
- * Returns authentication and security events with full audit details including:
1063
- * - Event type (login, logout, MFA, etc.)
1064
- * - Event status (success, failure, suspicious)
1065
- * - Device information, location, risk factors
1066
- *
1067
- * @param params - Query parameters for filtering and pagination
1068
- * @returns Paginated audit history response
1069
- *
1070
- * @example
1071
- * ```typescript
1072
- * const history = await client.getAuditHistory({
1073
- * page: 1,
1074
- * limit: 20,
1075
- * eventType: 'LOGIN_SUCCESS'
1076
- * });
1077
- * ```
1078
- */
1079
- async getAuditHistory(params) {
1080
- const entries = Object.entries(params ?? {}).map(([k, v]) => [k, String(v)]);
1081
- const query = entries.length > 0 ? `?${new URLSearchParams(entries).toString()}` : "";
1082
- const path = `${this.config.endpoints.auditHistory}${query}`;
1083
- return this.get(path, true);
1084
- }
1085
- /**
1086
- * Initialize client by hydrating state from storage.
1087
- * Call this on app startup to restore auth state.
1088
- */
1089
- async initialize() {
1090
- const userJson = await this.config.storage.getItem(USER_KEY2);
1091
- if (userJson) {
1092
- try {
1093
- this.currentUser = JSON.parse(userJson);
1094
- this.config.onAuthStateChange?.(this.currentUser);
1095
- } catch {
1096
- await this.config.storage.removeItem(USER_KEY2);
1097
- }
1098
- }
1099
- }
1100
- /**
1101
- * Determine if user is authenticated (async - checks tokens).
1102
- */
1103
- async isAuthenticated() {
1104
- const tokens = await this.tokenManager.getTokens();
1105
- return Boolean(tokens.accessToken);
1106
- }
1107
- /**
1108
- * Determine if user is authenticated (sync - checks cached user).
1109
- * Use this for guards and sync checks. Use `isAuthenticated()` for definitive check.
1110
- */
1111
- isAuthenticatedSync() {
1112
- return this.currentUser !== null;
1113
- }
1114
- /**
1115
- * Get current access token (may be null).
1116
- */
1117
- async getAccessToken() {
1118
- const tokens = await this.tokenManager.getTokens();
1119
- return tokens.accessToken ?? null;
1120
- }
1121
- /**
1122
- * Get current user (cached, sync).
1123
- */
1124
- getCurrentUser() {
1125
- return this.currentUser;
1126
- }
1127
- /**
1128
- * Get stored challenge session (for resuming challenge flows).
1129
- */
1130
- async getStoredChallenge() {
1131
- const raw = await this.config.storage.getItem(CHALLENGE_KEY2);
1132
- if (!raw) return null;
1133
- try {
1134
- return JSON.parse(raw);
1135
- } catch {
1136
- return null;
1137
- }
1138
- }
1139
- /**
1140
- * Clear stored challenge session.
1141
- */
1142
- async clearStoredChallenge() {
1143
- await this.config.storage.removeItem(CHALLENGE_KEY2);
1144
- }
1145
- /**
1146
- * Internal: handle auth response (tokens or challenge).
1147
- *
1148
- * In cookies mode: Tokens are set as httpOnly cookies by backend, not stored in client storage.
1149
- * In JSON mode: Tokens are stored in tokenManager for Authorization header.
1150
- */
1151
- async handleAuthResponse(response) {
1152
- if (response.challengeName) {
1153
- await this.persistChallenge(response);
1154
- return;
1155
- }
1156
- if (this.config.tokenDelivery === "json" && response.accessToken && response.refreshToken) {
1157
- await this.tokenManager.setTokens({
1158
- accessToken: response.accessToken,
1159
- refreshToken: response.refreshToken,
1160
- accessTokenExpiresAt: response.accessTokenExpiresAt ?? 0,
1161
- refreshTokenExpiresAt: response.refreshTokenExpiresAt ?? 0
1162
- });
1163
- }
1164
- if (this.config.tokenDelivery === "json" && response.deviceToken) {
1165
- await this.setDeviceToken(response.deviceToken);
1166
- }
1167
- if (response.user) {
1168
- const user = response.user;
1169
- user.sessionAuthMethod = response.authMethod ?? null;
1170
- await this.setUser(user);
1171
- }
1172
- await this.clearChallenge();
1173
- }
1174
- /**
1175
- * Persist challenge state.
1176
- */
1177
- async persistChallenge(challenge) {
1178
- await this.config.storage.setItem(CHALLENGE_KEY2, JSON.stringify(challenge));
1179
- }
1180
- /**
1181
- * Clear challenge state.
1182
- */
1183
- async clearChallenge() {
1184
- await this.config.storage.removeItem(CHALLENGE_KEY2);
1185
- }
1186
- /**
1187
- * Persist user.
1188
- */
1189
- async setUser(user) {
1190
- this.currentUser = user;
1191
- await this.config.storage.setItem(USER_KEY2, JSON.stringify(user));
1192
- this.config.onAuthStateChange?.(user);
1193
- }
1194
- /**
1195
- * Clear all auth state.
1196
- *
1197
- * @param forgetDevice - If true, also clear device token (for JSON mode)
1198
- */
1199
- async clearAuthState(forgetDevice) {
1200
- this.currentUser = null;
1201
- await this.tokenManager.clearTokens();
1202
- await this.config.storage.removeItem(USER_KEY2);
1203
- if (forgetDevice && this.config.tokenDelivery === "json") {
1204
- await this.config.storage.removeItem(this.config.deviceTrust.storageKey);
1205
- }
1206
- this.config.onAuthStateChange?.(null);
1207
- }
1208
- /**
1209
- * Persist device token (json mode mobile).
1210
- */
1211
- async setDeviceToken(token) {
1212
- await this.config.storage.setItem(this.config.deviceTrust.storageKey, token);
1213
- }
1214
- /**
1215
- * Determine token delivery mode for this environment.
1216
- */
1217
- getTokenDeliveryMode() {
1218
- return this.config.tokenDelivery;
1219
- }
1220
- /**
1221
- * Build request URL by combining baseUrl with path.
1222
- * @private
1223
- */
1224
- buildUrl(path) {
1225
- return `${this.config.baseUrl}${path}`;
1226
- }
1227
- /**
1228
- * Build request headers for authentication.
1229
- * @private
1230
- */
1231
- async buildHeaders(auth) {
1232
- const headers = {
1233
- "Content-Type": "application/json",
1234
- ...this.config.headers
1235
- };
1236
- if (auth && this.config.tokenDelivery === "json") {
1237
- const accessToken = (await this.tokenManager.getTokens()).accessToken;
1238
- if (accessToken) {
1239
- headers["Authorization"] = `Bearer ${accessToken}`;
1240
- }
1241
- }
1242
- if (this.config.tokenDelivery === "json") {
1243
- try {
1244
- const deviceToken = await this.config.storage.getItem(this.config.deviceTrust.storageKey);
1245
- if (deviceToken) {
1246
- headers[this.config.deviceTrust.headerName] = deviceToken;
1247
- }
1248
- } catch {
1249
- }
1250
- }
1251
- if (this.config.tokenDelivery === "cookies" && hasWindow()) {
1252
- const csrfToken = this.getCsrfToken();
1253
- if (csrfToken) {
1254
- headers[this.config.csrf.headerName] = csrfToken;
1255
- }
1256
- }
1257
- return headers;
1258
- }
1259
- /**
1260
- * Get CSRF token from cookie (browser only).
1261
- * @private
1262
- */
1263
- getCsrfToken() {
1264
- if (!hasWindow() || typeof document === "undefined") return null;
1265
- const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
1266
- return match ? decodeURIComponent(match[2]) : null;
1267
- }
1268
- /**
1269
- * Execute GET request.
1270
- * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1271
- */
1272
- async get(path, auth = false) {
1273
- const url = this.buildUrl(path);
1274
- const headers = await this.buildHeaders(auth);
1275
- const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1276
- const response = await this.config.httpAdapter.request({
1277
- method: "GET",
1278
- url,
1279
- headers,
1280
- credentials
1281
- });
1282
- return response.data;
1283
- }
1284
- /**
1285
- * Execute POST request.
1286
- * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1287
- */
1288
- async post(path, body, auth = false) {
1289
- const url = this.buildUrl(path);
1290
- const headers = await this.buildHeaders(auth);
1291
- const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1292
- const response = await this.config.httpAdapter.request({
1293
- method: "POST",
1294
- url,
1295
- headers,
1296
- body,
1297
- credentials
1298
- });
1299
- return response.data;
1300
- }
1301
- /**
1302
- * Execute PUT request.
1303
- * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1304
- */
1305
- async put(path, body, auth = false) {
1306
- const url = this.buildUrl(path);
1307
- const headers = await this.buildHeaders(auth);
1308
- const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1309
- const response = await this.config.httpAdapter.request({
1310
- method: "PUT",
1311
- url,
1312
- headers,
1313
- body,
1314
- credentials
1315
- });
1316
- return response.data;
1317
- }
1318
- /**
1319
- * Execute DELETE request.
1320
- * Note: 401 refresh is handled by framework interceptors (Angular) or manually.
1321
- */
1322
- async delete(path, auth = false) {
1323
- const url = this.buildUrl(path);
1324
- const headers = await this.buildHeaders(auth);
1325
- const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1326
- const response = await this.config.httpAdapter.request({
1327
- method: "DELETE",
1328
- url,
1329
- headers,
1330
- credentials
1331
- });
1332
- return response.data;
1333
- }
1334
- };
1335
- __name(_NAuthClient, "NAuthClient");
1336
- var NAuthClient = _NAuthClient;
1337
-
1338
- // src/angular/auth.service.ts
1339
- var AuthService = class {
1340
- /**
1341
- * @param config - Injected client configuration
1342
- *
1343
- * Note: AngularHttpAdapter is automatically injected via Angular DI.
1344
- * This ensures all requests go through Angular's HttpClient and interceptors.
1345
- */
1346
- constructor(config, injector) {
1347
- this.injector = injector;
1348
- __publicField(this, "client");
1349
- __publicField(this, "config");
1350
- __publicField(this, "currentUserSubject", new BehaviorSubject(null));
1351
- __publicField(this, "isAuthenticatedSubject", new BehaviorSubject(false));
1352
- __publicField(this, "challengeSubject", new BehaviorSubject(null));
1353
- __publicField(this, "authEventsSubject", new Subject());
1354
- __publicField(this, "initialized", false);
1355
- if (!config) {
1356
- throw new Error("NAUTH_CLIENT_CONFIG is required to initialize AuthService");
1357
- }
1358
- this.config = config;
1359
- const httpAdapter = config.httpAdapter ?? this.injector?.get(AngularHttpAdapter, null) ?? null;
1360
- if (!httpAdapter) {
1361
- throw new Error(
1362
- "AngularHttpAdapter is required. Ensure AngularHttpAdapter is provided in your module or pass httpAdapter in config."
1363
- );
1364
- }
1365
- this.client = new NAuthClient({
1366
- ...config,
1367
- httpAdapter,
1368
- // Automatically use Angular's HttpClient
1369
- onAuthStateChange: /* @__PURE__ */ __name((user) => {
1370
- this.currentUserSubject.next(user);
1371
- this.isAuthenticatedSubject.next(Boolean(user));
1372
- config.onAuthStateChange?.(user);
1373
- }, "onAuthStateChange")
1374
- });
1375
- this.client.on("*", (event) => {
1376
- this.authEventsSubject.next(event);
1377
- });
1378
- this.initialize();
1379
- }
1380
- // ============================================================================
1381
- // Reactive State Observables
1382
- // ============================================================================
1383
- /**
1384
- * Current user observable.
1385
- */
1386
- get currentUser$() {
1387
- return this.currentUserSubject.asObservable();
1388
- }
1389
- /**
1390
- * Authenticated state observable.
1391
- */
1392
- get isAuthenticated$() {
1393
- return this.isAuthenticatedSubject.asObservable();
1394
- }
1395
- /**
1396
- * Current challenge observable (for reactive challenge navigation).
1397
- */
1398
- get challenge$() {
1399
- return this.challengeSubject.asObservable();
1400
- }
1401
- /**
1402
- * Authentication events stream.
1403
- * Emits all auth lifecycle events for custom logic, analytics, or UI updates.
1404
- */
1405
- get authEvents$() {
1406
- return this.authEventsSubject.asObservable();
1407
- }
1408
- /**
1409
- * Successful authentication events stream.
1410
- * Emits when user successfully authenticates (login, signup, social auth).
1411
- */
1412
- get authSuccess$() {
1413
- return this.authEventsSubject.pipe(filter((e) => e.type === "auth:success"));
1414
- }
1415
- /**
1416
- * Authentication error events stream.
1417
- * Emits when authentication fails (login error, OAuth error, etc.).
1418
- */
1419
- get authError$() {
1420
- return this.authEventsSubject.pipe(filter((e) => e.type === "auth:error" || e.type === "oauth:error"));
1421
- }
1422
- // ============================================================================
1423
- // Sync State Accessors (for guards, templates)
1424
- // ============================================================================
1425
- /**
1426
- * Check if authenticated (sync, uses cached state).
1427
- */
1428
- isAuthenticated() {
1429
- return this.client.isAuthenticatedSync();
1430
- }
1431
- /**
1432
- * Get current user (sync, uses cached state).
1433
- */
1434
- getCurrentUser() {
1435
- return this.client.getCurrentUser();
1436
- }
1437
- /**
1438
- * Get current challenge (sync).
1439
- */
1440
- getCurrentChallenge() {
1441
- return this.challengeSubject.value;
1442
- }
1443
- // ============================================================================
1444
- // Core Auth Methods
1445
- // ============================================================================
1446
- /**
1447
- * Login with identifier and password.
1448
- *
1449
- * @param identifier - User email or username
1450
- * @param password - User password
1451
- * @returns Promise with auth response or challenge
1452
- *
1453
- * @example
1454
- * ```typescript
1455
- * const response = await this.auth.login('user@example.com', 'password');
1456
- * if (response.challengeName) {
1457
- * // Handle challenge
1458
- * } else {
1459
- * // Login successful
1460
- * }
1461
- * ```
1462
- */
1463
- async login(identifier, password) {
1464
- const res = await this.client.login(identifier, password);
1465
- return this.updateChallengeState(res);
1466
- }
1467
- /**
1468
- * Signup with credentials.
1469
- *
1470
- * @param payload - Signup request payload
1471
- * @returns Promise with auth response or challenge
1472
- *
1473
- * @example
1474
- * ```typescript
1475
- * const response = await this.auth.signup({
1476
- * email: 'new@example.com',
1477
- * password: 'SecurePass123!',
1478
- * firstName: 'John',
1479
- * });
1480
- * ```
1481
- */
1482
- async signup(payload) {
1483
- const res = await this.client.signup(payload);
1484
- return this.updateChallengeState(res);
1485
- }
1486
- /**
1487
- * Logout current session.
1488
- *
1489
- * @param forgetDevice - If true, removes device trust
1490
- *
1491
- * @example
1492
- * ```typescript
1493
- * await this.auth.logout();
1494
- * ```
1495
- */
1496
- async logout(forgetDevice) {
1497
- await this.client.logout(forgetDevice);
1498
- this.challengeSubject.next(null);
1499
- this.currentUserSubject.next(null);
1500
- this.isAuthenticatedSubject.next(false);
1501
- if (this.config.tokenDelivery === "cookies" && typeof document !== "undefined") {
1502
- const csrfCookieName = this.config.csrf?.cookieName ?? "nauth_csrf_token";
1503
- try {
1504
- const url = new URL(this.config.baseUrl);
1505
- document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${url.hostname}`;
1506
- document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
1507
- } catch {
1508
- document.cookie = `${csrfCookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
1509
- }
1510
- }
1511
- }
1512
- /**
1513
- * Logout all sessions.
1514
- *
1515
- * Revokes all active sessions for the current user across all devices.
1516
- * Optionally revokes all trusted devices if forgetDevices is true.
1517
- *
1518
- * @param forgetDevices - If true, also revokes all trusted devices (default: false)
1519
- * @returns Promise with number of sessions revoked
1520
- *
1521
- * @example
1522
- * ```typescript
1523
- * const result = await this.auth.logoutAll();
1524
- * console.log(`Revoked ${result.revokedCount} sessions`);
1525
- * ```
1526
- */
1527
- async logoutAll(forgetDevices) {
1528
- const res = await this.client.logoutAll(forgetDevices);
1529
- this.challengeSubject.next(null);
1530
- this.currentUserSubject.next(null);
1531
- this.isAuthenticatedSubject.next(false);
1532
- return res;
1533
- }
1534
- /**
1535
- * Refresh tokens.
1536
- *
1537
- * @returns Promise with new tokens
1538
- *
1539
- * @example
1540
- * ```typescript
1541
- * const tokens = await this.auth.refresh();
1542
- * ```
1543
- */
1544
- async refresh() {
1545
- return this.client.refreshTokens();
1546
- }
1547
- // ============================================================================
1548
- // Account Recovery (Forgot Password)
1549
- // ============================================================================
1550
- /**
1551
- * Request a password reset code (forgot password).
1552
- *
1553
- * @param identifier - User email, username, or phone
1554
- * @returns Promise with password reset response
1555
- *
1556
- * @example
1557
- * ```typescript
1558
- * await this.auth.forgotPassword('user@example.com');
1559
- * ```
1560
- */
1561
- async forgotPassword(identifier) {
1562
- return this.client.forgotPassword(identifier);
1563
- }
1564
- /**
1565
- * Confirm a password reset code and set a new password.
1566
- *
1567
- * @param identifier - User email, username, or phone
1568
- * @param code - One-time reset code
1569
- * @param newPassword - New password
1570
- * @returns Promise with confirmation response
1571
- *
1572
- * @example
1573
- * ```typescript
1574
- * await this.auth.confirmForgotPassword('user@example.com', '123456', 'NewPass123!');
1575
- * ```
1576
- */
1577
- async confirmForgotPassword(identifier, code, newPassword) {
1578
- return this.client.confirmForgotPassword(identifier, code, newPassword);
1579
- }
1580
- /**
1581
- * Change user password (requires current password).
1582
- *
1583
- * @param oldPassword - Current password
1584
- * @param newPassword - New password (must meet requirements)
1585
- * @returns Promise that resolves when password is changed
1586
- *
1587
- * @example
1588
- * ```typescript
1589
- * await this.auth.changePassword('oldPassword123', 'newSecurePassword456!');
1590
- * ```
1591
- */
1592
- async changePassword(oldPassword, newPassword) {
1593
- return this.client.changePassword(oldPassword, newPassword);
1594
- }
1595
- /**
1596
- * Request password change (must change on next login).
1597
- *
1598
- * @returns Promise that resolves when request is sent
1599
- *
1600
- * @example
1601
- * ```typescript
1602
- * await this.auth.requestPasswordChange();
1603
- * ```
1604
- */
1605
- async requestPasswordChange() {
1606
- return this.client.requestPasswordChange();
1607
- }
1608
- // ============================================================================
1609
- // Profile Management
1610
- // ============================================================================
1611
- /**
1612
- * Get current user profile.
1613
- *
1614
- * @returns Promise of current user profile
1615
- *
1616
- * @example
1617
- * ```typescript
1618
- * const user = await this.auth.getProfile();
1619
- * console.log('User profile:', user);
1620
- * ```
1621
- */
1622
- async getProfile() {
1623
- const user = await this.client.getProfile();
1624
- this.currentUserSubject.next(user);
1625
- return user;
1626
- }
1627
- /**
1628
- * Update user profile.
1629
- *
1630
- * @param updates - Profile fields to update
1631
- * @returns Promise of updated user profile
1632
- *
1633
- * @example
1634
- * ```typescript
1635
- * const user = await this.auth.updateProfile({ firstName: 'John', lastName: 'Doe' });
1636
- * console.log('Profile updated:', user);
1637
- * ```
1638
- */
1639
- async updateProfile(updates) {
1640
- const user = await this.client.updateProfile(updates);
1641
- this.currentUserSubject.next(user);
1642
- return user;
1643
- }
1644
- // ============================================================================
1645
- // Challenge Flow Methods (Essential for any auth flow)
1646
- // ============================================================================
1647
- /**
1648
- * Respond to a challenge (VERIFY_EMAIL, VERIFY_PHONE, MFA_REQUIRED, etc.).
1649
- *
1650
- * @param response - Challenge response data
1651
- * @returns Promise with auth response or next challenge
1652
- *
1653
- * @example
1654
- * ```typescript
1655
- * const result = await this.auth.respondToChallenge({
1656
- * session: challengeSession,
1657
- * type: 'VERIFY_EMAIL',
1658
- * code: '123456',
1659
- * });
1660
- * ```
1661
- */
1662
- async respondToChallenge(response) {
1663
- const res = await this.client.respondToChallenge(response);
1664
- return this.updateChallengeState(res);
1665
- }
1666
- /**
1667
- * Resend challenge code.
1668
- *
1669
- * @param session - Challenge session token
1670
- * @returns Promise with destination information
1671
- *
1672
- * @example
1673
- * ```typescript
1674
- * const result = await this.auth.resendCode(session);
1675
- * console.log('Code sent to:', result.destination);
1676
- * ```
1677
- */
1678
- async resendCode(session) {
1679
- return this.client.resendCode(session);
1680
- }
1681
- /**
1682
- * Get MFA setup data (for MFA_SETUP_REQUIRED challenge).
1683
- *
1684
- * Returns method-specific setup information:
1685
- * - TOTP: { secret, qrCode, manualEntryKey }
1686
- * - SMS: { maskedPhone }
1687
- * - Email: { maskedEmail }
1688
- * - Passkey: WebAuthn registration options
1689
- *
1690
- * @param session - Challenge session token
1691
- * @param method - MFA method to set up
1692
- * @returns Promise of setup data response
1693
- *
1694
- * @example
1695
- * ```typescript
1696
- * const setupData = await this.auth.getSetupData(session, 'totp');
1697
- * console.log('QR Code:', setupData.setupData.qrCode);
1698
- * ```
1699
- */
1700
- async getSetupData(session, method) {
1701
- return this.client.getSetupData(session, method);
1702
- }
1703
- /**
1704
- * Get MFA challenge data (for MFA_REQUIRED challenge - e.g., passkey options).
1705
- *
1706
- * @param session - Challenge session token
1707
- * @param method - Challenge method
1708
- * @returns Promise of challenge data response
1709
- *
1710
- * @example
1711
- * ```typescript
1712
- * const challengeData = await this.auth.getChallengeData(session, 'passkey');
1713
- * ```
1714
- */
1715
- async getChallengeData(session, method) {
1716
- return this.client.getChallengeData(session, method);
1717
- }
1718
- /**
1719
- * Clear stored challenge (when navigating away from challenge flow).
1720
- *
1721
- * @returns Promise that resolves when challenge is cleared
1722
- *
1723
- * @example
1724
- * ```typescript
1725
- * await this.auth.clearChallenge();
1726
- * ```
1727
- */
1728
- async clearChallenge() {
1729
- await this.client.clearStoredChallenge();
1730
- this.challengeSubject.next(null);
1731
- }
1732
- // ============================================================================
1733
- // Social Authentication
1734
- // ============================================================================
1735
- /**
1736
- * Initiate social OAuth login flow.
1737
- * Redirects the browser to backend `/auth/social/:provider/redirect`.
1738
- *
1739
- * @param provider - Social provider ('google', 'apple', 'facebook')
1740
- * @param options - Optional redirect options
1741
- * @returns Promise that resolves when redirect starts
1742
- *
1743
- * @example
1744
- * ```typescript
1745
- * await this.auth.loginWithSocial('google', { returnTo: '/auth/callback' });
1746
- * ```
1747
- */
1748
- async loginWithSocial(provider, options) {
1749
- return this.client.loginWithSocial(provider, options);
1750
- }
1751
- /**
1752
- * Exchange an exchangeToken (from redirect callback URL) into an AuthResponse.
1753
- *
1754
- * Used for `tokenDelivery: 'json'` or hybrid flows where the backend redirects back
1755
- * with `exchangeToken` instead of setting cookies.
1756
- *
1757
- * @param exchangeToken - One-time exchange token from the callback URL
1758
- * @returns Promise of AuthResponse
1759
- *
1760
- * @example
1761
- * ```typescript
1762
- * const response = await this.auth.exchangeSocialRedirect(exchangeToken);
1763
- * ```
1764
- */
1765
- async exchangeSocialRedirect(exchangeToken) {
1766
- const res = await this.client.exchangeSocialRedirect(exchangeToken);
1767
- return this.updateChallengeState(res);
1768
- }
1769
- /**
1770
- * Verify native social token (mobile).
1771
- *
1772
- * @param request - Social verification request with provider and token
1773
- * @returns Promise of AuthResponse
1774
- *
1775
- * @example
1776
- * ```typescript
1777
- * const result = await this.auth.verifyNativeSocial({
1778
- * provider: 'google',
1779
- * idToken: nativeIdToken,
1780
- * });
1781
- * ```
1782
- */
1783
- async verifyNativeSocial(request) {
1784
- const res = await this.client.verifyNativeSocial(request);
1785
- return this.updateChallengeState(res);
1786
- }
1787
- /**
1788
- * Get linked social accounts.
1789
- *
1790
- * @returns Promise of linked accounts response
1791
- *
1792
- * @example
1793
- * ```typescript
1794
- * const accounts = await this.auth.getLinkedAccounts();
1795
- * console.log('Linked providers:', accounts.providers);
1796
- * ```
1797
- */
1798
- async getLinkedAccounts() {
1799
- return this.client.getLinkedAccounts();
1800
- }
1801
- /**
1802
- * Link social account.
1803
- *
1804
- * @param provider - Social provider to link
1805
- * @param code - OAuth authorization code
1806
- * @param state - OAuth state parameter
1807
- * @returns Promise with success message
1808
- *
1809
- * @example
1810
- * ```typescript
1811
- * await this.auth.linkSocialAccount('google', code, state);
1812
- * ```
1813
- */
1814
- async linkSocialAccount(provider, code, state) {
1815
- return this.client.linkSocialAccount(provider, code, state);
1816
- }
1817
- /**
1818
- * Unlink social account.
1819
- *
1820
- * @param provider - Social provider to unlink
1821
- * @returns Promise with success message
1822
- *
1823
- * @example
1824
- * ```typescript
1825
- * await this.auth.unlinkSocialAccount('google');
1826
- * ```
1827
- */
1828
- async unlinkSocialAccount(provider) {
1829
- return this.client.unlinkSocialAccount(provider);
1830
- }
1831
- // ============================================================================
1832
- // MFA Management
1833
- // ============================================================================
1834
- /**
1835
- * Get MFA status for the current user.
1836
- *
1837
- * @returns Promise of MFA status
1838
- *
1839
- * @example
1840
- * ```typescript
1841
- * const status = await this.auth.getMfaStatus();
1842
- * console.log('MFA enabled:', status.enabled);
1843
- * ```
1844
- */
1845
- async getMfaStatus() {
1846
- return this.client.getMfaStatus();
1847
- }
1848
- /**
1849
- * Get MFA devices for the current user.
1850
- *
1851
- * @returns Promise of MFA devices array
1852
- *
1853
- * @example
1854
- * ```typescript
1855
- * const devices = await this.auth.getMfaDevices();
1856
- * ```
1857
- */
1858
- async getMfaDevices() {
1859
- return this.client.getMfaDevices();
1860
- }
1861
- /**
1862
- * Setup MFA device (authenticated user).
1863
- *
1864
- * @param method - MFA method to set up
1865
- * @returns Promise of setup data
1866
- *
1867
- * @example
1868
- * ```typescript
1869
- * const setupData = await this.auth.setupMfaDevice('totp');
1870
- * ```
1871
- */
1872
- async setupMfaDevice(method) {
1873
- return this.client.setupMfaDevice(method);
1874
- }
1875
- /**
1876
- * Verify MFA setup (authenticated user).
1877
- *
1878
- * @param method - MFA method
1879
- * @param setupData - Setup data from setupMfaDevice
1880
- * @param deviceName - Optional device name
1881
- * @returns Promise with device ID
1882
- *
1883
- * @example
1884
- * ```typescript
1885
- * const result = await this.auth.verifyMfaSetup('totp', { code: '123456' }, 'My Phone');
1886
- * ```
1887
- */
1888
- async verifyMfaSetup(method, setupData, deviceName) {
1889
- return this.client.verifyMfaSetup(method, setupData, deviceName);
1890
- }
1891
- /**
1892
- * Remove MFA device.
1893
- *
1894
- * @param method - MFA method to remove
1895
- * @returns Promise with success message
1896
- *
1897
- * @example
1898
- * ```typescript
1899
- * await this.auth.removeMfaDevice('sms');
1900
- * ```
1901
- */
1902
- async removeMfaDevice(method) {
1903
- return this.client.removeMfaDevice(method);
1904
- }
1905
- /**
1906
- * Set preferred MFA method.
1907
- *
1908
- * @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey')
1909
- * @returns Promise with success message
1910
- *
1911
- * @example
1912
- * ```typescript
1913
- * await this.auth.setPreferredMfaMethod('totp');
1914
- * ```
1915
- */
1916
- async setPreferredMfaMethod(method) {
1917
- return this.client.setPreferredMfaMethod(method);
1918
- }
1919
- /**
1920
- * Generate backup codes.
1921
- *
1922
- * @returns Promise of backup codes array
1923
- *
1924
- * @example
1925
- * ```typescript
1926
- * const codes = await this.auth.generateBackupCodes();
1927
- * console.log('Backup codes:', codes);
1928
- * ```
1929
- */
1930
- async generateBackupCodes() {
1931
- return this.client.generateBackupCodes();
1932
- }
1933
- /**
1934
- * Set MFA exemption (admin/test scenarios).
1935
- *
1936
- * @param exempt - Whether to exempt user from MFA
1937
- * @param reason - Optional reason for exemption
1938
- * @returns Promise that resolves when exemption is set
1939
- *
1940
- * @example
1941
- * ```typescript
1942
- * await this.auth.setMfaExemption(true, 'Test account');
1943
- * ```
1944
- */
1945
- async setMfaExemption(exempt, reason) {
1946
- return this.client.setMfaExemption(exempt, reason);
1947
- }
1948
- // ============================================================================
1949
- // Device Trust
1950
- // ============================================================================
1951
- /**
1952
- * Trust current device.
1953
- *
1954
- * @returns Promise with device token
1955
- *
1956
- * @example
1957
- * ```typescript
1958
- * const result = await this.auth.trustDevice();
1959
- * console.log('Device trusted:', result.deviceToken);
1960
- * ```
1961
- */
1962
- async trustDevice() {
1963
- return this.client.trustDevice();
1964
- }
1965
- /**
1966
- * Check if the current device is trusted.
1967
- *
1968
- * @returns Promise with trusted status
1969
- *
1970
- * @example
1971
- * ```typescript
1972
- * const result = await this.auth.isTrustedDevice();
1973
- * if (result.trusted) {
1974
- * console.log('This device is trusted');
1975
- * }
1976
- * ```
1977
- */
1978
- async isTrustedDevice() {
1979
- return this.client.isTrustedDevice();
1980
- }
1981
- // ============================================================================
1982
- // Audit History
1983
- // ============================================================================
1984
- /**
1985
- * Get paginated audit history for the current user.
1986
- *
1987
- * @param params - Query parameters for filtering and pagination
1988
- * @returns Promise of audit history response
1989
- *
1990
- * @example
1991
- * ```typescript
1992
- * const history = await this.auth.getAuditHistory({
1993
- * page: 1,
1994
- * limit: 20,
1995
- * eventType: 'LOGIN_SUCCESS'
1996
- * });
1997
- * console.log('Audit history:', history);
1998
- * ```
1999
- */
2000
- async getAuditHistory(params) {
2001
- return this.client.getAuditHistory(params);
2002
- }
2003
- // ============================================================================
2004
- // Escape Hatch
2005
- // ============================================================================
2006
- /**
2007
- * Expose underlying NAuthClient for advanced scenarios.
2008
- *
2009
- * @deprecated All core functionality is now exposed directly on AuthService as Promises.
2010
- * Use the direct methods on AuthService instead (e.g., `auth.changePassword()` instead of `auth.getClient().changePassword()`).
2011
- * This method is kept for backward compatibility only and may be removed in a future version.
2012
- *
2013
- * @returns The underlying NAuthClient instance
2014
- *
2015
- * @example
2016
- * ```typescript
2017
- * // Deprecated - use direct methods instead
2018
- * const status = await this.auth.getClient().getMfaStatus();
2019
- *
2020
- * // Preferred - use direct methods
2021
- * const status = await this.auth.getMfaStatus();
2022
- * ```
2023
- */
2024
- getClient() {
2025
- return this.client;
2026
- }
2027
- // ============================================================================
2028
- // Internal Methods
2029
- // ============================================================================
2030
- /**
2031
- * Initialize by hydrating state from storage.
2032
- * Called automatically on construction.
2033
- */
2034
- async initialize() {
2035
- if (this.initialized) return;
2036
- this.initialized = true;
2037
- await this.client.initialize();
2038
- const storedChallenge = await this.client.getStoredChallenge();
2039
- if (storedChallenge) {
2040
- this.challengeSubject.next(storedChallenge);
2041
- }
2042
- const user = this.client.getCurrentUser();
2043
- if (user) {
2044
- this.currentUserSubject.next(user);
2045
- this.isAuthenticatedSubject.next(true);
2046
- }
2047
- }
2048
- /**
2049
- * Update challenge state after auth response.
2050
- */
2051
- updateChallengeState(response) {
2052
- if (response.challengeName) {
2053
- this.challengeSubject.next(response);
2054
- } else {
2055
- this.challengeSubject.next(null);
2056
- }
2057
- return response;
2058
- }
2059
- };
2060
- __name(AuthService, "AuthService");
2061
- AuthService = __decorateClass([
2062
- Injectable2({
2063
- providedIn: "root"
2064
- }),
2065
- __decorateParam(0, Optional()),
2066
- __decorateParam(0, Inject(NAUTH_CLIENT_CONFIG))
2067
- ], AuthService);
2068
-
2069
- // src/angular/auth.interceptor.ts
2070
- import { inject as inject2, PLATFORM_ID } from "@angular/core";
2071
- import { isPlatformBrowser } from "@angular/common";
2072
- import { HttpClient as HttpClient2, HttpErrorResponse as HttpErrorResponse2 } from "@angular/common/http";
2073
- import { Router } from "@angular/router";
2074
- import { catchError, switchMap, throwError, filter as filter2, take, BehaviorSubject as BehaviorSubject2, from } from "rxjs";
2075
- var isRefreshing = false;
2076
- var refreshTokenSubject = new BehaviorSubject2(null);
2077
- var retriedRequests = /* @__PURE__ */ new WeakSet();
2078
- function getCsrfToken(cookieName) {
2079
- if (typeof document === "undefined") return null;
2080
- const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
2081
- return match ? decodeURIComponent(match[2]) : null;
2082
- }
2083
- __name(getCsrfToken, "getCsrfToken");
2084
- var authInterceptor = /* @__PURE__ */ __name((req, next) => {
2085
- const config = inject2(NAUTH_CLIENT_CONFIG);
2086
- const http = inject2(HttpClient2);
2087
- const authService = inject2(AuthService);
2088
- const platformId = inject2(PLATFORM_ID);
2089
- const router = inject2(Router);
2090
- const isBrowser = isPlatformBrowser(platformId);
2091
- if (!isBrowser) {
2092
- return next(req);
2093
- }
2094
- const tokenDelivery = config.tokenDelivery;
2095
- const baseUrl = config.baseUrl;
2096
- const endpoints = config.endpoints ?? {};
2097
- const refreshPath = endpoints.refresh ?? "/refresh";
2098
- const loginPath = endpoints.login ?? "/login";
2099
- const signupPath = endpoints.signup ?? "/signup";
2100
- const socialExchangePath = endpoints.socialExchange ?? "/social/exchange";
2101
- const refreshUrl = `${baseUrl}${refreshPath}`;
2102
- const isAuthApiRequest = req.url.includes(baseUrl);
2103
- const isRefreshEndpoint = req.url.includes(refreshPath);
2104
- const isPublicEndpoint = req.url.includes(loginPath) || req.url.includes(signupPath) || req.url.includes(socialExchangePath);
2105
- let authReq = req;
2106
- if (tokenDelivery === "cookies") {
2107
- authReq = authReq.clone({ withCredentials: true });
2108
- if (["POST", "PUT", "PATCH", "DELETE"].includes(req.method)) {
2109
- const csrfCookieName = config.csrf?.cookieName ?? "nauth_csrf_token";
2110
- const csrfHeaderName = config.csrf?.headerName ?? "x-csrf-token";
2111
- const csrfToken = getCsrfToken(csrfCookieName);
2112
- if (csrfToken) {
2113
- authReq = authReq.clone({ setHeaders: { [csrfHeaderName]: csrfToken } });
2114
- }
2115
- }
2116
- }
2117
- return next(authReq).pipe(
2118
- catchError((error) => {
2119
- const shouldHandle = error instanceof HttpErrorResponse2 && error.status === 401 && isAuthApiRequest && !isRefreshEndpoint && !isPublicEndpoint && !retriedRequests.has(req);
2120
- if (!shouldHandle) {
2121
- return throwError(() => error);
2122
- }
2123
- if (config.debug) {
2124
- console.warn("[nauth-interceptor] 401 detected:", req.url);
2125
- }
2126
- if (!isRefreshing) {
2127
- isRefreshing = true;
2128
- refreshTokenSubject.next(null);
2129
- if (config.debug) {
2130
- console.warn("[nauth-interceptor] Starting refresh...");
2131
- }
2132
- const refresh$ = tokenDelivery === "cookies" ? http.post(refreshUrl, {}, { withCredentials: true }) : from(authService.refresh());
2133
- return refresh$.pipe(
2134
- switchMap((response) => {
2135
- if (config.debug) {
2136
- console.warn("[nauth-interceptor] Refresh successful");
2137
- }
2138
- isRefreshing = false;
2139
- const newToken = "accessToken" in response ? response.accessToken : "success";
2140
- refreshTokenSubject.next(newToken ?? "success");
2141
- const retryReq = buildRetryRequest(authReq, tokenDelivery, newToken);
2142
- retriedRequests.add(retryReq);
2143
- if (config.debug) {
2144
- console.warn("[nauth-interceptor] Retrying:", req.url);
2145
- }
2146
- return next(retryReq);
2147
- }),
2148
- catchError((err) => {
2149
- if (config.debug) {
2150
- console.error("[nauth-interceptor] Refresh failed:", err);
2151
- }
2152
- isRefreshing = false;
2153
- refreshTokenSubject.next(null);
2154
- if (config.redirects?.sessionExpired) {
2155
- router.navigateByUrl(config.redirects.sessionExpired).catch((navError) => {
2156
- if (config.debug) {
2157
- console.error("[nauth-interceptor] Navigation failed:", navError);
2158
- }
2159
- });
2160
- }
2161
- return throwError(() => err);
2162
- })
2163
- );
2164
- } else {
2165
- if (config.debug) {
2166
- console.warn("[nauth-interceptor] Waiting for refresh...");
2167
- }
2168
- return refreshTokenSubject.pipe(
2169
- filter2((token) => token !== null),
2170
- take(1),
2171
- switchMap((token) => {
2172
- if (config.debug) {
2173
- console.warn("[nauth-interceptor] Refresh done, retrying:", req.url);
2174
- }
2175
- const retryReq = buildRetryRequest(authReq, tokenDelivery, token);
2176
- retriedRequests.add(retryReq);
2177
- return next(retryReq);
2178
- })
2179
- );
2180
- }
2181
- })
2182
- );
2183
- }, "authInterceptor");
2184
- function buildRetryRequest(originalReq, tokenDelivery, newToken) {
2185
- if (tokenDelivery === "json" && newToken && newToken !== "success") {
2186
- return originalReq.clone({
2187
- setHeaders: { Authorization: `Bearer ${newToken}` }
2188
- });
2189
- }
2190
- return originalReq.clone();
2191
- }
2192
- __name(buildRetryRequest, "buildRetryRequest");
2193
- var _AuthInterceptor = class _AuthInterceptor {
2194
- intercept(req, next) {
2195
- return authInterceptor(req, next);
2196
- }
2197
- };
2198
- __name(_AuthInterceptor, "AuthInterceptor");
2199
- var AuthInterceptor = _AuthInterceptor;
2200
-
2201
- // src/angular/auth.guard.ts
2202
- import { inject as inject3 } from "@angular/core";
2203
- import { Router as Router2 } from "@angular/router";
2204
- function authGuard(redirectTo = "/login") {
2205
- return () => {
2206
- const auth = inject3(AuthService);
2207
- const router = inject3(Router2);
2208
- if (auth.isAuthenticated()) {
2209
- return true;
2210
- }
2211
- return router.createUrlTree([redirectTo]);
2212
- };
2213
- }
2214
- __name(authGuard, "authGuard");
2215
- var _AuthGuard = class _AuthGuard {
2216
- /**
2217
- * @param auth - Authentication service
2218
- * @param router - Angular router
2219
- */
2220
- constructor(auth, router) {
2221
- this.auth = auth;
2222
- this.router = router;
2223
- }
2224
- /**
2225
- * Check if route can be activated.
2226
- *
2227
- * @returns True if authenticated, otherwise redirects to login
2228
- */
2229
- canActivate() {
2230
- if (this.auth.isAuthenticated()) {
2231
- return true;
2232
- }
2233
- return this.router.createUrlTree(["/login"]);
2234
- }
2235
- };
2236
- __name(_AuthGuard, "AuthGuard");
2237
- var AuthGuard = _AuthGuard;
2238
-
2239
- // src/angular/social-redirect-callback.guard.ts
2240
- import { inject as inject4, PLATFORM_ID as PLATFORM_ID2 } from "@angular/core";
2241
- import { isPlatformBrowser as isPlatformBrowser2 } from "@angular/common";
2242
- var socialRedirectCallbackGuard = /* @__PURE__ */ __name(async () => {
2243
- const auth = inject4(AuthService);
2244
- const config = inject4(NAUTH_CLIENT_CONFIG);
2245
- const platformId = inject4(PLATFORM_ID2);
2246
- const isBrowser = isPlatformBrowser2(platformId);
2247
- if (!isBrowser) {
2248
- return false;
2249
- }
2250
- const params = new URLSearchParams(window.location.search);
2251
- const error = params.get("error");
2252
- const exchangeToken = params.get("exchangeToken");
2253
- if (error) {
2254
- const errorUrl = config.redirects?.oauthError || "/login";
2255
- window.location.replace(errorUrl);
2256
- return false;
2257
- }
2258
- if (!exchangeToken) {
2259
- try {
2260
- await auth.getProfile();
2261
- } catch {
2262
- const errorUrl = config.redirects?.oauthError || "/login";
2263
- window.location.replace(errorUrl);
2264
- return false;
2265
- }
2266
- const successUrl2 = config.redirects?.success || "/";
2267
- window.location.replace(successUrl2);
2268
- return false;
2269
- }
2270
- const response = await auth.exchangeSocialRedirect(exchangeToken);
2271
- if (response.challengeName) {
2272
- const challengeBase = config.redirects?.challengeBase || "/auth/challenge";
2273
- const challengeRoute = response.challengeName.toLowerCase().replace(/_/g, "-");
2274
- window.location.replace(`${challengeBase}/${challengeRoute}`);
2275
- return false;
2276
- }
2277
- const successUrl = config.redirects?.success || "/";
2278
- window.location.replace(successUrl);
2279
- return false;
2280
- }, "socialRedirectCallbackGuard");
2281
-
2282
- // src/angular/auth.module.ts
2283
- import { NgModule } from "@angular/core";
2284
- import { HTTP_INTERCEPTORS } from "@angular/common/http";
2285
- var NAuthModule = class {
2286
- /**
2287
- * Configure the module with client settings.
2288
- *
2289
- * @param config - Client configuration
2290
- */
2291
- static forRoot(config) {
2292
- return {
2293
- ngModule: NAuthModule,
2294
- providers: [
2295
- { provide: NAUTH_CLIENT_CONFIG, useValue: config },
2296
- { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
2297
- ]
2298
- };
2299
- }
2300
- };
2301
- __name(NAuthModule, "NAuthModule");
2302
- NAuthModule = __decorateClass([
2303
- NgModule({})
2304
- ], NAuthModule);
2305
- export {
2306
- AngularHttpAdapter,
2307
- AuthGuard,
2308
- AuthInterceptor,
2309
- AuthService,
2310
- NAUTH_CLIENT_CONFIG,
2311
- NAuthModule,
2312
- authGuard,
2313
- authInterceptor,
2314
- socialRedirectCallbackGuard
2315
- };
2316
- //# sourceMappingURL=index.mjs.map