@nauth-toolkit/client-angular 0.1.56 → 0.1.58

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.
Files changed (66) hide show
  1. package/esm2022/lib/auth.guard.mjs +83 -0
  2. package/esm2022/lib/auth.interceptor.mjs +158 -0
  3. package/esm2022/lib/social-redirect-callback.guard.mjs +81 -0
  4. package/esm2022/nauth-toolkit-client-angular.mjs +5 -0
  5. package/esm2022/ngmodule/auth.interceptor.class.mjs +109 -0
  6. package/esm2022/ngmodule/auth.service.mjs +777 -0
  7. package/esm2022/ngmodule/http-adapter.mjs +127 -0
  8. package/esm2022/ngmodule/nauth.module.mjs +65 -0
  9. package/esm2022/ngmodule/tokens.mjs +6 -0
  10. package/esm2022/public-api.mjs +19 -0
  11. package/esm2022/src/standalone/nauth-toolkit-client-angular-src-standalone.mjs +5 -0
  12. package/esm2022/src/standalone/public-api.mjs +12 -0
  13. package/esm2022/standalone/auth.guard.mjs +83 -0
  14. package/esm2022/standalone/auth.interceptor.mjs +158 -0
  15. package/esm2022/standalone/auth.service.mjs +777 -0
  16. package/esm2022/standalone/http-adapter.mjs +127 -0
  17. package/esm2022/standalone/nauth-toolkit-client-angular-standalone.mjs +5 -0
  18. package/esm2022/standalone/public-api.mjs +16 -0
  19. package/esm2022/standalone/social-redirect-callback.guard.mjs +81 -0
  20. package/esm2022/standalone/tokens.mjs +6 -0
  21. package/fesm2022/nauth-toolkit-client-angular-src-standalone.mjs +17 -0
  22. package/fesm2022/nauth-toolkit-client-angular-src-standalone.mjs.map +1 -0
  23. package/fesm2022/nauth-toolkit-client-angular-standalone.mjs +1229 -0
  24. package/fesm2022/nauth-toolkit-client-angular-standalone.mjs.map +1 -0
  25. package/fesm2022/nauth-toolkit-client-angular.mjs +1390 -0
  26. package/fesm2022/nauth-toolkit-client-angular.mjs.map +1 -0
  27. package/index.d.ts +5 -0
  28. package/{src/lib/auth.guard.ts → lib/auth.guard.d.ts} +15 -37
  29. package/lib/auth.interceptor.d.ts +15 -0
  30. package/lib/social-redirect-callback.guard.d.ts +25 -0
  31. package/ngmodule/auth.interceptor.class.d.ts +34 -0
  32. package/ngmodule/auth.service.d.ts +580 -0
  33. package/ngmodule/http-adapter.d.ts +53 -0
  34. package/ngmodule/nauth.module.d.ts +31 -0
  35. package/{src/ngmodule/tokens.ts → ngmodule/tokens.d.ts} +1 -2
  36. package/package.json +30 -20
  37. package/{src/public-api.ts → public-api.d.ts} +0 -6
  38. package/src/standalone/index.d.ts +5 -0
  39. package/src/standalone/{public-api.ts → public-api.d.ts} +0 -2
  40. package/standalone/{auth.guard.ts → auth.guard.d.ts} +15 -37
  41. package/standalone/auth.interceptor.d.ts +15 -0
  42. package/standalone/auth.service.d.ts +580 -0
  43. package/standalone/http-adapter.d.ts +53 -0
  44. package/standalone/index.d.ts +5 -0
  45. package/standalone/{public-api.ts → public-api.d.ts} +1 -6
  46. package/standalone/social-redirect-callback.guard.d.ts +25 -0
  47. package/standalone/{tokens.ts → tokens.d.ts} +1 -2
  48. package/ng-package.json +0 -12
  49. package/src/lib/auth.interceptor.ts +0 -194
  50. package/src/lib/social-redirect-callback.guard.ts +0 -87
  51. package/src/ngmodule/auth.interceptor.class.ts +0 -124
  52. package/src/ngmodule/auth.service.ts +0 -865
  53. package/src/ngmodule/http-adapter.ts +0 -79
  54. package/src/ngmodule/nauth.module.ts +0 -59
  55. package/src/package.json +0 -11
  56. package/src/standalone/ng-package.json +0 -7
  57. package/src/standalone/package.json +0 -8
  58. package/standalone/auth.interceptor.ts +0 -194
  59. package/standalone/auth.service.ts +0 -865
  60. package/standalone/http-adapter.ts +0 -79
  61. package/standalone/ng-package.json +0 -7
  62. package/standalone/package.json +0 -8
  63. package/standalone/social-redirect-callback.guard.ts +0 -87
  64. package/tsconfig.json +0 -10
  65. package/tsconfig.lib.json +0 -28
  66. package/tsconfig.lib.prod.json +0 -10
package/ng-package.json DELETED
@@ -1,12 +0,0 @@
1
- {
2
- "$schema": "node_modules/ng-packagr/ng-package.schema.json",
3
- "dest": "./dist",
4
- "lib": {
5
- "entryFile": "src/public-api.ts",
6
- "flatModuleFile": "nauth-toolkit-client-angular"
7
- },
8
- "allowedNonPeerDependencies": [
9
- "@nauth-toolkit/client"
10
- ]
11
- }
12
-
@@ -1,194 +0,0 @@
1
- import { inject, PLATFORM_ID } from '@angular/core';
2
- import { isPlatformBrowser } from '@angular/common';
3
- import { HttpHandlerFn, HttpInterceptorFn, HttpRequest, HttpClient, HttpErrorResponse } from '@angular/common/http';
4
- import { Router } from '@angular/router';
5
- import { catchError, switchMap, throwError, filter, take, BehaviorSubject, from } from 'rxjs';
6
- import { NAUTH_CLIENT_CONFIG } from '../ngmodule/tokens';
7
- import { AuthService } from '../ngmodule/auth.service';
8
-
9
- /**
10
- * Refresh state management.
11
- * BehaviorSubject pattern is the industry-standard for token refresh.
12
- */
13
- let isRefreshing = false;
14
- const refreshTokenSubject = new BehaviorSubject<string | null>(null);
15
-
16
- /**
17
- * Track retried requests to prevent infinite loops.
18
- */
19
- const retriedRequests = new WeakSet<HttpRequest<unknown>>();
20
-
21
- /**
22
- * Get CSRF token from cookie.
23
- */
24
- function getCsrfToken(cookieName: string): string | null {
25
- if (typeof document === 'undefined') return null;
26
- const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
27
- return match ? decodeURIComponent(match[2]) : null;
28
- }
29
-
30
- /**
31
- * Angular HTTP interceptor for nauth-toolkit.
32
- *
33
- * Handles:
34
- * - Cookies mode: withCredentials + CSRF tokens + refresh via POST
35
- * - JSON mode: refresh via SDK, retry with new token
36
- */
37
- export const authInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => {
38
- const config = inject(NAUTH_CLIENT_CONFIG);
39
- const http = inject(HttpClient);
40
- const authService = inject(AuthService);
41
- const platformId = inject(PLATFORM_ID);
42
- const router = inject(Router);
43
- const isBrowser = isPlatformBrowser(platformId);
44
-
45
- if (!isBrowser) {
46
- return next(req);
47
- }
48
-
49
- const tokenDelivery = config.tokenDelivery;
50
- const baseUrl = config.baseUrl;
51
- const endpoints = config.endpoints ?? {};
52
- const refreshPath = endpoints.refresh ?? '/refresh';
53
- const loginPath = endpoints.login ?? '/login';
54
- const signupPath = endpoints.signup ?? '/signup';
55
- const socialExchangePath = endpoints.socialExchange ?? '/social/exchange';
56
- const refreshUrl = `${baseUrl}${refreshPath}`;
57
-
58
- const isAuthApiRequest = req.url.includes(baseUrl);
59
- const isRefreshEndpoint = req.url.includes(refreshPath);
60
- const isPublicEndpoint =
61
- req.url.includes(loginPath) || req.url.includes(signupPath) || req.url.includes(socialExchangePath);
62
-
63
- // Build request with credentials (cookies mode only)
64
- let authReq = req;
65
- if (tokenDelivery === 'cookies') {
66
- authReq = authReq.clone({ withCredentials: true });
67
-
68
- if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
69
- const csrfCookieName = config.csrf?.cookieName ?? 'nauth_csrf_token';
70
- const csrfHeaderName = config.csrf?.headerName ?? 'x-csrf-token';
71
- const csrfToken = getCsrfToken(csrfCookieName);
72
- if (csrfToken) {
73
- authReq = authReq.clone({ setHeaders: { [csrfHeaderName]: csrfToken } });
74
- }
75
- }
76
- }
77
-
78
- return next(authReq).pipe(
79
- catchError((error: unknown) => {
80
- const shouldHandle =
81
- error instanceof HttpErrorResponse &&
82
- error.status === 401 &&
83
- isAuthApiRequest &&
84
- !isRefreshEndpoint &&
85
- !isPublicEndpoint &&
86
- !retriedRequests.has(req);
87
-
88
- if (!shouldHandle) {
89
- return throwError(() => error);
90
- }
91
-
92
- if (config.debug) {
93
- console.warn('[nauth-interceptor] 401 detected:', req.url);
94
- }
95
-
96
- if (!isRefreshing) {
97
- isRefreshing = true;
98
- refreshTokenSubject.next(null);
99
-
100
- if (config.debug) {
101
- console.warn('[nauth-interceptor] Starting refresh...');
102
- }
103
-
104
- // Refresh based on mode
105
- const refresh$ =
106
- tokenDelivery === 'cookies'
107
- ? http.post<{ accessToken?: string }>(refreshUrl, {}, { withCredentials: true })
108
- : from(authService.refresh());
109
-
110
- return refresh$.pipe(
111
- switchMap((response) => {
112
- if (config.debug) {
113
- console.warn('[nauth-interceptor] Refresh successful');
114
- }
115
- isRefreshing = false;
116
-
117
- // Get new token (JSON mode) or signal success (cookies mode)
118
- const newToken = 'accessToken' in response ? response.accessToken : 'success';
119
- refreshTokenSubject.next(newToken ?? 'success');
120
-
121
- // Build retry request
122
- const retryReq = buildRetryRequest(authReq, tokenDelivery, newToken);
123
- retriedRequests.add(retryReq);
124
-
125
- if (config.debug) {
126
- console.warn('[nauth-interceptor] Retrying:', req.url);
127
- }
128
- return next(retryReq);
129
- }),
130
- catchError((err) => {
131
- if (config.debug) {
132
- console.error('[nauth-interceptor] Refresh failed:', err);
133
- }
134
- isRefreshing = false;
135
- refreshTokenSubject.next(null);
136
-
137
- // Handle session expiration - redirect to configured URL
138
- if (config.redirects?.sessionExpired) {
139
- router.navigateByUrl(config.redirects.sessionExpired).catch((navError) => {
140
- if (config.debug) {
141
- console.error('[nauth-interceptor] Navigation failed:', navError);
142
- }
143
- });
144
- }
145
-
146
- return throwError(() => err);
147
- }),
148
- );
149
- } else {
150
- // Wait for ongoing refresh
151
- if (config.debug) {
152
- console.warn('[nauth-interceptor] Waiting for refresh...');
153
- }
154
- return refreshTokenSubject.pipe(
155
- filter((token): token is string => token !== null),
156
- take(1),
157
- switchMap((token) => {
158
- if (config.debug) {
159
- console.warn('[nauth-interceptor] Refresh done, retrying:', req.url);
160
- }
161
- const retryReq = buildRetryRequest(authReq, tokenDelivery, token);
162
- retriedRequests.add(retryReq);
163
- return next(retryReq);
164
- }),
165
- );
166
- }
167
- }),
168
- );
169
- };
170
-
171
- /**
172
- * Build retry request with appropriate auth.
173
- */
174
- function buildRetryRequest(
175
- originalReq: HttpRequest<unknown>,
176
- tokenDelivery: string,
177
- newToken?: string,
178
- ): HttpRequest<unknown> {
179
- if (tokenDelivery === 'json' && newToken && newToken !== 'success') {
180
- return originalReq.clone({
181
- setHeaders: { Authorization: `Bearer ${newToken}` },
182
- });
183
- }
184
- return originalReq.clone();
185
- }
186
-
187
- /**
188
- * Class-based interceptor for NgModule compatibility.
189
- */
190
- export class AuthInterceptor {
191
- intercept(req: HttpRequest<unknown>, next: HttpHandlerFn) {
192
- return authInterceptor(req, next);
193
- }
194
- }
@@ -1,87 +0,0 @@
1
- import { inject, PLATFORM_ID } from '@angular/core';
2
- import { isPlatformBrowser } from '@angular/common';
3
- import { type CanActivateFn } from '@angular/router';
4
- import { AuthService } from '../ngmodule/auth.service';
5
- import { NAUTH_CLIENT_CONFIG } from '../ngmodule/tokens';
6
-
7
- /**
8
- * Social redirect callback route guard.
9
- *
10
- * This guard supports the redirect-first social flow where the backend redirects
11
- * back to the frontend with:
12
- * - `appState` (always optional)
13
- * - `exchangeToken` (present for json/hybrid flows, and for cookie flows that return a challenge)
14
- * - `error` / `error_description` (provider errors)
15
- *
16
- * Behavior:
17
- * - If `exchangeToken` exists: exchanges it via backend and redirects to success or challenge routes.
18
- * - If no `exchangeToken`: treat as cookie-success path and redirect to success route.
19
- * - If `error` exists: redirects to oauthError route.
20
- *
21
- * @example
22
- * ```typescript
23
- * import { socialRedirectCallbackGuard } from '@nauth-toolkit/client/angular';
24
- *
25
- * export const routes: Routes = [
26
- * { path: 'auth/callback', canActivate: [socialRedirectCallbackGuard], component: CallbackComponent },
27
- * ];
28
- * ```
29
- */
30
- export const socialRedirectCallbackGuard: CanActivateFn = async (): Promise<boolean> => {
31
- const auth = inject(AuthService);
32
- const config = inject(NAUTH_CLIENT_CONFIG);
33
- const platformId = inject(PLATFORM_ID);
34
- const isBrowser = isPlatformBrowser(platformId);
35
-
36
- if (!isBrowser) {
37
- return false;
38
- }
39
-
40
- const params = new URLSearchParams(window.location.search);
41
- const error = params.get('error');
42
- const exchangeToken = params.get('exchangeToken');
43
-
44
- // Provider error: redirect to oauthError
45
- if (error) {
46
- const errorUrl = config.redirects?.oauthError || '/login';
47
- window.location.replace(errorUrl);
48
- return false;
49
- }
50
-
51
- // No exchangeToken: cookie success path; redirect to success.
52
- //
53
- // Note: we do not "activate" the callback route to avoid consumers needing to render a page.
54
- if (!exchangeToken) {
55
- // ============================================================================
56
- // Cookies mode: hydrate user state before redirecting
57
- // ============================================================================
58
- // WHY: In cookie delivery, the OAuth callback completes via browser redirects, so the frontend
59
- // does not receive a JSON AuthResponse to populate the SDK's cached `currentUser`.
60
- //
61
- // Without this, sync guards (`authGuard`) can immediately redirect to /login because
62
- // `currentUser` is still null even though cookies were set successfully.
63
- try {
64
- await auth.getProfile();
65
- } catch {
66
- const errorUrl = config.redirects?.oauthError || '/login';
67
- window.location.replace(errorUrl);
68
- return false;
69
- }
70
- const successUrl = config.redirects?.success || '/';
71
- window.location.replace(successUrl);
72
- return false;
73
- }
74
-
75
- // Exchange token and route accordingly
76
- const response = await auth.exchangeSocialRedirect(exchangeToken);
77
- if (response.challengeName) {
78
- const challengeBase = config.redirects?.challengeBase || '/auth/challenge';
79
- const challengeRoute = response.challengeName.toLowerCase().replace(/_/g, '-');
80
- window.location.replace(`${challengeBase}/${challengeRoute}`);
81
- return false;
82
- }
83
-
84
- const successUrl = config.redirects?.success || '/';
85
- window.location.replace(successUrl);
86
- return false;
87
- };
@@ -1,124 +0,0 @@
1
- import { Injectable, Inject } from '@angular/core';
2
- import {
3
- HttpInterceptor,
4
- HttpRequest,
5
- HttpHandler,
6
- HttpEvent,
7
- HttpClient,
8
- HttpErrorResponse,
9
- } from '@angular/common/http';
10
- import { Router } from '@angular/router';
11
- import { Observable, catchError, switchMap, throwError, filter, take, BehaviorSubject, from } from 'rxjs';
12
- import { NAUTH_CLIENT_CONFIG } from './tokens';
13
- import { AuthService } from './auth.service';
14
- import { NAuthClientConfig } from '@nauth-toolkit/client';
15
-
16
- /**
17
- * Refresh state management.
18
- */
19
- let isRefreshing = false;
20
- const refreshTokenSubject = new BehaviorSubject<string | null>(null);
21
- const retriedRequests = new WeakSet<HttpRequest<unknown>>();
22
-
23
- /**
24
- * Get CSRF token from cookie.
25
- */
26
- function getCsrfToken(cookieName: string): string | null {
27
- if (typeof document === 'undefined') return null;
28
- const match = document.cookie.match(new RegExp(`(^| )${cookieName}=([^;]+)`));
29
- return match ? decodeURIComponent(match[2]) : null;
30
- }
31
-
32
- /**
33
- * Class-based HTTP interceptor for NgModule apps (Angular < 17).
34
- *
35
- * For standalone components (Angular 17+), use the functional `authInterceptor` instead.
36
- *
37
- * @example
38
- * ```typescript
39
- * // app.module.ts
40
- * import { HTTP_INTERCEPTORS } from '@angular/common/http';
41
- * import { AuthInterceptorClass } from '@nauth-toolkit/client-angular';
42
- *
43
- * @NgModule({
44
- * providers: [
45
- * { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorClass, multi: true }
46
- * ]
47
- * })
48
- * ```
49
- */
50
- @Injectable()
51
- export class AuthInterceptorClass implements HttpInterceptor {
52
- constructor(
53
- @Inject(NAUTH_CLIENT_CONFIG) private readonly config: NAuthClientConfig,
54
- private readonly http: HttpClient,
55
- private readonly authService: AuthService,
56
- private readonly router: Router,
57
- ) {}
58
-
59
- intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
60
- const tokenDelivery = this.config.tokenDelivery;
61
- const baseUrl = this.config.baseUrl;
62
-
63
- // ============================================================================
64
- // COOKIES MODE: withCredentials + CSRF token
65
- // ============================================================================
66
- if (tokenDelivery === 'cookies') {
67
- let clonedReq = req.clone({ withCredentials: true });
68
-
69
- // Add CSRF token header if it's a mutating request
70
- if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
71
- const csrfToken = getCsrfToken(this.config.csrf?.cookieName || 'XSRF-TOKEN');
72
- if (csrfToken) {
73
- clonedReq = clonedReq.clone({
74
- setHeaders: { [this.config.csrf?.headerName || 'X-XSRF-TOKEN']: csrfToken },
75
- });
76
- }
77
- }
78
-
79
- return next.handle(clonedReq).pipe(
80
- catchError((error: HttpErrorResponse) => {
81
- if (error.status === 401 && !retriedRequests.has(req)) {
82
- retriedRequests.add(req);
83
-
84
- if (!isRefreshing) {
85
- isRefreshing = true;
86
- refreshTokenSubject.next(null);
87
-
88
- return from(
89
- this.http
90
- .post<{ accessToken?: string }>(`${baseUrl}/refresh`, {}, { withCredentials: true })
91
- .toPromise(),
92
- ).pipe(
93
- switchMap(() => {
94
- isRefreshing = false;
95
- refreshTokenSubject.next('refreshed');
96
- return next.handle(clonedReq);
97
- }),
98
- catchError((refreshError) => {
99
- isRefreshing = false;
100
- this.authService.logout();
101
- this.router.navigate([this.config.redirects?.sessionExpired || '/login']);
102
- return throwError(() => refreshError);
103
- }),
104
- );
105
- } else {
106
- return refreshTokenSubject.pipe(
107
- filter((token) => token !== null),
108
- take(1),
109
- switchMap(() => next.handle(clonedReq)),
110
- );
111
- }
112
- }
113
-
114
- return throwError(() => error);
115
- }),
116
- );
117
- }
118
-
119
- // ============================================================================
120
- // JSON MODE: Delegate to SDK for token handling
121
- // ============================================================================
122
- return next.handle(req);
123
- }
124
- }