@securitydept/token-set-context-client-angular 0.2.0-beta.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.
@@ -0,0 +1,838 @@
1
+ import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
2
+ import * as i0 from '@angular/core';
3
+ import { WritableSignal, InjectionToken, Provider, EnvironmentProviders, OnInit } from '@angular/core';
4
+ import { Observable } from 'rxjs';
5
+ import { ClientReadinessState } from '@securitydept/token-set-context-client/frontend-oidc-mode';
6
+ import { OidcModeClient, OidcCallbackClient, TokenSetClientEntry as TokenSetClientEntry$1, ClientInitializationPriority, TokenSetAuthRegistry as TokenSetAuthRegistry$1, ClientMeta, ClientKeySelector, ClientFilter, ClientQueryOptions } from '@securitydept/token-set-context-client/registry';
7
+ export { ClientFilter, ClientInitializationPriority, ClientKeySelector, ClientMeta, ClientQueryOptions, OidcCallbackClient, OidcModeClient } from '@securitydept/token-set-context-client/registry';
8
+ import { AuthSnapshot } from '@securitydept/token-set-context-client/orchestration';
9
+ import { UrlTree, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateFn, Route } from '@angular/router';
10
+ import { AuthRequirement, PlannerHost, RequirementsClientSetComposition } from '@securitydept/client/auth-coordination';
11
+
12
+ type TokenSetAngularClient = OidcModeClient & OidcCallbackClient;
13
+ /**
14
+ * A registration entry for a single token-set auth client.
15
+ *
16
+ * Each client is identified by a unique string key (e.g. "main", "admin",
17
+ * the provider ID, or the requirement kind), so that routes, interceptors,
18
+ * and callbacks can discriminate between multiple concurrent auth sources.
19
+ *
20
+ * ## Sync vs Async client factory
21
+ *
22
+ * `clientFactory` supports both synchronous and asynchronous materialization:
23
+ *
24
+ * - **Sync** (`() => OidcModeClient`): The client config is available at
25
+ * registration time. Classic inline config or pre-resolved projections.
26
+ *
27
+ * - **Async** (`() => Promise<OidcModeClient>`): The client config must be
28
+ * resolved asynchronously (e.g. fetched from a backend config projection
29
+ * endpoint). The registry tracks readiness state and provides `whenReady()`
30
+ * for guards/interceptors that need to wait.
31
+ *
32
+ * When `clientFactory` returns a Promise, the registry enters
33
+ * `ClientReadinessState.Initializing` for this key and transitions to
34
+ * `Ready` or `Failed` when the promise settles.
35
+ *
36
+ * Two additional discrimination axes are supported:
37
+ * - `requirementKind`: maps a RequirementKind (or custom string) → this client.
38
+ * Guards and resolvers can look up the client for a pending requirement without
39
+ * knowing the concrete key.
40
+ * - `providerFamily`: maps a named provider family (e.g. "google", "internal-sso")
41
+ * → this client. Useful when multiple clients share the same kind but differ
42
+ * by provider / audience.
43
+ */
44
+ interface TokenSetClientEntry extends Omit<TokenSetClientEntry$1<TokenSetAngularClient>, "clientFactory"> {
45
+ /**
46
+ * Factory that creates the OIDC mode client.
47
+ *
48
+ * May return the client synchronously (inline config) or a Promise
49
+ * (async config projection resolution). When a Promise is returned,
50
+ * the registry tracks initialization readiness automatically.
51
+ */
52
+ clientFactory: () => TokenSetAngularClient | Promise<TokenSetAngularClient>;
53
+ /**
54
+ * Initialization priority. Defaults to `"primary"` (eager). Set to
55
+ * `"lazy"` to defer clientFactory execution until the registry is asked
56
+ * for this key via `whenReady(key)` / `preload(key)` / `idleWarmup()`.
57
+ */
58
+ priority?: ClientInitializationPriority;
59
+ }
60
+
61
+ /**
62
+ * Per-client Angular service that bridges a single OIDC mode client to
63
+ * Angular signals + RxJS.
64
+ *
65
+ * Iteration 110 change: lifecycle teardown is now explicit. Construct with
66
+ * `new TokenSetAuthService(client, autoRestore)` and call `.dispose()` when
67
+ * the service owner tears down. The shared registry core handles this
68
+ * automatically — adopters that wire the service directly (rare) must call
69
+ * `dispose()` themselves, typically bound to a `DestroyRef.onDestroy`.
70
+ */
71
+ declare class TokenSetAuthService {
72
+ /** The underlying SDK client instance. */
73
+ readonly client: TokenSetAngularClient;
74
+ /** Current auth snapshot as an Angular signal. */
75
+ readonly authState: WritableSignal<AuthSnapshot | null>;
76
+ /** Current auth snapshot as an RxJS Observable. */
77
+ readonly authState$: Observable<AuthSnapshot | null>;
78
+ /** Promise that resolves when initial state restore completes (or null if skipped). */
79
+ readonly restorePromise: Promise<AuthSnapshot | null> | null;
80
+ private readonly cleanup;
81
+ private disposed;
82
+ constructor(
83
+ /** The underlying SDK client instance. */
84
+ client: TokenSetAngularClient, autoRestore: boolean);
85
+ /** Whether the user is currently authenticated. */
86
+ isAuthenticated(): boolean;
87
+ /** Current access token, or null. */
88
+ accessToken(): string | null;
89
+ /**
90
+ * Release all resources owned by this service.
91
+ *
92
+ * - Unsubscribes the SDK state bridge
93
+ * - Calls `client.dispose()`
94
+ *
95
+ * Idempotent: subsequent calls are no-ops. Called by the shared registry
96
+ * at teardown; adopters invoking TokenSetAuthService directly must call
97
+ * this themselves (typically bound to `DestroyRef.onDestroy`).
98
+ */
99
+ dispose(): void;
100
+ }
101
+
102
+ type AngularClient = TokenSetAngularClient;
103
+ declare class TokenSetAuthRegistry {
104
+ /**
105
+ * Shared framework-neutral registry core. Angular consumers rarely need
106
+ * direct access, but this is exposed so adapter-internal helpers
107
+ * (`CallbackResumeService`, `bearer-interceptor`) can query the core
108
+ * directly when they don't need Angular-specific behaviour.
109
+ */
110
+ readonly core: TokenSetAuthRegistry$1<AngularClient, TokenSetAuthService>;
111
+ constructor();
112
+ /**
113
+ * Register a client entry. Supports sync / async / lazy priority.
114
+ *
115
+ * Iteration 110 change: the second `destroyRef` argument is no longer
116
+ * required — the registry pulls its own `DestroyRef` via injection and
117
+ * binds teardown once per Angular scope.
118
+ */
119
+ register(entry: TokenSetClientEntry & {
120
+ priority?: "primary" | "lazy";
121
+ clientFactory: () => AngularClient;
122
+ }): TokenSetAuthService;
123
+ register(entry: TokenSetClientEntry & {
124
+ priority?: "primary" | "lazy";
125
+ clientFactory: () => Promise<AngularClient>;
126
+ }): Promise<TokenSetAuthService>;
127
+ register(entry: TokenSetClientEntry): TokenSetAuthService | Promise<TokenSetAuthService> | undefined;
128
+ /**
129
+ * Manually dispose the registry. Normally bound to the ambient
130
+ * `DestroyRef` at construction; call this explicitly when instantiating
131
+ * the registry outside of an Angular injection context (e.g. in unit
132
+ * tests).
133
+ */
134
+ dispose(): void;
135
+ isReady(key: string): boolean;
136
+ readinessState(key: string): ClientReadinessState;
137
+ whenReady(key: string): Promise<TokenSetAuthService>;
138
+ /**
139
+ * Preload a lazy client without throwing on rejection. Callers are
140
+ * expected to attach `.catch` handlers for fire-and-forget usage.
141
+ */
142
+ preload(key: string): Promise<TokenSetAuthService>;
143
+ /**
144
+ * Schedule preload for every lazy+not-initialized client using
145
+ * `requestIdleCallback` / `setTimeout` fallback.
146
+ */
147
+ idleWarmup(): () => void;
148
+ reset(key: string): void;
149
+ metaFor(clientKey: string): ClientMeta | undefined;
150
+ get(key: string): TokenSetAuthService | undefined;
151
+ require(key: string): TokenSetAuthService;
152
+ keys(): string[];
153
+ entries(): Array<[string, TokenSetAuthService]>;
154
+ clientKeyGenForUrl(url: string): Generator<string, void, unknown>;
155
+ clientKeyGenForCallback(url: string): Generator<string, void, unknown>;
156
+ clientKeyGenForRequirement(requirementKind: string): Generator<string, void, unknown>;
157
+ clientKeyGenForProviderFamily(providerFamily: string): Generator<string, void, unknown>;
158
+ clientKeyListForUrl(url: string): string[];
159
+ clientKeyListForCallback(url: string): string[];
160
+ clientKeyListForRequirement(requirementKind: string): string[];
161
+ clientKeyListForProviderFamily(providerFamily: string): string[];
162
+ clientKeyForUrl(url: string, selector?: ClientKeySelector): string | undefined;
163
+ clientKeyForCallback(url: string, selector?: ClientKeySelector): string | undefined;
164
+ clientKeyForRequirement(requirementKind: string, selector?: ClientKeySelector): string | undefined;
165
+ clientKeyForProviderFamily(providerFamily: string, selector?: ClientKeySelector): string | undefined;
166
+ requireForRequirement(requirementKind: string, selector?: ClientKeySelector): TokenSetAuthService;
167
+ requireForProviderFamily(providerFamily: string, selector?: ClientKeySelector): TokenSetAuthService;
168
+ clientKeyGenForFilter(filter: ClientFilter): Generator<string, void, unknown>;
169
+ clientKeyGenForOptions(options: ClientQueryOptions): Generator<string, void, unknown>;
170
+ clientKeysForOptions(options: ClientQueryOptions): string[];
171
+ accessToken(key?: string): string | null;
172
+ static ɵfac: i0.ɵɵFactoryDeclaration<TokenSetAuthRegistry, never>;
173
+ static ɵprov: i0.ɵɵInjectableDeclaration<TokenSetAuthRegistry>;
174
+ }
175
+
176
+ /**
177
+ * Adopter-tunable behaviour for the token-set bearer interceptor.
178
+ *
179
+ * Iteration 150 (review 1) lifted `strictUrlMatch` out of the implicit
180
+ * single-client convenience path into an explicit option, so multi-backend
181
+ * adopters can guarantee that bearer tokens never leak outside the URL
182
+ * patterns they registered with `provideTokenSetAuth({ clients: [...] })`.
183
+ */
184
+ interface BearerInterceptorOptions {
185
+ /**
186
+ * When `true`, the interceptor injects a bearer header ONLY for requests
187
+ * whose URL matches a registered client's `urlPatterns`. Requests with no
188
+ * matching client receive no `Authorization` header even when a token is
189
+ * available elsewhere in the registry.
190
+ *
191
+ * When `false` (default, single-client convenience), the interceptor
192
+ * falls back to `registry.accessToken()` for unmatched URLs — useful only
193
+ * when the host issues all HTTP traffic to one already-known backend.
194
+ *
195
+ * Adopters with more than one backend, more than one OIDC audience, or
196
+ * any third-party HTTP traffic from the same Angular host MUST set this
197
+ * to `true` to prevent cross-origin token leakage.
198
+ *
199
+ * @default false
200
+ */
201
+ strictUrlMatch?: boolean;
202
+ }
203
+ /**
204
+ * DI token for {@link BearerInterceptorOptions}. Adopters normally configure
205
+ * options via `provideTokenSetBearerInterceptor({ ... })`; the token is
206
+ * exported for advanced cases where the options need to be supplied or
207
+ * overridden separately (for example, in tests).
208
+ */
209
+ declare const TOKEN_SET_BEARER_INTERCEPTOR_OPTIONS: InjectionToken<BearerInterceptorOptions>;
210
+ /**
211
+ * Angular class-based bearer-token interceptor (`HTTP_INTERCEPTORS` style).
212
+ *
213
+ * Selects the correct access token from the multi-client registry by URL
214
+ * pattern. Behaviour for unmatched URLs is governed by
215
+ * {@link BearerInterceptorOptions.strictUrlMatch}.
216
+ *
217
+ * Prefer the functional version via `createTokenSetBearerInterceptor()` +
218
+ * `withInterceptors()` when using `provideHttpClient`. Use this class-based
219
+ * version when you need classic `HTTP_INTERCEPTORS` multi-provider style
220
+ * (e.g. NgModule apps).
221
+ *
222
+ * @example
223
+ * ```ts
224
+ * // NgModule providers:
225
+ * provideTokenSetBearerInterceptor({ strictUrlMatch: true })
226
+ * ```
227
+ */
228
+ declare class TokenSetBearerInterceptor implements HttpInterceptor {
229
+ private readonly registry;
230
+ private readonly options;
231
+ intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>;
232
+ static ɵfac: i0.ɵɵFactoryDeclaration<TokenSetBearerInterceptor, never>;
233
+ static ɵprov: i0.ɵɵInjectableDeclaration<TokenSetBearerInterceptor>;
234
+ }
235
+ /**
236
+ * Create an `HTTP_INTERCEPTORS` multi-provider entry for bearer token injection.
237
+ *
238
+ * Returns a single `Provider` object that registers {@link TokenSetBearerInterceptor}
239
+ * as a class-based HTTP interceptor. Suitable for NgModule `providers` arrays.
240
+ *
241
+ * For functional-interceptor style (standalone apps using `provideHttpClient`),
242
+ * use `createTokenSetBearerInterceptor()` with `withInterceptors()` instead.
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * @NgModule({
247
+ * providers: [
248
+ * provideTokenSetAuth({ clients: [...] }),
249
+ * provideTokenSetBearerInterceptor(), // <— replaces hand-written AuthInterceptor
250
+ * provideHttpClient(withInterceptorsFromDi()),
251
+ * ],
252
+ * })
253
+ * export class AppModule {}
254
+ * ```
255
+ */
256
+ /**
257
+ * Create an `HTTP_INTERCEPTORS` multi-provider entry for bearer token injection.
258
+ *
259
+ * Returns Angular providers that register {@link TokenSetBearerInterceptor}
260
+ * as a class-based HTTP interceptor and (optionally) the
261
+ * {@link BearerInterceptorOptions} that govern its URL-match behaviour.
262
+ * Suitable for NgModule `providers` arrays.
263
+ *
264
+ * For functional-interceptor style (standalone apps using `provideHttpClient`),
265
+ * use `createTokenSetBearerInterceptor()` with `withInterceptors()` instead.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * @NgModule({
270
+ * providers: [
271
+ * provideTokenSetAuth({ clients: [...] }),
272
+ * // Adopters with multiple backends or any third-party HTTP traffic
273
+ * // MUST opt into strictUrlMatch to prevent token leakage.
274
+ * provideTokenSetBearerInterceptor({ strictUrlMatch: true }),
275
+ * provideHttpClient(withInterceptorsFromDi()),
276
+ * ],
277
+ * })
278
+ * export class AppModule {}
279
+ * ```
280
+ */
281
+ declare function provideTokenSetBearerInterceptor(options?: BearerInterceptorOptions): Provider[];
282
+ /**
283
+ * Create an Angular `HttpInterceptorFn` that injects bearer authorization
284
+ * headers, selecting the correct token from the multi-client registry
285
+ * based on URL pattern matching.
286
+ *
287
+ * If no URL pattern matches, falls back to the first available token
288
+ * (single-client convenience).
289
+ *
290
+ * ## Async client readiness
291
+ *
292
+ * The interceptor does **not** block or delay the HTTP request waiting for
293
+ * an async client to materialize. If a client is still initializing when the
294
+ * request fires, the request proceeds without an Authorization header.
295
+ *
296
+ * This is intentional: blocking HTTP for client initialization would deadlock
297
+ * apps that make HTTP requests during initialization itself. Route guards
298
+ * (which use `registry.whenReady()`) are the correct place to enforce
299
+ * "client must be ready before user reaches this route".
300
+ *
301
+ * For NgModule-style apps using `HTTP_INTERCEPTORS`, use
302
+ * `provideTokenSetBearerInterceptor()` instead.
303
+ *
304
+ * @example
305
+ * ```ts
306
+ * import { provideHttpClient, withInterceptors } from "@angular/common/http";
307
+ * import { createTokenSetBearerInterceptor } from "@securitydept/token-set-context-client-angular";
308
+ *
309
+ * provideHttpClient(withInterceptors([
310
+ * createTokenSetBearerInterceptor(registry),
311
+ * ]));
312
+ * ```
313
+ */
314
+ /**
315
+ * Create an Angular `HttpInterceptorFn` that injects bearer authorization
316
+ * headers, selecting the correct token from the multi-client registry
317
+ * based on URL pattern matching.
318
+ *
319
+ * If no URL pattern matches, the unmatched-URL behaviour is governed by
320
+ * {@link BearerInterceptorOptions.strictUrlMatch}: the default falls back
321
+ * to `registry.accessToken()` (single-client convenience), while
322
+ * `strictUrlMatch: true` returns no token, ensuring bearer headers are
323
+ * never injected for URLs outside the registered patterns.
324
+ *
325
+ * ## Async client readiness
326
+ *
327
+ * The interceptor does **not** block or delay the HTTP request waiting for
328
+ * an async client to materialize. If a client is still initializing when the
329
+ * request fires, the request proceeds without an Authorization header.
330
+ *
331
+ * This is intentional: blocking HTTP for client initialization would deadlock
332
+ * apps that make HTTP requests during initialization itself. Route guards
333
+ * (which use `registry.whenReady()`) are the correct place to enforce
334
+ * "client must be ready before user reaches this route".
335
+ *
336
+ * For NgModule-style apps using `HTTP_INTERCEPTORS`, use
337
+ * `provideTokenSetBearerInterceptor()` instead.
338
+ *
339
+ * @example
340
+ * ```ts
341
+ * import { provideHttpClient, withInterceptors } from "@angular/common/http";
342
+ * import { createTokenSetBearerInterceptor } from "@securitydept/token-set-context-client-angular";
343
+ *
344
+ * provideHttpClient(withInterceptors([
345
+ * createTokenSetBearerInterceptor(registry, { strictUrlMatch: true }),
346
+ * ]));
347
+ * ```
348
+ */
349
+ declare function createTokenSetBearerInterceptor(registry: TokenSetAuthRegistry, options?: BearerInterceptorOptions): (req: {
350
+ url: string;
351
+ clone(update: {
352
+ setHeaders?: Record<string, string>;
353
+ }): unknown;
354
+ }, next: (req: unknown) => Observable<unknown>) => Observable<unknown>;
355
+
356
+ /**
357
+ * Angular-native service for handling OIDC redirect callbacks,
358
+ * with multi-client discrimination support.
359
+ *
360
+ * The post-authentication redirect URI is propagated automatically through
361
+ * the core client's pending state (set via `loginWithRedirect({ postAuthRedirectUri })`
362
+ * and recovered in `handleCallback()`). No manual URL storage is required.
363
+ *
364
+ * @example
365
+ * ```ts
366
+ * @Component({ ... })
367
+ * export class AuthCallbackComponent {
368
+ * private readonly callbackService = inject(CallbackResumeService);
369
+ * private readonly router = inject(Router);
370
+ *
371
+ * async ngOnInit() {
372
+ * const result = await this.callbackService.handleCallback(
373
+ * window.location.href,
374
+ * );
375
+ * this.router.navigateByUrl(result.resumeUrl, { replaceUrl: true });
376
+ * }
377
+ * }
378
+ * ```
379
+ */
380
+ declare class CallbackResumeService {
381
+ private readonly registry;
382
+ /**
383
+ * Check whether a URL is an OIDC authorization callback for any registered
384
+ * client in this registry.
385
+ *
386
+ * This is a convenience wrapper over `clientKeyForCallback()`. Use it for
387
+ * programmatic early-exit guards (e.g. in a service constructor) before
388
+ * calling `handleCallback()`.
389
+ *
390
+ * @param url - The full URL to check (e.g. `window.location.href`).
391
+ * @returns `true` when the URL matches a registered callback path and
392
+ * contains an `code` or `error` query parameter.
393
+ */
394
+ isCallback(url: string): boolean;
395
+ /**
396
+ * Handle the OIDC callback, auto-detecting which client the callback
397
+ * belongs to via registered callback paths.
398
+ *
399
+ * The `resumeUrl` in the result is taken directly from the core client's
400
+ * pending state (`postAuthRedirectUri` set at `loginWithRedirect()` time),
401
+ * falling back to `"/"` when no redirect URI was recorded.
402
+ *
403
+ * @param callbackUrl - The full current URL (e.g. `window.location.href`).
404
+ * @param explicitClientKey - Optional: force-select a client key instead of
405
+ * auto-detecting from registered callback paths.
406
+ */
407
+ handleCallback(callbackUrl: string, explicitClientKey?: string): Promise<{
408
+ clientKey: string;
409
+ snapshot: AuthSnapshot;
410
+ /** The URL to navigate to after a successful callback. */
411
+ resumeUrl: string;
412
+ }>;
413
+ static ɵfac: i0.ɵɵFactoryDeclaration<CallbackResumeService, never>;
414
+ static ɵprov: i0.ɵɵInjectableDeclaration<CallbackResumeService>;
415
+ }
416
+
417
+ /**
418
+ * A failing entry returned to `onUnauthenticated` when one or more clients
419
+ * could not be verified as authenticated.
420
+ */
421
+ interface UnauthenticatedEntry {
422
+ /** The unauthenticated `TokenSetAuthService`. */
423
+ readonly service: TokenSetAuthService;
424
+ /** The client key for this service. */
425
+ readonly clientKey: string;
426
+ /** Full client metadata (urlPatterns, callbackPath, requirementKind, providerFamily). */
427
+ readonly meta: ClientMeta;
428
+ }
429
+
430
+ /**
431
+ * Check whether the current URL is an OIDC authorization callback.
432
+ */
433
+ declare function isOidcCallback(options: {
434
+ currentUrl: string;
435
+ callbackPath: string;
436
+ }): boolean;
437
+
438
+ /**
439
+ * Options for {@link provideTokenSetAuth}.
440
+ */
441
+ interface ProvideTokenSetAuthOptions {
442
+ /**
443
+ * Adapter/host registration entries.
444
+ *
445
+ * Each entry must have a unique `key`. The entry itself owns how one client
446
+ * composes auth-context config and runtime capabilities; Angular DI here only
447
+ * owns host registration, readiness wiring, and lifecycle.
448
+ */
449
+ clients: TokenSetClientEntry[];
450
+ /**
451
+ * When true (default), schedule `registry.idleWarmup()` during Angular
452
+ * environment initialization so `priority: "lazy"` clients get
453
+ * preloaded in the browser's idle callback.
454
+ *
455
+ * Disable for tests that want deterministic, manual materialization
456
+ * control.
457
+ *
458
+ * @default true
459
+ */
460
+ idleWarmup?: boolean;
461
+ }
462
+ /**
463
+ * Create Angular providers for the multi-client token-set auth integration.
464
+ *
465
+ * Registers all services into Angular DI so adopters can directly inject
466
+ * `TokenSetAuthRegistry`, `CallbackResumeService`, and look up individual
467
+ * `TokenSetAuthService` instances by key.
468
+ *
469
+ * ## Async client initialization
470
+ *
471
+ * When a client's `clientFactory` returns a `Promise` (e.g. because it
472
+ * needs to fetch a config projection from a backend endpoint), the
473
+ * registry tracks its initialization state automatically. Guards and
474
+ * interceptors should use `registry.whenReady(key)` to await
475
+ * materialization before accessing the service.
476
+ *
477
+ * @example
478
+ * ```ts
479
+ * import { provideTokenSetAuth } from "@securitydept/token-set-context-client-angular";
480
+ * import { resolveConfigProjection, networkConfigSource, createFrontendOidcModeClient }
481
+ * from "@securitydept/token-set-context-client/frontend-oidc-mode";
482
+ *
483
+ * export const appConfig = {
484
+ * providers: [
485
+ * provideTokenSetAuth({
486
+ * clients: [
487
+ * {
488
+ * key: "main",
489
+ * // Async clientFactory: fetches config projection from backend
490
+ * clientFactory: async () => {
491
+ * const resolved = await resolveConfigProjection([
492
+ * networkConfigSource({
493
+ * apiEndpoint: "https://api.example.com/api",
494
+ * redirectUri: `${location.origin}/auth/callback`,
495
+ * }),
496
+ * ]);
497
+ * return createFrontendOidcModeClient(resolved.config, runtime);
498
+ * },
499
+ * urlPatterns: ["/api/"],
500
+ * callbackPath: "/auth/callback",
501
+ * },
502
+ * ],
503
+ * }),
504
+ * ],
505
+ * };
506
+ * ```
507
+ */
508
+ declare function provideTokenSetAuth(options: ProvideTokenSetAuthOptions): (Provider | EnvironmentProviders)[];
509
+
510
+ /**
511
+ * How to select a token-set client from the registry for a specific requirement.
512
+ *
513
+ * Choose exactly one:
514
+ * - `clientKey` — direct key lookup (explicit, single client)
515
+ * - `query` — composite filter query ({@link ClientQueryOptions})
516
+ */
517
+ type TokenSetClientSelector = {
518
+ clientKey: string;
519
+ query?: never;
520
+ } | {
521
+ clientKey?: never;
522
+ query: ClientQueryOptions;
523
+ };
524
+ /**
525
+ * Policy override for a specific requirement ID in
526
+ * {@link CreateTokenSetRouteAggregationGuardOptions.requirementPolicies}.
527
+ *
528
+ * Allows fine-grained control per declared requirement:
529
+ * - `selector` overrides the default kind→client registry lookup (use when
530
+ * you need a specific client key or a query instead of all clients of that kind).
531
+ * - `onUnauthenticated` overrides both `requirementHandlers[kind]` and
532
+ * `defaultOnUnauthenticated` for this exact requirement.
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * createTokenSetRouteAggregationGuard({
537
+ * requirementPolicies: {
538
+ * "confluence-oidc": {
539
+ * selector: { clientKey: "confluence" },
540
+ * onUnauthenticated: (failing, req) => {
541
+ * inject(AuthService).redirectToLogin("confluence").subscribe();
542
+ * return false;
543
+ * },
544
+ * },
545
+ * "admin-oidc": {
546
+ * selector: { query: { providerFamily: "internal-sso" } },
547
+ * onUnauthenticated: () => "/admin/login",
548
+ * },
549
+ * },
550
+ * })
551
+ * ```
552
+ */
553
+ interface TokenSetRequirementPolicy {
554
+ /**
555
+ * Override the default kind→client registry lookup for this requirement.
556
+ *
557
+ * When omitted, the guard resolves clients via
558
+ * `registry.clientKeyListForRequirement(requirement.kind)`.
559
+ */
560
+ selector?: TokenSetClientSelector;
561
+ /**
562
+ * Handler called when this requirement is selected as pending by the planner.
563
+ *
564
+ * Takes precedence over `requirementHandlers[kind]` and
565
+ * `defaultOnUnauthenticated`.
566
+ *
567
+ * Return:
568
+ * - `true` — allow navigation
569
+ * - `false` — block navigation
570
+ * - `string` — redirect URL path
571
+ * - `UrlTree` — Angular router tree
572
+ */
573
+ onUnauthenticated: (unauthenticated: ReadonlyArray<UnauthenticatedEntry>, requirement: AuthRequirement) => boolean | string | UrlTree;
574
+ }
575
+ /**
576
+ * Options for {@link createTokenSetRouteAggregationGuard}.
577
+ */
578
+ interface CreateTokenSetRouteAggregationGuardOptions {
579
+ /**
580
+ * Per-requirement-id policies.
581
+ *
582
+ * Keys are `AuthRequirement.id` strings (not kind). Policies declared here
583
+ * take precedence over {@link requirementHandlers} and
584
+ * {@link defaultOnUnauthenticated}.
585
+ *
586
+ * Use this for fine-grained control:
587
+ * - override client selection (specific key or composite query)
588
+ * - per-requirement redirect behaviour
589
+ * - multi-client / providerFamily selection per requirement
590
+ *
591
+ * @example
592
+ * ```ts
593
+ * createTokenSetRouteAggregationGuard({
594
+ * requirementPolicies: {
595
+ * "confluence-oidc": {
596
+ * selector: { clientKey: "confluence" },
597
+ * onUnauthenticated: () => "/auth/confluence",
598
+ * },
599
+ * "admin-oidc": {
600
+ * selector: { query: { providerFamily: "internal-sso" } },
601
+ * onUnauthenticated: () => "/auth/admin",
602
+ * },
603
+ * },
604
+ * })
605
+ * ```
606
+ */
607
+ requirementPolicies?: Record<string, TokenSetRequirementPolicy>;
608
+ /**
609
+ * Per-requirement-kind handlers.
610
+ *
611
+ * When the planner selects a pending requirement whose `kind` maps to an
612
+ * entry here (and no `requirementPolicies[id]` is set), that handler is
613
+ * called instead of `defaultOnUnauthenticated`.
614
+ *
615
+ * Keys are `AuthRequirement.kind` strings.
616
+ *
617
+ * @example
618
+ * ```ts
619
+ * createTokenSetRouteAggregationGuard({
620
+ * requirementHandlers: {
621
+ * frontend_oidc: (failing, req) => {
622
+ * inject(AuthService).redirectToLogin(failing[0].clientKey).subscribe();
623
+ * return false;
624
+ * },
625
+ * },
626
+ * })
627
+ * ```
628
+ */
629
+ requirementHandlers?: Record<string, (unauthenticated: ReadonlyArray<UnauthenticatedEntry>, requirement: AuthRequirement) => boolean | string | UrlTree>;
630
+ /**
631
+ * Fallback handler used when no `requirementPolicies[id]` or
632
+ * `requirementHandlers[kind]` is found for the pending requirement.
633
+ */
634
+ defaultOnUnauthenticated?: (unauthenticated: ReadonlyArray<UnauthenticatedEntry>, requirement: AuthRequirement) => boolean | string | UrlTree;
635
+ /**
636
+ * Custom route data key for reading requirements from route segments.
637
+ * @default "authRequirements"
638
+ */
639
+ requirementsKey?: string;
640
+ /**
641
+ * Inline planner-host instance. If provided, used instead of injecting
642
+ * `AUTH_PLANNER_HOST` from Angular DI.
643
+ */
644
+ plannerHost?: PlannerHost;
645
+ /**
646
+ * Resolve the planner-host for the current target route chain.
647
+ *
648
+ * Use this when planner-host selection depends on route metadata or other
649
+ * route-tree state. Takes precedence over `plannerHost` and DI lookup.
650
+ */
651
+ plannerHostResolver?: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => PlannerHost | undefined;
652
+ }
653
+ /**
654
+ * Create an Angular `CanActivateFn` that performs full-route requirement
655
+ * aggregation and single-pass planner evaluation.
656
+ *
657
+ * **Canonical Angular Router auth pattern** (route-metadata driven):
658
+ * 1. Requirements are declared in route `data` using `withRouteRequirements()`.
659
+ * 2. When the guard runs, it walks `route.pathFromRoot` to collect ALL
660
+ * requirements from every ancestor segment in a single pass.
661
+ * 3. Each requirement's `kind` is mapped to one or more registry clients,
662
+ * unless overridden by a `requirementPolicies[id].selector`.
663
+ * 4. The complete candidate set is handed to the `PlannerHost` for a
664
+ * single `evaluate()` call — the planner selects the first unresolved
665
+ * requirement and calls the matching handler.
666
+ *
667
+ * **Handler resolution order** (most specific wins):
668
+ * 1. `requirementPolicies[requirement.id].onUnauthenticated`
669
+ * 2. `requirementHandlers[requirement.kind]`
670
+ * 3. `defaultOnUnauthenticated`
671
+ * 4. Block navigation (`false`) if none of the above is provided.
672
+ *
673
+ * **Client resolution order** for a requirement:
674
+ * 1. `requirementPolicies[requirement.id].selector.clientKey` — single explicit key
675
+ * 2. `requirementPolicies[requirement.id].selector.query` — composite query
676
+ * 3. `registry.clientKeyListForRequirement(requirement.kind)` — default mapping
677
+ *
678
+ * This model enables:
679
+ * - One-pass requirement collection (no per-segment DI scope accumulation)
680
+ * - One-call planner evaluation (chooser sees the full set at once)
681
+ * - One redirect decision (no per-segment guard coordination needed)
682
+ * - Fine-grained per-requirement policy via `requirementPolicies`
683
+ *
684
+ * @example
685
+ * ```ts
686
+ * // routes.ts — declare requirements in route data
687
+ * import { withRouteRequirements } from "@securitydept/client-angular";
688
+ * import { createTokenSetRouteAggregationGuard } from "@securitydept/token-set-context-client-angular";
689
+ *
690
+ * // Simple — kind-level handler
691
+ * const guard = createTokenSetRouteAggregationGuard({
692
+ * requirementHandlers: {
693
+ * frontend_oidc: (_failing, _req) => {
694
+ * inject(AuthService).redirectToLogin("confluence").subscribe();
695
+ * return false;
696
+ * },
697
+ * },
698
+ * });
699
+ *
700
+ * // Fine-grained — per-requirement policy
701
+ * const guard = createTokenSetRouteAggregationGuard({
702
+ * requirementPolicies: {
703
+ * "confluence-oidc": {
704
+ * selector: { clientKey: "confluence" },
705
+ * onUnauthenticated: () => "/auth/confluence",
706
+ * },
707
+ * "admin-oidc": {
708
+ * selector: { query: { providerFamily: "internal-sso" } },
709
+ * onUnauthenticated: (failing) => "/auth/admin",
710
+ * },
711
+ * },
712
+ * });
713
+ *
714
+ * export const routes: Routes = [
715
+ * {
716
+ * path: "",
717
+ * data: withRouteRequirements([{ id: "session", kind: "session" }]),
718
+ * children: [
719
+ * {
720
+ * path: "confluence",
721
+ * data: withRouteRequirements([{ id: "confluence-oidc", kind: "frontend_oidc" }]),
722
+ * canActivate: [guard],
723
+ * },
724
+ * ],
725
+ * },
726
+ * ];
727
+ * ```
728
+ */
729
+ declare function createTokenSetRouteAggregationGuard(options?: CreateTokenSetRouteAggregationGuardOptions): CanActivateFn;
730
+
731
+ /**
732
+ * Route data key for choosing a planner-host registered at the route root.
733
+ */
734
+ declare const TOKEN_SET_ROUTE_PLANNER_HOST_KEY_DATA_KEY = "tokenSetPlannerHostKey";
735
+ /**
736
+ * Serializable route-level security declaration.
737
+ *
738
+ * This object is safe to embed in Angular route metadata. Non-serializable
739
+ * runtime policy (planner host instances, callbacks, chooser implementations)
740
+ * belongs in {@link SecureRouteRootSecurityOptions}.
741
+ */
742
+ interface SecureRouteSecurityOptions {
743
+ /**
744
+ * Requirements declared at this route segment.
745
+ * @default []
746
+ */
747
+ requirements?: AuthRequirement[];
748
+ /**
749
+ * How this segment composes with ancestor route requirements.
750
+ * @default merge
751
+ */
752
+ composition?: RequirementsClientSetComposition;
753
+ /**
754
+ * Serializable lookup key for a planner-host provided by the root route.
755
+ *
756
+ * The nearest declared key on the active route chain wins.
757
+ */
758
+ plannerHostKey?: string;
759
+ }
760
+ /**
761
+ * Root-level runtime policy for a secured route tree.
762
+ *
763
+ * Everything here is intentionally non-serializable and lives outside route
764
+ * metadata. Child `secureRoute()` calls only reference these policies by
765
+ * serializable keys / requirement ids.
766
+ */
767
+ interface SecureRouteRootSecurityOptions extends SecureRouteSecurityOptions, Omit<CreateTokenSetRouteAggregationGuardOptions, "plannerHost" | "plannerHostResolver"> {
768
+ /**
769
+ * Named planner-host instances available to the secured route tree.
770
+ */
771
+ plannerHosts?: Record<string, PlannerHost>;
772
+ /**
773
+ * Fallback planner-host key when no route segment declares one.
774
+ */
775
+ defaultPlannerHostKey?: string;
776
+ }
777
+ type SecureRouteOptions = Omit<Route, "path" | "data"> & {
778
+ data?: Record<string, unknown>;
779
+ };
780
+ /**
781
+ * Build a secured child route declaration.
782
+ *
783
+ * The returned route contains only serializable metadata:
784
+ * requirements, composition strategy, planner-host lookup key, and any extra
785
+ * route data the caller provides.
786
+ */
787
+ declare function secureRoute(path: string, securityOptions?: SecureRouteSecurityOptions, routeOptions?: SecureRouteOptions): Route;
788
+ /**
789
+ * Build a secured route-tree root.
790
+ *
791
+ * This is the canonical Angular adopter entry for token-set route security:
792
+ * root-level runtime policy stays here, child routes use {@link secureRoute}
793
+ * for serializable declarations only.
794
+ */
795
+ declare function secureRouteRoot(path: string, securityOptions?: SecureRouteRootSecurityOptions, routeOptions?: SecureRouteOptions): Route;
796
+ /**
797
+ * Alias with a token-set-specific name for callers who prefer explicit imports.
798
+ */
799
+ declare const secureTokenSetRoute: typeof secureRoute;
800
+ /**
801
+ * Alias with a token-set-specific name for callers who prefer explicit imports.
802
+ */
803
+ declare const secureTokenSetRouteRoot: typeof secureRouteRoot;
804
+
805
+ /**
806
+ * Drop-in standalone Angular component for OIDC redirect callback routes.
807
+ *
808
+ * Handles the full callback lifecycle on initialization:
809
+ * 1. Calls `CallbackResumeService.handleCallback()` with the current URL.
810
+ * 2. Navigates to `result.resumeUrl` (the post-auth redirect set at login time).
811
+ * 3. On error: logs and falls back to navigating to `"/"`.
812
+ *
813
+ * Register as a route component — no additional glue needed:
814
+ * ```ts
815
+ * import { TokenSetCallbackComponent } from "@securitydept/token-set-context-client-angular";
816
+ *
817
+ * export const routes: Routes = [
818
+ * { path: "auth/callback", component: TokenSetCallbackComponent },
819
+ * ];
820
+ * ```
821
+ *
822
+ * For custom error handling or UI, subclass this component or build your own
823
+ * using `CallbackResumeService` directly.
824
+ */
825
+ declare class TokenSetCallbackComponent implements OnInit {
826
+ private readonly callbackService;
827
+ private readonly router;
828
+ ngOnInit(): void;
829
+ static ɵfac: i0.ɵɵFactoryDeclaration<TokenSetCallbackComponent, never>;
830
+ static ɵcmp: i0.ɵɵComponentDeclaration<TokenSetCallbackComponent, "token-set-callback", never, {}, {}, never, never, true, never>;
831
+ }
832
+
833
+ /** InjectionToken for the multi-client auth registry. */
834
+ declare const TOKEN_SET_AUTH_REGISTRY: InjectionToken<TokenSetAuthRegistry>;
835
+
836
+ export { CallbackResumeService, TOKEN_SET_AUTH_REGISTRY, TOKEN_SET_BEARER_INTERCEPTOR_OPTIONS, TOKEN_SET_ROUTE_PLANNER_HOST_KEY_DATA_KEY, TokenSetAuthRegistry, TokenSetAuthService, TokenSetBearerInterceptor, TokenSetCallbackComponent, createTokenSetBearerInterceptor, createTokenSetRouteAggregationGuard, isOidcCallback, provideTokenSetAuth, provideTokenSetBearerInterceptor, secureRoute, secureRouteRoot, secureTokenSetRoute, secureTokenSetRouteRoot };
837
+ export type { BearerInterceptorOptions, CreateTokenSetRouteAggregationGuardOptions, ProvideTokenSetAuthOptions, SecureRouteRootSecurityOptions, SecureRouteSecurityOptions, TokenSetAngularClient, TokenSetClientEntry, TokenSetClientSelector, TokenSetRequirementPolicy, UnauthenticatedEntry };
838
+ //# sourceMappingURL=securitydept-token-set-context-client-angular.d.ts.map