@rdlabo/ionic-angular-kit 21.5.0 → 21.5.2

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.
package/README.md CHANGED
@@ -416,9 +416,7 @@ provideKitAuth(() => ({
416
416
  exchange: async (ctx) => {
417
417
  const remote = await auth.exchangeCredential(ctx);
418
418
  const authSubject = auth.currentSubject();
419
- return remote && authSubject
420
- ? { ...remote, authSubject }
421
- : false;
419
+ return remote && authSubject ? { ...remote, authSubject } : false;
422
420
  },
423
421
  currentAuthSubject: () => auth.currentSubject(),
424
422
  isUnavailableError: isOfflineFallbackError,
@@ -635,7 +633,7 @@ fields and ignored server fields are never persisted.
635
633
  ```typescript
636
634
  // app.config.ts
637
635
  import { provideHttpClient, withInterceptors } from '@angular/common/http';
638
- import { kitAuthInterceptor, provideKitHttp, KitReloadAlertController } from '@rdlabo/ionic-angular-kit';
636
+ import { isIdentityAuthFailure, kitAuthInterceptor, provideKitHttp, KitReloadAlertController } from '@rdlabo/ionic-angular-kit';
639
637
 
640
638
  export const appConfig: ApplicationConfig = {
641
639
  providers: [
@@ -647,10 +645,17 @@ export const appConfig: ApplicationConfig = {
647
645
  // Required for the new offline auth boundary. Kept opt-in so existing applications retain
648
646
  // their current interceptor behavior until they wire KitAuthAccessService.
649
647
  enforceAuthAccessMode: true,
648
+ // Only an explicitly tagged global identity failure may revoke shared access.
649
+ // Omission keeps the legacy 401/403 revoke policy for existing applications.
650
+ isAuthAccessDenial: (_req, error) => isIdentityAuthFailure(error),
650
651
  getAuthHeaders: async (req) => ({
651
652
  Authorization: `Bearer ${await auth.getToken()}`,
652
653
  }),
653
- onUnauthorized: (req) => auth.signOut(),
654
+ // Status-independent: handles both new identity 401 and tagged historical identity 403.
655
+ onAuthAccessDenial: () => auth.signOut(),
656
+ onUnauthorized: (_req, error) => {
657
+ // Feature UX for reauthentication/credential failures may inspect the error here.
658
+ },
654
659
  // Fleet-canonical "network error → offer reload" (see KitReloadAlertController).
655
660
  onNetworkError: (status) =>
656
661
  reload.present({
@@ -686,8 +691,9 @@ because that also skips authentication headers and error handling, and do not gl
686
691
 
687
692
  **Error dispatch** (after retries, in `catchError`):
688
693
 
689
- 1. With `enforceAuthAccessMode`, `401` / `403` → revoke access, notify the matching hook, and reject
690
- without consulting `offlineFallback`
694
+ 1. With `enforceAuthAccessMode`, `401` / `403` never consults `offlineFallback`. The matching hook is
695
+ notified and the error is rejected. Shared access is revoked only when `isAuthAccessDenial`
696
+ returns `true`; omitting it preserves the legacy behavior that revokes on both 401 and 403.
691
697
  2. Otherwise, `offlineFallback` non-null → return fallback observable (no further hooks called)
692
698
  3. `401` → `onUnauthorized` · `403` → `onForbidden`
693
699
  4. `0` (connected) → `onNetworkError` · `429` → `onRateLimited(retryAfter?)` · `502/503/504` → `onServerBusy(status, retryAfter?)`
@@ -696,6 +702,36 @@ because that also skips authentication headers and error handling, and do not gl
696
702
 
697
703
  Plus: a `getAuthHeaders` rejection → `onAuthError(request, error)` (the request is never sent).
698
704
 
705
+ The shared `401` body carries `authFailureScope`:
706
+
707
+ - `identity`: the Firebase/global identity cannot be established; global session and replica/outbox
708
+ invalidation is allowed.
709
+ - `reauthentication`: the identity remains valid, but a recent sign-in/step-up is required.
710
+ - `credential`: only a feature-owned delegated credential is invalid.
711
+
712
+ `getAuthFailureScope(error)` reads this explicit field and returns `null` for untagged legacy
713
+ responses. It also accepts an explicitly tagged historical `403` identity failure for products
714
+ whose installed clients still require that status; new APIs use `401`.
715
+ `isIdentityAuthFailure(error)` is therefore intentionally strict. Put destructive global cleanup in
716
+ `onAuthAccessDenial`; it runs for a classified identity failure independently of whether a compatible
717
+ server returned 401 or 403. `onUnauthorized` receives the complete `HttpErrorResponse` for status-specific UX.
718
+ An untagged `403` remains a resource/scope/business permission failure and never implies global
719
+ identity loss. Existing callbacks that accept only the request remain source-compatible, and applications
720
+ that omit `isAuthAccessDenial` retain the historical 401/403 revocation behavior.
721
+
722
+ Deploy the API contract before enabling the strict client classifier:
723
+
724
+ | Combination | Result |
725
+ | ---------------------------- | ----------------------------------------------------------------------------------------------------------- |
726
+ | Tagged API + legacy client | The extra body fields are ignored and the client's existing status behavior is preserved. |
727
+ | Untagged API + strict client | Global identity loss cannot be identified safely, so the client retains local identity state. |
728
+ | Tagged API + strict client | Only `identity` with `AUTH_IDENTITY_INVALID` revokes global access; narrower failures remain feature-owned. |
729
+
730
+ For products whose installed clients historically require auth failure as `403`, deploy an explicitly
731
+ tagged legacy `403` identity response first. The strict classifier accepts it only with the matching
732
+ `statusCode`, scope, and `AUTH_IDENTITY_INVALID` code. Do not infer identity from an untagged legacy
733
+ 401/403: that would collapse `credential` and `reauthentication` back into destructive global logout.
734
+
699
735
  **Note (0.0.9):** `onNetworkError` is now narrowed to genuine network failures (status `0`); `502/503/429` moved to `onServerBusy`/`onRateLimited`. Existing configs stay valid — they just fire less often — so adopt the new hooks only if you want to distinguish server-busy / rate-limit from a connection loss.
700
736
 
701
737
  ### KitReloadAlertController
@@ -963,11 +999,7 @@ export class AuthService {
963
999
  // request and pass it as expectedUser; the kit checks object identity after `before` completes
964
1000
  // and immediately before invoking Firebase signOut.
965
1001
  signOutDeniedSession(expectedUser: User) {
966
- return kitSignOut(
967
- this.#auth,
968
- { before: () => this.clearDeniedSessionTransport() },
969
- { expectedUser },
970
- );
1002
+ return kitSignOut(this.#auth, { before: () => this.clearDeniedSessionTransport() }, { expectedUser });
971
1003
  }
972
1004
  }
973
1005
  ```
@@ -1840,6 +1840,17 @@ const KIT_HTTP_CONFIG = new InjectionToken('@rdlabo/ionic-angular-kit:http');
1840
1840
  * ```
1841
1841
  */
1842
1842
  const provideKitHttp = (configFactory) => makeEnvironmentProviders([{ provide: KIT_HTTP_CONFIG, useFactory: configFactory }]);
1843
+ /**
1844
+ * True when shared remote access should be revoked for an auth-related failure.
1845
+ *
1846
+ * @remarks
1847
+ * Only meaningful when {@link KitHttpConfig.enforceAuthAccessMode} is enabled and
1848
+ * {@link isExplicitAuthDenial} already matched. When {@link KitHttpConfig.isAuthAccessDenial} is
1849
+ * omitted, every explicit denial revokes access (legacy default).
1850
+ *
1851
+ * @internal
1852
+ */
1853
+ const shouldRevokeAuthAccess = (config, req, error) => config.isAuthAccessDenial?.(req, error) ?? isExplicitAuthDenial(error);
1843
1854
  /**
1844
1855
  * Classify a final (post-retry) error and invoke the matching {@link KitHttpConfig} hook.
1845
1856
  *
@@ -1850,10 +1861,10 @@ const dispatchError = (config, req, error) => {
1850
1861
  const retryAfterMs = parseRetryAfterMs(error);
1851
1862
  const retryAfterSeconds = retryAfterMs === null ? undefined : Math.round(retryAfterMs / 1000);
1852
1863
  if (status === 401) {
1853
- config.onUnauthorized?.(req);
1864
+ config.onUnauthorized?.(req, error);
1854
1865
  }
1855
1866
  else if (status === 403) {
1856
- config.onForbidden?.(req);
1867
+ config.onForbidden?.(req, error);
1857
1868
  }
1858
1869
  else if (status === 0) {
1859
1870
  // Genuine network/transport failure. Only surface it when the device is actually connected
@@ -1932,8 +1943,10 @@ const kitAuthInterceptor = (request, next) => {
1932
1943
  }
1933
1944
  return from(Promise.resolve(config.getAuthHeaders(request))).pipe(catchError((headerError) => {
1934
1945
  // getAuthHeaders failed → the request is never sent; classify it instead of failing silently.
1935
- if (config.enforceAuthAccessMode && isExplicitAuthDenial(headerError))
1946
+ if (config.enforceAuthAccessMode && isExplicitAuthDenial(headerError) && shouldRevokeAuthAccess(config, request, headerError)) {
1936
1947
  access.clear();
1948
+ config.onAuthAccessDenial?.(request, headerError);
1949
+ }
1937
1950
  config.onAuthError?.(request, headerError);
1938
1951
  return throwError(() => headerError);
1939
1952
  }), mergeMap((authHeaders) => {
@@ -1972,7 +1985,10 @@ const kitAuthInterceptor = (request, next) => {
1972
1985
  }
1973
1986
  }), catchError((error) => {
1974
1987
  if (config.enforceAuthAccessMode && isExplicitAuthDenial(error)) {
1975
- access.clear();
1988
+ if (shouldRevokeAuthAccess(config, req, error)) {
1989
+ access.clear();
1990
+ config.onAuthAccessDenial?.(req, error);
1991
+ }
1976
1992
  dispatchError(config, req, error);
1977
1993
  return throwError(() => error);
1978
1994
  }
@@ -1988,6 +2004,47 @@ const kitAuthInterceptor = (request, next) => {
1988
2004
  }));
1989
2005
  };
1990
2006
 
2007
+ /**
2008
+ * Shared lifecycle boundary carried by an authentication failure response.
2009
+ *
2010
+ * Only `identity` invalidates the application's global authenticated identity.
2011
+ * The other scopes retain it and let the owning feature handle recovery.
2012
+ */
2013
+ const AUTH_FAILURE_SCOPES = {
2014
+ identity: 'identity',
2015
+ reauthentication: 'reauthentication',
2016
+ credential: 'credential',
2017
+ };
2018
+ const AUTH_IDENTITY_INVALID_CODE = 'AUTH_IDENTITY_INVALID';
2019
+ const isRecord = (value) => typeof value === 'object' && value !== null;
2020
+ const isAuthFailureScope = (value) => Object.values(AUTH_FAILURE_SCOPES).some((scope) => scope === value);
2021
+ /**
2022
+ * Reads the explicit auth-failure scope from an Angular `HttpErrorResponse` or
2023
+ * from a body-like value. Tagged historical 403 identity responses are
2024
+ * supported for installed-client compatibility. Untagged 401/403 responses
2025
+ * intentionally return `null`.
2026
+ */
2027
+ const getAuthFailureScope = (error) => {
2028
+ if (!isRecord(error))
2029
+ return null;
2030
+ const body = isRecord(error['error']) ? error['error'] : error;
2031
+ const status = typeof error['status'] === 'number' ? error['status'] : body['statusCode'];
2032
+ if (status !== 401 && status !== 403)
2033
+ return null;
2034
+ if (body['statusCode'] !== status || typeof body['code'] !== 'string')
2035
+ return null;
2036
+ const scope = body['authFailureScope'];
2037
+ if (!isAuthFailureScope(scope))
2038
+ return null;
2039
+ if (status === 403 && scope !== AUTH_FAILURE_SCOPES.identity)
2040
+ return null;
2041
+ if (scope === AUTH_FAILURE_SCOPES.identity && body['code'] !== AUTH_IDENTITY_INVALID_CODE)
2042
+ return null;
2043
+ return scope;
2044
+ };
2045
+ /** True only for an explicitly tagged global identity failure. */
2046
+ const isIdentityAuthFailure = (error) => getAuthFailureScope(error) === AUTH_FAILURE_SCOPES.identity;
2047
+
1991
2048
  /** Stable per-tab/application-run ID shared by realtime connections and write headers. */
1992
2049
  const KIT_REALTIME_CLIENT_ID = crypto.randomUUID();
1993
2050
  /** Convert an HTTP(S) endpoint to its WebSocket equivalent. */
@@ -2709,5 +2766,5 @@ function mountViewModel(host, onMount) {
2709
2766
  * Generated bundle index. Do not edit.
2710
2767
  */
2711
2768
 
2712
- export { KIT_AUTH_BOOTSTRAP_REQUEST, KIT_AUTH_CONFIG, KIT_AUTH_RECOVERY_CONFIG, KIT_HTTP_CONFIG, KIT_LAST_AUTH_EMAIL_KEY, KIT_OVERLAY_CONFIG, KIT_REALTIME_CLIENT_ID, KIT_THEME_STORAGE_KEY, KitAuthAccessService, KitAuthInputDirective, KitAuthRecoveryService, KitLoadingController, KitMaintenanceController, KitOverlayController, KitRealtimeConnection, KitRealtimeLivenessWatchdog, KitReloadAlertController, KitStorageService, arrayConcatById, disableHandler, isExplicitAuthDenial, isMaintenanceError, kitAuthInterceptor, kitChangeEventDisabled, kitClearStoragePreservingKeys, kitCreateDidEnter, kitForgetEmail, kitImpact, kitIsValidEmail, kitKeyboardInit, kitPresentAuthFailedAlert, kitPresentLanguageActionSheet, kitRealtimeProtocols, kitRecallEmail, kitRememberEmail, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, mountViewModel, objectEqual, provideKitAuth, provideKitHttp, provideKitOverlay, toKitWebSocketUrl };
2769
+ export { AUTH_FAILURE_SCOPES, AUTH_IDENTITY_INVALID_CODE, KIT_AUTH_BOOTSTRAP_REQUEST, KIT_AUTH_CONFIG, KIT_AUTH_RECOVERY_CONFIG, KIT_HTTP_CONFIG, KIT_LAST_AUTH_EMAIL_KEY, KIT_OVERLAY_CONFIG, KIT_REALTIME_CLIENT_ID, KIT_THEME_STORAGE_KEY, KitAuthAccessService, KitAuthInputDirective, KitAuthRecoveryService, KitLoadingController, KitMaintenanceController, KitOverlayController, KitRealtimeConnection, KitRealtimeLivenessWatchdog, KitReloadAlertController, KitStorageService, arrayConcatById, disableHandler, getAuthFailureScope, isExplicitAuthDenial, isIdentityAuthFailure, isMaintenanceError, kitAuthInterceptor, kitChangeEventDisabled, kitClearStoragePreservingKeys, kitCreateDidEnter, kitForgetEmail, kitImpact, kitIsValidEmail, kitKeyboardInit, kitPresentAuthFailedAlert, kitPresentLanguageActionSheet, kitRealtimeProtocols, kitRecallEmail, kitRememberEmail, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, mountViewModel, objectEqual, provideKitAuth, provideKitHttp, provideKitOverlay, toKitWebSocketUrl };
2713
2770
  //# sourceMappingURL=rdlabo-ionic-angular-kit.mjs.map