@edsis/angular 22.0.34 → 22.0.37

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,12 +1,11 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, makeEnvironmentProviders, provideEnvironmentInitializer, Component, DestroyRef, signal, computed, input, effect } from '@angular/core';
2
+ import { InjectionToken, inject, signal, computed, Injectable, makeEnvironmentProviders, provideEnvironmentInitializer, Component, DestroyRef, Injector, viewChild, effect, afterNextRender, input } from '@angular/core';
3
3
  import { DOCUMENT, Location } from '@angular/common';
4
- import { HttpErrorResponse, HttpContextToken, provideHttpClient, withFetch, withInterceptors, HttpContext } from '@angular/common/http';
4
+ import { HttpErrorResponse, HttpContextToken, HttpClient, HttpContext, provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
5
5
  import { Router, RouterOutlet, RouterLink, ActivatedRoute } from '@angular/router';
6
6
  import { AuthSessionService, AuthMagicLinkService } from '@edsis/sdk/auth';
7
7
  import { ApiConfiguration, provideApiConfiguration } from '@edsis/sdk/shared';
8
- import { UserProfileService } from '@edsis/sdk/user';
9
- import { firstValueFrom, throwError, from, startWith, finalize } from 'rxjs';
8
+ import { firstValueFrom, throwError, from, timeout, startWith, finalize } from 'rxjs';
10
9
  import { switchMap, catchError } from 'rxjs/operators';
11
10
  import { LayoutComponent, LayoutFluidComponent } from '@edsis/theme/layout';
12
11
  import { toSignal, takeUntilDestroyed } from '@angular/core/rxjs-interop';
@@ -25,17 +24,24 @@ const DEFAULT_LOGIN_PATH = '/login';
25
24
  const DEFAULT_LOGOUT_PATH = '/logout';
26
25
  const DEFAULT_VERIFY_PATH = '/verify';
27
26
  const DEFAULT_AUTHENTICATED_HOME_PATH = '/dashboard';
27
+ const DEFAULT_HEALTH_CHECK_TIMEOUT_MS = 4000;
28
28
  const EDSIS_AUTH_CONFIG = new InjectionToken('EDSIS_AUTH_CONFIG');
29
29
  function resolveEdsisAuthConfig(config) {
30
30
  const loginPath = normalizePath(config.loginPath, DEFAULT_LOGIN_PATH);
31
+ const apiUrl = normalizeAbsoluteUrl(config.apiUrl, 'apiUrl');
31
32
  return {
32
- apiUrl: normalizeAbsoluteUrl(config.apiUrl, 'apiUrl'),
33
+ apiUrl,
33
34
  appUrl: normalizeAbsoluteUrl(config.appUrl, 'appUrl'),
34
35
  loginPath,
35
36
  logoutPath: normalizePath(config.logoutPath, DEFAULT_LOGOUT_PATH),
36
37
  verifyPath: normalizePath(config.verifyPath, DEFAULT_VERIFY_PATH),
37
38
  authenticatedHomePath: normalizePath(config.authenticatedHomePath, DEFAULT_AUTHENTICATED_HOME_PATH),
38
39
  guestHomePath: normalizePath(config.guestHomePath, loginPath),
40
+ healthCheck: {
41
+ enabled: config.healthCheck?.enabled ?? false,
42
+ url: config.healthCheck?.url ?? `${apiUrl.replace(/\/+$/, '')}/health`,
43
+ timeoutMs: config.healthCheck?.timeoutMs ?? DEFAULT_HEALTH_CHECK_TIMEOUT_MS,
44
+ },
39
45
  };
40
46
  }
41
47
  function normalizeAbsoluteUrl(value, label) {
@@ -73,6 +79,10 @@ const DEFAULT_EDSIS_AUTH_MESSAGES = {
73
79
  oauthGoogleAria: 'Login dengan Google segera hadir',
74
80
  oauthMicrosoftAria: 'Login dengan Microsoft segera hadir',
75
81
  oauthAppleAria: 'Login dengan Apple segera hadir',
82
+ healthUnavailableTitle: 'Layanan sedang tidak tersedia',
83
+ healthUnavailableBody: 'Kami tidak dapat menghubungi server autentikasi. Silakan coba lagi.',
84
+ healthRetry: 'Coba lagi',
85
+ healthChecking: 'Memeriksa ketersediaan layanan…',
76
86
  },
77
87
  logout: {
78
88
  title: 'Mengakhiri sesi Edsis.',
@@ -122,10 +132,11 @@ const AUTH_SESSION_CHANGE_EVENT = 'edsis-auth-session-change';
122
132
  const AUTH_SESSION_PEER_CHANNEL_NAME = 'edsis-auth-session-peer';
123
133
  const EMPTY_SESSION_FINGERPRINT = '__empty_session__';
124
134
  const JWT_PART_COUNT = 3;
125
- const TOKEN_EXPIRY_SKEW_MS = 30_000;
135
+ const TOKEN_EXPIRY_SKEW_MS = 60_000;
126
136
  const PEER_SESSION_REQUEST_TIMEOUT_MS = 150;
127
137
  const TRUSTED_OPAQUE_TOKEN_REVALIDATION_MS = 90_000;
128
138
  const AUTH_SESSION_MONITOR_INTERVAL_MS = 10_000;
139
+ const AUTH_REFRESH_LOCK_NAME = 'edsis-auth-refresh';
129
140
  let validatedAccessToken = '';
130
141
  let validatedUntilEpochMs = 0;
131
142
  let failedSessionFingerprint = null;
@@ -431,9 +442,11 @@ function startAuthSessionMonitor(documentRef, authSessionService, options) {
431
442
  if (!hadRefreshCandidate) {
432
443
  return;
433
444
  }
445
+ // Refresh proaktif: validateStoredSession memakai jendela TOKEN_EXPIRY_SKEW_MS,
446
+ // sehingga rotasi hanya terjadi <60 dtk sebelum kedaluwarsa — bukan tiap tick.
434
447
  const isSessionValid = options?.validateSession
435
448
  ? await options.validateSession()
436
- : await validateStoredSession(documentRef, authSessionService, { forceRefresh: true });
449
+ : await validateStoredSession(documentRef, authSessionService);
437
450
  if (!disposed && !isSessionValid && hadRefreshCandidate) {
438
451
  options?.onSessionInvalid?.();
439
452
  }
@@ -457,6 +470,24 @@ function startAuthSessionMonitor(documentRef, authSessionService, options) {
457
470
  documentRef.removeEventListener('visibilitychange', handleVisibilityChange);
458
471
  };
459
472
  }
473
+ // Refresh token bersifat sekali pakai (rotasi): dua refresh bersamaan memicu
474
+ // deteksi reuse di server dan seluruh sesi di-revoke. Web Locks menserialisasi
475
+ // rotasi lintas-tab; dedupe dalam-tab ditangani oleh pendingSessionValidation.
476
+ async function refreshSessionWithLock(documentRef, authSessionService, options) {
477
+ const performRefresh = async () => {
478
+ if (!options?.forceRefresh && hasValidatedSession(documentRef)) {
479
+ return;
480
+ }
481
+ const response = await firstValueFrom(authSessionService.refreshAuthToken());
482
+ persistSession(documentRef, response.data);
483
+ };
484
+ const locks = documentRef.defaultView?.navigator?.locks;
485
+ if (locks?.request) {
486
+ await locks.request(AUTH_REFRESH_LOCK_NAME, performRefresh);
487
+ return;
488
+ }
489
+ await performRefresh();
490
+ }
460
491
  async function validateStoredSession(documentRef, authSessionService, options) {
461
492
  ensureSessionPeerChannel(documentRef);
462
493
  if (!options?.forceRefresh && hasValidatedSession(documentRef)) {
@@ -480,8 +511,7 @@ async function validateStoredSession(documentRef, authSessionService, options) {
480
511
  if (hasFailedSessionFingerprint(documentRef)) {
481
512
  return false;
482
513
  }
483
- const response = await firstValueFrom(authSessionService.refreshAuthToken());
484
- persistSession(documentRef, response.data);
514
+ await refreshSessionWithLock(documentRef, authSessionService, options);
485
515
  return hasValidatedSession(documentRef);
486
516
  }
487
517
  catch (error) {
@@ -620,6 +650,59 @@ const edsisAuthInterceptor = (request, next) => {
620
650
  }));
621
651
  };
622
652
 
653
+ /**
654
+ * Health-check backend auth untuk `AuthLoginPage` (internal, di-provide oleh
655
+ * `provideEdsisAuth`). Sehat = HTTP 2xx dalam `timeoutMs`; body tidak diparse.
656
+ * Tanpa polling — hanya on-load, pre-submit, dan Retry manual.
657
+ */
658
+ class AuthHealthService {
659
+ http = inject(HttpClient);
660
+ config = inject(EDSIS_AUTH_CONFIG);
661
+ _status = signal('idle', /* @ts-ignore */
662
+ ...(ngDevMode ? [{ debugName: "_status" }] : /* istanbul ignore next */ []));
663
+ status = this._status.asReadonly();
664
+ isChecking = computed(() => this._status() === 'checking', /* @ts-ignore */
665
+ ...(ngDevMode ? [{ debugName: "isChecking" }] : /* istanbul ignore next */ []));
666
+ isUnhealthy = computed(() => this._status() === 'unhealthy', /* @ts-ignore */
667
+ ...(ngDevMode ? [{ debugName: "isUnhealthy" }] : /* istanbul ignore next */ []));
668
+ inFlight = false;
669
+ /** true jika sehat ATAU health-check dimatikan. Tak pernah throw. */
670
+ async check() {
671
+ const healthCheck = this.config.healthCheck;
672
+ if (!healthCheck.enabled) {
673
+ this._status.set('healthy');
674
+ return true;
675
+ }
676
+ if (this.inFlight) {
677
+ return this._status() === 'healthy';
678
+ }
679
+ this.inFlight = true;
680
+ this._status.set('checking');
681
+ try {
682
+ await firstValueFrom(this.http
683
+ .get(healthCheck.url, {
684
+ observe: 'response',
685
+ context: new HttpContext().set(EDSIS_SKIP_AUTH, true),
686
+ })
687
+ .pipe(timeout(healthCheck.timeoutMs)));
688
+ this._status.set('healthy');
689
+ return true;
690
+ }
691
+ catch {
692
+ this._status.set('unhealthy');
693
+ return false;
694
+ }
695
+ finally {
696
+ this.inFlight = false;
697
+ }
698
+ }
699
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.5", ngImport: i0, type: AuthHealthService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
700
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.5", ngImport: i0, type: AuthHealthService });
701
+ }
702
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.5", ngImport: i0, type: AuthHealthService, decorators: [{
703
+ type: Injectable
704
+ }] });
705
+
623
706
  function provideEdsisAuth(config) {
624
707
  const resolvedConfig = resolveEdsisAuthConfig(config);
625
708
  return makeEnvironmentProviders([
@@ -629,24 +712,9 @@ function provideEdsisAuth(config) {
629
712
  const documentRef = inject(DOCUMENT);
630
713
  const authSessionService = inject(AuthSessionService);
631
714
  const router = inject(Router, { optional: true });
632
- const userProfileService = inject(UserProfileService);
715
+ // Validasi default monitor memakai /v1/auth/refresh (cookie HttpOnly) saat
716
+ // access token mendekati kedaluwarsa, sehingga sesi tidak logout tiap 15 menit.
633
717
  startAuthSessionMonitor(documentRef, authSessionService, {
634
- validateSession: async () => {
635
- if (!readStoredAccessToken(documentRef)) {
636
- return true;
637
- }
638
- try {
639
- await firstValueFrom(userProfileService.getCurrentUser(undefined, new HttpContext().set(EDSIS_SKIP_SESSION_REFRESH, true)));
640
- return true;
641
- }
642
- catch (error) {
643
- if (error instanceof HttpErrorResponse && error.status === 401) {
644
- clearStoredSession(documentRef);
645
- return false;
646
- }
647
- return true;
648
- }
649
- },
650
718
  onSessionInvalid: () => {
651
719
  if (router) {
652
720
  void router.navigateByUrl(resolvedConfig.guestHomePath, { replaceUrl: true });
@@ -671,6 +739,7 @@ function provideEdsisAuth(config) {
671
739
  provide: EDSIS_AUTH_MESSAGES,
672
740
  useValue: mergeEdsisAuthMessages(config.messages),
673
741
  },
742
+ AuthHealthService,
674
743
  ]);
675
744
  }
676
745
 
@@ -792,9 +861,11 @@ function normalizeText(value) {
792
861
  class AuthLoginPage {
793
862
  destroyRef = inject(DestroyRef);
794
863
  formBuilder = inject(FormBuilder);
864
+ injector = inject(Injector);
795
865
  authMagicLinkService = inject(AuthMagicLinkService);
796
866
  authConfig = inject(EDSIS_AUTH_CONFIG);
797
867
  messages = inject(EDSIS_AUTH_MESSAGES);
868
+ health = inject(AuthHealthService);
798
869
  form = this.formBuilder.nonNullable.group({
799
870
  email: ['', [Validators.required, Validators.email, Validators.maxLength(255)]],
800
871
  });
@@ -806,9 +877,22 @@ class AuthLoginPage {
806
877
  ...(ngDevMode ? [{ debugName: "errorMessage" }] : /* istanbul ignore next */ []));
807
878
  emailControl = this.form.controls.email;
808
879
  emailFeedbackId = 'email-feedback';
880
+ healthBannerId = 'auth-health-banner';
881
+ retryButton = viewChild('healthRetryButton', /* @ts-ignore */
882
+ ...(ngDevMode ? [{ debugName: "retryButton" }] : /* istanbul ignore next */ []));
809
883
  emailControlState = toSignal(this.emailControl.events.pipe(startWith(null)), {
810
884
  initialValue: null,
811
885
  });
886
+ constructor() {
887
+ // On-load health check: non-blocking, no-op saat healthCheck.enabled=false.
888
+ void this.health.check();
889
+ effect(() => {
890
+ if (this.health.status() !== 'unhealthy') {
891
+ return;
892
+ }
893
+ afterNextRender(() => this.retryButton()?.nativeElement.focus(), { injector: this.injector });
894
+ });
895
+ }
812
896
  hasInlineError = computed(() => {
813
897
  this.emailControlState();
814
898
  return this.emailControl.invalid && (this.emailControl.dirty || this.emailControl.touched);
@@ -861,11 +945,18 @@ class AuthLoginPage {
861
945
  }
862
946
  }, /* @ts-ignore */
863
947
  ...(ngDevMode ? [{ debugName: "emailFieldClasses" }] : /* istanbul ignore next */ []));
864
- submit() {
948
+ retryHealth() {
949
+ void this.health.check();
950
+ }
951
+ async submit() {
865
952
  if (this.form.invalid) {
866
953
  this.form.markAllAsTouched();
867
954
  return;
868
955
  }
956
+ // Pre-submit re-check: backend bisa mati setelah halaman dimuat.
957
+ if (!(await this.health.check())) {
958
+ return;
959
+ }
869
960
  this.isSubmitting.set(true);
870
961
  this.responseMessage.set(null);
871
962
  this.errorMessage.set(null);
@@ -889,7 +980,7 @@ class AuthLoginPage {
889
980
  });
890
981
  }
891
982
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.5", ngImport: i0, type: AuthLoginPage, deps: [], target: i0.ɵɵFactoryTarget.Component });
892
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.5", type: AuthLoginPage, isStandalone: true, selector: "edsis-auth-login-page", host: { classAttribute: "block" }, ngImport: i0, template: `
983
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.0.5", type: AuthLoginPage, isStandalone: true, selector: "edsis-auth-login-page", host: { classAttribute: "block" }, viewQueries: [{ propertyName: "retryButton", first: true, predicate: ["healthRetryButton"], descendants: true, isSignal: true }], ngImport: i0, template: `
893
984
  <Card
894
985
  class="w-full overflow-hidden rounded-none border-border/80 bg-card/95 shadow-2xl backdrop-blur-sm"
895
986
  >
@@ -922,6 +1013,30 @@ class AuthLoginPage {
922
1013
  </CardHeader>
923
1014
 
924
1015
  <CardContent class="pt-4 sm:pt-5">
1016
+ @if (health.isUnhealthy()) {
1017
+ <div
1018
+ [id]="healthBannerId"
1019
+ role="alert"
1020
+ aria-live="assertive"
1021
+ class="mb-5 space-y-1 rounded-none border border-destructive bg-destructive/10 p-4 text-destructive"
1022
+ >
1023
+ <p class="font-medium">{{ messages.login.healthUnavailableTitle }}</p>
1024
+ <p class="text-sm">{{ messages.login.healthUnavailableBody }}</p>
1025
+ <button
1026
+ #healthRetryButton
1027
+ Button
1028
+ type="button"
1029
+ variant="outline"
1030
+ size="sm"
1031
+ class="mt-2 border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive"
1032
+ [disabled]="health.isChecking()"
1033
+ (click)="retryHealth()"
1034
+ >
1035
+ {{ health.isChecking() ? messages.login.healthChecking : messages.login.healthRetry }}
1036
+ </button>
1037
+ </div>
1038
+ }
1039
+
925
1040
  <form class="space-y-6" [formGroup]="form" (ngSubmit)="submit()">
926
1041
  <div class="space-y-3">
927
1042
  <label Label for="email" class="sr-only">Alamat email</label>
@@ -963,7 +1078,8 @@ class AuthLoginPage {
963
1078
  type="submit"
964
1079
  variant="default"
965
1080
  size="sm"
966
- [disabled]="form.invalid || isSubmitting()"
1081
+ [disabled]="form.invalid || isSubmitting() || health.isChecking() || health.isUnhealthy()"
1082
+ [attr.aria-describedby]="health.isUnhealthy() ? healthBannerId : null"
967
1083
  class="order-30 h-12! min-w-24 rounded-none px-5 text-sm font-medium"
968
1084
  >
969
1085
  {{ isSubmitting() ? messages.login.submitting : messages.login.submit }}
@@ -1142,6 +1258,30 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.5", ngImpor
1142
1258
  </CardHeader>
1143
1259
 
1144
1260
  <CardContent class="pt-4 sm:pt-5">
1261
+ @if (health.isUnhealthy()) {
1262
+ <div
1263
+ [id]="healthBannerId"
1264
+ role="alert"
1265
+ aria-live="assertive"
1266
+ class="mb-5 space-y-1 rounded-none border border-destructive bg-destructive/10 p-4 text-destructive"
1267
+ >
1268
+ <p class="font-medium">{{ messages.login.healthUnavailableTitle }}</p>
1269
+ <p class="text-sm">{{ messages.login.healthUnavailableBody }}</p>
1270
+ <button
1271
+ #healthRetryButton
1272
+ Button
1273
+ type="button"
1274
+ variant="outline"
1275
+ size="sm"
1276
+ class="mt-2 border-destructive/50 text-destructive hover:bg-destructive/10 hover:text-destructive"
1277
+ [disabled]="health.isChecking()"
1278
+ (click)="retryHealth()"
1279
+ >
1280
+ {{ health.isChecking() ? messages.login.healthChecking : messages.login.healthRetry }}
1281
+ </button>
1282
+ </div>
1283
+ }
1284
+
1145
1285
  <form class="space-y-6" [formGroup]="form" (ngSubmit)="submit()">
1146
1286
  <div class="space-y-3">
1147
1287
  <label Label for="email" class="sr-only">Alamat email</label>
@@ -1183,7 +1323,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.5", ngImpor
1183
1323
  type="submit"
1184
1324
  variant="default"
1185
1325
  size="sm"
1186
- [disabled]="form.invalid || isSubmitting()"
1326
+ [disabled]="form.invalid || isSubmitting() || health.isChecking() || health.isUnhealthy()"
1327
+ [attr.aria-describedby]="health.isUnhealthy() ? healthBannerId : null"
1187
1328
  class="order-30 h-12! min-w-24 rounded-none px-5 text-sm font-medium"
1188
1329
  >
1189
1330
  {{ isSubmitting() ? messages.login.submitting : messages.login.submit }}
@@ -1305,7 +1446,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.5", ngImpor
1305
1446
  </Card>
1306
1447
  `,
1307
1448
  }]
1308
- }] });
1449
+ }], ctorParameters: () => [], propDecorators: { retryButton: [{ type: i0.ViewChild, args: ['healthRetryButton', { isSignal: true }] }] } });
1309
1450
 
1310
1451
  class AuthLogoutPage {
1311
1452
  destroyRef = inject(DestroyRef);