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