@passflow/core 0.30.1 → 0.31.0

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/dist/index.d.cts CHANGED
@@ -207,9 +207,10 @@ declare class TokenDeliveryManager {
207
207
  */
208
208
  getSessionState(): SessionState;
209
209
  /**
210
- * Reset delivery manager to initial state
210
+ * Reset delivery manager to initial state. With `keepStored`, only the in-memory state is reset:
211
+ * the stored mode and session state belong to another app's session and stay.
211
212
  */
212
- reset(): void;
213
+ reset(keepStored?: boolean): void;
213
214
  /**
214
215
  * Load persisted delivery mode from storage
215
216
  */
@@ -263,6 +264,8 @@ type Storage = {
263
264
  interface StorageManagerParams {
264
265
  storage?: Storage;
265
266
  prefix?: string;
267
+ /** The app the stored tokens must be issued for; see `setAppId()`. */
268
+ appId?: string;
266
269
  }
267
270
  declare class StorageManager {
268
271
  private keyStoragePrefix;
@@ -275,7 +278,29 @@ declare class StorageManager {
275
278
  private readonly CSRF_TOKEN_KEY;
276
279
  private readonly DELIVERY_MODE_KEY;
277
280
  private storage;
278
- constructor({ storage, prefix }?: StorageManagerParams);
281
+ private appId;
282
+ constructor({ storage, prefix, appId }?: StorageManagerParams);
283
+ /**
284
+ * Sets the app the stored tokens must be issued for. A stored token whose `aud` does not name
285
+ * this app reads as absent, so another app's session on the same origin never counts as this
286
+ * app's. With no app id, every stored token counts.
287
+ */
288
+ setAppId(appId: string | undefined): void;
289
+ /** The stored value, or undefined when it is a JWT issued for another app than this one. */
290
+ private ownToken;
291
+ private readToken;
292
+ /** The keys a stored token lives in: the JSON tokens and the cookie-mode ID token. */
293
+ private tokenValueKeys;
294
+ /** Whether `key` holds a token issued for another app: this instance leaves it in place. */
295
+ private holdsOtherAppToken;
296
+ /**
297
+ * Whether the stored session is only another app's: some key holds another app's token and none
298
+ * holds this app's. The keys every session shares (scopes, delivery mode, CSRF token) are then
299
+ * that app's, and this instance's clearing leaves them in place.
300
+ */
301
+ holdsOnlyOtherAppSession(): boolean;
302
+ /** Removes the token in `key` unless it is another app's. */
303
+ private removeOwnToken;
279
304
  /**
280
305
  * Save tokens to storage with conditional logic based on delivery mode
281
306
  * In cookie/BFF mode: ONLY save ID token (not access/refresh tokens)
@@ -301,7 +326,23 @@ declare class StorageManager {
301
326
  */
302
327
  hasCookieModeIdToken(): boolean;
303
328
  deleteToken(tokenType: TokenType): void;
329
+ /**
330
+ * Clears this app's stored session, key by key: a key holding another app's token stays. The
331
+ * keys every session shares (scopes, delivery mode, CSRF token) stay only when the stored session
332
+ * is another app's alone, and the hosted sign-in record only when another app wrote it.
333
+ */
304
334
  deleteTokens(): void;
335
+ /**
336
+ * Records that the stored session came from the hosted login, with the address it landed on.
337
+ * The hosted login keeps a session of its own, which a sign-out then ends too.
338
+ */
339
+ setHostedSignIn(returnUrl: string): void;
340
+ /**
341
+ * The address the hosted sign-in of the stored session landed on, or undefined. A record another
342
+ * app wrote on the same origin does not count.
343
+ */
344
+ getHostedSignIn(): string | undefined;
345
+ private hostedSignInKey;
305
346
  getDeviceId(): string | undefined;
306
347
  setDeviceId(deviceId: string): void;
307
348
  deleteDeviceId(): void;
@@ -347,6 +388,7 @@ declare class StorageManager {
347
388
  * Clear the CSRF token from storage
348
389
  */
349
390
  clearCsrfToken(): void;
391
+ private removeCsrfToken;
350
392
  /**
351
393
  * Every storage key the token session lives in (JSON tokens, scopes, the cookie-mode ID token,
352
394
  * CSRF token and delivery mode). The refresh coordinator filters `storage` events by it, so
@@ -361,144 +403,6 @@ declare class DeviceService {
361
403
  getDeviceId(): string;
362
404
  generateUniqueDeviceId(): string;
363
405
  }
364
- /**
365
- * RFC 9470 step-up challenge parsing.
366
- *
367
- * A upgrade challenge is the server saying "this session is valid, but not
368
- * strong enough". It arrives in two shapes, both carrying the same
369
- * `WWW-Authenticate` vocabulary:
370
- *
371
- * - `401` from a protected resource (RFC 9470 §3), emitted by the
372
- * RequireAuthLevel / RequireFreshAuth middleware.
373
- * - `403` from `/auth/session/exchange`, which keeps its ADR-2 JSON body
374
- * (`{"error": "upgrade_required", ...}`) alongside the same header.
375
- *
376
- * Telling this apart from an ordinary `401` matters more than it looks: an
377
- * expired session and an insufficient one are the same status code with
378
- * opposite remedies. Clearing tokens on a upgrade challenge logs the user out
379
- * at the exact moment they were asked to prove *more*.
380
- */
381
- /** The error code RFC 9470 §3 defines for an insufficient authentication event. */
382
- export declare const INSUFFICIENT_USER_AUTHENTICATION = "insufficient_user_authentication";
383
- /** The ADR-2 error code `/auth/session/exchange` returns in its 403 body. */
384
- export declare const UPGRADE_REQUIRED = "upgrade_required";
385
- /**
386
- * What the server demands before it will serve the original request.
387
- *
388
- * Both fields are optional because the two middlewares challenge on different
389
- * axes: RequireAuthLevel names an `acrValues` and omits `maxAge`, while
390
- * RequireFreshAuth does the reverse. A challenge carrying neither is still
391
- * valid — it means "re-prove a factor" without further qualification.
392
- */
393
- type UpgradeChallenge = {
394
- /**
395
- * Required authentication context class (`acr`), e.g. `'2'`.
396
- *
397
- * After a two-channel merge this is the raw list of the channel that SET THE
398
- * BAR, with the header preferred on a numeric tie. A channel that contributed
399
- * no level never supplies it — showing `"2gold"` as the bar would
400
- * misrepresent what the server demanded.
401
- */
402
- acrValues?: string;
403
- /**
404
- * The parsed bar: `max` over each channel's `min` participating level
405
- * (§13.2.1a). `undefined` means unknown or unconstrained on this axis.
406
- *
407
- * Optional, and absent from the single-channel parsers' output, so
408
- * `parseChallengeHeader` / `parseChallengeBody` keep the exact shape they
409
- * ship with. `readUpgradeChallenge` always sets it when a level was parsed.
410
- */
411
- requiredLevel?: number;
412
- /** Maximum permitted age of the authentication event, in seconds. */
413
- maxAge?: number;
414
- /** The status that carried the challenge: 401 (protected resource) or 403 (session exchange). */
415
- status: number;
416
- /**
417
- * Every channel that PARSED AS A CHALLENGE in any field — not only the
418
- * channels that won a comparison. An opaque header contributes no constraint
419
- * yet must still be counted, because only something that saw and discarded it
420
- * can report it. `length === 2` means "both channels carried a challenge".
421
- *
422
- * Set by `readUpgradeChallenge`; absent from the single-channel parsers.
423
- */
424
- channels?: ChallengeChannel[];
425
- };
426
- /** Which wire channel a challenge was read from. */
427
- type ChallengeChannel = 'header' | 'body';
428
- /**
429
- * Reads a upgrade challenge out of a `WWW-Authenticate` header, or returns
430
- * `undefined` when the header is absent or describes some other failure.
431
- *
432
- * The header must both use the `Bearer` scheme and carry
433
- * `error="insufficient_user_authentication"`. A bare `WWW-Authenticate: Bearer`
434
- * (what an expired token produces) is deliberately NOT a upgrade challenge.
435
- */
436
- export declare const parseChallengeHeader: (header: string | undefined | null, status: number) => UpgradeChallenge | undefined;
437
- /**
438
- * Reads a upgrade challenge out of the ADR-2 `403` body. Used as a fallback
439
- * for `/auth/session/exchange`, whose JSON body is the documented SDK contract
440
- * even though it also sets the standard header.
441
- */
442
- export declare const parseChallengeBody: (body: unknown, status: number) => UpgradeChallenge | undefined;
443
- /** The bar a challenge demanded, or an elevation reached, on both axes. */
444
- type AssuranceBar = {
445
- /** The raw winning `acr_values` list, for display and diagnostics. */
446
- acrValues?: string;
447
- /** The parsed bar. `undefined` = unknown, or not constrained on this axis. */
448
- level?: number;
449
- /** The freshness constraint, when that is what was demanded. */
450
- maxAge?: number;
451
- };
452
- /** The reasons the SDK can decline to act on a challenge, or act on a suspect one. */
453
- type UpgradeDiagnosticReason = 'no-channel' | 'header-required-but-absent' | 'channels-disagree' | 'channels-unorderable' | 'zero-constraint-ignored' | 'challenge-out-of-scope' | 'elevated-insufficient' | 'replay-unsupported';
454
- /**
455
- * One diagnostic record.
456
- *
457
- * A diagnostic is the only observable signal of the response-rewriting and the
458
- * misconfiguration this design warns about, so it routes through a callback
459
- * whose DEFAULT sink is `console.warn` — never `debug`, which is invisible in
460
- * every default configuration. A deployment where step-up silently never fires
461
- * must be distinguishable from one where it was never required.
462
- */
463
- type UpgradeDiagnostic = {
464
- status: number;
465
- /**
466
- * The request's URL. The parser does not know it — it is handed a status, a
467
- * header reader and a body — so it emits `''` and the core, which owns the
468
- * request context, fills it in before forwarding to the sink.
469
- */
470
- url: string;
471
- reason: UpgradeDiagnosticReason;
472
- detail?: {
473
- obtained?: AssuranceBar;
474
- required?: AssuranceBar;
475
- /** Raw channel inputs, including values discarded as unorderable. */
476
- header?: string;
477
- body?: string;
478
- /** Which field was discarded, for `'zero-constraint-ignored'`. */
479
- field?: 'acr_values' | 'max_age';
480
- /** Which operation, for per-waiter reasons. */
481
- method?: string;
482
- /** A human-readable sentence naming the fix. The default sink prints it. */
483
- message?: string;
484
- };
485
- };
486
- /** Where diagnostics go. `console.warn` is the default sink, not the only one. */
487
- type UpgradeDiagnosticSink = (diagnostic: UpgradeDiagnostic) => void;
488
- /**
489
- * Resolves a upgrade challenge from a response, from either channel.
490
- *
491
- * The SHIPPED export: same name, same three parameters, same return, published
492
- * in `@passflow/core@0.14.1`. It is now a thin delegate over
493
- * `readUpgradeChallenge`, so there is one merge rule rather than two parsers
494
- * that can drift — but it discards the diagnostics, which is why a caller that
495
- * needs them (the core) calls the sibling directly.
496
- *
497
- * Returns `undefined` for every response that is not a upgrade challenge —
498
- * including ordinary `401`s, which callers must keep treating as "session
499
- * expired".
500
- */
501
- export declare const parseUpgradeChallenge: (status: number, getHeader: (name: string) => string | undefined | null, body?: unknown) => UpgradeChallenge | undefined;
502
406
  /**
503
407
  * Synchronous key-value storage interface.
504
408
  * Compatible with localStorage (web) and react-native-mmkv (RN).
@@ -816,8 +720,223 @@ export declare class WebAdapter implements PlatformAdapter {
816
720
  * Exported so consuming code can reference it without allocating a new instance.
817
721
  */
818
722
  export declare const webAdapter: WebAdapter;
723
+ /** Factor types the upgrade protocol understands, named as `upgrade.type` on the wire. */
724
+ type UpgradeFactorType = 'totp' | 'recovery_codes' | 'passkey' | 'email_otp' | 'sms_otp';
725
+ /** The prepare round's result — `POST /auth/upgrade/begin`, normalised to camelCase. */
726
+ type UpgradePrepared = {
727
+ challengeId: string;
728
+ method: string;
729
+ /** RFC 3339. The server gives a challenge five minutes; treat it as a hard deadline. */
730
+ expiresAt: string;
731
+ /** WebAuthn assertion options, present only for a passkey upgrade. */
732
+ webauthn?: PublicKeyCredentialRequestOptionsJSON;
733
+ /** Masked delivery target (`j***@x.com`), present only for email / SMS OTP. */
734
+ codeSentTo?: string;
735
+ };
736
+ /**
737
+ * The `upgrade.assertion` payload. Deliberately an open record: the server
738
+ * types this field as `json.RawMessage` so new factors can extend the shape
739
+ * without a wire-format change.
740
+ */
741
+ type UpgradeAssertion = {
742
+ challenge_id?: string;
743
+ code?: string;
744
+ credential?: AuthenticationResponseJSON;
745
+ };
746
+ /** What a factor needs from the UI before it can be asserted. */
747
+ type UpgradeFactorInput =
748
+ /** A user-typed value: an OTP or a recovery code. */
749
+ 'code' |
750
+ /** Nothing typed — the ceremony itself collects the proof (a passkey prompt). */
751
+ 'none';
752
+ type UpgradeAssertContext = {
753
+ /** The value the user typed, for factors whose `input` is `'code'`. */
754
+ code?: string;
755
+ /** The prepare round's result, for factors where `requiresPrepare` is true. */
756
+ prepared?: UpgradePrepared;
757
+ /** Platform seam for the WebAuthn ceremony — keeps non-web adapters working. */
758
+ platform: PlatformAdapter;
759
+ };
760
+ type UpgradeFactor = {
761
+ type: UpgradeFactorType;
762
+ /** Whether `POST /auth/upgrade/begin` must run before the user can produce proof. */
763
+ requiresPrepare: boolean;
764
+ /** What the UI must collect before `assert` can run. */
765
+ input: UpgradeFactorInput;
766
+ /** Turns the user's response into the assertion blob sent as `upgrade.assertion`. */
767
+ assert(ctx: UpgradeAssertContext): Promise<UpgradeAssertion>;
768
+ };
769
+ /** Thrown when a factor cannot produce proof — a cancelled prompt, or missing prerequisites. */
770
+ export declare class UpgradeFactorError extends Error {
771
+ readonly factor: UpgradeFactorType;
772
+ /** True when the user dismissed the ceremony rather than failing it. */
773
+ readonly cancelled: boolean;
774
+ constructor(factor: UpgradeFactorType, message: string, cancelled?: boolean);
775
+ }
776
+ /**
777
+ * TOTP — the canonical one-shot factor. The code is derived from a shared
778
+ * secret and the clock, so nothing needs to be fetched first.
779
+ */
780
+ export declare const totpFactor: UpgradeFactor;
781
+ /**
782
+ * Recovery codes — also one-shot. Verified against the user's stored code set,
783
+ * so like TOTP there is no challenge to issue.
784
+ */
785
+ export declare const recoveryCodesFactor: UpgradeFactor;
786
+ /**
787
+ * Passkey — the challenge-response factor. The prepare round supplies the
788
+ * server nonce and, critically, an `allowCredentials` list scoped to the
789
+ * signed-in user; the ceremony signs it and the assertion goes back with the
790
+ * challenge id that binds it to this session.
791
+ */
792
+ export declare const passkeyFactor: UpgradeFactor;
793
+ /**
794
+ * The factors this SDK can actually complete.
795
+ *
796
+ * `email_otp` and `sms_otp` are intentionally ABSENT. The server routes them
797
+ * (`upgradePrepareMethod` accepts both) but has no OTP transport, so no user can
798
+ * enrol them and `upgradeMethodRegistered` refuses the prepare round. Adding
799
+ * them later is one entry here plus a factor whose assert returns
800
+ * `{ challenge_id, code }` — no change to anything that consumes this registry.
801
+ */
802
+ export declare const DEFAULT_UPGRADE_FACTORS: readonly UpgradeFactor[];
803
+ /** Indexes a factor list by type for lookup during a challenge. */
804
+ export declare const factorRegistry: (factors?: readonly UpgradeFactor[]) => Map<UpgradeFactorType, UpgradeFactor>;
805
+ /** The error code RFC 9470 §3 defines for an insufficient authentication event. */
806
+ export declare const INSUFFICIENT_USER_AUTHENTICATION = "insufficient_user_authentication";
807
+ /** The ADR-2 error code `/auth/session/exchange` returns in its 403 body. */
808
+ export declare const UPGRADE_REQUIRED = "upgrade_required";
809
+ /**
810
+ * What the server demands before it will serve the original request.
811
+ *
812
+ * Both fields are optional because the two middlewares challenge on different
813
+ * axes: RequireAuthLevel names an `acrValues` and omits `maxAge`, while
814
+ * RequireFreshAuth does the reverse. A challenge carrying neither is still
815
+ * valid — it means "re-prove a factor" without further qualification.
816
+ */
817
+ type UpgradeChallenge = {
818
+ /**
819
+ * Required authentication context class (`acr`), e.g. `'2'`.
820
+ *
821
+ * After a two-channel merge this is the raw list of the channel that SET THE
822
+ * BAR, with the header preferred on a numeric tie. A channel that contributed
823
+ * no level never supplies it — showing `"2gold"` as the bar would
824
+ * misrepresent what the server demanded.
825
+ */
826
+ acrValues?: string;
827
+ /**
828
+ * The parsed bar: `max` over each channel's `min` participating level
829
+ * (§13.2.1a). `undefined` means unknown or unconstrained on this axis.
830
+ *
831
+ * Optional, and absent from the single-channel parsers' output, so
832
+ * `parseChallengeHeader` / `parseChallengeBody` keep the exact shape they
833
+ * ship with. `readUpgradeChallenge` always sets it when a level was parsed.
834
+ */
835
+ requiredLevel?: number;
836
+ /** Maximum permitted age of the authentication event, in seconds. */
837
+ maxAge?: number;
838
+ /** The status that carried the challenge: 401 (protected resource) or 403 (session exchange). */
839
+ status: number;
840
+ /**
841
+ * The factors this user can use, in the order to offer them, from the `403` body's
842
+ * `available_factors`. Absent when the server does not send it (older servers, the header channel).
843
+ */
844
+ availableFactors?: UpgradeFactorType[];
845
+ /**
846
+ * The `403` body's `sign_in_required`: `true` when only a fresh sign-in can meet
847
+ * the challenge, `false` when a step-up could but `availableFactors` names none
848
+ * this account has (for example a device-bound passkey for AAL3). Absent from
849
+ * older servers.
850
+ */
851
+ signInRequired?: boolean;
852
+ /**
853
+ * Every channel that PARSED AS A CHALLENGE in any field — not only the
854
+ * channels that won a comparison. An opaque header contributes no constraint
855
+ * yet must still be counted, because only something that saw and discarded it
856
+ * can report it. `length === 2` means "both channels carried a challenge".
857
+ *
858
+ * Set by `readUpgradeChallenge`; absent from the single-channel parsers.
859
+ */
860
+ channels?: ChallengeChannel[];
861
+ };
862
+ /** Which wire channel a challenge was read from. */
863
+ type ChallengeChannel = 'header' | 'body';
864
+ /**
865
+ * Reads a upgrade challenge out of a `WWW-Authenticate` header, or returns
866
+ * `undefined` when the header is absent or describes some other failure.
867
+ *
868
+ * The header must both use the `Bearer` scheme and carry
869
+ * `error="insufficient_user_authentication"`. A bare `WWW-Authenticate: Bearer`
870
+ * (what an expired token produces) is deliberately NOT a upgrade challenge.
871
+ */
872
+ export declare const parseChallengeHeader: (header: string | undefined | null, status: number) => UpgradeChallenge | undefined;
873
+ /**
874
+ * Reads a upgrade challenge out of the ADR-2 `403` body. Used as a fallback
875
+ * for `/auth/session/exchange`, whose JSON body is the documented SDK contract
876
+ * even though it also sets the standard header.
877
+ */
878
+ export declare const parseChallengeBody: (body: unknown, status: number) => UpgradeChallenge | undefined;
879
+ /** The bar a challenge demanded, or an elevation reached, on both axes. */
880
+ type AssuranceBar = {
881
+ /** The raw winning `acr_values` list, for display and diagnostics. */
882
+ acrValues?: string;
883
+ /** The parsed bar. `undefined` = unknown, or not constrained on this axis. */
884
+ level?: number;
885
+ /** The freshness constraint, when that is what was demanded. */
886
+ maxAge?: number;
887
+ };
888
+ /** The reasons the SDK can decline to act on a challenge, or act on a suspect one. */
889
+ type UpgradeDiagnosticReason = 'no-channel' | 'header-required-but-absent' | 'channels-disagree' | 'channels-unorderable' | 'zero-constraint-ignored' | 'challenge-out-of-scope' | 'elevated-insufficient' | 'replay-unsupported';
890
+ /**
891
+ * One diagnostic record.
892
+ *
893
+ * A diagnostic is the only observable signal of the response-rewriting and the
894
+ * misconfiguration this design warns about, so it routes through a callback
895
+ * whose DEFAULT sink is `console.warn` — never `debug`, which is invisible in
896
+ * every default configuration. A deployment where step-up silently never fires
897
+ * must be distinguishable from one where it was never required.
898
+ */
899
+ type UpgradeDiagnostic = {
900
+ status: number;
901
+ /**
902
+ * The request's URL. The parser does not know it — it is handed a status, a
903
+ * header reader and a body — so it emits `''` and the core, which owns the
904
+ * request context, fills it in before forwarding to the sink.
905
+ */
906
+ url: string;
907
+ reason: UpgradeDiagnosticReason;
908
+ detail?: {
909
+ obtained?: AssuranceBar;
910
+ required?: AssuranceBar;
911
+ /** Raw channel inputs, including values discarded as unorderable. */
912
+ header?: string;
913
+ body?: string;
914
+ /** Which field was discarded, for `'zero-constraint-ignored'`. */
915
+ field?: 'acr_values' | 'max_age';
916
+ /** Which operation, for per-waiter reasons. */
917
+ method?: string;
918
+ /** A human-readable sentence naming the fix. The default sink prints it. */
919
+ message?: string;
920
+ };
921
+ };
922
+ /** Where diagnostics go. `console.warn` is the default sink, not the only one. */
923
+ type UpgradeDiagnosticSink = (diagnostic: UpgradeDiagnostic) => void;
924
+ /**
925
+ * Resolves a upgrade challenge from a response, from either channel.
926
+ *
927
+ * The SHIPPED export: same name, same three parameters, same return, published
928
+ * in `@passflow/core@0.14.1`. It is now a thin delegate over
929
+ * `readUpgradeChallenge`, so there is one merge rule rather than two parsers
930
+ * that can drift — but it discards the diagnostics, which is why a caller that
931
+ * needs them (the core) calls the sibling directly.
932
+ *
933
+ * Returns `undefined` for every response that is not a upgrade challenge —
934
+ * including ordinary `401`s, which callers must keep treating as "session
935
+ * expired".
936
+ */
937
+ export declare const parseUpgradeChallenge: (status: number, getHeader: (name: string) => string | undefined | null, body?: unknown) => UpgradeChallenge | undefined;
819
938
  /**
820
- * Public types of multi-tab-safe token refresh (PFL-792, architecture §2.2-2.5).
939
+ * Public types of multi-tab-safe token refresh.
821
940
  *
822
941
  * @module refresh/types
823
942
  */
@@ -907,88 +1026,6 @@ type SessionExpiredReason =
907
1026
  'identity_changed' |
908
1027
  /** Legacy members, never emitted. */
909
1028
  'token_invalid' | 'logged_out';
910
- /** Factor types the upgrade protocol understands, named as `upgrade.type` on the wire. */
911
- type UpgradeFactorType = 'totp' | 'recovery_codes' | 'passkey' | 'email_otp' | 'sms_otp';
912
- /** The prepare round's result — `POST /auth/upgrade/begin`, normalised to camelCase. */
913
- type UpgradePrepared = {
914
- challengeId: string;
915
- method: string;
916
- /** RFC 3339. The server gives a challenge five minutes; treat it as a hard deadline. */
917
- expiresAt: string;
918
- /** WebAuthn assertion options, present only for a passkey upgrade. */
919
- webauthn?: PublicKeyCredentialRequestOptionsJSON;
920
- /** Masked delivery target (`j***@x.com`), present only for email / SMS OTP. */
921
- codeSentTo?: string;
922
- };
923
- /**
924
- * The `upgrade.assertion` payload. Deliberately an open record: the server
925
- * types this field as `json.RawMessage` so new factors can extend the shape
926
- * without a wire-format change.
927
- */
928
- type UpgradeAssertion = {
929
- challenge_id?: string;
930
- code?: string;
931
- credential?: AuthenticationResponseJSON;
932
- };
933
- /** What a factor needs from the UI before it can be asserted. */
934
- type UpgradeFactorInput =
935
- /** A user-typed value: an OTP or a recovery code. */
936
- 'code' |
937
- /** Nothing typed — the ceremony itself collects the proof (a passkey prompt). */
938
- 'none';
939
- type UpgradeAssertContext = {
940
- /** The value the user typed, for factors whose `input` is `'code'`. */
941
- code?: string;
942
- /** The prepare round's result, for factors where `requiresPrepare` is true. */
943
- prepared?: UpgradePrepared;
944
- /** Platform seam for the WebAuthn ceremony — keeps non-web adapters working. */
945
- platform: PlatformAdapter;
946
- };
947
- type UpgradeFactor = {
948
- type: UpgradeFactorType;
949
- /** Whether `POST /auth/upgrade/begin` must run before the user can produce proof. */
950
- requiresPrepare: boolean;
951
- /** What the UI must collect before `assert` can run. */
952
- input: UpgradeFactorInput;
953
- /** Turns the user's response into the assertion blob sent as `upgrade.assertion`. */
954
- assert(ctx: UpgradeAssertContext): Promise<UpgradeAssertion>;
955
- };
956
- /** Thrown when a factor cannot produce proof — a cancelled prompt, or missing prerequisites. */
957
- export declare class UpgradeFactorError extends Error {
958
- readonly factor: UpgradeFactorType;
959
- /** True when the user dismissed the ceremony rather than failing it. */
960
- readonly cancelled: boolean;
961
- constructor(factor: UpgradeFactorType, message: string, cancelled?: boolean);
962
- }
963
- /**
964
- * TOTP — the canonical one-shot factor. The code is derived from a shared
965
- * secret and the clock, so nothing needs to be fetched first.
966
- */
967
- export declare const totpFactor: UpgradeFactor;
968
- /**
969
- * Recovery codes — also one-shot. Verified against the user's stored code set,
970
- * so like TOTP there is no challenge to issue.
971
- */
972
- export declare const recoveryCodesFactor: UpgradeFactor;
973
- /**
974
- * Passkey — the challenge-response factor. The prepare round supplies the
975
- * server nonce and, critically, an `allowCredentials` list scoped to the
976
- * signed-in user; the ceremony signs it and the assertion goes back with the
977
- * challenge id that binds it to this session.
978
- */
979
- export declare const passkeyFactor: UpgradeFactor;
980
- /**
981
- * The factors this SDK can actually complete.
982
- *
983
- * `email_otp` and `sms_otp` are intentionally ABSENT. The server routes them
984
- * (`upgradePrepareMethod` accepts both) but has no OTP transport, so no user can
985
- * enrol them and `upgradeMethodRegistered` refuses the prepare round. Adding
986
- * them later is one entry here plus a factor whose assert returns
987
- * `{ challenge_id, code }` — no change to anything that consumes this registry.
988
- */
989
- export declare const DEFAULT_UPGRADE_FACTORS: readonly UpgradeFactor[];
990
- /** Indexes a factor list by type for lookup during a challenge. */
991
- export declare const factorRegistry: (factors?: readonly UpgradeFactor[]) => Map<UpgradeFactorType, UpgradeFactor>;
992
1029
  export type RequestOptions<D> = {
993
1030
  data?: D;
994
1031
  config?: AxiosRequestConfig;
@@ -1224,7 +1261,6 @@ export type PassflowAuthorizationResponse = Tokens & {
1224
1261
  code?: string;
1225
1262
  /** Where the server sends the user next; a password reset answers with its link's redirect. */
1226
1263
  redirect_url?: string;
1227
- requires_2fa?: boolean;
1228
1264
  challenge_id?: string;
1229
1265
  tfa_token?: string;
1230
1266
  token_delivery?: 'json_body' | 'cookie' | 'mobile';
@@ -1259,7 +1295,6 @@ export type PassflowEmailCodePayload = {
1259
1295
  export declare const isEmailVerificationStep: (response: unknown) => response is PassflowEmailVerificationStep;
1260
1296
  export type PassflowValidationResponse = Tokens & {
1261
1297
  redirect_url: string;
1262
- requires_2fa?: boolean;
1263
1298
  challenge_id?: string;
1264
1299
  tfa_token?: string;
1265
1300
  /** PKCE app: the code to redeem with the verifier, in place of tokens. */
@@ -1306,6 +1341,14 @@ export declare class PassflowError extends Error {
1306
1341
  cause?: unknown;
1307
1342
  });
1308
1343
  }
1344
+ /** Id of the 403 a password sign-in answers with when the user must change the password first. */
1345
+ export declare const PASSWORD_CHANGE_REQUIRED_ERROR_ID = "error.api.password.change.required";
1346
+ /** The sign-in was refused until the user changes the password; no token comes with it. */
1347
+ export declare class PassflowPasswordChangeRequiredError extends PassflowError {
1348
+ constructor(error: PassflowResponseError['error'], options?: {
1349
+ cause?: unknown;
1350
+ });
1351
+ }
1309
1352
  export type PassflowSignInPayload = {
1310
1353
  password: string;
1311
1354
  scopes?: string[];
@@ -1416,7 +1459,6 @@ export type PassflowPasswordlessStatusResponse = {
1416
1459
  status?: undefined;
1417
1460
  redirect_url?: string;
1418
1461
  tfa_token?: string;
1419
- requires_2fa?: boolean;
1420
1462
  challenge_id?: string;
1421
1463
  };
1422
1464
  export type PassflowPasswordlessApprovalInfoPayload = {
@@ -1485,16 +1527,22 @@ export type AuthStrategies = {
1485
1527
  };
1486
1528
  export type AppType = 'web' | 'spa' | 'bff' | 'android' | 'ios' | 'desktop' | 'm2m' | 'other';
1487
1529
  export type TokenDeliveryMethod = 'json_body' | 'cookie' | '';
1530
+ /**
1531
+ * The public app-settings read (`GET /app/settings`) sends only `id`, `name`, `description`,
1532
+ * `offline`, `type`, `custom_email_templates`, `auth_strategies`, the four registration and
1533
+ * merge flags, `force_passwordless_login`, `login_app_theme`, `pkce_enabled`, `public_client`,
1534
+ * and `defaults` when the server has them; the rest come with admin reads.
1535
+ */
1488
1536
  export type AppSettings = {
1489
1537
  id: string;
1490
- secret: string;
1491
- active: boolean;
1538
+ secret?: string;
1539
+ active?: boolean;
1492
1540
  name: string;
1493
1541
  description: string;
1494
1542
  offline: boolean;
1495
1543
  type: AppType;
1496
- redirect_urls: string[] | null;
1497
- origins: string[] | null;
1544
+ redirect_urls?: string[] | null;
1545
+ origins?: string[] | null;
1498
1546
  custom_email_templates: boolean;
1499
1547
  auth_strategies: AuthStrategies[];
1500
1548
  force_passwordless_login: boolean;
@@ -1508,14 +1556,14 @@ export type AppSettings = {
1508
1556
  * on servers that do not report it.
1509
1557
  */
1510
1558
  public_client?: boolean;
1511
- custom_sms_messages: boolean;
1559
+ custom_sms_messages?: boolean;
1512
1560
  registration_allowed: boolean;
1513
- invite_only_registration: boolean;
1561
+ invite_only_registration?: boolean;
1514
1562
  passwordless_registration_allowed: boolean;
1515
1563
  anonymous_registration_allowed: boolean;
1516
- create_tenant_on_registration: 'never' | 'always' | 'optional';
1564
+ create_tenant_on_registration?: 'never' | 'always' | 'optional';
1517
1565
  fim_merge_by_email_allowed: boolean;
1518
- debug_otp_code_allowed: boolean;
1566
+ debug_otp_code_allowed?: boolean;
1519
1567
  /**
1520
1568
  * WRITE-ONLY. Every read and write answer returns it as an empty string; the stored code is
1521
1569
  * never echoed. On write, a blank or absent value keeps the stored code and a non-blank value
@@ -1526,7 +1574,7 @@ export type AppSettings = {
1526
1574
  debug_otp_code_for_registration?: string;
1527
1575
  /** READ-ONLY. `true` when a `debug_otp_code_for_registration` is stored. Ignored on write. */
1528
1576
  debug_otp_code_set?: boolean;
1529
- defaults: DefaultAppSettings;
1577
+ defaults?: DefaultAppSettings;
1530
1578
  login_app_theme: LoginWebAppTheme;
1531
1579
  login_app_settings?: unknown;
1532
1580
  token_delivery_method?: TokenDeliveryMethod;
@@ -1598,6 +1646,11 @@ export type PassflowPasskeyRegisterStartPayload = {
1598
1646
  scopes: string[];
1599
1647
  create_tenant?: boolean;
1600
1648
  relying_party_id: string;
1649
+ /**
1650
+ * Must exactly match one of the app's registered redirect URLs: scheme and host are compared
1651
+ * case-insensitively, path and query exactly. Empty is allowed. Otherwise the server refuses
1652
+ * with 400 `error.app.redirect.url.not.registered`.
1653
+ */
1601
1654
  redirect_url: string;
1602
1655
  code_challenge?: string;
1603
1656
  };
@@ -1857,9 +1910,12 @@ export type TwoFactorRegenerateRequest = {
1857
1910
  };
1858
1911
  export type TwoFactorStatusResponse = {
1859
1912
  enabled: boolean;
1860
- policy: TwoFactorPolicy;
1913
+ enabled_at?: string;
1861
1914
  recovery_codes_remaining: number;
1915
+ /** Digits in the TOTP code. Present only when the user holds a TOTP enrolment. */
1862
1916
  totp_digits?: 6 | 8;
1917
+ /** Seconds per TOTP step. Present only when the user holds a TOTP enrolment. */
1918
+ totp_period?: number;
1863
1919
  };
1864
1920
  export type TwoFactorSetupResponse = {
1865
1921
  secret: string;
@@ -1867,12 +1923,18 @@ export type TwoFactorSetupResponse = {
1867
1923
  qr_code: string;
1868
1924
  /** The `otpauth://` URL the QR code holds. */
1869
1925
  qr_code_url?: string;
1926
+ /** Digits in the TOTP code. The setup answer always sends it. */
1870
1927
  totp_digits?: 6 | 8;
1928
+ /** Seconds per TOTP step. The setup answer always sends it. */
1929
+ totp_period?: number;
1871
1930
  };
1872
1931
  export type TwoFactorConfirmResponse = {
1873
- success: true;
1874
- enabled?: boolean;
1875
- recovery_codes: string[];
1932
+ enabled: boolean;
1933
+ /**
1934
+ * The server issues recovery codes on every enrolment; the field is optional only so an older or
1935
+ * different server that omits it doesn't break the type.
1936
+ */
1937
+ recovery_codes?: string[];
1876
1938
  };
1877
1939
  /**
1878
1940
  * What a sign-in waiting on its second factor can do next, decided by the server:
@@ -1885,13 +1947,34 @@ export type TwoFactorEnrollment = 'verify' | 'email_link' | 'direct' | 'unavaila
1885
1947
  /** GET /auth/2fa/enrollment */
1886
1948
  export type TwoFactorEnrollmentResponse = {
1887
1949
  enrollment: TwoFactorEnrollment;
1950
+ /** Digits in the user's TOTP code. Present only when the user holds a TOTP enrolment. */
1951
+ totp_digits?: 6 | 8;
1952
+ /** Seconds per TOTP step. Present only when the user holds a TOTP enrolment. */
1953
+ totp_period?: number;
1954
+ /**
1955
+ * Whether this sign-in may ask to trust the device (`trust_device`), as the app allows.
1956
+ * Absent from servers older than the flag; treat absent as unknown.
1957
+ */
1958
+ device_trust_available?: boolean;
1888
1959
  };
1889
1960
  /** POST /auth/2fa/enrollment/email-link */
1890
1961
  export type TwoFactorSetupLinkResponse = {
1891
1962
  email_sent: boolean;
1892
1963
  };
1893
- export type TwoFactorVerifyResponse = Tokens & {
1894
- success: true;
1964
+ /**
1965
+ * How a sign-in under an OIDC parent (hosted login, `/oidc/authorize`) continues once its second
1966
+ * factor is done: no tokens, the browser goes to `redirect_url` (the relying party's callback with
1967
+ * its code), or posts `form_post` for `response_mode=form_post`.
1968
+ */
1969
+ export type TwoFactorParentAnswer = {
1970
+ redirect_url?: string;
1971
+ form_post?: {
1972
+ action: string;
1973
+ fields: Record<string, string>;
1974
+ };
1975
+ };
1976
+ export type TwoFactorVerifyResponse = Tokens & TwoFactorParentAnswer & {
1977
+ success?: true;
1895
1978
  /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
1896
1979
  code?: string;
1897
1980
  };
@@ -1923,16 +2006,16 @@ export type TwoFactorTrustedDevicesResponse = {
1923
2006
  devices: TwoFactorTrustedDevice[];
1924
2007
  };
1925
2008
  export type TwoFactorRecoveryResponse = Tokens & {
1926
- success: true;
1927
- remaining_recovery_codes: number;
2009
+ success?: true;
2010
+ /** Codes left after this one. The server may leave it out. */
2011
+ remaining_recovery_codes?: number;
1928
2012
  /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
1929
2013
  code?: string;
1930
2014
  };
1931
2015
  export type TwoFactorDisableResponse = {
1932
- success: true;
2016
+ disabled: true;
1933
2017
  };
1934
2018
  export type TwoFactorRegenerateResponse = {
1935
- success: true;
1936
2019
  recovery_codes: string[];
1937
2020
  };
1938
2021
  /**
@@ -1988,10 +2071,20 @@ export interface TwoFactorChallengeRequest {
1988
2071
  export interface TwoFactorChallengeResponse {
1989
2072
  challenge_id: string;
1990
2073
  method: TwoFactorMethod;
1991
- alternative_methods: TwoFactorMethod[];
2074
+ /** Other methods the user can switch to. Absent from the answer to a switch. */
2075
+ alternative_methods?: TwoFactorMethod[];
1992
2076
  expires_at: string;
1993
2077
  code_sent_to?: string;
1994
2078
  webauthn_options?: unknown;
2079
+ /** Digits in the TOTP code. TOTP challenges only. */
2080
+ totp_digits?: 6 | 8;
2081
+ /** Seconds per TOTP step. TOTP challenges only. */
2082
+ totp_period?: number;
2083
+ /**
2084
+ * Whether this sign-in may ask to trust the device (`trust_device`), as the app allows.
2085
+ * Absent from servers older than the flag; treat absent as unknown.
2086
+ */
2087
+ device_trust_available?: boolean;
1995
2088
  }
1996
2089
  /**
1997
2090
  * Verify Request for v2 2FA flow
@@ -2005,22 +2098,26 @@ export interface TwoFactorVerifyRequestV2 {
2005
2098
  /**
2006
2099
  * Verify Response from v2 2FA flow
2007
2100
  */
2008
- export interface TwoFactorVerifyResponseV2 {
2009
- success: boolean;
2101
+ export interface TwoFactorVerifyResponseV2 extends TwoFactorParentAnswer {
2010
2102
  access_token?: string;
2011
2103
  refresh_token?: string;
2104
+ id_token?: string;
2012
2105
  /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
2013
2106
  code?: string;
2014
- device_trusted?: boolean;
2015
2107
  }
2016
2108
  /**
2017
2109
  * Registered Two-Factor Method
2018
2110
  */
2019
2111
  export interface RegisteredTwoFactorMethod {
2020
- id: string;
2112
+ id?: string;
2021
2113
  method: TwoFactorMethod;
2022
- name: string;
2023
- created_at: string;
2114
+ name?: string;
2115
+ user_id?: string;
2116
+ app_id?: string;
2117
+ /** `true` when this passkey also signs the user in as the first factor. */
2118
+ is_passkey_for_1fa?: boolean;
2119
+ created_at?: string;
2120
+ updated_at?: string;
2024
2121
  last_used_at?: string;
2025
2122
  }
2026
2123
  /**
@@ -2058,7 +2155,7 @@ export interface CLIAuthCompleteRequest {
2058
2155
  */
2059
2156
  type AxiosUpgradeHandler = (error: AxiosError, challenge: UpgradeChallenge) => Promise<AxiosResponse>;
2060
2157
  /**
2061
- * The pre-request refresh (PFL-792). Installed by `Passflow` on every client it owns; it asks the
2158
+ * The pre-request refresh. Installed by `Passflow` on every client it owns; it asks the
2062
2159
  * instance's refresh controller, which coordinates with the other tabs and owns retries, strikes
2063
2160
  * and the session end. Resolves with the tokens to send (`undefined` once the session ended).
2064
2161
  *
@@ -2567,7 +2664,7 @@ export declare class TwoFactorApiClient {
2567
2664
  * What a sign-in waiting on its second factor can do next
2568
2665
  * GET /auth/2fa/enrollment
2569
2666
  */
2570
- getEnrollment(tfaToken: string): Promise<TwoFactorEnrollment>;
2667
+ getEnrollment(tfaToken: string): Promise<TwoFactorEnrollmentResponse>;
2571
2668
  /**
2572
2669
  * Email the user a link to set up 2FA
2573
2670
  * POST /auth/2fa/enrollment/email-link
@@ -3523,6 +3620,9 @@ export declare enum PassflowEvent {
3523
3620
  TwoFactorSetupMagicLinkFailed = "2fa:magic_link_failed",
3524
3621
  TwoFactorChallengeReceived = "two_factor_challenge_received",
3525
3622
  TwoFactorMethodSwitched = "two_factor_method_switched",
3623
+ /**
3624
+ * @deprecated The server keeps device trust in a cookie and the SDK no longer emits this event.
3625
+ */
3526
3626
  TwoFactorDeviceTrusted = "two_factor_device_trusted",
3527
3627
  /** Token refresh entered a transient-failure episode (once per episode, per tab). */
3528
3628
  RefreshFailing = "refresh:failing",
@@ -3641,9 +3741,10 @@ type PassflowEventPayload = {
3641
3741
  [PassflowEvent.TwoFactorVerified]: {
3642
3742
  tokens?: Tokens;
3643
3743
  };
3744
+ /** `remainingCodes` is undefined when the server did not send the count. */
3644
3745
  [PassflowEvent.TwoFactorRecoveryUsed]: {
3645
3746
  tokens?: Tokens;
3646
- remainingCodes: number;
3747
+ remainingCodes?: number;
3647
3748
  };
3648
3749
  [PassflowEvent.TwoFactorRecoveryCodesLow]: {
3649
3750
  tokens?: Tokens;
@@ -3799,6 +3900,15 @@ export type AuthRedirectOptions = {
3799
3900
  /** Simple mode only: echoed back with the tokens. In SDK mode the SDK generates `state` itself. */
3800
3901
  state?: string;
3801
3902
  };
3903
+ /** Options of `logOut()`. */
3904
+ export type LogOutOptions = {
3905
+ /**
3906
+ * After a hosted sign-in: where the hosted login sends the browser once its own session has
3907
+ * ended. It must match one of the app's registered redirect URLs; an unmatched one leaves the
3908
+ * user on the Passflow server's start page. Default: the address the hosted sign-in landed on.
3909
+ */
3910
+ postLogoutRedirectUri?: string;
3911
+ };
3802
3912
  /** How this instance's refresh controller coordinates (architecture §3.3, §3.4). */
3803
3913
  export type AuthServiceRefreshOptions = {
3804
3914
  coordination: ResolvedCoordination;
@@ -3834,7 +3944,7 @@ export declare class AuthService {
3834
3944
  */
3835
3945
  private emailChallenges;
3836
3946
  /**
3837
- * The one place this instance sends `/auth/refresh` (PFL-792). Every refresh path asks it: the
3947
+ * The one place this instance sends `/auth/refresh`. Every refresh path asks it: the
3838
3948
  * explicit `refreshToken()`, the upgrade commit, `getTokens(true)`/`session()` and, once
3839
3949
  * `Passflow` attaches it, `TokenCacheService.getTokensWithRefresh()`.
3840
3950
  */
@@ -3880,12 +3990,14 @@ export declare class AuthService {
3880
3990
  * its answer through here too.
3881
3991
  */
3882
3992
  private applyAuthResponse;
3993
+ /** A registration that leaves the user signed in: `Register`, then `SignIn` with the same payload. */
3994
+ private notifyRegisteredAndSignedIn;
3883
3995
  /**
3884
3996
  * Reports whether a sign-in response is still waiting on its second factor,
3885
3997
  * and when it is, hands the 2FA token on.
3886
3998
  *
3887
3999
  * Every sign-in path can end this way: the server answers with a
3888
- * `tfa_token` (or `requires_2fa`) in place of tokens. That response is not
4000
+ * `tfa_token` in place of tokens. That response is not
3889
4001
  * a session, so on `true` the caller returns it as it is — without
3890
4002
  * `processAuthResponse`, a `SignIn`/`Register` event or a session check.
3891
4003
  * The `TwoFactorRequired` event is what the TwoFactorService listens to, so
@@ -3956,6 +4068,8 @@ export declare class AuthService {
3956
4068
  * caller saves them itself. An answer that carries no tokens is left alone.
3957
4069
  */
3958
4070
  applyTokens(tokens: Tokens): Promise<void>;
4071
+ /** Emits `SignIn` for a sign-in its second factor finished, then runs the session check. */
4072
+ notifySignedIn(tokens: Tokens): Promise<void>;
3959
4073
  /**
3960
4074
  * Forward tokens to BFF server for httpOnly cookie storage
3961
4075
  */
@@ -4000,7 +4114,7 @@ export declare class AuthService {
4000
4114
  */
4001
4115
  verifyEmailCode(payload: PassflowEmailCodePayload): Promise<PassflowAuthorizationResponse>;
4002
4116
  /**
4003
- * Signs this tab out under the refresh lock (PFL-792 §2.8): stops this tab's refresh callers and
4117
+ * Signs this tab out under the refresh lock: stops this tab's refresh callers and
4004
4118
  * retry timer, waits at most 5 s for the lock (a request already in flight lands first), posts
4005
4119
  * `signed-out` to the other tabs, calls the logout API with the NEWEST stored refresh token (best
4006
4120
  * effort), then deletes the stored tokens, id token and CSRF token and clears the token cache.
@@ -4011,12 +4125,21 @@ export declare class AuthService {
4011
4125
  */
4012
4126
  logOut(): Promise<string | undefined>;
4013
4127
  /**
4014
- * `Passflow.reset()` (PFL-792 amendment A2): the same local sign-out, synchronously, with no
4128
+ * `Passflow.reset()`: the same local sign-out, synchronously, with no
4015
4129
  * API call and no lock. Emits no `SignOut`; the caller emits one.
4016
4130
  *
4017
4131
  * @returns the `sub` of the session that ended, when known
4018
4132
  */
4019
4133
  resetSession(): string | undefined;
4134
+ /**
4135
+ * Where the page goes to end the hosted login's own session, when the stored session came from
4136
+ * the hosted login; undefined otherwise. The hosted login keeps a session cookie on the Passflow
4137
+ * host that only a top-level visit to `/oidc/end_session` can end. With the stored ID token as
4138
+ * `id_token_hint` the server ends it at once and redirects to `post_logout_redirect_uri`, which
4139
+ * must match one of the app's registered redirect URLs: by default the address the hosted
4140
+ * sign-in landed on. Read before `logOut()`, which deletes what it is built from.
4141
+ */
4142
+ hostedEndSessionUrl(postLogoutRedirectUri?: string): string | undefined;
4020
4143
  /** The logout API call. Server-side cleanup is best effort: every failure is ignored. */
4021
4144
  private callLogoutApi;
4022
4145
  /** Deletes every local trace of the session (both delivery modes) and clears the token cache. */
@@ -4077,7 +4200,7 @@ export declare class AuthService {
4077
4200
  *
4078
4201
  * Both go through the refresh controller, the one place this instance sends `/auth/refresh`: it
4079
4202
  * coordinates with other tabs, saves with a compare-and-set, classifies failures and emits the
4080
- * events (PFL-792). A plain refresh is "fresh": it is satisfied only by tokens from a request
4203
+ * events. A plain refresh is "fresh": it is satisfied only by tokens from a request
4081
4204
  * sent at or after the call. A failure keeps the tokens unless it really ends the session.
4082
4205
  *
4083
4206
  * The upgrade commit is the one path that is never classified: any failure rejects with the
@@ -4474,6 +4597,8 @@ export interface SignInCompleter {
4474
4597
  applyTokens(tokens: Tokens): Promise<void>;
4475
4598
  hasPendingPkceSignIn(): boolean;
4476
4599
  forgetPkceSignIn(): void;
4600
+ /** Reports a finished sign-in: emits `SignIn` with these tokens, then runs the session check. */
4601
+ notifySignedIn(tokens: Tokens): Promise<void>;
4477
4602
  }
4478
4603
  /**
4479
4604
  * Service for managing Two-Factor Authentication
@@ -4485,7 +4610,7 @@ export declare class TwoFactorService {
4485
4610
  private partialAuthState?;
4486
4611
  private readonly PARTIAL_AUTH_TIMEOUT_MS;
4487
4612
  private readonly SESSION_STORAGE_KEY;
4488
- private totpDigits;
4613
+ private totpDigits?;
4489
4614
  private magicLinkSession?;
4490
4615
  constructor(twoFactorApi: TwoFactorApiClient, subscribeStore: PassflowStore, signInCompleter?: SignInCompleter | undefined);
4491
4616
  /**
@@ -4514,8 +4639,9 @@ export declare class TwoFactorService {
4514
4639
  /**
4515
4640
  * What the sign-in waiting on its second factor can do next. Read this before asking for a code:
4516
4641
  * the server decides, and only `verify` means the user has a factor to enter a code from.
4642
+ * With a TOTP enrolment the answer carries `totp_digits`, which `verify` then expects.
4517
4643
  */
4518
- getEnrollment(): Promise<TwoFactorEnrollment>;
4644
+ getEnrollment(): Promise<TwoFactorEnrollmentResponse>;
4519
4645
  /**
4520
4646
  * Email the user a link to set up 2FA (`email_link`). They sign in again after enrolling.
4521
4647
  */
@@ -4529,8 +4655,14 @@ export declare class TwoFactorService {
4529
4655
  * show the recovery codes, then `verify` with the same code finishes it.
4530
4656
  */
4531
4657
  confirmEnrollment(code: string): Promise<TwoFactorConfirmResponse>;
4658
+ /**
4659
+ * Refuses a code of the wrong shape before any request: exactly the known digit count, or
4660
+ * 6 or 8 digits while the count is unknown (the server then decides).
4661
+ */
4532
4662
  private assertTotpCode;
4533
4663
  private requirePendingTfaToken;
4664
+ /** Keeps the TOTP digit count the server sent; an answer without one leaves it unchanged. */
4665
+ private storeTotpDigits;
4534
4666
  private setupStarted;
4535
4667
  private setupConfirmed;
4536
4668
  /**
@@ -4629,7 +4761,7 @@ export declare class TwoFactorService {
4629
4761
  getMagicLinkSessionToken(): string | null;
4630
4762
  /**
4631
4763
  * Get configured TOTP digit count
4632
- * Returns the number of digits (6 or 8) for TOTP codes
4764
+ * Returns the number of digits (6 or 8) for TOTP codes; 6 until a server answer gives the count
4633
4765
  * Useful for UI components that need to render the correct number of input fields
4634
4766
  */
4635
4767
  getTotpDigits(): 6 | 8;
@@ -4773,6 +4905,13 @@ type UpgradePromptRequest = {
4773
4905
  challenge: UpgradeChallenge;
4774
4906
  factors: readonly UpgradeFactor[];
4775
4907
  }) => void;
4908
+ /**
4909
+ * Called when the controller closes an OPEN prompt itself: a joining challenge
4910
+ * whose `availableFactors` is empty means only a fresh sign-in can meet it, so
4911
+ * the flight ends with `UpgradeSignInRequiredError` and the prompt's answer is
4912
+ * no longer read. A prompt subscribes the same way as to `onRequirementRaised`.
4913
+ */
4914
+ onClosed?: () => void;
4776
4915
  };
4777
4916
  /** The user's answer to an upgrade prompt. */
4778
4917
  type UpgradePromptResult = {
@@ -4934,6 +5073,16 @@ export declare class UpgradeCancelledError extends Error {
4934
5073
  readonly cause?: unknown;
4935
5074
  constructor(cause?: unknown);
4936
5075
  }
5076
+ /**
5077
+ * Raised when only a fresh sign-in can meet the challenge (`sign_in_required: true`,
5078
+ * for `prompt=login` or `max_age=0`; from an older server, an empty
5079
+ * `available_factors`). Sign the user in again, for example with `authRedirect()`
5080
+ * in an embedded app.
5081
+ */
5082
+ export declare class UpgradeSignInRequiredError extends Error {
5083
+ readonly code: 'upgrade_sign_in_required';
5084
+ constructor(message?: string);
5085
+ }
4937
5086
  /** Raised when no registered factor can satisfy the challenge. */
4938
5087
  export declare class UpgradeUnsatisfiableError extends Error {
4939
5088
  readonly code: 'upgrade_unsatisfiable';
@@ -4945,6 +5094,8 @@ export declare class UpgradeController {
4945
5094
  private readonly platform;
4946
5095
  private readonly registry;
4947
5096
  private readonly available;
5097
+ /** Ends the open prompt's race in `collect`; set only while a prompt is open. */
5098
+ private closeOpenPrompt?;
4948
5099
  private readonly maxAttempts;
4949
5100
  private readonly readObtainedBar?;
4950
5101
  private readonly onFlightSettled?;
@@ -5178,6 +5329,8 @@ export declare const isUpgradeCancelled: (response: object) => boolean;
5178
5329
  export declare const isUpgradeExhausted: (response: object) => boolean;
5179
5330
  export declare const isUpgradeInsufficient: (response: object) => boolean;
5180
5331
  export declare const isUpgradeUnsatisfiable: (response: object) => boolean;
5332
+ /** Only a fresh sign-in can meet the challenge (`available_factors: []`): sign the user in again. */
5333
+ export declare const isUpgradeSignInRequired: (response: object) => boolean;
5181
5334
  export declare const isUpgradeUnavailable: (response: object) => boolean;
5182
5335
  export declare const isUpgradeSessionChanged: (response: object) => boolean;
5183
5336
  /** FR1's non-retryable 400 class. */
@@ -5224,6 +5377,8 @@ type UpgradeErrorKind =
5224
5377
  'challenge_spent' |
5225
5378
  /** The server's per-challenge attempt budget is burned. Stop; a fresh prepare will not help. */
5226
5379
  'exhausted' |
5380
+ /** The server's rate limit answered 429. Stop; try again after `retryAfter` seconds. */
5381
+ 'rate_limited' |
5227
5382
  /**
5228
5383
  * The CONTROLLER's local attempt budget is burned: the user has answered
5229
5384
  * wrongly `maxAttempts` times and the elevation gives up.
@@ -5284,7 +5439,7 @@ export declare const UpgradeErrorIds: {
5284
5439
  *
5285
5440
  * `error.2fa.not_enabled` was missing from this list, which signed out a user
5286
5441
  * who had no 2FA enrolled the moment an elevation reached the commit round —
5287
- * the exact lock-out PFL-497 exists to prevent. The set is kept complete for
5442
+ * the exact lock-out the upgrade flow must never cause. The set is kept complete for
5288
5443
  * documentation and for callers, but the invalidation decision no longer rests
5289
5444
  * on it: see `invalidatesSessionOnCommit`, which is the inverse predicate.
5290
5445
  */
@@ -5311,6 +5466,8 @@ type UpgradeTransportErrorInit = {
5311
5466
  status?: number;
5312
5467
  /** The `PassflowError.id`, verbatim, when the server supplied one. */
5313
5468
  errorId?: string;
5469
+ /** Seconds from the `Retry-After` header of a 429. */
5470
+ retryAfter?: number;
5314
5471
  cause?: unknown;
5315
5472
  };
5316
5473
  /** Which round of the transaction failed. The same status means different things on each. */
@@ -5329,6 +5486,8 @@ export declare class UpgradeTransportError extends Error {
5329
5486
  readonly kind: UpgradeErrorKind;
5330
5487
  readonly status?: number;
5331
5488
  readonly errorId?: string;
5489
+ /** Seconds to wait before trying again, from the `Retry-After` header of a 429. */
5490
+ readonly retryAfter?: number;
5332
5491
  readonly retryable: boolean;
5333
5492
  /** Declared here rather than inherited: `Error.cause` is ES2022 and this build targets ES2021 libs. */
5334
5493
  readonly cause?: unknown;
@@ -5491,7 +5650,7 @@ type UpgradeFacade = {
5491
5650
  * Orders the factors to offer for a challenge. Index 0 is the suggested
5492
5651
  * method; the rest are the "use another way" alternatives.
5493
5652
  *
5494
- * The suggested slot is not only a UX choice: PFL-510 treats a non-suggested
5653
+ * The suggested slot is not only a UX choice: risk scoring treats a non-suggested
5495
5654
  * choice as a minor risk signal, so whatever leads here becomes the behavioural
5496
5655
  * baseline deviation is measured against.
5497
5656
  *
@@ -5499,7 +5658,7 @@ type UpgradeFacade = {
5499
5658
  * enrolled credentials before calling, when known.
5500
5659
  * @param challenge - What the server demanded (`acrValues`, `maxAge`).
5501
5660
  * @returns The factors to offer, most-preferred first. Empty only when
5502
- * `available` was empty — this never drops a factor of its own accord.
5661
+ * `available` was empty, or the server's list names none of them.
5503
5662
  */
5504
5663
  export declare const selectFactors: (available: readonly UpgradeFactor[], challenge: UpgradeChallenge) => readonly UpgradeFactor[];
5505
5664
  export declare class Passflow {
@@ -6087,6 +6246,14 @@ export declare class Passflow {
6087
6246
  /**
6088
6247
  * Sign out the current user and clear all tokens.
6089
6248
  *
6249
+ * When the session came from the hosted login (`authRedirect()`, either mode), the page then
6250
+ * leaves for the server's `/oidc/end_session`, which ends the hosted login's own session and
6251
+ * sends the browser to `options.postLogoutRedirectUri`, by default the address the hosted
6252
+ * sign-in landed on. Code after `await logOut()` may then not run. A sign-in made in the app
6253
+ * itself never navigates.
6254
+ *
6255
+ * @param options.postLogoutRedirectUri - where to return after a hosted sign-out; must match one
6256
+ * of the app's registered redirect URLs
6090
6257
  * @returns Promise that resolves when sign-out is complete
6091
6258
  * @throws {PassflowError} If sign-out request fails
6092
6259
  *
@@ -6101,7 +6268,7 @@ export declare class Passflow {
6101
6268
  * }
6102
6269
  * ```
6103
6270
  */
6104
- logOut(): Promise<void>;
6271
+ logOut(options?: LogOutOptions): Promise<void>;
6105
6272
  /**
6106
6273
  * Initiate federated authentication (OAuth) with a popup window.
6107
6274
  *
@@ -6163,7 +6330,7 @@ export declare class Passflow {
6163
6330
  * ```
6164
6331
  */
6165
6332
  reset(error?: string): void;
6166
- /** The one `SignOut` of `logOut()`/`reset()` in this tab (PFL-792 §2.4). */
6333
+ /** The one `SignOut` of `logOut()`/`reset()` in this tab. */
6167
6334
  private notifySignedOut;
6168
6335
  /**
6169
6336
  * Releases what this instance holds for token refresh: leaves the refresh lock queue, cancels
@@ -6713,12 +6880,14 @@ export declare class Passflow {
6713
6880
  * What the sign-in waiting on its second factor can do next. The server decides; read this
6714
6881
  * before asking for a code, and call `requestChallenge` only on `verify`.
6715
6882
  *
6716
- * @returns `verify`: ask for a code. `email_link`: `sendTwoFactorSetupLink`, then the user signs
6717
- * in again after enrolling. `direct`: `beginTwoFactorEnrollment`, `confirmTwoFactorEnrollment`,
6718
- * then `verifyTwoFactor`. `unavailable`: tell the user to contact the administrator.
6883
+ * @returns The server's answer. Its `enrollment`: `verify`: ask for a code. `email_link`:
6884
+ * `sendTwoFactorSetupLink`, then the user signs in again after enrolling. `direct`:
6885
+ * `beginTwoFactorEnrollment`, `confirmTwoFactorEnrollment`, then `verifyTwoFactor`.
6886
+ * `unavailable`: tell the user to contact the administrator. With a TOTP enrolment it also
6887
+ * carries `totp_digits` (6 or 8) and `totp_period`; `verifyTwoFactor` then expects that many digits.
6719
6888
  * @throws {PassflowError} A 401 means the sign-in is over: sign in again.
6720
6889
  */
6721
- getTwoFactorEnrollment(): Promise<TwoFactorEnrollment>;
6890
+ getTwoFactorEnrollment(): Promise<TwoFactorEnrollmentResponse>;
6722
6891
  /**
6723
6892
  * Email the user a link to set up 2FA, on a sign-in whose enrollment is `email_link`.
6724
6893
  * The budget is 3 requests in 5 minutes, shared with `requestChallenge`, so limit resends.
@@ -6754,10 +6923,14 @@ export declare class Passflow {
6754
6923
  *
6755
6924
  * @example
6756
6925
  * ```typescript
6757
- * // After signIn returns requires_2fa: true
6926
+ * // After signIn answers with a tfa_token
6758
6927
  * if (passflow.isTwoFactorVerificationRequired()) {
6759
- * const response = await passflow.verifyTwoFactor('123456', { trustDevice: true });
6760
- * console.log('Authentication complete', response.access_token);
6928
+ * const { enrollment, totp_digits = 6 } = await passflow.getTwoFactorEnrollment();
6929
+ * if (enrollment === 'verify') {
6930
+ * const code = await askForCode(totp_digits); // an input sized to the digit count
6931
+ * const response = await passflow.verifyTwoFactor(code, { trustDevice: true });
6932
+ * console.log('Authentication complete', response.access_token);
6933
+ * }
6761
6934
  * }
6762
6935
  * ```
6763
6936
  */
@@ -6773,10 +6946,12 @@ export declare class Passflow {
6773
6946
  *
6774
6947
  * @example
6775
6948
  * ```typescript
6776
- * // After signIn returns requires_2fa: true
6777
- * const result = await passflow.useTwoFactorRecoveryCode('ABCD-1234');
6949
+ * // After signIn answers with a tfa_token
6950
+ * const result = await passflow.useTwoFactorRecoveryCode('ABCD-EFGH-JKMN');
6778
6951
  * console.log('Authenticated with recovery code');
6779
- * console.log(`${result.remaining_recovery_codes} recovery codes remaining`);
6952
+ * if (result.remaining_recovery_codes !== undefined) {
6953
+ * console.log(`${result.remaining_recovery_codes} recovery codes remaining`);
6954
+ * }
6780
6955
  * ```
6781
6956
  */
6782
6957
  useTwoFactorRecoveryCode(code: string, options?: TwoFactorCompletionOptions): Promise<TwoFactorRecoveryResponse>;