@edsis/angular 22.0.67 → 22.0.69

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,14 +1,14 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, signal, computed, Injectable, makeEnvironmentProviders, provideEnvironmentInitializer, Component, DestroyRef, Injector, viewChild, ElementRef, effect, afterNextRender, input } from '@angular/core';
3
- import { DOCUMENT, Location } from '@angular/common';
4
- import { HttpErrorResponse, HttpContextToken, HttpClient, HttpContext, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
2
+ import { InjectionToken, inject, signal, computed, Injectable, makeEnvironmentProviders, provideAppInitializer, Component, DestroyRef, Injector, viewChild, ElementRef, effect, afterNextRender, input } from '@angular/core';
3
+ import { HttpClient, HttpErrorResponse, HttpContextToken, HttpContext, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
4
+ import { provideApiConfiguration } from '@edsis/sdk/shared';
5
5
  import { Router, RouterOutlet, ActivatedRoute, RouterLink } from '@angular/router';
6
- import { AuthSessionService, AuthMagicLinkService } from '@edsis/sdk/auth';
7
- import { ApiConfiguration, provideApiConfiguration } from '@edsis/sdk/shared';
8
6
  import { firstValueFrom, throwError, from, timeout, startWith, finalize } from 'rxjs';
9
- import { switchMap, catchError } from 'rxjs/operators';
7
+ import { catchError, switchMap } from 'rxjs/operators';
10
8
  import { LayoutComponent, LayoutFluidComponent } from '@edsis/theme/layout';
9
+ import { DOCUMENT, Location } from '@angular/common';
11
10
  import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
11
+ import { AuthSessionService, AuthMagicLinkService } from '@edsis/sdk/auth';
12
12
  import { AlertComponent, AlertDescriptionComponent } from '@edsis/component/alert';
13
13
  import { AspectRatioComponent } from '@edsis/component/aspect-ratio';
14
14
  import { ButtonComponent } from '@edsis/component/button';
@@ -158,534 +158,200 @@ function mergeEdsisAuthMessages(override) {
158
158
  };
159
159
  }
160
160
 
161
- const AUTH_SESSION_STORAGE_KEYS = ['access_token', 'user_id', 'role', 'name'];
162
- const AUTH_SESSION_METADATA_STORAGE_KEYS = ['access_token_trusted'];
163
- const AUTH_SESSION_PERSISTENT_HINT_KEY = 'edsis_auth_refresh_hint';
164
- const AUTH_SESSION_CHANGE_EVENT = 'edsis-auth-session-change';
165
- const AUTH_SESSION_PEER_CHANNEL_NAME = 'edsis-auth-session-peer';
166
- const EMPTY_SESSION_FINGERPRINT = '__empty_session__';
167
- const JWT_PART_COUNT = 3;
168
- const TOKEN_EXPIRY_SKEW_MS = 60_000;
169
- const PEER_SESSION_REQUEST_TIMEOUT_MS = 150;
170
- const TRUSTED_OPAQUE_TOKEN_REVALIDATION_MS = 90_000;
171
- const AUTH_SESSION_MONITOR_INTERVAL_MS = 10_000;
172
- const AUTH_REFRESH_LOCK_NAME = 'edsis-auth-refresh';
173
- let validatedAccessToken = '';
174
- let validatedUntilEpochMs = 0;
175
- let failedSessionFingerprint = null;
176
- let pendingSessionValidation = null;
177
- let sessionPeerChannel = null;
178
- let sessionPeerChannelOwner = null;
179
- let sessionPeerId = '';
180
- let sessionMonitorCleanup = null;
181
- let sessionMonitorOwner = null;
182
- function clearSessionMonitor() {
183
- sessionMonitorCleanup?.();
184
- sessionMonitorCleanup = null;
185
- sessionMonitorOwner = null;
186
- }
187
- function ɵresetAuthSessionModuleState() {
188
- clearValidatedSession();
189
- clearFailedSessionFingerprint();
190
- pendingSessionValidation = null;
191
- clearSessionMonitor();
192
- sessionPeerChannel?.close();
193
- sessionPeerChannel = null;
194
- sessionPeerChannelOwner = null;
195
- sessionPeerId = '';
196
- }
197
- function getSessionStorage(documentRef) {
198
- return documentRef.defaultView?.sessionStorage ?? null;
199
- }
200
- function getLocalStorage(documentRef) {
201
- return documentRef.defaultView?.localStorage ?? null;
202
- }
203
- function createSessionPeerId(windowRef) {
204
- return windowRef.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`;
205
- }
206
- function isSessionPeerResponseMessage(message) {
207
- return message.type === 'session-response';
208
- }
209
- function buildStoredSessionData(documentRef) {
210
- const session = readStoredSession(documentRef);
211
- if (!session) {
212
- return null;
213
- }
214
- return {
215
- access_token: session.accessToken,
216
- name: session.name,
217
- role: session.role,
218
- user_id: session.userId,
219
- };
161
+ /** Native desktop features are optional; browser consumers have no bridge. */
162
+ async function setAuthNotificationBadge(unreadCount) {
163
+ const desktop = typeof window === 'undefined' ? undefined : window.EDSIS_DESKTOP;
164
+ await desktop?.setNotificationBadge(unreadCount);
220
165
  }
221
- function ensureSessionPeerChannel(documentRef) {
222
- const windowRef = documentRef.defaultView;
223
- if (!windowRef?.BroadcastChannel) {
224
- return null;
225
- }
226
- if (sessionPeerChannel && sessionPeerChannelOwner === windowRef) {
227
- return sessionPeerChannel;
228
- }
229
- sessionPeerChannel?.close();
230
- sessionPeerId = createSessionPeerId(windowRef);
231
- sessionPeerChannelOwner = windowRef;
232
- sessionPeerChannel = new windowRef.BroadcastChannel(AUTH_SESSION_PEER_CHANNEL_NAME);
233
- sessionPeerChannel.addEventListener('message', (event) => {
234
- const message = event.data;
235
- if (message.type !== 'session-request' || message.senderId === sessionPeerId) {
236
- return;
166
+ /**
167
+ * Cookie-backed authentication state. The access token intentionally exists
168
+ * only in this service instance; the long-lived refresh token is an HttpOnly
169
+ * cookie owned by the server.
170
+ */
171
+ class AuthService {
172
+ http = inject(HttpClient);
173
+ config = inject(EDSIS_AUTH_CONFIG);
174
+ router = inject(Router, { optional: true });
175
+ accessTokenState = signal('', /* @ts-ignore */
176
+ ...(ngDevMode ? [{ debugName: "accessTokenState" }] : /* istanbul ignore next */ []));
177
+ userState = signal(null, /* @ts-ignore */
178
+ ...(ngDevMode ? [{ debugName: "userState" }] : /* istanbul ignore next */ []));
179
+ refreshInFlight = null;
180
+ initialized = false;
181
+ accessToken = this.accessTokenState.asReadonly();
182
+ user = this.userState.asReadonly();
183
+ isAuthenticated = computed(() => Boolean(this.accessTokenState()), /* @ts-ignore */
184
+ ...(ngDevMode ? [{ debugName: "isAuthenticated" }] : /* istanbul ignore next */ []));
185
+ get apiUrl() {
186
+ return this.config.apiUrl.replace(/\/+$/u, '');
187
+ }
188
+ async login(credentials) {
189
+ const email = credentials.email?.trim();
190
+ const username = credentials.username?.trim();
191
+ if (Boolean(email) === Boolean(username)) {
192
+ throw new Error('Auth login requires exactly one of email or username.');
237
193
  }
238
- const sessionData = buildStoredSessionData(documentRef);
239
- if (!sessionData) {
194
+ const response = await firstValueFrom(this.http.post(`${this.apiUrl}/api/auth/login`, {
195
+ ...(email ? { email } : { username }),
196
+ password: credentials.password,
197
+ ...(credentials.deviceType ? { deviceType: credentials.deviceType } : {}),
198
+ }, { withCredentials: true }));
199
+ this.applyTokenResponse(response);
200
+ return this.loadCurrentUser();
201
+ }
202
+ /** Restores an existing cookie session. A missing/expired cookie is normal. */
203
+ async initialize() {
204
+ if (this.initialized) {
240
205
  return;
241
206
  }
242
- sessionPeerChannel?.postMessage({
243
- type: 'session-response',
244
- requestId: message.requestId,
245
- senderId: sessionPeerId,
246
- sessionData,
247
- });
248
- });
249
- return sessionPeerChannel;
250
- }
251
- async function restoreSessionFromPeer(documentRef) {
252
- const windowRef = documentRef.defaultView;
253
- const channel = ensureSessionPeerChannel(documentRef);
254
- if (!windowRef || !channel || !sessionPeerId) {
255
- return false;
256
- }
257
- const requestId = createSessionPeerId(windowRef);
258
- return new Promise((resolve) => {
259
- let settled = false;
260
- let timeoutId = 0;
261
- const finish = (result) => {
262
- if (settled) {
263
- return;
207
+ this.initialized = true;
208
+ if (await this.refresh()) {
209
+ try {
210
+ await this.loadCurrentUser();
264
211
  }
265
- settled = true;
266
- windowRef.clearTimeout(timeoutId);
267
- channel.removeEventListener('message', handleMessage);
268
- resolve(result);
269
- };
270
- const handleMessage = (event) => {
271
- const message = event.data;
272
- if (!isSessionPeerResponseMessage(message) ||
273
- message.senderId === sessionPeerId ||
274
- message.requestId !== requestId) {
275
- return;
276
- }
277
- if (!readSessionDataValue(message.sessionData, 'access_token')) {
278
- finish(false);
279
- return;
212
+ catch (error) {
213
+ // The interceptor has already attempted one cookie refresh. If it
214
+ // ultimately produced 401, startup remains an anonymous state rather
215
+ // than a rejected app initializer.
216
+ if (error instanceof HttpErrorResponse && error.status === 401) {
217
+ this.clearSession();
218
+ return;
219
+ }
220
+ throw error;
280
221
  }
281
- persistSession(documentRef, message.sessionData);
282
- finish(true);
283
- };
284
- timeoutId = windowRef.setTimeout(() => finish(false), PEER_SESSION_REQUEST_TIMEOUT_MS);
285
- channel.addEventListener('message', handleMessage);
286
- channel.postMessage({
287
- type: 'session-request',
288
- requestId,
289
- senderId: sessionPeerId,
290
- });
291
- });
292
- }
293
- function readSessionStorageValue(documentRef, storageKey) {
294
- return getSessionStorage(documentRef)?.getItem(storageKey)?.trim() ?? '';
295
- }
296
- function readSessionDataValue(sessionData, storageKey) {
297
- const value = sessionData?.[storageKey];
298
- return typeof value === 'string' ? value.trim() : '';
299
- }
300
- function notifySessionChange(documentRef) {
301
- documentRef.defaultView?.dispatchEvent(new Event(AUTH_SESSION_CHANGE_EVENT));
302
- }
303
- function clearValidatedSession() {
304
- validatedAccessToken = '';
305
- validatedUntilEpochMs = 0;
306
- }
307
- function clearFailedSessionFingerprint() {
308
- failedSessionFingerprint = null;
309
- }
310
- function readSessionFingerprint(documentRef) {
311
- return readStoredAccessToken(documentRef) || EMPTY_SESSION_FINGERPRINT;
312
- }
313
- function hasFailedSessionFingerprint(documentRef) {
314
- return failedSessionFingerprint === readSessionFingerprint(documentRef);
315
- }
316
- function markFailedSessionFingerprint(documentRef) {
317
- failedSessionFingerprint = readSessionFingerprint(documentRef);
318
- }
319
- function readTrustedAccessToken(documentRef) {
320
- return readSessionStorageValue(documentRef, 'access_token_trusted');
321
- }
322
- function hasRefreshCandidate(documentRef) {
323
- return Boolean(readStoredAccessToken(documentRef) ||
324
- readTrustedAccessToken(documentRef) ||
325
- getLocalStorage(documentRef)?.getItem(AUTH_SESSION_PERSISTENT_HINT_KEY));
326
- }
327
- function shouldClearSessionAfterRefreshFailure(error) {
328
- if (error instanceof HttpErrorResponse) {
329
- return error.status === 401 || error.status === 403;
330
- }
331
- if (error instanceof Error) {
332
- return /invalid refresh token|unauthorized|forbidden/iu.test(error.message);
333
- }
334
- return false;
335
- }
336
- function getTokenExpiryEpochMs(documentRef, accessToken) {
337
- const windowRef = documentRef.defaultView;
338
- const tokenParts = accessToken.split('.');
339
- if (!windowRef?.atob || tokenParts.length !== JWT_PART_COUNT) {
340
- return null;
341
- }
342
- const normalizedPayload = tokenParts[1].replace(/-/g, '+').replace(/_/g, '/');
343
- const paddedPayload = normalizedPayload.padEnd(Math.ceil(normalizedPayload.length / 4) * 4, '=');
344
- try {
345
- const parsedPayload = JSON.parse(windowRef.atob(paddedPayload));
346
- return typeof parsedPayload.exp === 'number' ? parsedPayload.exp * 1000 : null;
347
- }
348
- catch {
349
- return null;
350
- }
351
- }
352
- function markValidatedSession(documentRef) {
353
- const accessToken = readStoredAccessToken(documentRef);
354
- if (!accessToken) {
355
- clearValidatedSession();
356
- return;
357
- }
358
- const tokenExpiryEpochMs = getTokenExpiryEpochMs(documentRef, accessToken);
359
- if (!tokenExpiryEpochMs) {
360
- if (readTrustedAccessToken(documentRef) !== accessToken) {
361
- clearValidatedSession();
362
- return;
363
222
  }
364
- validatedAccessToken = accessToken;
365
- validatedUntilEpochMs = Date.now() + TRUSTED_OPAQUE_TOKEN_REVALIDATION_MS;
366
- return;
367
223
  }
368
- validatedAccessToken = accessToken;
369
- validatedUntilEpochMs = tokenExpiryEpochMs;
370
- }
371
- function hasValidatedSession(documentRef) {
372
- const accessToken = readStoredAccessToken(documentRef);
373
- if (!accessToken) {
374
- clearValidatedSession();
375
- return false;
376
- }
377
- if (accessToken !== validatedAccessToken) {
378
- markValidatedSession(documentRef);
379
- }
380
- if (!validatedAccessToken) {
381
- clearValidatedSession();
382
- return false;
383
- }
384
- return validatedUntilEpochMs > Date.now() + TOKEN_EXPIRY_SKEW_MS;
385
- }
386
- function hasStoredSession(documentRef) {
387
- return Boolean(readStoredAccessToken(documentRef));
388
- }
389
- function readStoredAccessToken(documentRef) {
390
- return readSessionStorageValue(documentRef, 'access_token');
391
- }
392
- function readStoredSession(documentRef) {
393
- const accessToken = readStoredAccessToken(documentRef);
394
- if (!accessToken) {
395
- return null;
396
- }
397
- const userId = readSessionStorageValue(documentRef, 'user_id');
398
- const role = readSessionStorageValue(documentRef, 'role');
399
- const name = readSessionStorageValue(documentRef, 'name');
400
- return {
401
- accessToken,
402
- userId: userId || undefined,
403
- role: role || undefined,
404
- name: name || undefined,
405
- };
406
- }
407
- function persistSession(documentRef, sessionData) {
408
- ensureSessionPeerChannel(documentRef);
409
- const sessionStorageRef = getSessionStorage(documentRef);
410
- if (!sessionStorageRef) {
411
- clearValidatedSession();
412
- notifySessionChange(documentRef);
413
- return null;
414
- }
415
- const nextAccessToken = readSessionDataValue(sessionData, 'access_token');
416
- if (!nextAccessToken) {
417
- for (const storageKey of AUTH_SESSION_STORAGE_KEYS) {
418
- sessionStorageRef.removeItem(storageKey);
419
- }
420
- for (const storageKey of AUTH_SESSION_METADATA_STORAGE_KEYS) {
421
- sessionStorageRef.removeItem(storageKey);
224
+ /** One shared refresh operation for initializer and concurrent 401 retries. */
225
+ refresh() {
226
+ if (this.refreshInFlight) {
227
+ return this.refreshInFlight;
422
228
  }
423
- getLocalStorage(documentRef)?.removeItem(AUTH_SESSION_PERSISTENT_HINT_KEY);
424
- clearValidatedSession();
425
- clearFailedSessionFingerprint();
426
- notifySessionChange(documentRef);
427
- return null;
229
+ this.refreshInFlight = firstValueFrom(this.http.post(`${this.apiUrl}/api/auth/refresh`, null, {
230
+ withCredentials: true,
231
+ }))
232
+ .then((response) => {
233
+ this.applyTokenResponse(response);
234
+ return Boolean(this.accessTokenState());
235
+ })
236
+ .catch((error) => {
237
+ this.clearSession();
238
+ // A 401 on startup is an expected anonymous state, not an application error.
239
+ if (!(error instanceof HttpErrorResponse) || error.status !== 401) {
240
+ throw error;
241
+ }
242
+ return false;
243
+ })
244
+ .finally(() => {
245
+ this.refreshInFlight = null;
246
+ });
247
+ return this.refreshInFlight;
428
248
  }
429
- sessionStorageRef.setItem('access_token', nextAccessToken);
430
- sessionStorageRef.setItem('access_token_trusted', nextAccessToken);
431
- getLocalStorage(documentRef)?.setItem(AUTH_SESSION_PERSISTENT_HINT_KEY, '1');
432
- for (const storageKey of AUTH_SESSION_STORAGE_KEYS.slice(1)) {
433
- if (!sessionData || !Object.hasOwn(sessionData, storageKey)) {
434
- continue;
435
- }
436
- const nextValue = readSessionDataValue(sessionData, storageKey);
437
- if (nextValue) {
438
- sessionStorageRef.setItem(storageKey, nextValue);
439
- continue;
249
+ async loadCurrentUser() {
250
+ const token = this.accessTokenState();
251
+ if (!token) {
252
+ return null;
440
253
  }
441
- sessionStorageRef.removeItem(storageKey);
442
- }
443
- markValidatedSession(documentRef);
444
- clearFailedSessionFingerprint();
445
- notifySessionChange(documentRef);
446
- return readStoredSession(documentRef);
447
- }
448
- function clearStoredSession(documentRef, options) {
449
- const sessionStorageRef = getSessionStorage(documentRef);
450
- for (const storageKey of AUTH_SESSION_STORAGE_KEYS) {
451
- sessionStorageRef?.removeItem(storageKey);
452
- }
453
- for (const storageKey of AUTH_SESSION_METADATA_STORAGE_KEYS) {
454
- sessionStorageRef?.removeItem(storageKey);
455
- }
456
- getLocalStorage(documentRef)?.removeItem(AUTH_SESSION_PERSISTENT_HINT_KEY);
457
- clearValidatedSession();
458
- if (!options?.preserveFailedSessionFingerprint) {
459
- clearFailedSessionFingerprint();
460
- }
461
- notifySessionChange(documentRef);
462
- }
463
- function startAuthSessionMonitor(documentRef, authSessionService, options) {
464
- const windowRef = documentRef.defaultView;
465
- if (!windowRef) {
466
- return;
467
- }
468
- if (sessionMonitorCleanup && sessionMonitorOwner === windowRef) {
469
- return;
254
+ const response = await firstValueFrom(this.http.get(`${this.apiUrl}/api/auth/me`, {
255
+ withCredentials: true,
256
+ headers: { Authorization: `Bearer ${token}` },
257
+ }));
258
+ const user = response;
259
+ this.userState.set(user);
260
+ return user;
470
261
  }
471
- clearSessionMonitor();
472
- let disposed = false;
473
- const runValidation = async () => {
474
- const hadRefreshCandidate = hasRefreshCandidate(documentRef);
475
- if (!hadRefreshCandidate) {
476
- return;
477
- }
478
- // Refresh proaktif: validateStoredSession memakai jendela TOKEN_EXPIRY_SKEW_MS,
479
- // sehingga rotasi hanya terjadi <60 dtk sebelum kedaluwarsa — bukan tiap tick.
480
- const isSessionValid = options?.validateSession
481
- ? await options.validateSession()
482
- : await validateStoredSession(documentRef, authSessionService);
483
- if (!disposed && !isSessionValid && hadRefreshCandidate) {
484
- options?.onSessionInvalid?.();
485
- }
486
- };
487
- const handleFocus = () => {
488
- void runValidation();
489
- };
490
- const handleVisibilityChange = () => {
491
- if (documentRef.visibilityState === 'visible') {
492
- void runValidation();
262
+ async logout() {
263
+ try {
264
+ await firstValueFrom(this.http.post(`${this.apiUrl}/api/auth/logout`, null, { withCredentials: true }));
493
265
  }
494
- };
495
- const intervalId = windowRef.setInterval(handleFocus, AUTH_SESSION_MONITOR_INTERVAL_MS);
496
- windowRef.addEventListener('focus', handleFocus);
497
- documentRef.addEventListener('visibilitychange', handleVisibilityChange);
498
- sessionMonitorOwner = windowRef;
499
- sessionMonitorCleanup = () => {
500
- disposed = true;
501
- windowRef.clearInterval(intervalId);
502
- windowRef.removeEventListener('focus', handleFocus);
503
- documentRef.removeEventListener('visibilitychange', handleVisibilityChange);
504
- };
505
- }
506
- // Refresh token bersifat sekali pakai (rotasi): dua refresh bersamaan memicu
507
- // deteksi reuse di server dan seluruh sesi di-revoke. Web Locks menserialisasi
508
- // rotasi lintas-tab; dedupe dalam-tab ditangani oleh pendingSessionValidation.
509
- async function refreshSessionWithLock(documentRef, authSessionService, options) {
510
- const performRefresh = async () => {
511
- if (!options?.forceRefresh && hasValidatedSession(documentRef)) {
512
- return;
266
+ finally {
267
+ this.clearSession();
513
268
  }
514
- const response = await firstValueFrom(authSessionService.refreshAuthToken());
515
- persistSession(documentRef, response.data);
516
- };
517
- const locks = documentRef.defaultView?.navigator?.locks;
518
- if (locks?.request) {
519
- await locks.request(AUTH_REFRESH_LOCK_NAME, performRefresh);
520
- return;
521
269
  }
522
- await performRefresh();
523
- }
524
- async function validateStoredSession(documentRef, authSessionService, options) {
525
- ensureSessionPeerChannel(documentRef);
526
- if (!options?.forceRefresh && hasValidatedSession(documentRef)) {
527
- return true;
528
- }
529
- if (pendingSessionValidation) {
530
- return pendingSessionValidation;
270
+ clearSession() {
271
+ this.accessTokenState.set('');
272
+ this.userState.set(null);
531
273
  }
532
- pendingSessionValidation = (async () => {
533
- try {
534
- if (!options?.forceRefresh &&
535
- !hasStoredSession(documentRef) &&
536
- (await restoreSessionFromPeer(documentRef))) {
537
- return true;
538
- }
539
- if (!options?.forceRefresh && hasValidatedSession(documentRef)) {
540
- return true;
541
- }
542
- if (!options?.forceRefresh && !hasRefreshCandidate(documentRef)) {
543
- clearValidatedSession();
544
- return false;
545
- }
546
- if (hasFailedSessionFingerprint(documentRef)) {
547
- return false;
548
- }
549
- await refreshSessionWithLock(documentRef, authSessionService, options);
550
- return hasValidatedSession(documentRef);
551
- }
552
- catch (error) {
553
- if (!shouldClearSessionAfterRefreshFailure(error)) {
554
- clearValidatedSession();
555
- return hasStoredSession(documentRef);
556
- }
557
- clearStoredSession(documentRef, { preserveFailedSessionFingerprint: true });
558
- markFailedSessionFingerprint(documentRef);
559
- return false;
274
+ /** Allows existing OAuth exchanges to establish the same memory-only state. */
275
+ acceptTokenResponse(response) {
276
+ if (response && typeof response === 'object') {
277
+ this.applyTokenResponse(response);
560
278
  }
561
- finally {
562
- pendingSessionValidation = null;
279
+ }
280
+ redirectToLogin() {
281
+ this.clearSession();
282
+ void this.router?.navigateByUrl(this.config.guestHomePath, { replaceUrl: true });
283
+ }
284
+ applyTokenResponse(response) {
285
+ const isPersistentResponse = 'accessToken' in response;
286
+ const token = isPersistentResponse
287
+ ? response.accessToken
288
+ : response.access_token ?? response.data?.access_token;
289
+ this.accessTokenState.set(typeof token === 'string' ? token : '');
290
+ const user = isPersistentResponse ? response.user : response.user ?? response.data?.user;
291
+ if (user) {
292
+ this.userState.set(user);
563
293
  }
564
- })();
565
- return pendingSessionValidation;
566
- }
567
- function injectSessionState() {
568
- const documentRef = inject(DOCUMENT);
569
- const authSessionService = inject(AuthSessionService);
570
- return validateStoredSession(documentRef, authSessionService);
571
- }
572
- function injectSessionRefresh() {
573
- const documentRef = inject(DOCUMENT);
574
- const authSessionService = inject(AuthSessionService);
575
- return validateStoredSession(documentRef, authSessionService, { forceRefresh: true });
576
- }
577
- function injectSessionClear() {
578
- clearStoredSession(inject(DOCUMENT));
294
+ }
295
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: AuthService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
296
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: AuthService, providedIn: 'root' });
579
297
  }
298
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImport: i0, type: AuthService, decorators: [{
299
+ type: Injectable,
300
+ args: [{ providedIn: 'root' }]
301
+ }] });
580
302
 
581
- const PROTECTED_API_PATH_PREFIX = '/v1/';
582
- const AUTH_PATH_PREFIX = '/v1/auth/';
583
- const HEALTH_PATH = '/health';
584
303
  const EDSIS_SKIP_AUTH = new HttpContextToken(() => false);
585
- const EDSIS_SKIP_SESSION_REFRESH = new HttpContextToken(() => false);
586
304
  const EDSIS_AUTH_RETRY = new HttpContextToken(() => false);
587
- function normalizeUrl(url) {
305
+ const AUTH_ENDPOINTS = new Set(['/api/auth/login', '/api/auth/refresh', '/api/auth/logout']);
306
+ function apiPath(url, apiUrl) {
307
+ // A consumer may use Angular's same-origin dev/prod proxy (`/api/...`) even
308
+ // when `apiUrl` names the upstream origin. Such relative URLs are API calls.
309
+ if (url.startsWith('/')) {
310
+ return url.split(/[?#]/, 1)[0] ?? url;
311
+ }
588
312
  try {
589
- return new URL(url);
313
+ const resolved = new URL(url);
314
+ const api = new URL(apiUrl);
315
+ return resolved.origin === api.origin ? resolved.pathname : null;
590
316
  }
591
317
  catch {
592
318
  return null;
593
319
  }
594
320
  }
595
- function resolveApiPath(url, rootUrl) {
596
- const normalizedUrl = normalizeUrl(url);
597
- const normalizedRootUrl = normalizeUrl(rootUrl);
598
- if (normalizedUrl && normalizedRootUrl) {
599
- if (normalizedUrl.origin !== normalizedRootUrl.origin) {
600
- return null;
601
- }
602
- if (!normalizedUrl.pathname.startsWith(normalizedRootUrl.pathname)) {
603
- return null;
604
- }
605
- const apiPath = normalizedUrl.pathname.slice(normalizedRootUrl.pathname.length) || '/';
606
- return apiPath.startsWith('/') ? apiPath : `/${apiPath}`;
607
- }
608
- if (url.startsWith(rootUrl)) {
609
- const apiPath = url.slice(rootUrl.length).split(/[?#]/, 1)[0] ?? '/';
610
- return apiPath.startsWith('/') ? apiPath : `/${apiPath}`;
611
- }
612
- if (url.startsWith('/')) {
613
- return url.split(/[?#]/, 1)[0] ?? url;
614
- }
615
- return null;
616
- }
617
- function isAuthRequest(apiPath) {
618
- return apiPath.startsWith(AUTH_PATH_PREFIX);
619
- }
620
- function isProtectedApiRequest(apiPath) {
621
- return apiPath.startsWith(PROTECTED_API_PATH_PREFIX) && !isAuthRequest(apiPath);
622
- }
623
- function isHealthRequest(apiPath) {
624
- return apiPath === HEALTH_PATH;
625
- }
626
- function isHandledRequest(apiPath) {
627
- return isProtectedApiRequest(apiPath) || isAuthRequest(apiPath) || isHealthRequest(apiPath);
628
- }
629
- function applyCookieCredentials(request, apiPath) {
630
- return isAuthRequest(apiPath) && !request.withCredentials
631
- ? request.clone({ withCredentials: true })
632
- : request;
321
+ function isApiRequest(url, apiUrl) {
322
+ return apiPath(url, apiUrl) !== null;
633
323
  }
634
- function applyBearerToken(request, accessToken, isRetry = false) {
324
+ function authorize(request, token, retry = false) {
635
325
  return request.clone({
636
- context: isRetry ? request.context.set(EDSIS_AUTH_RETRY, true) : request.context,
637
- setHeaders: {
638
- Authorization: `Bearer ${accessToken}`,
639
- },
326
+ withCredentials: true,
327
+ context: retry ? request.context.set(EDSIS_AUTH_RETRY, true) : request.context,
328
+ setHeaders: token ? { Authorization: `Bearer ${token}` } : {},
640
329
  });
641
330
  }
642
- async function resolveAccessToken(documentRef, authSessionService, options) {
643
- const isSessionValid = await validateStoredSession(documentRef, authSessionService, options);
644
- return isSessionValid ? readStoredAccessToken(documentRef) : '';
645
- }
646
- function handleUnauthorizedError(error, request, next, documentRef, authSessionService) {
647
- if (!(error instanceof HttpErrorResponse) ||
648
- error.status !== 401 ||
649
- request.context.get(EDSIS_AUTH_RETRY) ||
650
- request.context.get(EDSIS_SKIP_SESSION_REFRESH)) {
651
- return throwError(() => error);
652
- }
653
- return from(resolveAccessToken(documentRef, authSessionService, { forceRefresh: true })).pipe(switchMap((refreshedAccessToken) => {
654
- if (!refreshedAccessToken) {
655
- clearStoredSession(documentRef);
656
- return throwError(() => error);
657
- }
658
- return next(applyBearerToken(request, refreshedAccessToken, true));
659
- }), catchError((refreshError) => {
660
- if (shouldClearSessionAfterRefreshFailure(refreshError)) {
661
- clearStoredSession(documentRef);
662
- }
663
- return throwError(() => error);
664
- }));
665
- }
666
331
  const edsisAuthInterceptor = (request, next) => {
667
- const documentRef = inject(DOCUMENT);
668
- const apiConfiguration = inject(ApiConfiguration);
669
- const authSessionService = inject(AuthSessionService);
670
- if (request.context.get(EDSIS_SKIP_AUTH)) {
671
- return next(request);
672
- }
673
- const apiPath = resolveApiPath(request.url, apiConfiguration.rootUrl);
674
- if (!apiPath || !isHandledRequest(apiPath)) {
332
+ const auth = inject(AuthService);
333
+ if (request.context.get(EDSIS_SKIP_AUTH) || !isApiRequest(request.url, auth.apiUrl)) {
675
334
  return next(request);
676
335
  }
677
- const preparedRequest = applyCookieCredentials(request, apiPath);
678
- if (isAuthRequest(apiPath) || isHealthRequest(apiPath)) {
679
- return next(preparedRequest);
336
+ const path = apiPath(request.url, auth.apiUrl);
337
+ const isAuthEndpoint = AUTH_ENDPOINTS.has(path ?? '') || path?.startsWith('/v1/auth/');
338
+ const prepared = authorize(request, isAuthEndpoint ? '' : auth.accessToken());
339
+ if (isAuthEndpoint) {
340
+ return next(prepared);
680
341
  }
681
- const skipSessionRefresh = request.context.get(EDSIS_SKIP_SESSION_REFRESH);
682
- return from(skipSessionRefresh
683
- ? Promise.resolve(readStoredAccessToken(documentRef))
684
- : resolveAccessToken(documentRef, authSessionService)).pipe(switchMap((accessToken) => {
685
- const authorizedRequest = accessToken
686
- ? applyBearerToken(preparedRequest, accessToken)
687
- : preparedRequest;
688
- return next(authorizedRequest).pipe(catchError((error) => handleUnauthorizedError(error, preparedRequest, next, documentRef, authSessionService)));
342
+ return next(prepared).pipe(catchError((error) => {
343
+ if (!(error instanceof HttpErrorResponse) || error.status !== 401 || request.context.get(EDSIS_AUTH_RETRY)) {
344
+ return throwError(() => error);
345
+ }
346
+ return from(auth.refresh()).pipe(switchMap((refreshed) => {
347
+ if (!refreshed) {
348
+ return throwError(() => error);
349
+ }
350
+ return next(authorize(request, auth.accessToken(), true));
351
+ }), catchError(() => {
352
+ auth.redirectToLogin();
353
+ return throwError(() => error);
354
+ }));
689
355
  }));
690
356
  };
691
357
 
@@ -747,29 +413,8 @@ function provideEdsisAuth(config) {
747
413
  return makeEnvironmentProviders([
748
414
  provideApiConfiguration(resolvedConfig.apiUrl),
749
415
  provideHttpClient(withFetch(), withInterceptors([edsisAuthInterceptor, ...(config.httpInterceptors ?? [])])),
750
- provideEnvironmentInitializer(() => {
751
- const documentRef = inject(DOCUMENT);
752
- const authSessionService = inject(AuthSessionService);
753
- const router = inject(Router, { optional: true });
754
- // Validasi default monitor memakai /v1/auth/refresh (cookie HttpOnly) saat
755
- // access token mendekati kedaluwarsa, sehingga sesi tidak logout tiap 15 menit.
756
- startAuthSessionMonitor(documentRef, authSessionService, {
757
- onSessionInvalid: () => {
758
- if (router) {
759
- void router.navigateByUrl(resolvedConfig.guestHomePath, { replaceUrl: true });
760
- return;
761
- }
762
- const windowRef = documentRef.defaultView;
763
- if (!windowRef) {
764
- return;
765
- }
766
- const guestUrl = new URL(resolvedConfig.guestHomePath, windowRef.location.origin).toString();
767
- if (windowRef.location.href !== guestUrl) {
768
- windowRef.location.replace(guestUrl);
769
- }
770
- },
771
- });
772
- }),
416
+ // Completes before initial navigation, therefore guards see restored state.
417
+ provideAppInitializer(() => inject(AuthService).initialize()),
773
418
  {
774
419
  provide: EDSIS_AUTH_CONFIG,
775
420
  useValue: resolvedConfig,
@@ -785,7 +430,8 @@ function provideEdsisAuth(config) {
785
430
  const authenticatedGuard = async () => {
786
431
  const router = inject(Router);
787
432
  const authConfig = inject(EDSIS_AUTH_CONFIG);
788
- if (await injectSessionState()) {
433
+ const auth = inject(AuthService);
434
+ if (auth.isAuthenticated()) {
789
435
  return true;
790
436
  }
791
437
  return router.parseUrl(authConfig.guestHomePath);
@@ -793,12 +439,14 @@ const authenticatedGuard = async () => {
793
439
  const homeRedirectGuard = async () => {
794
440
  const router = inject(Router);
795
441
  const authConfig = inject(EDSIS_AUTH_CONFIG);
796
- return router.parseUrl((await injectSessionState()) ? authConfig.authenticatedHomePath : authConfig.guestHomePath);
442
+ const auth = inject(AuthService);
443
+ return router.parseUrl(auth.isAuthenticated() ? authConfig.authenticatedHomePath : authConfig.guestHomePath);
797
444
  };
798
445
  const guestOnlyGuard = async () => {
799
446
  const router = inject(Router);
800
447
  const authConfig = inject(EDSIS_AUTH_CONFIG);
801
- if (!(await injectSessionState())) {
448
+ const auth = inject(AuthService);
449
+ if (!auth.isAuthenticated()) {
802
450
  return true;
803
451
  }
804
452
  return router.parseUrl(authConfig.authenticatedHomePath);
@@ -945,6 +593,7 @@ class AuthGoogleCallbackPage {
945
593
  router = inject(Router);
946
594
  location = inject(Location);
947
595
  authSessionService = inject(AuthSessionService);
596
+ authService = inject(AuthService);
948
597
  authConfig = inject(EDSIS_AUTH_CONFIG);
949
598
  messages = inject(EDSIS_AUTH_MESSAGES);
950
599
  loginPath = this.authConfig.loginPath;
@@ -1011,8 +660,8 @@ class AuthGoogleCallbackPage {
1011
660
  .pipe(takeUntilDestroyed(this.destroyRef))
1012
661
  .subscribe({
1013
662
  next: (response) => {
1014
- const session = persistSession(this.documentRef, response.data);
1015
- if (!session) {
663
+ this.authService.acceptTokenResponse(response);
664
+ if (!this.authService.isAuthenticated()) {
1016
665
  this.fail(this.messages.google.missingAccessToken);
1017
666
  return;
1018
667
  }
@@ -1825,9 +1474,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.6", ngImpor
1825
1474
 
1826
1475
  class AuthLogoutPage {
1827
1476
  destroyRef = inject(DestroyRef);
1828
- documentRef = inject(DOCUMENT);
1829
1477
  router = inject(Router);
1830
- authSessionService = inject(AuthSessionService);
1478
+ authService = inject(AuthService);
1831
1479
  authConfig = inject(EDSIS_AUTH_CONFIG);
1832
1480
  messages = inject(EDSIS_AUTH_MESSAGES);
1833
1481
  guestHomePath = this.authConfig.guestHomePath;
@@ -1837,18 +1485,16 @@ class AuthLogoutPage {
1837
1485
  message = signal(this.messages.logout.pending, /* @ts-ignore */
1838
1486
  ...(ngDevMode ? [{ debugName: "message" }] : /* istanbul ignore next */ []));
1839
1487
  ngOnInit() {
1840
- clearStoredSession(this.documentRef);
1841
- this.authSessionService
1842
- .logoutAuthSession()
1488
+ from(this.authService.logout())
1843
1489
  .pipe(takeUntilDestroyed(this.destroyRef), finalize(() => {
1844
1490
  if (this.state() === 'pending') {
1845
1491
  this.state.set('success');
1846
1492
  }
1847
1493
  }))
1848
1494
  .subscribe({
1849
- next: (response) => {
1495
+ next: () => {
1850
1496
  this.state.set('success');
1851
- this.message.set(getResponseMessage(response, this.messages.logout.success));
1497
+ this.message.set(this.messages.logout.success);
1852
1498
  void this.router.navigateByUrl(this.guestHomePath, { replaceUrl: true });
1853
1499
  },
1854
1500
  error: (error) => {
@@ -2022,6 +1668,7 @@ class AuthVerifyPage {
2022
1668
  location = inject(Location);
2023
1669
  authMagicLinkService = inject(AuthMagicLinkService);
2024
1670
  authConfig = inject(EDSIS_AUTH_CONFIG);
1671
+ authService = inject(AuthService);
2025
1672
  messages = inject(EDSIS_AUTH_MESSAGES);
2026
1673
  queryParamMap = toSignal(this.route.queryParamMap, {
2027
1674
  initialValue: this.route.snapshot.queryParamMap,
@@ -2077,8 +1724,8 @@ class AuthVerifyPage {
2077
1724
  })
2078
1725
  .subscribe({
2079
1726
  next: (response) => {
2080
- const session = persistSession(this.documentRef, response.data);
2081
- if (!session) {
1727
+ this.authService.acceptTokenResponse(response);
1728
+ if (!this.authService.isAuthenticated()) {
2082
1729
  this.state.set('error');
2083
1730
  this.message.set(this.messages.verify.missingAccessToken);
2084
1731
  return;
@@ -2288,5 +1935,5 @@ const authRoutes = [
2288
1935
  * Generated bundle index. Do not edit.
2289
1936
  */
2290
1937
 
2291
- export { AUTH_SESSION_CHANGE_EVENT, AuthGoogleCallbackPage, AuthLoginPage, AuthLogoutPage, AuthShellPage, AuthVerifyPage, DEFAULT_EDSIS_AUTH_MESSAGES, EDSIS_AUTH_CONFIG, EDSIS_AUTH_MESSAGES, EDSIS_SKIP_AUTH, EDSIS_SKIP_SESSION_REFRESH, GOOGLE_OAUTH_AUTHORIZE_URL, GOOGLE_OAUTH_CALLBACK_ROUTE_PATH, GOOGLE_OAUTH_STATE_STORAGE_KEY, authRoutes, authenticatedGuard, buildGoogleAuthorizeUrl, clearStoredSession, consumeGoogleOauthState, createGoogleOauthState, edsisAuthInterceptor, guestOnlyGuard, hasStoredSession, homeRedirectGuard, injectSessionClear, injectSessionRefresh, injectSessionState, mergeEdsisAuthMessages, persistSession, provideEdsisAuth, readStoredAccessToken, readStoredSession, resolveEdsisAuthConfig, shouldClearSessionAfterRefreshFailure, startAuthSessionMonitor, storeGoogleOauthState, validateStoredSession, ɵresetAuthSessionModuleState };
1938
+ export { AuthGoogleCallbackPage, AuthLoginPage, AuthLogoutPage, AuthService, AuthShellPage, AuthVerifyPage, DEFAULT_EDSIS_AUTH_MESSAGES, EDSIS_AUTH_CONFIG, EDSIS_AUTH_MESSAGES, EDSIS_SKIP_AUTH, GOOGLE_OAUTH_AUTHORIZE_URL, GOOGLE_OAUTH_CALLBACK_ROUTE_PATH, GOOGLE_OAUTH_STATE_STORAGE_KEY, authRoutes, authenticatedGuard, buildGoogleAuthorizeUrl, consumeGoogleOauthState, createGoogleOauthState, edsisAuthInterceptor, guestOnlyGuard, homeRedirectGuard, mergeEdsisAuthMessages, provideEdsisAuth, resolveEdsisAuthConfig, setAuthNotificationBadge, storeGoogleOauthState };
2292
1939
  //# sourceMappingURL=edsis-angular-module-auth.mjs.map