@rdlabo/ionic-angular-kit 21.4.11 → 21.5.1

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
@@ -408,36 +408,35 @@ step immediately invalidates every in-flight auth lease; the second serializes c
408
408
  already in progress and removes the manifest and user replica.
409
409
 
410
410
  ```ts
411
- provideKitAuth(() => {
412
- const offline = inject(OfflineCoordinatorService);
413
- return {
414
- authState: () => auth.state$,
415
- onAuthorized: async () => {
416
- const session = await auth.exchangeCredential();
417
- return {
418
- activate: (lease) => offline.prepareRemoteSession(session.userId, session.groupIds, session.subject, lease),
419
- resume: () => offline.resumeRemoteSession(),
420
- };
411
+ import { createOfflineAuthBridge, isOfflineFallbackError } from '@rdlabo/ionic-angular-kit/offline';
412
+
413
+ provideKitAuth(() => ({
414
+ authState: () => auth.state$,
415
+ ...createOfflineAuthBridge({
416
+ exchange: async (ctx) => {
417
+ const remote = await auth.exchangeCredential(ctx);
418
+ const authSubject = auth.currentSubject();
419
+ return remote && authSubject ? { ...remote, authSubject } : false;
421
420
  },
422
- onUnavailable: async (_state, _error, lease) => (await offline.activateOfflineSession(auth.currentSubject(), lease)) !== null,
421
+ currentAuthSubject: () => auth.currentSubject(),
423
422
  isUnavailableError: isOfflineFallbackError,
424
- remoteRecovery: {
425
- availability: () => auth.authorityAvailable$,
426
- reauthenticate: async () => {
427
- const session = await auth.tryExchangeCredential();
428
- return session
429
- ? {
430
- activate: (lease) => offline.prepareRemoteSession(session.userId, session.groupIds, session.subject, lease),
431
- resume: () => offline.resumeRemoteSession(),
432
- }
433
- : false;
434
- },
435
- },
436
- redirects,
437
- };
438
- });
423
+ availability: () => auth.authorityAvailable$,
424
+ }),
425
+ redirects,
426
+ }));
439
427
  ```
440
428
 
429
+ `createOfflineAuthBridge` owns `exchange` → `prepareRemoteSession` → kit `grantRemote` → `resumeRemoteSession`
430
+ ordering via `KitRemoteAccessRecovery`. Product code keeps consent, error UI, and credential mapping inside
431
+ `exchange(context)` (`phase: 'authorize' | 'recover'`, optional route state, lease). Return `null`/`false` to decline
432
+ without throwing; thrown errors are never swallowed and remain available to the guard's unavailable/denial
433
+ classification. The returned identity requires a positive `userId`, non-negative numeric scope ids (including the
434
+ current user-scope compatibility value `0`), and a non-empty `authSubject`. The bridge compares that subject before
435
+ session activation, immediately before the coordinator commits through a composite lease, and around remote resume.
436
+ Optional `isIdentityCurrent` can add provider object-identity checks. `onRemoteResumed` receives the identity, phase,
437
+ route state, and post-grant lease for safe redirects or other product side effects. Default recovery availability
438
+ follows `offline.networkState !== 'offline'`.
439
+
441
440
  Register `offlineInterceptor` before `kitAuthInterceptor`. In local mode the auth interceptor synthesizes a
442
441
  transport-unavailable error before generating credentials or touching the network; the outer offline interceptor
443
442
  may then serve a matched `GET` from the replica. In `none` mode the same request is rejected and no local data is
@@ -646,6 +645,9 @@ export const appConfig: ApplicationConfig = {
646
645
  // Required for the new offline auth boundary. Kept opt-in so existing applications retain
647
646
  // their current interceptor behavior until they wire KitAuthAccessService.
648
647
  enforceAuthAccessMode: true,
648
+ // Optional. Use this only when the API distinguishes invalid identity (401) from
649
+ // authenticated resource permission (403). Omission keeps the legacy 401/403 revoke policy.
650
+ isAuthAccessDenial: (_req, error) => error.status === 401,
649
651
  getAuthHeaders: async (req) => ({
650
652
  Authorization: `Bearer ${await auth.getToken()}`,
651
653
  }),
@@ -685,8 +687,9 @@ because that also skips authentication headers and error handling, and do not gl
685
687
 
686
688
  **Error dispatch** (after retries, in `catchError`):
687
689
 
688
- 1. With `enforceAuthAccessMode`, `401` / `403` → revoke access, notify the matching hook, and reject
689
- without consulting `offlineFallback`
690
+ 1. With `enforceAuthAccessMode`, `401` / `403` never consults `offlineFallback`. The matching hook is
691
+ notified and the error is rejected. Shared access is revoked only when `isAuthAccessDenial`
692
+ returns `true`; omitting it preserves the legacy behavior that revokes on both 401 and 403.
690
693
  2. Otherwise, `offlineFallback` non-null → return fallback observable (no further hooks called)
691
694
  3. `401` → `onUnauthorized` · `403` → `onForbidden`
692
695
  4. `0` (connected) → `onNetworkError` · `429` → `onRateLimited(retryAfter?)` · `502/503/504` → `onServerBusy(status, retryAfter?)`
@@ -962,11 +965,7 @@ export class AuthService {
962
965
  // request and pass it as expectedUser; the kit checks object identity after `before` completes
963
966
  // and immediately before invoking Firebase signOut.
964
967
  signOutDeniedSession(expectedUser: User) {
965
- return kitSignOut(
966
- this.#auth,
967
- { before: () => this.clearDeniedSessionTransport() },
968
- { expectedUser },
969
- );
968
+ return kitSignOut(this.#auth, { before: () => this.clearDeniedSessionTransport() }, { expectedUser });
970
969
  }
971
970
  }
972
971
  ```
@@ -1,6 +1,8 @@
1
1
  import * as i0 from '@angular/core';
2
2
  import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
3
  import { KitStorageService } from '@rdlabo/ionic-angular-kit';
4
+ import { toObservable } from '@angular/core/rxjs-interop';
5
+ import { map, distinctUntilChanged } from 'rxjs/operators';
4
6
  import { App } from '@capacitor/app';
5
7
  import { Network } from '@capacitor/network';
6
8
  import { Capacitor } from '@capacitor/core';
@@ -2164,6 +2166,110 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2164
2166
  args: [{ providedIn: 'root' }]
2165
2167
  }] });
2166
2168
 
2169
+ /**
2170
+ * Builds the offline-aware {@link KitAuthConfig} fragment for guarded route activation and recovery.
2171
+ *
2172
+ * @remarks
2173
+ * The bridge owns `exchange` → {@link OfflineCoordinatorService.prepareRemoteSession} → kit
2174
+ * `grantRemote` → {@link OfflineCoordinatorService.resumeRemoteSession} ordering by returning
2175
+ * {@link KitRemoteAccessRecovery}. Product consent, error UI, and DTO mapping stay outside.
2176
+ *
2177
+ * @example
2178
+ * ```ts
2179
+ * provideKitAuth(() => ({
2180
+ * authState: () => auth.state$,
2181
+ * ...createOfflineAuthBridge({
2182
+ * exchange: async (ctx) => {
2183
+ * const identity = await auth.exchangeCredential(ctx);
2184
+ * const authSubject = auth.currentSubject();
2185
+ * return identity && authSubject ? { ...identity, authSubject } : false;
2186
+ * },
2187
+ * currentAuthSubject: () => auth.currentSubject(),
2188
+ * isUnavailableError: isOfflineFallbackError,
2189
+ * }),
2190
+ * redirects,
2191
+ * }));
2192
+ * ```
2193
+ */
2194
+ function createOfflineAuthBridge(options) {
2195
+ const offline = options.offline ?? inject(OfflineCoordinatorService);
2196
+ const { exchange, currentAuthSubject, isUnavailableError, isIdentityCurrent, onRemoteResumed, retryDelayMs } = options;
2197
+ const defaultAvailability$ = options.availability
2198
+ ? undefined
2199
+ : toObservable(offline.networkState).pipe(map((state) => state !== 'offline'), distinctUntilChanged());
2200
+ const availability = options.availability ?? (() => defaultAvailability$);
2201
+ const identityStillCurrent = (lease, identity) => lease.isCurrent() && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);
2202
+ const resolveRemoteAccess = async (phase, state, lease) => {
2203
+ if (!lease.isCurrent())
2204
+ return false;
2205
+ const identity = await exchange({ phase, state, lease });
2206
+ if (!lease.isCurrent())
2207
+ return false;
2208
+ if (identity === null || identity === false)
2209
+ return false;
2210
+ assertOfflineRemoteIdentity(identity);
2211
+ if (!identityStillCurrent(lease, identity))
2212
+ return false;
2213
+ return {
2214
+ activate: async (activateLease) => {
2215
+ if (!identityStillCurrent(activateLease, identity))
2216
+ return false;
2217
+ const identityLease = {
2218
+ isCurrent: () => identityStillCurrent(activateLease, identity),
2219
+ };
2220
+ const prepared = await offline.prepareRemoteSession(identity.userId, identity.scopeIds, identity.authSubject, identityLease);
2221
+ return prepared && identityLease.isCurrent();
2222
+ },
2223
+ resume: async (resumeLease) => {
2224
+ const resumeStillCurrent = () => (resumeLease?.isCurrent() ?? true) && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);
2225
+ if (!resumeStillCurrent())
2226
+ return;
2227
+ await offline.resumeRemoteSession();
2228
+ if (!resumeStillCurrent())
2229
+ return;
2230
+ if (onRemoteResumed) {
2231
+ await onRemoteResumed({
2232
+ phase,
2233
+ state,
2234
+ lease: resumeLease ?? lease,
2235
+ identity,
2236
+ });
2237
+ if (!resumeStillCurrent())
2238
+ return;
2239
+ }
2240
+ },
2241
+ };
2242
+ };
2243
+ return {
2244
+ isUnavailableError,
2245
+ onAuthorized: (state, lease) => resolveRemoteAccess('authorize', state, lease),
2246
+ onUnavailable: async (_state, _error, lease) => {
2247
+ if (!lease.isCurrent())
2248
+ return false;
2249
+ const manifest = await offline.activateOfflineSession(currentAuthSubject(), lease);
2250
+ if (!lease.isCurrent())
2251
+ return false;
2252
+ return manifest !== null;
2253
+ },
2254
+ remoteRecovery: {
2255
+ retryDelayMs,
2256
+ availability,
2257
+ reauthenticate: (lease) => resolveRemoteAccess('recover', undefined, lease),
2258
+ },
2259
+ };
2260
+ }
2261
+ function assertOfflineRemoteIdentity(identity) {
2262
+ if (!Number.isSafeInteger(identity.userId) || identity.userId <= 0) {
2263
+ throw new Error('Offline remote identity userId must be a positive safe integer.');
2264
+ }
2265
+ if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => !Number.isSafeInteger(scopeId) || scopeId < 0)) {
2266
+ throw new Error('Offline remote identity scopeIds must contain only non-negative safe integers.');
2267
+ }
2268
+ if (typeof identity.authSubject !== 'string' || identity.authSubject.length === 0) {
2269
+ throw new Error('Offline remote identity authSubject must be a non-empty string.');
2270
+ }
2271
+ }
2272
+
2167
2273
  /** outbox再送時にoffline interceptorだけを迂回する。認証・retryは維持する。 */
2168
2274
  const OFFLINE_BYPASS = new HttpContextToken(() => false);
2169
2275
  /** Header attached to responses served from the local replica fallback. */
@@ -2808,5 +2914,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2808
2914
  * Generated bundle index. Do not edit.
2809
2915
  */
2810
2916
 
2811
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2917
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2812
2918
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map