@nauth-toolkit/client 0.1.3

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