@passflow/core 0.33.0 → 0.35.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
@@ -1,5 +1,5 @@
1
- import { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, CreateAxiosDefaults } from "axios";
2
1
  import { AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsJSON, RegistrationResponseJSON } from "@simplewebauthn/browser";
2
+ import { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, CreateAxiosDefaults } from "axios";
3
3
  type Tenant = {
4
4
  id: string;
5
5
  name: string;
@@ -312,8 +312,15 @@ declare class StorageManager {
312
312
  * Save tokens to storage with conditional logic based on delivery mode
313
313
  * In cookie/BFF mode: ONLY save ID token (not access/refresh tokens)
314
314
  * In JSON mode: save all tokens (existing behavior)
315
+ *
316
+ * A token or scope list that `tokens` does not name stays stored, as a refresh answer needs. With
317
+ * `replace` (a new session) and an access token, in JSON mode, it is removed instead, so nothing
318
+ * of the previous session is left beside the new one. Another app's tokens always stay, and so
319
+ * do its scopes when only its session is stored.
315
320
  */
316
- saveTokens(tokens: Tokens, deliveryMode?: TokenDeliveryMode): void;
321
+ saveTokens(tokens: Tokens, deliveryMode?: TokenDeliveryMode, options?: {
322
+ replace?: boolean;
323
+ }): void;
317
324
  getToken(tokenType: TokenType): string | undefined;
318
325
  /**
319
326
  * Get tokens from storage with conditional logic based on delivery mode
@@ -404,14 +411,6 @@ declare class StorageManager {
404
411
  tokenKeys(): string[];
405
412
  private getKeyForTokenType;
406
413
  }
407
- declare class DeviceService {
408
- private storageManager;
409
- /** The id this service minted; used when the storage keeps nothing (server rendering). */
410
- private mintedDeviceId;
411
- constructor(storageManager?: StorageManager);
412
- getDeviceId(): string;
413
- generateUniqueDeviceId(): string;
414
- }
415
414
  /**
416
415
  * Synchronous key-value storage interface.
417
416
  * Compatible with localStorage (web) and react-native-mmkv (RN).
@@ -589,6 +588,13 @@ interface PlatformAdapter {
589
588
  * In redirect mode on web, the promise may never resolve.
590
589
  */
591
590
  openAuthUrl(url: string, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
591
+ /**
592
+ * Optional. Opens the auth window now, while the user's click still allows it, and navigates it
593
+ * when `url` resolves; closes it and rejects with the same error if `url` rejects. Used for a
594
+ * federated start that must be POSTed first (an app in `human_only` bot mode). Without it the
595
+ * SDK waits for the URL and calls `openAuthUrl`.
596
+ */
597
+ openPendingAuthUrl?(url: Promise<string>, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
592
598
  /**
593
599
  * Optional passkey support. If the platform does not support passkeys,
594
600
  * this property is undefined. The SDK checks for undefined before calling.
@@ -662,8 +668,8 @@ export declare class WebAdapter implements PlatformAdapter {
662
668
  * document.addEventListener('visibilitychange', handler) where document.hidden
663
669
  * (token-cache-service.ts:134-145, complementary to onForeground)
664
670
  *
665
- * NOTE: Not currently called by the SDK. Included in the interface for
666
- * React Native adapter compatibility (future use).
671
+ * NOTE: The SDK does not call it. It is part of the `PlatformAdapter` interface
672
+ * so an adapter for another platform, such as React Native, can offer it.
667
673
  */
668
674
  onBackground(callback: () => void): () => void;
669
675
  /**
@@ -689,6 +695,15 @@ export declare class WebAdapter implements PlatformAdapter {
689
695
  * (auth-service.ts:813)
690
696
  */
691
697
  openAuthUrl(url: string, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
698
+ /**
699
+ * Opens a blank popup at once, inside the user's click, and sends it to `url` once that
700
+ * resolves. A blocked popup falls back to a full-page redirect to the URL; a rejected `url`
701
+ * closes the popup and rejects with the same error. Other modes wait for the URL and behave as
702
+ * `openAuthUrl`.
703
+ */
704
+ openPendingAuthUrl(url: Promise<string>, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
705
+ /** Polls the popup until it returns to `expectedReturnOrigin`, closes, or times out. */
706
+ private watchPopup;
692
707
  /**
693
708
  * Replaces:
694
709
  * startRegistration({ optionsJSON: publicKey }) from @simplewebauthn/browser
@@ -729,6 +744,97 @@ export declare class WebAdapter implements PlatformAdapter {
729
744
  * Exported so consuming code can reference it without allocating a new instance.
730
745
  */
731
746
  export declare const webAdapter: WebAdapter;
747
+ /**
748
+ * Public types of multi-tab-safe token refresh.
749
+ *
750
+ * @module refresh/types
751
+ */
752
+ /** Options of one lock request: exclusive mode only, as the SDK uses `navigator.locks`. */
753
+ interface RefreshLockOptions {
754
+ ifAvailable?: boolean;
755
+ steal?: boolean;
756
+ signal?: AbortSignal;
757
+ }
758
+ /** The part of `navigator.locks` (LockManager) the SDK uses: exclusive mode only. */
759
+ interface RefreshLockManager {
760
+ request(name: string, options: RefreshLockOptions, callback: (lock: unknown) => unknown): Promise<unknown>;
761
+ }
762
+ /** The part of BroadcastChannel the SDK uses. Must not deliver an instance's own posts to itself. */
763
+ interface RefreshChannel {
764
+ postMessage(message: unknown): void;
765
+ addEventListener(type: 'message', listener: (event: {
766
+ data: unknown;
767
+ }) => void): void;
768
+ removeEventListener(type: 'message', listener: (event: {
769
+ data: unknown;
770
+ }) => void): void;
771
+ close(): void;
772
+ }
773
+ /** Time source for every refresh timer of one instance (heartbeat, silence, retry, waits). */
774
+ interface RefreshClock {
775
+ /** Epoch ms. */
776
+ now(): number;
777
+ /** Runs `fn` after `ms`; returns the cancel. */
778
+ setTimeout(fn: () => void, ms: number): () => void;
779
+ /** `[0, 1)` for backoff jitter. Default `Math.random`. */
780
+ random?(): number;
781
+ }
782
+ /** Transports for the cross-tab protocol, supplied by tests, Electron or custom hosts. */
783
+ interface RefreshCoordinator {
784
+ locks: RefreshLockManager;
785
+ /** One per Passflow instance; closed by `dispose()`. */
786
+ channel: RefreshChannel;
787
+ /** Default: `crypto.randomUUID()` or a random string. */
788
+ tabId?: string;
789
+ /** Another tab wrote the shared token storage. Called once at construction; returns unsubscribe. */
790
+ onStorageChange?: (listener: () => void) => () => void;
791
+ /** Default: `Date.now` / `setTimeout` / `Math.random`. */
792
+ clock?: RefreshClock;
793
+ }
794
+ /** How tabs of this origin coordinate token refresh (`PassflowConfig.refreshCoordination`). */
795
+ type RefreshCoordination = 'web-locks' | 'none' | RefreshCoordinator;
796
+ /** What asked for a refresh (`ErrorPayload.source`). */
797
+ type RefreshTrigger =
798
+ /** `Passflow.refreshToken()` / `AuthService.refreshToken()` */
799
+ 'refresh-token' |
800
+ /** `TokenCacheService.getTokensWithRefresh()` */
801
+ 'token-check' |
802
+ /** `getTokens(true)` / `session({ doRefresh: true })` */
803
+ 'session' |
804
+ /** An SDK API call whose access token expires within 30 s */
805
+ 'pre-request' |
806
+ /** Step-up commit */
807
+ 'upgrade' |
808
+ /** The scheduled retry, with no new caller */
809
+ 'retry' |
810
+ /** The held-tab send */
811
+ 'held';
812
+ /** How a failed `/auth/refresh` is read (architecture §2.6). */
813
+ type RefreshFailureKind = 'transient' | 'blocked' | 'auth';
814
+ /** Refresh details on `ErrorPayload` for operations `refresh` and `upgrade.commit`. */
815
+ interface RefreshErrorInfo {
816
+ classification: RefreshFailureKind;
817
+ /** A retry is scheduled (transient, or auth with strikes left). */
818
+ willRetry: boolean;
819
+ /** Epoch ms of the retry, when `willRetry`. */
820
+ nextRetryAt?: number;
821
+ /** Auth failures since the last success, after this one. */
822
+ strikes: number;
823
+ /** Resolved `refreshStrikes`. */
824
+ maxStrikes: number;
825
+ }
826
+ /** Whether an event was caused by this tab's own action or learnt from another tab. */
827
+ type EventOrigin = 'this-tab' | 'other-tab';
828
+ /** Why a session ended (`SessionExpired.reason`). */
829
+ type SessionExpiredReason =
830
+ /** `refreshStrikes` auth failures (this tab, or another tab of the lineage). */
831
+ 'refresh_failed' |
832
+ /** `error.token.blocked` and no successor within 20 s; this tab only. */
833
+ 'successor_timeout' |
834
+ /** Storage now holds another user's tokens. */
835
+ 'identity_changed' |
836
+ /** Legacy members, never emitted. */
837
+ 'token_invalid' | 'logged_out';
732
838
  /** Factor types the upgrade protocol understands, named as `upgrade.type` on the wire. */
733
839
  type UpgradeFactorType = 'totp' | 'recovery_codes' | 'passkey' | 'email_otp' | 'sms_otp';
734
840
  /** The prepare round's result — `POST /auth/upgrade/begin`, normalised to camelCase. */
@@ -811,549 +917,345 @@ export declare const passkeyFactor: UpgradeFactor;
811
917
  export declare const DEFAULT_UPGRADE_FACTORS: readonly UpgradeFactor[];
812
918
  /** Indexes a factor list by type for lookup during a challenge. */
813
919
  export declare const factorRegistry: (factors?: readonly UpgradeFactor[]) => Map<UpgradeFactorType, UpgradeFactor>;
814
- /** The error code RFC 9470 §3 defines for an insufficient authentication event. */
815
- export declare const INSUFFICIENT_USER_AUTHENTICATION = "insufficient_user_authentication";
816
- /** The ADR-2 error code `/auth/session/exchange` returns in its 403 body. */
817
- export declare const UPGRADE_REQUIRED = "upgrade_required";
920
+ export type RequestOptions<D> = {
921
+ data?: D;
922
+ config?: AxiosRequestConfig;
923
+ };
924
+ export declare enum RequestMethod {
925
+ GET = "get",
926
+ POST = "post",
927
+ PUT = "put",
928
+ PATCH = "patch",
929
+ DELETE = "delete"
930
+ }
931
+ export declare enum PassflowEndpointPaths {
932
+ signin = "/auth/login",
933
+ signup = "/auth/register",
934
+ pkceExchange = "/auth/pkce_exchange",
935
+ redirectCheck = "/auth/redirect/check",
936
+ signInWithProvider = "/auth/federated/start/",
937
+ passwordless = "/auth/passwordless/start",
938
+ passwordlessComplete = "/auth/passwordless/complete",
939
+ passwordlessStatus = "/auth/passwordless/status",
940
+ passwordlessApprovalInfo = "/auth/passwordless/approval/info",
941
+ passwordlessApprovalDecide = "/auth/passwordless/approval/decide",
942
+ logout = "/user/logout",
943
+ refresh = "/auth/refresh",
944
+ validateSession = "/user/me",
945
+ sendPasswordResetEmail = "/auth/password/reset",
946
+ resetPassword = "/auth/password/change",
947
+ appSettings = "/app/settings",
948
+ passkeyRegisterStart = "/auth/passkey/register/start",
949
+ passkeyRegisterComplete = "/auth/passkey/register/complete",
950
+ passkeyAuthenticateStart = "/auth/passkey/authenticate/start",
951
+ passkeyAuthenticateComplete = "/auth/passkey/authenticate/complete",
952
+ passkeyValidate = "/auth/validate",
953
+ settingsAll = "/settings",
954
+ settingsPasswordPolicy = "/settings/password",
955
+ settingsPasskey = "/settings/passkey",
956
+ userPasskey = "/user/passkey",
957
+ addUserPasskey = "/user/passkey/add/start",
958
+ completeAddUserPasskey = "/user/passkey/add/complete",
959
+ userSessions = "/user/sessions",
960
+ userSessionsRevokeOthers = "/user/sessions/revoke-others",
961
+ joinInvitation = "/user/tenant/join",
962
+ tenantPath = "/user/tenant",
963
+ invitationsPath = "/user/tenant/:tenantID/invitations",
964
+ requestInvitation = "/user/invite",
965
+ invitationDelete = "/user/invite/:invitationID",
966
+ invitationResend = "/user/invite/:invitationID/resend",
967
+ invitationGetLink = "/user/invite/:invitationID/link",
968
+ twoFactor = "/user/2fa",
969
+ twoFactorStatus = "/user/2fa/status",
970
+ twoFactorSetupBegin = "/user/2fa/setup/begin",
971
+ twoFactorSetupConfirm = "/user/2fa/setup/confirm",
972
+ twoFactorVerify = "/auth/2fa/verify",
973
+ twoFactorRecovery = "/auth/2fa/recovery",
974
+ twoFactorRegenerateCodes = "/user/2fa/recovery-codes/regenerate",
975
+ twoFactorSetupMagicLink = "/auth/2fa-setup", // :token param appended in API call
976
+ twoFactorEnrollment = "/auth/2fa/enrollment",
977
+ twoFactorEnrollmentEmailLink = "/auth/2fa/enrollment/email-link",
978
+ twoFactorEnrollmentBegin = "/auth/2fa/setup/begin",
979
+ twoFactorEnrollmentConfirm = "/auth/2fa/setup/confirm",
980
+ TwoFactorMethodsAvailable = "/v2/user/2fa/methods/available",
981
+ TwoFactorMethodsRegistered = "/v2/user/2fa/methods",
982
+ TwoFactorSetupStart = "/v2/user/2fa/setup/start",
983
+ TwoFactorSetupComplete = "/v2/user/2fa/setup/complete",
984
+ TwoFactorMethodRemove = "/v2/user/2fa/methods/:id",
985
+ TwoFactorChallenge = "/v2/auth/2fa/challenge",
986
+ TwoFactorVerifyV2 = "/v2/auth/2fa/verify",
987
+ TwoFactorAlternative = "/v2/auth/2fa/alternative",
988
+ TwoFactorTrustedDevices = "/v2/user/2fa/trusted-devices",
989
+ TwoFactorTrustedDeviceRevoke = "/v2/user/2fa/trusted-devices/:id",
990
+ cliAuthStatus = "/cli/auth/status/:sessionId",
991
+ cliAuthComplete = "/cli/auth/complete",
992
+ upgradeStart = "/auth/upgrade/start",
993
+ hostedUpgradeStart = "/auth/session/upgrade/start",
994
+ hostedUpgrade = "/auth/session/upgrade",
995
+ antiBotChallenge = "/auth/anti-bot/challenge",
996
+ deviceAntiBotChallenge = "/oidc/device/anti-bot/challenge"
997
+ }
998
+ export declare enum PassflowAdminEndpointPaths {
999
+ passkeyRegisterStart = "/admin/auth/passkey/register/start",
1000
+ passkeyRegisterComplete = "/admin/auth/passkey/register/complete",
1001
+ passkeyAuthenticateStart = "/admin/auth/passkey/authenticate/start",
1002
+ passkeyAuthenticateComplete = "/admin/auth/passkey/authenticate/complete",
1003
+ passkeyValidate = "/admin/auth/validate",
1004
+ logout = "/admin/auth/logout"
1005
+ }
818
1006
  /**
819
- * What the server demands before it will serve the original request.
820
- *
821
- * Both fields are optional because the two middlewares challenge on different
822
- * axes: RequireAuthLevel names an `acrValues` and omits `maxAge`, while
823
- * RequireFreshAuth does the reverse. A challenge carrying neither is still
824
- * valid — it means "re-prove a factor" without further qualification.
1007
+ * BFF (Backend-for-Frontend) configuration for secure token storage.
1008
+ * When enabled, tokens are sent to the BFF server which stores them in httpOnly cookies.
825
1009
  */
826
- type UpgradeChallenge = {
1010
+ export type TokenExchangeConfig = {
827
1011
  /**
828
- * Required authentication context class (`acr`), e.g. `'2'`.
829
- *
830
- * After a two-channel merge this is the raw list of the channel that SET THE
831
- * BAR, with the header preferred on a numeric tie. A channel that contributed
832
- * no level never supplies it — showing `"2gold"` as the bar would
833
- * misrepresent what the server demanded.
1012
+ * Enable token exchange mode. When true, authorization code is sent to your server
1013
+ * for token exchange instead of being exchanged directly from the browser.
834
1014
  */
835
- acrValues?: string;
1015
+ enabled: boolean;
836
1016
  /**
837
- * The parsed bar: `max` over each channel's `min` participating level
838
- * (§13.2.1a). `undefined` means unknown or unconstrained on this axis.
839
- *
840
- * Optional, and absent from the single-channel parsers' output, so
841
- * `parseChallengeHeader` / `parseChallengeBody` keep the exact shape they
842
- * ship with. `readUpgradeChallenge` always sets it when a level was parsed.
1017
+ * URL to send authorization code for server-side token exchange.
1018
+ * Your server exchanges the code for tokens and stores them in httpOnly cookies.
1019
+ * @example '/api/auth/callback'
843
1020
  */
844
- requiredLevel?: number;
845
- /** Maximum permitted age of the authentication event, in seconds. */
846
- maxAge?: number;
847
- /** The status that carried the challenge: 401 (protected resource) or 403 (session exchange). */
848
- status: number;
1021
+ callbackUrl: string;
849
1022
  /**
850
- * The factors this user can use, in the order to offer them, from the `403` body's
851
- * `available_factors`. Absent when the server does not send it (older servers, the header channel).
1023
+ * URL to call for token refresh. BFF reads refresh_token from httpOnly cookie
1024
+ * and returns new tokens (also stored in cookies).
1025
+ * @example '/api/auth/refresh'
852
1026
  */
853
- availableFactors?: UpgradeFactorType[];
1027
+ refreshUrl?: string;
854
1028
  /**
855
- * The `403` body's `sign_in_required`: `true` when only a fresh sign-in can meet
856
- * the challenge, `false` when a step-up could but `availableFactors` names none
857
- * this account has (for example a device-bound passkey for AAL3). Absent from
858
- * older servers.
1029
+ * URL to call for logout. BFF clears httpOnly cookies.
1030
+ * @example '/api/auth/logout'
859
1031
  */
860
- signInRequired?: boolean;
1032
+ logoutUrl?: string;
861
1033
  /**
862
- * Every channel that PARSED AS A CHALLENGE in any field — not only the
863
- * channels that won a comparison. An opaque header contributes no constraint
864
- * yet must still be counted, because only something that saw and discarded it
865
- * can report it. `length === 2` means "both channels carried a challenge".
866
- *
867
- * Set by `readUpgradeChallenge`; absent from the single-channel parsers.
1034
+ * URL to check authentication status (whether httpOnly cookies are valid).
1035
+ * @example '/api/auth/status'
868
1036
  */
869
- channels?: ChallengeChannel[];
1037
+ statusUrl?: string;
870
1038
  };
871
- /** Which wire channel a challenge was read from. */
872
- type ChallengeChannel = 'header' | 'body';
873
- /**
874
- * Reads a upgrade challenge out of a `WWW-Authenticate` header, or returns
875
- * `undefined` when the header is absent or describes some other failure.
1039
+ /** @deprecated Use TokenExchangeConfig instead */
1040
+ export type BFFConfig = TokenExchangeConfig;
1041
+ export type PassflowConfig = {
1042
+ url?: string;
1043
+ appId?: string;
1044
+ scopes?: string[];
1045
+ createTenantForNewUser?: boolean;
1046
+ parseQueryParams?: boolean;
1047
+ /**
1048
+ * Leaves a federated `?code=` landing alone in the constructor and in `handleTokensRedirect`,
1049
+ * so that only `completeFederatedLanding()` takes it. For hosts that build the instance during
1050
+ * render and may discard it. Token and `#tfa_token` landings are not affected.
1051
+ */
1052
+ deferFederatedLanding?: boolean;
1053
+ keyStoragePrefix?: string;
1054
+ /**
1055
+ * Token exchange configuration for secure server-side token handling.
1056
+ * When enabled, authorization code is sent to your server which exchanges it
1057
+ * for tokens and stores them in httpOnly cookies. Tokens never touch the browser.
1058
+ */
1059
+ tokenExchange?: TokenExchangeConfig;
1060
+ /**
1061
+ * Platform adapter for cross-platform compatibility.
1062
+ * Defaults to WebAdapter (browser APIs) if not provided.
1063
+ * Pass a custom adapter to support React Native or other platforms.
1064
+ */
1065
+ platform?: PlatformAdapter;
1066
+ /**
1067
+ * Assurance upgrade (step-up) configuration. Construction-time only: the
1068
+ * prompt handler is deliberately NOT here, because it is a lifetime-scoped
1069
+ * resource that has to be torn down, which configuration cannot express.
1070
+ */
1071
+ upgrade?: PassflowUpgradeConfig;
1072
+ /**
1073
+ * How tabs of this origin coordinate token refresh.
1074
+ * - `'web-locks'` (default): a Web Lock plus a BroadcastChannel, on a browser page whose
1075
+ * `platform.storage` is shared by every tab (the default web adapter's localStorage) and that
1076
+ * has `navigator.locks` and `BroadcastChannel`. Elsewhere it falls back to `'none'`; on a
1077
+ * browser page with shared storage the fallback writes one `[passflow]` warning, at the first
1078
+ * refresh.
1079
+ * - `'none'`: no cross-tab coordination. Single flight within this instance, compare-and-set
1080
+ * save, per-instance retries.
1081
+ * - a `RefreshCoordinator` object: the same protocol as `'web-locks'` over the transports
1082
+ * you supply (tests, Electron, custom hosts). Never falls back.
1083
+ */
1084
+ refreshCoordination?: RefreshCoordination;
1085
+ /**
1086
+ * Authentication failures of `/auth/refresh` counted since the last successful refresh or
1087
+ * adoption, after which the session ends. Transient failures in between neither add a strike nor
1088
+ * reset the count. Default 3. A non-integer is floored; a value below 1 or not a finite number
1089
+ * uses the default.
1090
+ */
1091
+ refreshStrikes?: number;
1092
+ /**
1093
+ * Same-origin URL of the anti-bot worker script shipped as `@passflow/core/anti-bot-worker.js`,
1094
+ * for example `'/anti-bot-worker.js'`. Used only by apps in `human_only` bot mode with the
1095
+ * built-in check. Without it the proof of work runs on the main thread.
1096
+ */
1097
+ antiBotWorkerUrl?: string;
1098
+ };
1099
+ export type PassflowUpgradeConfig = {
1100
+ /** Relying-party id forwarded verbatim to `POST /auth/upgrade/start` for passkey upgrades. */
1101
+ relyingPartyId?: string;
1102
+ /** Overrides the factor set offered during an upgrade. Defaults to what this SDK can complete. */
1103
+ factors?: readonly UpgradeFactor[];
1104
+ };
1105
+ /**
1106
+ * Passflow's own API, as an interception scope — "domain 1".
876
1107
  *
877
- * The header must both use the `Bearer` scheme and carry
878
- * `error="insufficient_user_authentication"`. A bare `WWW-Authenticate: Bearer`
879
- * (what an expired token produces) is deliberately NOT a upgrade challenge.
1108
+ * A challenge arriving from here is handled with zero configuration, because
1109
+ * `url` is an input the SDK already takes and whatever it points at is
1110
+ * unambiguously ours.
880
1111
  */
881
- export declare const parseChallengeHeader: (header: string | undefined | null, status: number) => UpgradeChallenge | undefined;
1112
+ export type UpgradeDomain = {
1113
+ /** The API origin, e.g. `https://api.passflow.dev`. */
1114
+ origin: string;
1115
+ /** The path prefix when `url` carries one, normalised without a trailing slash. */
1116
+ pathPrefix?: string;
1117
+ };
882
1118
  /**
883
- * Reads a upgrade challenge out of the ADR-2 `403` body. Used as a fallback
884
- * for `/auth/session/exchange`, whose JSON body is the documented SDK contract
885
- * even though it also sets the standard header.
1119
+ * Resolves domain 1 from `PassflowConfig.url`.
1120
+ *
1121
+ * `url` is OPTIONAL, and the absent case is specified rather than guessed: the
1122
+ * domain is EMPTY (`null`), and nothing throws. Throwing would break apps that
1123
+ * never enabled step-up, and substituting a default origin — `PASSFLOW_CLOUD_URL`,
1124
+ * the document origin, the origin the first 401 came from — would be the SDK
1125
+ * inferring a trust boundary it has no information about. An empty domain is not
1126
+ * silent: the first parseable challenge on an attached surface must raise a
1127
+ * diagnostic naming `url` as the fix.
1128
+ *
1129
+ * Note this deliberately does NOT mirror `AxiosClient`'s `url || PASSFLOW_CLOUD_URL`
1130
+ * fallback. That fallback decides where to send our own traffic; this decides
1131
+ * whose 401s may drive a security prompt, and the two questions do not share an
1132
+ * answer.
886
1133
  */
887
- export declare const parseChallengeBody: (body: unknown, status: number) => UpgradeChallenge | undefined;
888
- /** The bar a challenge demanded, or an elevation reached, on both axes. */
889
- type AssuranceBar = {
890
- /** The raw winning `acr_values` list, for display and diagnostics. */
891
- acrValues?: string;
892
- /** The parsed bar. `undefined` = unknown, or not constrained on this axis. */
893
- level?: number;
894
- /** The freshness constraint, when that is what was demanded. */
895
- maxAge?: number;
1134
+ export declare const resolveUpgradeDomain: (url?: string) => UpgradeDomain | null;
1135
+ /** The raw `POST /auth/upgrade/start` body, snake_case exactly as the server sends it. */
1136
+ export type UpgradeStartWire = {
1137
+ challenge_id: string;
1138
+ method: string;
1139
+ /** RFC 3339. The server enforces the TTL; the SDK carries this for display only. */
1140
+ expires_at: string;
1141
+ /** WebAuthn assertion options, present only for a passkey upgrade. */
1142
+ webauthn?: PublicKeyCredentialRequestOptionsJSON;
1143
+ /** Masked delivery target (`j***@x.com`), present only for email / SMS OTP. */
1144
+ code_sent_to?: string;
896
1145
  };
897
- /** The reasons the SDK can decline to act on a challenge, or act on a suspect one. */
898
- type UpgradeDiagnosticReason = 'no-channel' | 'header-required-but-absent' | 'channels-disagree' | 'channels-unorderable' | 'zero-constraint-ignored' | 'challenge-out-of-scope' | 'elevated-insufficient' | 'replay-unsupported';
899
1146
  /**
900
- * One diagnostic record.
1147
+ * The `upgrade` field of `POST /auth/refresh` — the commit round.
1148
+ * Also the whole body of `POST /auth/session/upgrade`.
901
1149
  *
902
- * A diagnostic is the only observable signal of the response-rewriting and the
903
- * misconfiguration this design warns about, so it routes through a callback
904
- * whose DEFAULT sink is `console.warn` — never `debug`, which is invisible in
905
- * every default configuration. A deployment where step-up silently never fires
906
- * must be distinguishable from one where it was never required.
1150
+ * The server types `assertion` as `json.RawMessage`, so a new factor can extend
1151
+ * the payload without a wire-format change.
907
1152
  */
908
- type UpgradeDiagnostic = {
909
- status: number;
1153
+ export type UpgradeRefreshField = {
1154
+ type: string;
1155
+ assertion: UpgradeAssertion;
1156
+ };
1157
+ export type PassflowAuthorizationResponse = Tokens & {
910
1158
  /**
911
- * The request's URL. The parser does not know it — it is handed a status, a
912
- * header reader and a body — so it emits `''` and the core, which owns the
913
- * request context, fills it in before forwarding to the sink.
1159
+ * The authorization code a PKCE app answers with in place of tokens. The SDK
1160
+ * redeems it, so a response handed back to a caller never carries one.
914
1161
  */
915
- url: string;
916
- reason: UpgradeDiagnosticReason;
917
- detail?: {
918
- obtained?: AssuranceBar;
919
- required?: AssuranceBar;
920
- /** Raw channel inputs, including values discarded as unorderable. */
921
- header?: string;
922
- body?: string;
923
- /** Which field was discarded, for `'zero-constraint-ignored'`. */
924
- field?: 'acr_values' | 'max_age';
925
- /** Which operation, for per-waiter reasons. */
926
- method?: string;
927
- /** A human-readable sentence naming the fix. The default sink prints it. */
928
- message?: string;
929
- };
1162
+ code?: string;
1163
+ /** Where the server sends the user next; a password reset answers with its link's redirect. */
1164
+ redirect_url?: string;
1165
+ challenge_id?: string;
1166
+ tfa_token?: string;
1167
+ token_delivery?: 'json_body' | 'cookie' | 'mobile';
1168
+ cookies?: string[];
1169
+ csrf_token?: string;
1170
+ /** `true` when the server needs the email proven before this sign-in finishes. No tokens come with it. */
1171
+ email_verification_required?: boolean;
1172
+ /** Human-readable text from the server, e.g. "We sent a code to a***@example.com." */
1173
+ message?: string;
930
1174
  };
931
- /** Where diagnostics go. `console.warn` is the default sink, not the only one. */
932
- type UpgradeDiagnosticSink = (diagnostic: UpgradeDiagnostic) => void;
933
1175
  /**
934
- * Resolves a upgrade challenge from a response, from either channel.
935
- *
936
- * The SHIPPED export: same name, same three parameters, same return, published
937
- * in `@passflow/core@0.14.1`. It is now a thin delegate over
938
- * `readUpgradeChallenge`, so there is one merge rule rather than two parsers
939
- * that can drift — but it discards the diagnostics, which is why a caller that
940
- * needs them (the core) calls the sibling directly.
941
- *
942
- * Returns `undefined` for every response that is not a upgrade challenge —
943
- * including ordinary `401`s, which callers must keep treating as "session
944
- * expired".
1176
+ * A sign-up, sign-in or password change that waits for the email to be proven.
1177
+ * With `challenge_id`: a code was emailed, finish with `Passflow.verifyEmailCode`.
1178
+ * Without: the code budget is spent and a link was emailed instead.
1179
+ * `message` is what the server sent; a malformed answer may leave it out.
945
1180
  */
946
- export declare const parseUpgradeChallenge: (status: number, getHeader: (name: string) => string | undefined | null, body?: unknown) => UpgradeChallenge | undefined;
1181
+ export type PassflowEmailVerificationStep = {
1182
+ email_verification_required: true;
1183
+ message: string;
1184
+ challenge_id?: string;
1185
+ };
1186
+ /** The emailed code for a `PassflowEmailVerificationStep` that carried a `challenge_id`. */
1187
+ export type PassflowEmailCodePayload = {
1188
+ challenge_id: string;
1189
+ otp: string;
1190
+ };
947
1191
  /**
948
- * Public types of multi-tab-safe token refresh.
949
- *
950
- * @module refresh/types
1192
+ * Whether an auth answer is an email verification step rather than a session. Only the
1193
+ * `email_verification_required` flag is checked, so an answer with the flag is never taken
1194
+ * for a session.
951
1195
  */
952
- /** Options of one lock request: exclusive mode only, as the SDK uses `navigator.locks`. */
953
- interface RefreshLockOptions {
954
- ifAvailable?: boolean;
955
- steal?: boolean;
956
- signal?: AbortSignal;
1196
+ export declare const isEmailVerificationStep: (response: unknown) => response is PassflowEmailVerificationStep;
1197
+ export type PassflowValidationResponse = Tokens & {
1198
+ redirect_url: string;
1199
+ challenge_id?: string;
1200
+ tfa_token?: string;
1201
+ /** PKCE app: the code to redeem with the verifier, in place of tokens. */
1202
+ code?: string;
1203
+ };
1204
+ export type PassflowSuccessResponse = {
1205
+ result: 'ok';
1206
+ };
1207
+ export type PassflowLogoutResponse = {
1208
+ status: 'ok';
1209
+ };
1210
+ export interface PassflowSessionValidationResponse {
1211
+ valid: boolean;
1212
+ user?: {
1213
+ id: string;
1214
+ email?: string;
1215
+ username?: string;
1216
+ [key: string]: unknown;
1217
+ };
1218
+ expires_at?: number;
957
1219
  }
958
- /** The part of `navigator.locks` (LockManager) the SDK uses: exclusive mode only. */
959
- interface RefreshLockManager {
960
- request(name: string, options: RefreshLockOptions, callback: (lock: unknown) => unknown): Promise<unknown>;
961
- }
962
- /** The part of BroadcastChannel the SDK uses. Must not deliver an instance's own posts to itself. */
963
- interface RefreshChannel {
964
- postMessage(message: unknown): void;
965
- addEventListener(type: 'message', listener: (event: {
966
- data: unknown;
967
- }) => void): void;
968
- removeEventListener(type: 'message', listener: (event: {
969
- data: unknown;
970
- }) => void): void;
971
- close(): void;
972
- }
973
- /** Time source for every refresh timer of one instance (heartbeat, silence, retry, waits). */
974
- interface RefreshClock {
975
- /** Epoch ms. */
976
- now(): number;
977
- /** Runs `fn` after `ms`; returns the cancel. */
978
- setTimeout(fn: () => void, ms: number): () => void;
979
- /** `[0, 1)` for backoff jitter. Default `Math.random`. */
980
- random?(): number;
981
- }
982
- /** Transports for the cross-tab protocol, supplied by tests, Electron or custom hosts. */
983
- interface RefreshCoordinator {
984
- locks: RefreshLockManager;
985
- /** One per Passflow instance; closed by `dispose()`. */
986
- channel: RefreshChannel;
987
- /** Default: `crypto.randomUUID()` or a random string. */
988
- tabId?: string;
989
- /** Another tab wrote the shared token storage. Called once at construction; returns unsubscribe. */
990
- onStorageChange?: (listener: () => void) => () => void;
991
- /** Default: `Date.now` / `setTimeout` / `Math.random`. */
992
- clock?: RefreshClock;
993
- }
994
- /** How tabs of this origin coordinate token refresh (`PassflowConfig.refreshCoordination`). */
995
- type RefreshCoordination = 'web-locks' | 'none' | RefreshCoordinator;
996
- /** What asked for a refresh (`ErrorPayload.source`). */
997
- type RefreshTrigger =
998
- /** `Passflow.refreshToken()` / `AuthService.refreshToken()` */
999
- 'refresh-token' |
1000
- /** `TokenCacheService.getTokensWithRefresh()` */
1001
- 'token-check' |
1002
- /** `getTokens(true)` / `session({ doRefresh: true })` */
1003
- 'session' |
1004
- /** An SDK API call whose access token expires within 30 s */
1005
- 'pre-request' |
1006
- /** Step-up commit */
1007
- 'upgrade' |
1008
- /** The scheduled retry, with no new caller */
1009
- 'retry' |
1010
- /** The held-tab send */
1011
- 'held';
1012
- /** How a failed `/auth/refresh` is read (architecture §2.6). */
1013
- type RefreshFailureKind = 'transient' | 'blocked' | 'auth';
1014
- /** Refresh details on `ErrorPayload` for operations `refresh` and `upgrade.commit`. */
1015
- interface RefreshErrorInfo {
1016
- classification: RefreshFailureKind;
1017
- /** A retry is scheduled (transient, or auth with strikes left). */
1018
- willRetry: boolean;
1019
- /** Epoch ms of the retry, when `willRetry`. */
1020
- nextRetryAt?: number;
1021
- /** Auth failures since the last success, after this one. */
1022
- strikes: number;
1023
- /** Resolved `refreshStrikes`. */
1024
- maxStrikes: number;
1025
- }
1026
- /** Whether an event was caused by this tab's own action or learnt from another tab. */
1027
- type EventOrigin = 'this-tab' | 'other-tab';
1028
- /** Why a session ended (`SessionExpired.reason`). */
1029
- type SessionExpiredReason =
1030
- /** `refreshStrikes` auth failures (this tab, or another tab of the lineage). */
1031
- 'refresh_failed' |
1032
- /** `error.token.blocked` and no successor within 20 s; this tab only. */
1033
- 'successor_timeout' |
1034
- /** Storage now holds another user's tokens. */
1035
- 'identity_changed' |
1036
- /** Legacy members, never emitted. */
1037
- 'token_invalid' | 'logged_out';
1038
- export type RequestOptions<D> = {
1039
- data?: D;
1040
- config?: AxiosRequestConfig;
1041
- };
1042
- export declare enum RequestMethod {
1043
- GET = "get",
1044
- POST = "post",
1045
- PUT = "put",
1046
- PATCH = "patch",
1047
- DELETE = "delete"
1048
- }
1049
- export declare enum PassflowEndpointPaths {
1050
- signin = "/auth/login",
1051
- signup = "/auth/register",
1052
- pkceExchange = "/auth/pkce_exchange",
1053
- redirectCheck = "/auth/redirect/check",
1054
- signInWithProvider = "/auth/federated/start/",
1055
- passwordless = "/auth/passwordless/start",
1056
- passwordlessComplete = "/auth/passwordless/complete",
1057
- passwordlessStatus = "/auth/passwordless/status",
1058
- passwordlessApprovalInfo = "/auth/passwordless/approval/info",
1059
- passwordlessApprovalDecide = "/auth/passwordless/approval/decide",
1060
- logout = "/user/logout",
1061
- refresh = "/auth/refresh",
1062
- validateSession = "/user/me",
1063
- sendPasswordResetEmail = "/auth/password/reset",
1064
- resetPassword = "/auth/password/change",
1065
- appSettings = "/app/settings",
1066
- passkeyRegisterStart = "/auth/passkey/register/start",
1067
- passkeyRegisterComplete = "/auth/passkey/register/complete",
1068
- passkeyAuthenticateStart = "/auth/passkey/authenticate/start",
1069
- passkeyAuthenticateComplete = "/auth/passkey/authenticate/complete",
1070
- passkeyValidate = "/auth/validate",
1071
- settingsAll = "/settings",
1072
- settingsPasswordPolicy = "/settings/password",
1073
- settingsPasskey = "/settings/passkey",
1074
- userPasskey = "/user/passkey",
1075
- addUserPasskey = "/user/passkey/add/start",
1076
- completeAddUserPasskey = "/user/passkey/add/complete",
1077
- userSessions = "/user/sessions",
1078
- userSessionsRevokeOthers = "/user/sessions/revoke-others",
1079
- joinInvitation = "/user/tenant/join",
1080
- tenantPath = "/user/tenant",
1081
- invitationsPath = "/user/tenant/:tenantID/invitations",
1082
- requestInvitation = "/user/invite",
1083
- invitationDelete = "/user/invite/:invitationID",
1084
- invitationResend = "/user/invite/:invitationID/resend",
1085
- invitationGetLink = "/user/invite/:invitationID/link",
1086
- twoFactor = "/user/2fa",
1087
- twoFactorStatus = "/user/2fa/status",
1088
- twoFactorSetupBegin = "/user/2fa/setup/begin",
1089
- twoFactorSetupConfirm = "/user/2fa/setup/confirm",
1090
- twoFactorVerify = "/auth/2fa/verify",
1091
- twoFactorRecovery = "/auth/2fa/recovery",
1092
- twoFactorRegenerateCodes = "/user/2fa/recovery-codes/regenerate",
1093
- twoFactorSetupMagicLink = "/auth/2fa-setup", // :token param appended in API call
1094
- twoFactorEnrollment = "/auth/2fa/enrollment",
1095
- twoFactorEnrollmentEmailLink = "/auth/2fa/enrollment/email-link",
1096
- twoFactorEnrollmentBegin = "/auth/2fa/setup/begin",
1097
- twoFactorEnrollmentConfirm = "/auth/2fa/setup/confirm",
1098
- TwoFactorMethodsAvailable = "/v2/user/2fa/methods/available",
1099
- TwoFactorMethodsRegistered = "/v2/user/2fa/methods",
1100
- TwoFactorSetupStart = "/v2/user/2fa/setup/start",
1101
- TwoFactorSetupComplete = "/v2/user/2fa/setup/complete",
1102
- TwoFactorMethodRemove = "/v2/user/2fa/methods/:id",
1103
- TwoFactorChallenge = "/v2/auth/2fa/challenge",
1104
- TwoFactorVerifyV2 = "/v2/auth/2fa/verify",
1105
- TwoFactorAlternative = "/v2/auth/2fa/alternative",
1106
- TwoFactorTrustedDevices = "/v2/user/2fa/trusted-devices",
1107
- TwoFactorTrustedDeviceRevoke = "/v2/user/2fa/trusted-devices/:id",
1108
- cliAuthStatus = "/cli/auth/status/:sessionId",
1109
- cliAuthComplete = "/cli/auth/complete",
1110
- upgradeStart = "/auth/upgrade/start",
1111
- hostedUpgradeStart = "/auth/session/upgrade/start",
1112
- hostedUpgrade = "/auth/session/upgrade"
1113
- }
1114
- export declare enum PassflowAdminEndpointPaths {
1115
- passkeyRegisterStart = "/admin/auth/passkey/register/start",
1116
- passkeyRegisterComplete = "/admin/auth/passkey/register/complete",
1117
- passkeyAuthenticateStart = "/admin/auth/passkey/authenticate/start",
1118
- passkeyAuthenticateComplete = "/admin/auth/passkey/authenticate/complete",
1119
- passkeyValidate = "/admin/auth/validate",
1120
- logout = "/admin/auth/logout"
1121
- }
1122
- /**
1123
- * BFF (Backend-for-Frontend) configuration for secure token storage.
1124
- * When enabled, tokens are sent to the BFF server which stores them in httpOnly cookies.
1125
- */
1126
- export type TokenExchangeConfig = {
1127
- /**
1128
- * Enable token exchange mode. When true, authorization code is sent to your server
1129
- * for token exchange instead of being exchanged directly from the browser.
1130
- */
1131
- enabled: boolean;
1132
- /**
1133
- * URL to send authorization code for server-side token exchange.
1134
- * Your server exchanges the code for tokens and stores them in httpOnly cookies.
1135
- * @example '/api/auth/callback'
1136
- */
1137
- callbackUrl: string;
1138
- /**
1139
- * URL to call for token refresh. BFF reads refresh_token from httpOnly cookie
1140
- * and returns new tokens (also stored in cookies).
1141
- * @example '/api/auth/refresh'
1142
- */
1143
- refreshUrl?: string;
1144
- /**
1145
- * URL to call for logout. BFF clears httpOnly cookies.
1146
- * @example '/api/auth/logout'
1147
- */
1148
- logoutUrl?: string;
1149
- /**
1150
- * URL to check authentication status (whether httpOnly cookies are valid).
1151
- * @example '/api/auth/status'
1152
- */
1153
- statusUrl?: string;
1154
- };
1155
- /** @deprecated Use TokenExchangeConfig instead */
1156
- export type BFFConfig = TokenExchangeConfig;
1157
- export type PassflowConfig = {
1158
- url?: string;
1159
- appId?: string;
1160
- scopes?: string[];
1161
- createTenantForNewUser?: boolean;
1162
- parseQueryParams?: boolean;
1163
- /**
1164
- * Leaves a federated `?code=` landing alone in the constructor and in `handleTokensRedirect`,
1165
- * so that only `completeFederatedLanding()` takes it. For hosts that build the instance during
1166
- * render and may discard it. Token and `#tfa_token` landings are not affected.
1167
- */
1168
- deferFederatedLanding?: boolean;
1169
- keyStoragePrefix?: string;
1170
- /**
1171
- * Token exchange configuration for secure server-side token handling.
1172
- * When enabled, authorization code is sent to your server which exchanges it
1173
- * for tokens and stores them in httpOnly cookies. Tokens never touch the browser.
1174
- */
1175
- tokenExchange?: TokenExchangeConfig;
1176
- /**
1177
- * Platform adapter for cross-platform compatibility.
1178
- * Defaults to WebAdapter (browser APIs) if not provided.
1179
- * Pass a custom adapter to support React Native or other platforms.
1180
- */
1181
- platform?: PlatformAdapter;
1182
- /**
1183
- * Assurance upgrade (step-up) configuration. Construction-time only: the
1184
- * prompt handler is deliberately NOT here, because it is a lifetime-scoped
1185
- * resource that has to be torn down, which configuration cannot express.
1186
- */
1187
- upgrade?: PassflowUpgradeConfig;
1188
- /**
1189
- * How tabs of this origin coordinate token refresh.
1190
- * - `'web-locks'` (default): a Web Lock plus a BroadcastChannel, on a browser page whose
1191
- * `platform.storage` is shared by every tab (the default web adapter's localStorage) and that
1192
- * has `navigator.locks` and `BroadcastChannel`. Elsewhere it falls back to `'none'`; on a
1193
- * browser page with shared storage the fallback writes one `[passflow]` warning, at the first
1194
- * refresh.
1195
- * - `'none'`: no cross-tab coordination. Single flight within this instance, compare-and-set
1196
- * save, per-instance retries.
1197
- * - a `RefreshCoordinator` object: the same protocol as `'web-locks'` over the transports
1198
- * you supply (tests, Electron, custom hosts). Never falls back.
1199
- */
1200
- refreshCoordination?: RefreshCoordination;
1201
- /**
1202
- * Authentication failures of `/auth/refresh` counted since the last successful refresh or
1203
- * adoption, after which the session ends. Transient failures in between neither add a strike nor
1204
- * reset the count. Default 3. A non-integer is floored; a value below 1 or not a finite number
1205
- * uses the default.
1206
- */
1207
- refreshStrikes?: number;
1208
- };
1209
- export type PassflowUpgradeConfig = {
1210
- /** Relying-party id forwarded verbatim to `POST /auth/upgrade/start` for passkey upgrades. */
1211
- relyingPartyId?: string;
1212
- /** Overrides the factor set offered during an upgrade. Defaults to what this SDK can complete. */
1213
- factors?: readonly UpgradeFactor[];
1214
- };
1215
- /**
1216
- * Passflow's own API, as an interception scope — "domain 1".
1217
- *
1218
- * A challenge arriving from here is handled with zero configuration, because
1219
- * `url` is an input the SDK already takes and whatever it points at is
1220
- * unambiguously ours.
1221
- */
1222
- export type UpgradeDomain = {
1223
- /** The API origin, e.g. `https://api.passflow.dev`. */
1224
- origin: string;
1225
- /** The path prefix when `url` carries one, normalised without a trailing slash. */
1226
- pathPrefix?: string;
1227
- };
1228
- /**
1229
- * Resolves domain 1 from `PassflowConfig.url`.
1230
- *
1231
- * `url` is OPTIONAL, and the absent case is specified rather than guessed: the
1232
- * domain is EMPTY (`null`), and nothing throws. Throwing would break apps that
1233
- * never enabled step-up, and substituting a default origin — `PASSFLOW_CLOUD_URL`,
1234
- * the document origin, the origin the first 401 came from — would be the SDK
1235
- * inferring a trust boundary it has no information about. An empty domain is not
1236
- * silent: the first parseable challenge on an attached surface must raise a
1237
- * diagnostic naming `url` as the fix.
1238
- *
1239
- * Note this deliberately does NOT mirror `AxiosClient`'s `url || PASSFLOW_CLOUD_URL`
1240
- * fallback. That fallback decides where to send our own traffic; this decides
1241
- * whose 401s may drive a security prompt, and the two questions do not share an
1242
- * answer.
1243
- */
1244
- export declare const resolveUpgradeDomain: (url?: string) => UpgradeDomain | null;
1245
- /** The raw `POST /auth/upgrade/start` body, snake_case exactly as the server sends it. */
1246
- export type UpgradeStartWire = {
1247
- challenge_id: string;
1248
- method: string;
1249
- /** RFC 3339. The server enforces the TTL; the SDK carries this for display only. */
1250
- expires_at: string;
1251
- /** WebAuthn assertion options, present only for a passkey upgrade. */
1252
- webauthn?: PublicKeyCredentialRequestOptionsJSON;
1253
- /** Masked delivery target (`j***@x.com`), present only for email / SMS OTP. */
1254
- code_sent_to?: string;
1255
- };
1256
- /**
1257
- * The `upgrade` field of `POST /auth/refresh` — the commit round.
1258
- * Also the whole body of `POST /auth/session/upgrade`.
1259
- *
1260
- * The server types `assertion` as `json.RawMessage`, so a new factor can extend
1261
- * the payload without a wire-format change.
1262
- */
1263
- export type UpgradeRefreshField = {
1264
- type: string;
1265
- assertion: UpgradeAssertion;
1266
- };
1267
- export type PassflowAuthorizationResponse = Tokens & {
1268
- /**
1269
- * The authorization code a PKCE app answers with in place of tokens. The SDK
1270
- * redeems it, so a response handed back to a caller never carries one.
1271
- */
1272
- code?: string;
1273
- /** Where the server sends the user next; a password reset answers with its link's redirect. */
1274
- redirect_url?: string;
1275
- challenge_id?: string;
1276
- tfa_token?: string;
1277
- token_delivery?: 'json_body' | 'cookie' | 'mobile';
1278
- cookies?: string[];
1279
- csrf_token?: string;
1280
- /** `true` when the server needs the email proven before this sign-in finishes. No tokens come with it. */
1281
- email_verification_required?: boolean;
1282
- /** Human-readable text from the server, e.g. "We sent a code to a***@example.com." */
1283
- message?: string;
1284
- };
1285
- /**
1286
- * A sign-up, sign-in or password change that waits for the email to be proven.
1287
- * With `challenge_id`: a code was emailed, finish with `Passflow.verifyEmailCode`.
1288
- * Without: the code budget is spent and a link was emailed instead.
1289
- * `message` is what the server sent; a malformed answer may leave it out.
1290
- */
1291
- export type PassflowEmailVerificationStep = {
1292
- email_verification_required: true;
1293
- message: string;
1294
- challenge_id?: string;
1295
- };
1296
- /** The emailed code for a `PassflowEmailVerificationStep` that carried a `challenge_id`. */
1297
- export type PassflowEmailCodePayload = {
1298
- challenge_id: string;
1299
- otp: string;
1300
- };
1301
- /**
1302
- * Whether an auth answer is an email verification step rather than a session. Only the
1303
- * `email_verification_required` flag is checked, so an answer with the flag is never taken
1304
- * for a session.
1305
- */
1306
- export declare const isEmailVerificationStep: (response: unknown) => response is PassflowEmailVerificationStep;
1307
- export type PassflowValidationResponse = Tokens & {
1308
- redirect_url: string;
1309
- challenge_id?: string;
1310
- tfa_token?: string;
1311
- /** PKCE app: the code to redeem with the verifier, in place of tokens. */
1312
- code?: string;
1313
- };
1314
- export type PassflowSuccessResponse = {
1315
- result: 'ok';
1316
- };
1317
- export type PassflowLogoutResponse = {
1318
- status: 'ok';
1319
- };
1320
- export interface PassflowSessionValidationResponse {
1321
- valid: boolean;
1322
- user?: {
1323
- id: string;
1324
- email?: string;
1325
- username?: string;
1326
- [key: string]: unknown;
1327
- };
1328
- expires_at?: number;
1329
- }
1330
- export type PassflowResponseError = {
1331
- error: {
1332
- id: string;
1333
- message: string;
1334
- status: number;
1335
- location: string;
1336
- time: string;
1337
- };
1338
- };
1339
- /** Id of the error a call rejects with when the Passflow API cannot be reached or its gateway answers 502, 503 or 504. */
1340
- export declare const SERVICE_UNAVAILABLE_ERROR_ID = "error.service.unavailable";
1341
- /** Message of the {@link SERVICE_UNAVAILABLE_ERROR_ID} error. */
1342
- export declare const SERVICE_UNAVAILABLE_MESSAGE = "Passflow is temporarily unavailable. Please try again in a moment.";
1343
- export declare class PassflowError extends Error {
1344
- id: string;
1345
- message: string;
1346
- status: number;
1347
- location: string;
1348
- time: string;
1349
- /** Declared here rather than inherited: `Error.cause` is ES2022 and this build targets ES2021 libs. */
1350
- readonly cause?: unknown;
1351
- constructor(error: PassflowResponseError['error'], options?: {
1352
- cause?: unknown;
1353
- });
1220
+ export type PassflowResponseError = {
1221
+ error: {
1222
+ id: string;
1223
+ message: string;
1224
+ status: number;
1225
+ location: string;
1226
+ time: string;
1227
+ };
1228
+ };
1229
+ /** Id of the error a call rejects with when the Passflow API cannot be reached or its gateway answers 502, 503 or 504. */
1230
+ export declare const SERVICE_UNAVAILABLE_ERROR_ID = "error.service.unavailable";
1231
+ /** Message of the {@link SERVICE_UNAVAILABLE_ERROR_ID} error. */
1232
+ export declare const SERVICE_UNAVAILABLE_MESSAGE = "Passflow is temporarily unavailable. Please try again in a moment.";
1233
+ export declare class PassflowError extends Error {
1234
+ id: string;
1235
+ message: string;
1236
+ status: number;
1237
+ location: string;
1238
+ time: string;
1239
+ /** Declared here rather than inherited: `Error.cause` is ES2022 and this build targets ES2021 libs. */
1240
+ readonly cause?: unknown;
1241
+ constructor(error: PassflowResponseError['error'], options?: {
1242
+ cause?: unknown;
1243
+ });
1354
1244
  }
1355
1245
  /** Id of the 403 a password sign-in answers with when the user must change the password first. */
1356
1246
  export declare const PASSWORD_CHANGE_REQUIRED_ERROR_ID = "error.api.password.change.required";
1247
+ /** The covered request carried no `X-Passflow-Anti-Bot` header on a `human_only` app (403). */
1248
+ export declare const ANTI_BOT_REQUIRED_ERROR_ID = "error.api.anti_bot.required";
1249
+ /** The anti-bot value was wrong, expired or used before (403). The built-in check is resent once. */
1250
+ export declare const ANTI_BOT_FAILED_ERROR_ID = "error.api.anti_bot.failed";
1251
+ /** The server could not check the anti-bot value right now (503, `Retry-After`). */
1252
+ export declare const ANTI_BOT_UNAVAILABLE_ERROR_ID = "error.api.anti_bot.unavailable";
1253
+ /** A `human_only` app uses its own provider and `setAntiBotTokenProvider()` was not called. */
1254
+ export declare const ANTI_BOT_PROVIDER_MISSING_ERROR_ID = "error.anti_bot.provider_missing";
1255
+ /** The token provider rejected or returned an empty string. */
1256
+ export declare const ANTI_BOT_PROVIDER_FAILED_ERROR_ID = "error.anti_bot.provider_failed";
1257
+ /** The built-in proof of work could not be solved: no Web Crypto, a worker error, or no number found. */
1258
+ export declare const ANTI_BOT_SOLVE_FAILED_ERROR_ID = "error.anti_bot.solve_failed";
1357
1259
  /** The sign-in was refused until the user changes the password; no token comes with it. */
1358
1260
  export declare class PassflowPasswordChangeRequiredError extends PassflowError {
1359
1261
  constructor(error: PassflowResponseError['error'], options?: {
@@ -1589,6 +1491,60 @@ export type AppSettings = {
1589
1491
  login_app_theme: LoginWebAppTheme;
1590
1492
  login_app_settings?: unknown;
1591
1493
  token_delivery_method?: TokenDeliveryMethod;
1494
+ /** Absent on servers that do not report it, which means `bot_friendly`. */
1495
+ bot_mode?: BotMode;
1496
+ /** Only when `human_only`. Absent on a `human_only` app means the built-in check. */
1497
+ anti_bot?: AntiBotSettings;
1498
+ };
1499
+ /** `human_only`: every sign-in start must carry an anti-bot value in `X-Passflow-Anti-Bot`. */
1500
+ export type BotMode = 'bot_friendly' | 'human_only';
1501
+ /** `builtin` is Passflow's proof of work; the others are the customer's own provider. */
1502
+ export type AntiBotProviderName = 'builtin' | 'turnstile' | 'hcaptcha' | 'recaptcha';
1503
+ export type AntiBotSettings = {
1504
+ provider: AntiBotProviderName;
1505
+ /** The provider's public site key, for a widget. Absent for `builtin`. */
1506
+ site_key?: string;
1507
+ };
1508
+ /**
1509
+ * `POST /auth/anti-bot/challenge` and `POST /oidc/device/anti-bot/challenge`. The answer is the
1510
+ * integer `number` in `[0, max]` with `hex(SHA-256(salt + ":" + number)) === challenge`.
1511
+ */
1512
+ export type AntiBotChallenge = {
1513
+ algorithm: 'SHA-256';
1514
+ app: string;
1515
+ exp: number;
1516
+ max: number;
1517
+ salt: string;
1518
+ challenge: string;
1519
+ signature: string;
1520
+ };
1521
+ /** The decoded `X-Passflow-Anti-Bot` value of the built-in check. */
1522
+ export type AntiBotSolution = Omit<AntiBotChallenge, 'algorithm'> & {
1523
+ number: number;
1524
+ };
1525
+ /** Options of one sign-in call. */
1526
+ export type PassflowAuthOptions = {
1527
+ /**
1528
+ * Sends `X-Passflow-Agent-Tool: 1`. Set only by agent tool actions; the server then refuses a
1529
+ * device parent. A federated start with it is sent as a POST, because a header cannot ride a
1530
+ * navigation.
1531
+ */
1532
+ agentTool?: boolean;
1533
+ };
1534
+ /** `POST /auth/federated/start/{provider}`: the same fields the GET start takes as query parameters. */
1535
+ export type PassflowFederatedStartBody = {
1536
+ device?: string;
1537
+ redirect_url: string;
1538
+ scopes: string[];
1539
+ create_tenant?: boolean;
1540
+ invite_token?: string;
1541
+ parent_challenge_id?: string;
1542
+ code_challenge?: string;
1543
+ code_challenge_method?: 'S256';
1544
+ state?: string;
1545
+ };
1546
+ export type PassflowFederatedStartResponse = {
1547
+ auth_url: string;
1592
1548
  };
1593
1549
  /**
1594
1550
  * A write-only app secret that the admin API clears by name with
@@ -2025,171 +1981,604 @@ export type TwoFactorVerifyResponse = Tokens & TwoFactorParentAnswer & {
2025
1981
  code?: string;
2026
1982
  };
2027
1983
  /**
2028
- * Options for the call that completes a sign-in with its second factor.
1984
+ * Options for the call that completes a sign-in with its second factor.
1985
+ */
1986
+ export type TwoFactorCompletionOptions = {
1987
+ /**
1988
+ * Ask the server to trust this device, so later sign-ins from it skip the
1989
+ * second factor where the app allows that. The server keeps the trust in
1990
+ * an HttpOnly cookie; nothing is stored by the SDK.
1991
+ */
1992
+ trustDevice?: boolean;
1993
+ };
1994
+ /**
1995
+ * A device the user trusted to stand in for their second factor on this app.
1996
+ */
1997
+ export type TwoFactorTrustedDevice = {
1998
+ id: string;
1999
+ user_agent?: string;
2000
+ created_at: string;
2001
+ last_used_at?: string;
2002
+ expires_at: string;
2003
+ /** True for the device the request came from. */
2004
+ current: boolean;
2005
+ };
2006
+ /** GET /v2/user/2fa/trusted-devices */
2007
+ export type TwoFactorTrustedDevicesResponse = {
2008
+ devices: TwoFactorTrustedDevice[];
2009
+ };
2010
+ export type TwoFactorRecoveryResponse = Tokens & {
2011
+ success?: true;
2012
+ /** Codes left after this one. The server may leave it out. */
2013
+ remaining_recovery_codes?: number;
2014
+ /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
2015
+ code?: string;
2016
+ };
2017
+ export type TwoFactorDisableResponse = {
2018
+ disabled: true;
2019
+ };
2020
+ export type TwoFactorRegenerateResponse = {
2021
+ recovery_codes: string[];
2022
+ };
2023
+ /**
2024
+ * Two-Factor magic link error codes
2025
+ */
2026
+ export type TwoFactorSetupMagicLinkErrorCode = 'INVALID_TOKEN' | 'EXPIRED_TOKEN' | 'REVOKED_TOKEN' | 'ALREADY_USED' | 'RATE_LIMITED' | 'SERVER_ERROR';
2027
+ /**
2028
+ * Two-Factor magic link error details
2029
+ */
2030
+ export type TwoFactorSetupMagicLinkError = {
2031
+ code: TwoFactorSetupMagicLinkErrorCode;
2032
+ message: string;
2033
+ retryAfter?: number;
2034
+ };
2035
+ /**
2036
+ * Response from magic link validation endpoint
2037
+ * Backend returns scoped session token for 2FA setup operations
2038
+ */
2039
+ export type TwoFactorSetupMagicLinkValidationResponse = {
2040
+ success: boolean;
2041
+ sessionToken?: string;
2042
+ userId?: string;
2043
+ expiresIn?: number;
2044
+ appId?: string | null;
2045
+ error?: TwoFactorSetupMagicLinkError;
2046
+ };
2047
+ /**
2048
+ * Internal session state for magic link 2FA setup
2049
+ * Stored in memory only, not persisted across page reloads
2050
+ */
2051
+ export type TwoFactorSetupMagicLinkSession = {
2052
+ sessionToken: string;
2053
+ userId: string;
2054
+ appId?: string | null;
2055
+ scope: '2fa_setup';
2056
+ timestamp: number;
2057
+ expiresAt: number;
2058
+ };
2059
+ /**
2060
+ * Two-Factor method types
2061
+ */
2062
+ export type TwoFactorMethod = 'totp' | 'email_otp' | 'sms_otp' | 'passkey' | 'push_fcm' | 'push_webpush' | 'recovery_codes';
2063
+ /**
2064
+ * Challenge Request for v2 2FA flow
2065
+ */
2066
+ export interface TwoFactorChallengeRequest {
2067
+ first_factor_method?: string;
2068
+ trust_device?: boolean;
2069
+ }
2070
+ /**
2071
+ * Challenge Response from v2 2FA flow
2072
+ */
2073
+ export interface TwoFactorChallengeResponse {
2074
+ challenge_id: string;
2075
+ method: TwoFactorMethod;
2076
+ /** Other methods the user can switch to. Absent from the answer to a switch. */
2077
+ alternative_methods?: TwoFactorMethod[];
2078
+ expires_at: string;
2079
+ code_sent_to?: string;
2080
+ webauthn_options?: unknown;
2081
+ /** Digits in the TOTP code. TOTP challenges only. */
2082
+ totp_digits?: 6 | 8;
2083
+ /** Seconds per TOTP step. TOTP challenges only. */
2084
+ totp_period?: number;
2085
+ /**
2086
+ * Whether this sign-in may ask to trust the device (`trust_device`), as the app allows.
2087
+ * Absent from servers older than the flag; treat absent as unknown.
2088
+ */
2089
+ device_trust_available?: boolean;
2090
+ }
2091
+ /**
2092
+ * Verify Request for v2 2FA flow
2093
+ */
2094
+ export interface TwoFactorVerifyRequestV2 {
2095
+ challenge_id: string;
2096
+ method: TwoFactorMethod;
2097
+ response: string;
2098
+ trust_device?: boolean;
2099
+ }
2100
+ /**
2101
+ * Verify Response from v2 2FA flow
2102
+ */
2103
+ export interface TwoFactorVerifyResponseV2 extends TwoFactorParentAnswer {
2104
+ access_token?: string;
2105
+ refresh_token?: string;
2106
+ id_token?: string;
2107
+ /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
2108
+ code?: string;
2109
+ }
2110
+ /**
2111
+ * Registered Two-Factor Method
2112
+ */
2113
+ export interface RegisteredTwoFactorMethod {
2114
+ id?: string;
2115
+ method: TwoFactorMethod;
2116
+ name?: string;
2117
+ user_id?: string;
2118
+ app_id?: string;
2119
+ /** `true` when this passkey also signs the user in as the first factor. */
2120
+ is_passkey_for_1fa?: boolean;
2121
+ created_at?: string;
2122
+ updated_at?: string;
2123
+ last_used_at?: string;
2124
+ }
2125
+ /**
2126
+ * Alternative Method Request
2127
+ */
2128
+ export interface TwoFactorAlternativeRequest {
2129
+ challenge_id: string;
2130
+ method: TwoFactorMethod;
2131
+ }
2132
+ export interface CLIAuthStatusResponse {
2133
+ status: 'pending' | 'completed' | 'expired' | 'failed';
2134
+ expires_at?: string;
2135
+ challenge?: Record<string, unknown>;
2136
+ access_token?: string;
2137
+ refresh_token?: string;
2138
+ user_id?: string;
2139
+ expires_in?: number;
2140
+ error?: string;
2141
+ }
2142
+ export interface CLIAuthCompleteRequest {
2143
+ session_id: string;
2144
+ access_token: string;
2145
+ refresh_token: string;
2146
+ user_id: string;
2147
+ expires_in: number;
2148
+ }
2149
+ /** The covered call an anti-bot value is produced for. */
2150
+ type AntiBotOperation = 'sign-in' | 'sign-up' | 'passwordless.start' | 'passkey.register' | 'passkey.authenticate' | 'password-reset.send' | 'federated.start' | 'session.exchange' | 'device.authenticate' | 'device.passkey.start';
2151
+ /** What a token provider is asked for. `action` is always `'passflow_auth'`. */
2152
+ type AntiBotTokenContext = {
2153
+ action: 'passflow_auth';
2154
+ operation: AntiBotOperation;
2155
+ };
2156
+ /**
2157
+ * The customer's own anti-bot provider (Turnstile, hCaptcha, reCAPTCHA): resolves with a token
2158
+ * the server verifies with that provider. A function with no parameters is accepted too.
2159
+ */
2160
+ type AntiBotTokenProvider = (context: AntiBotTokenContext) => Promise<string>;
2161
+ /** The device verification page's context for `POST /oidc/device/anti-bot/challenge`. */
2162
+ type AntiBotDeviceContext = {
2163
+ userCode: string;
2164
+ csrfToken: string;
2165
+ };
2166
+ /** The bot mode and provider an anti-bot value is produced for. */
2167
+ type AntiBotAppSettings = Pick<AppSettings, 'bot_mode' | 'anti_bot'>;
2168
+ type AntiBotTokenRequest = {
2169
+ operation: AntiBotOperation;
2170
+ /** Email, username or phone, sent with the challenge request; used by the server for difficulty only. */
2171
+ identifier?: string;
2172
+ /** Bot mode and provider when not this app's `/app/settings` (the device page: `/oidc/device/info`). */
2173
+ settings?: AntiBotAppSettings;
2174
+ device?: AntiBotDeviceContext;
2175
+ };
2176
+ declare class DeviceService {
2177
+ private storageManager;
2178
+ /** The id this service minted; used when the storage keeps nothing (server rendering). */
2179
+ private mintedDeviceId;
2180
+ constructor(storageManager?: StorageManager);
2181
+ getDeviceId(): string;
2182
+ generateUniqueDeviceId(): string;
2183
+ }
2184
+ /**
2185
+ * Passflow event types
2029
2186
  */
2030
- export type TwoFactorCompletionOptions = {
2187
+ export declare enum PassflowEvent {
2188
+ SignIn = "signin",
2189
+ SignInStart = "signin:start",
2190
+ Register = "register",
2191
+ RegisterStart = "register:start",
2192
+ /** A sign-up, sign-in or password change is waiting for the email to be proven (no session yet). */
2193
+ EmailVerificationRequired = "email-verification:required",
2194
+ SignOut = "signout",
2195
+ SessionRestored = "session:restored",
2196
+ SessionExpired = "session:expired",
2197
+ Error = "error",
2198
+ Refresh = "refresh",
2199
+ RefreshStart = "refresh:start",
2200
+ TokenCacheExpired = "token-cache-expired",
2201
+ TwoFactorRequired = "2fa:required",
2202
+ TwoFactorSetupStarted = "2fa:setup_started",
2203
+ TwoFactorEnabled = "2fa:enabled",
2204
+ TwoFactorDisabled = "2fa:disabled",
2205
+ TwoFactorVerified = "2fa:verified",
2206
+ TwoFactorRecoveryUsed = "2fa:recovery_used",
2207
+ TwoFactorRecoveryCodesLow = "2fa:recovery_low",
2208
+ TwoFactorRecoveryCodesExhausted = "2fa:recovery_exhausted",
2209
+ TwoFactorSetupMagicLinkValidated = "2fa:magic_link_validated",
2210
+ TwoFactorSetupMagicLinkFailed = "2fa:magic_link_failed",
2211
+ TwoFactorChallengeReceived = "two_factor_challenge_received",
2212
+ TwoFactorMethodSwitched = "two_factor_method_switched",
2031
2213
  /**
2032
- * Ask the server to trust this device, so later sign-ins from it skip the
2033
- * second factor where the app allows that. The server keeps the trust in
2034
- * an HttpOnly cookie; nothing is stored by the SDK.
2214
+ * @deprecated The server keeps device trust in a cookie and the SDK no longer emits this event.
2035
2215
  */
2036
- trustDevice?: boolean;
2037
- };
2216
+ TwoFactorDeviceTrusted = "two_factor_device_trusted",
2217
+ /** Token refresh entered a transient-failure episode (once per episode, per tab). */
2218
+ RefreshFailing = "refresh:failing",
2219
+ /** The transient-failure episode ended with a successful refresh or adoption. */
2220
+ RefreshRecovered = "refresh:recovered",
2221
+ /** A `human_only` app's covered call started producing its anti-bot value (a proof of work, or the provider's token). */
2222
+ AntiBotSolving = "anti-bot:solving",
2223
+ /** The anti-bot value is ready; the covered request goes out next. */
2224
+ AntiBotSolved = "anti-bot:solved"
2225
+ }
2038
2226
  /**
2039
- * A device the user trusted to stand in for their second factor on this app.
2227
+ * The SDK operation that failed (`ErrorPayload.operation`). The SDK sets it on every `Error` it
2228
+ * emits, so a subscriber can tell a failed sign-in from a failed refresh without parsing messages.
2040
2229
  */
2041
- export type TwoFactorTrustedDevice = {
2042
- id: string;
2043
- user_agent?: string;
2044
- created_at: string;
2045
- last_used_at?: string;
2046
- expires_at: string;
2047
- /** True for the device the request came from. */
2048
- current: boolean;
2049
- };
2050
- /** GET /v2/user/2fa/trusted-devices */
2051
- export type TwoFactorTrustedDevicesResponse = {
2052
- devices: TwoFactorTrustedDevice[];
2053
- };
2054
- export type TwoFactorRecoveryResponse = Tokens & {
2055
- success?: true;
2056
- /** Codes left after this one. The server may leave it out. */
2057
- remaining_recovery_codes?: number;
2058
- /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
2059
- code?: string;
2060
- };
2061
- export type TwoFactorDisableResponse = {
2062
- disabled: true;
2063
- };
2064
- export type TwoFactorRegenerateResponse = {
2065
- recovery_codes: string[];
2066
- };
2230
+ type PassflowOperation = 'sign-in' | 'sign-up' | 'passwordless.start' | 'passwordless.complete' | 'passwordless.wait' | 'passwordless.approval' | 'password-reset.send' | 'password-reset.complete' | 'email-verification.complete' | 'passkey.register' | 'passkey.authenticate' | 'federated.popup' | 'federated.redirect' | 'auth-redirect.url' | 'auth-redirect' | 'redirect.check' | 'auth.is-authenticated' | 'session.check' | 'session.list' | 'session.revoke' | 'session.revoke-others' | 'tokens.get' | 'tokens.load' | 'tokens.from-url' | 'oidc.redirect' | 'refresh' | 'upgrade.commit' | 'log-out' | 'reset' | 'anti-bot.token' | 'settings.app' | 'settings.all' | 'settings.password-policy' | 'settings.passkey' | 'passkey.list' | 'passkey.rename' | 'passkey.delete' | 'passkey.add' | 'tenant.create' | 'invitation.join' | 'invitation.request-link' | 'invitation.list' | 'invitation.delete' | 'invitation.resend' | 'invitation.get-link' | '2fa.status' | '2fa.setup.begin' | '2fa.setup.confirm' | '2fa.enrollment.read' | '2fa.enrollment.setup-link' | '2fa.verify' | '2fa.recovery.use' | '2fa.disable' | '2fa.recovery.regenerate' | '2fa.methods.available' | '2fa.methods.registered' | '2fa.method.setup.start' | '2fa.method.setup.complete' | '2fa.method.remove' | '2fa.challenge.request' | '2fa.challenge.verify' | '2fa.method.switch' | '2fa.trusted-devices.list' | '2fa.trusted-devices.revoke';
2067
2231
  /**
2068
- * Two-Factor magic link error codes
2232
+ * Error payload interface for structured error information
2069
2233
  */
2070
- export type TwoFactorSetupMagicLinkErrorCode = 'INVALID_TOKEN' | 'EXPIRED_TOKEN' | 'REVOKED_TOKEN' | 'ALREADY_USED' | 'RATE_LIMITED' | 'SERVER_ERROR';
2234
+ interface ErrorPayload {
2235
+ message: string;
2236
+ code?: string | number;
2237
+ details?: unknown;
2238
+ originalError?: unknown;
2239
+ /** The operation that failed. Always set by the SDK. */
2240
+ operation?: PassflowOperation;
2241
+ /** For operation `refresh` | `upgrade.commit`: what asked for the refresh. */
2242
+ source?: RefreshTrigger;
2243
+ /** For operation `refresh` | `upgrade.commit`: how the failure was classified and what follows. */
2244
+ refresh?: RefreshErrorInfo;
2245
+ }
2246
+ /** An `Error` payload as the SDK reports it: `operation` is required. */
2247
+ type OperationErrorPayload = ErrorPayload & {
2248
+ operation: PassflowOperation;
2249
+ };
2250
+ /** Which call produced an `EmailVerificationRequired` event. */
2251
+ type PassflowEmailVerificationOperation = 'sign-up' | 'sign-in' | 'reset-password';
2071
2252
  /**
2072
- * Two-Factor magic link error details
2253
+ * Event-specific payload types
2073
2254
  */
2074
- export type TwoFactorSetupMagicLinkError = {
2075
- code: TwoFactorSetupMagicLinkErrorCode;
2076
- message: string;
2077
- retryAfter?: number;
2255
+ type PassflowEventPayload = {
2256
+ [PassflowEvent.SignIn]: {
2257
+ tokens?: Tokens;
2258
+ parsedTokens?: ParsedTokens;
2259
+ /** `'other-tab'` only when an ended tab revives on a new session found in storage. Absent on this tab's own sign-in. */
2260
+ origin?: EventOrigin;
2261
+ /**
2262
+ * `'federated-landing'`: a federated redirect landed here and this instance exchanged its code.
2263
+ * `'tokens-in-url'`: tokens received in this page's URL were verified and saved.
2264
+ * `'oidc-landing'`: hosted sign-in returned an authorization code here and this instance redeemed it.
2265
+ */
2266
+ source?: 'federated-landing' | 'tokens-in-url' | 'oidc-landing';
2267
+ /** For `source: 'tokens-in-url'`: the `state` the URL carried with the tokens, when it had one. */
2268
+ state?: string;
2269
+ };
2270
+ [PassflowEvent.SignInStart]: {
2271
+ email?: string;
2272
+ provider?: string;
2273
+ };
2274
+ [PassflowEvent.Register]: {
2275
+ tokens?: Tokens;
2276
+ parsedTokens?: ParsedTokens;
2277
+ };
2278
+ [PassflowEvent.RegisterStart]: {
2279
+ email?: string;
2280
+ };
2281
+ [PassflowEvent.EmailVerificationRequired]: {
2282
+ /** The address the code or link went to, when the SDK knows it. */
2283
+ email?: string;
2284
+ /** Present when a code was emailed; absent when a link was emailed instead. */
2285
+ challengeId?: string;
2286
+ operation: PassflowEmailVerificationOperation;
2287
+ };
2288
+ [PassflowEvent.SignOut]: {
2289
+ /** `sub` of the session that ended, when known. */
2290
+ userId?: string;
2291
+ /** Always set by the SDK. `'other-tab'`: another tab signed out, or shared storage was emptied. */
2292
+ origin?: EventOrigin;
2293
+ };
2294
+ [PassflowEvent.SessionRestored]: {
2295
+ id: string;
2296
+ email?: string;
2297
+ username?: string;
2298
+ [key: string]: unknown;
2299
+ };
2300
+ [PassflowEvent.SessionExpired]: {
2301
+ reason: SessionExpiredReason;
2302
+ /** Always set by the SDK. */
2303
+ origin?: EventOrigin;
2304
+ };
2305
+ [PassflowEvent.Error]: ErrorPayload;
2306
+ [PassflowEvent.Refresh]: {
2307
+ tokens?: Tokens;
2308
+ parsedTokens?: ParsedTokens;
2309
+ /**
2310
+ * Always set by the SDK. `'refresh'`: this tab's request; `'upgrade'`: this tab's step-up
2311
+ * commit; `'adopted'`: tokens this tab did not request (another tab's, or found in storage).
2312
+ */
2313
+ source?: 'refresh' | 'upgrade' | 'adopted';
2314
+ };
2315
+ [PassflowEvent.RefreshStart]: {
2316
+ tokenId?: string;
2317
+ };
2318
+ [PassflowEvent.TokenCacheExpired]: {
2319
+ isExpired: boolean;
2320
+ };
2321
+ [PassflowEvent.TwoFactorRequired]: {
2322
+ email: string;
2323
+ challengeId: string;
2324
+ tfaToken: string;
2325
+ };
2326
+ [PassflowEvent.TwoFactorSetupStarted]: {
2327
+ secret: string;
2328
+ method?: TwoFactorMethod;
2329
+ };
2330
+ [PassflowEvent.TwoFactorEnabled]: {
2331
+ recoveryCodes: string[];
2332
+ clearRecoveryCodes: () => void;
2333
+ };
2334
+ [PassflowEvent.TwoFactorDisabled]: Record<string, never>;
2335
+ [PassflowEvent.TwoFactorVerified]: {
2336
+ tokens?: Tokens;
2337
+ };
2338
+ /** `remainingCodes` is undefined when the server did not send the count. */
2339
+ [PassflowEvent.TwoFactorRecoveryUsed]: {
2340
+ tokens?: Tokens;
2341
+ remainingCodes?: number;
2342
+ };
2343
+ [PassflowEvent.TwoFactorRecoveryCodesLow]: {
2344
+ tokens?: Tokens;
2345
+ remainingCodes: number;
2346
+ };
2347
+ [PassflowEvent.TwoFactorRecoveryCodesExhausted]: {
2348
+ tokens?: Tokens;
2349
+ };
2350
+ [PassflowEvent.TwoFactorSetupMagicLinkValidated]: {
2351
+ userId: string;
2352
+ appId?: string | null;
2353
+ expiresIn: number;
2354
+ sessionToken: string;
2355
+ };
2356
+ [PassflowEvent.TwoFactorSetupMagicLinkFailed]: {
2357
+ error: {
2358
+ code: 'INVALID_TOKEN' | 'EXPIRED_TOKEN' | 'REVOKED_TOKEN' | 'ALREADY_USED' | 'RATE_LIMITED' | 'SERVER_ERROR';
2359
+ message: string;
2360
+ retryAfter?: number;
2361
+ };
2362
+ };
2363
+ [PassflowEvent.TwoFactorChallengeReceived]: {
2364
+ challengeId: string;
2365
+ method: TwoFactorMethod;
2366
+ alternativeMethods: TwoFactorMethod[];
2367
+ };
2368
+ [PassflowEvent.TwoFactorMethodSwitched]: {
2369
+ challengeId: string;
2370
+ method: TwoFactorMethod;
2371
+ alternativeMethods: TwoFactorMethod[];
2372
+ };
2373
+ [PassflowEvent.TwoFactorDeviceTrusted]: Record<string, never>;
2374
+ [PassflowEvent.RefreshFailing]: {
2375
+ /** Epoch ms of the episode's first transient failure. */
2376
+ since: number;
2377
+ /** Epoch ms of the shared pending retry, when known. */
2378
+ nextRetryAt?: number;
2379
+ /** `'this-tab'` when this tab's own request failed. */
2380
+ origin: EventOrigin;
2381
+ };
2382
+ [PassflowEvent.RefreshRecovered]: {
2383
+ /** Same value as the `RefreshFailing` that opened the episode. */
2384
+ since: number;
2385
+ /** `'this-tab'`: own request succeeded; `'other-tab'`: adopted another tab's tokens. */
2386
+ origin: EventOrigin;
2387
+ };
2388
+ [PassflowEvent.AntiBotSolving]: {
2389
+ operation: AntiBotOperation;
2390
+ provider: AntiBotProviderName;
2391
+ };
2392
+ [PassflowEvent.AntiBotSolved]: {
2393
+ operation: AntiBotOperation;
2394
+ provider: AntiBotProviderName;
2395
+ };
2078
2396
  };
2079
2397
  /**
2080
- * Response from magic link validation endpoint
2081
- * Backend returns scoped session token for 2FA setup operations
2398
+ * Passflow subscriber interface
2082
2399
  */
2083
- export type TwoFactorSetupMagicLinkValidationResponse = {
2084
- success: boolean;
2085
- sessionToken?: string;
2086
- userId?: string;
2087
- expiresIn?: number;
2088
- appId?: string | null;
2089
- error?: TwoFactorSetupMagicLinkError;
2090
- };
2400
+ interface PassflowSubscriber {
2401
+ onAuthChange<E extends PassflowEvent>(eventType: E, payload?: PassflowEventPayload[E]): void;
2402
+ }
2091
2403
  /**
2092
- * Internal session state for magic link 2FA setup
2093
- * Stored in memory only, not persisted across page reloads
2404
+ * Store for managing Passflow event subscriptions
2094
2405
  */
2095
- export type TwoFactorSetupMagicLinkSession = {
2096
- sessionToken: string;
2097
- userId: string;
2098
- appId?: string | null;
2099
- scope: '2fa_setup';
2100
- timestamp: number;
2101
- expiresAt: number;
2406
+ declare class PassflowStore {
2407
+ private subscribers;
2408
+ /**
2409
+ * Subscribe to authentication events
2410
+ * @param subscriber The subscriber to register
2411
+ * @param events Optional specific events to subscribe to
2412
+ */
2413
+ subscribe(subscriber: PassflowSubscriber, events?: PassflowEvent[]): void;
2414
+ /**
2415
+ * Unsubscribe from authentication events
2416
+ * @param subscriber The subscriber to unregister
2417
+ * @param events Optional specific events to unsubscribe from
2418
+ */
2419
+ unsubscribe(subscriber: PassflowSubscriber, events?: PassflowEvent[]): void;
2420
+ /**
2421
+ * Notify subscribers of an event
2422
+ * @param eventType The type of event that occurred
2423
+ * @param payload Event-specific payload data
2424
+ */
2425
+ notify<E extends PassflowEvent>(eventType: E, payload?: PassflowEventPayload[E]): void;
2426
+ /**
2427
+ * Notify subscribers of an error, at most once per error object (`notifyError` in `error-report.ts`).
2428
+ * @returns whether the event was emitted
2429
+ */
2430
+ notifyError(payload: OperationErrorPayload): boolean;
2431
+ }
2432
+ /** A value for `X-Passflow-Anti-Bot`; `builtin` tells whether a `failed` answer may be resent once. */
2433
+ type AntiBotHeader = {
2434
+ value: string;
2435
+ builtin: boolean;
2102
2436
  };
2103
2437
  /**
2104
- * Two-Factor method types
2105
- */
2106
- export type TwoFactorMethod = 'totp' | 'email_otp' | 'sms_otp' | 'passkey' | 'push_fcm' | 'push_webpush' | 'recovery_codes';
2107
- /**
2108
- * Challenge Request for v2 2FA flow
2438
+ * Axios copies this object into each request's config (and each resend's), so the interceptors
2439
+ * may write `builtin` and `retried` on it.
2109
2440
  */
2110
- export interface TwoFactorChallengeRequest {
2111
- first_factor_method?: string;
2112
- trust_device?: boolean;
2113
- }
2441
+ type AntiBotMark = {
2442
+ operation: AntiBotOperation;
2443
+ identifier?: string;
2444
+ /** Set by the request interceptor: the value came from the built-in check. */
2445
+ builtin?: boolean;
2446
+ /** Set by the response interceptor before the one resend after `anti_bot.failed`. */
2447
+ retried?: boolean;
2448
+ };
2449
+ /** The error code RFC 9470 §3 defines for an insufficient authentication event. */
2450
+ export declare const INSUFFICIENT_USER_AUTHENTICATION = "insufficient_user_authentication";
2451
+ /** The ADR-2 error code `/auth/session/exchange` returns in its 403 body. */
2452
+ export declare const UPGRADE_REQUIRED = "upgrade_required";
2114
2453
  /**
2115
- * Challenge Response from v2 2FA flow
2454
+ * What the server demands before it will serve the original request.
2455
+ *
2456
+ * Both fields are optional because the two middlewares challenge on different
2457
+ * axes: RequireAuthLevel names an `acrValues` and omits `maxAge`, while
2458
+ * RequireFreshAuth does the reverse. A challenge carrying neither is still
2459
+ * valid — it means "re-prove a factor" without further qualification.
2116
2460
  */
2117
- export interface TwoFactorChallengeResponse {
2118
- challenge_id: string;
2119
- method: TwoFactorMethod;
2120
- /** Other methods the user can switch to. Absent from the answer to a switch. */
2121
- alternative_methods?: TwoFactorMethod[];
2122
- expires_at: string;
2123
- code_sent_to?: string;
2124
- webauthn_options?: unknown;
2125
- /** Digits in the TOTP code. TOTP challenges only. */
2126
- totp_digits?: 6 | 8;
2127
- /** Seconds per TOTP step. TOTP challenges only. */
2128
- totp_period?: number;
2461
+ type UpgradeChallenge = {
2129
2462
  /**
2130
- * Whether this sign-in may ask to trust the device (`trust_device`), as the app allows.
2131
- * Absent from servers older than the flag; treat absent as unknown.
2463
+ * Required authentication context class (`acr`), e.g. `'2'`.
2464
+ *
2465
+ * After a two-channel merge this is the raw list of the channel that SET THE
2466
+ * BAR, with the header preferred on a numeric tie. A channel that contributed
2467
+ * no level never supplies it — showing `"2gold"` as the bar would
2468
+ * misrepresent what the server demanded.
2132
2469
  */
2133
- device_trust_available?: boolean;
2134
- }
2470
+ acrValues?: string;
2471
+ /**
2472
+ * The parsed bar: `max` over each channel's `min` participating level
2473
+ * (§13.2.1a). `undefined` means unknown or unconstrained on this axis.
2474
+ *
2475
+ * Optional, and absent from the single-channel parsers' output, so
2476
+ * `parseChallengeHeader` / `parseChallengeBody` keep the exact shape they
2477
+ * ship with. `readUpgradeChallenge` always sets it when a level was parsed.
2478
+ */
2479
+ requiredLevel?: number;
2480
+ /** Maximum permitted age of the authentication event, in seconds. */
2481
+ maxAge?: number;
2482
+ /** The status that carried the challenge: 401 (protected resource) or 403 (session exchange). */
2483
+ status: number;
2484
+ /**
2485
+ * The factors this user can use, in the order to offer them, from the `403` body's
2486
+ * `available_factors`. Absent when the server does not send it (older servers, the header channel).
2487
+ */
2488
+ availableFactors?: UpgradeFactorType[];
2489
+ /**
2490
+ * The `403` body's `sign_in_required`: `true` when only a fresh sign-in can meet
2491
+ * the challenge, `false` when a step-up could but `availableFactors` names none
2492
+ * this account has (for example a device-bound passkey for AAL3). Absent from
2493
+ * older servers.
2494
+ */
2495
+ signInRequired?: boolean;
2496
+ /**
2497
+ * Every channel that PARSED AS A CHALLENGE in any field — not only the
2498
+ * channels that won a comparison. An opaque header contributes no constraint
2499
+ * yet must still be counted, because only something that saw and discarded it
2500
+ * can report it. `length === 2` means "both channels carried a challenge".
2501
+ *
2502
+ * Set by `readUpgradeChallenge`; absent from the single-channel parsers.
2503
+ */
2504
+ channels?: ChallengeChannel[];
2505
+ };
2506
+ /** Which wire channel a challenge was read from. */
2507
+ type ChallengeChannel = 'header' | 'body';
2135
2508
  /**
2136
- * Verify Request for v2 2FA flow
2509
+ * Reads a upgrade challenge out of a `WWW-Authenticate` header, or returns
2510
+ * `undefined` when the header is absent or describes some other failure.
2511
+ *
2512
+ * The header must both use the `Bearer` scheme and carry
2513
+ * `error="insufficient_user_authentication"`. A bare `WWW-Authenticate: Bearer`
2514
+ * (what an expired token produces) is deliberately NOT a upgrade challenge.
2137
2515
  */
2138
- export interface TwoFactorVerifyRequestV2 {
2139
- challenge_id: string;
2140
- method: TwoFactorMethod;
2141
- response: string;
2142
- trust_device?: boolean;
2143
- }
2516
+ export declare const parseChallengeHeader: (header: string | undefined | null, status: number) => UpgradeChallenge | undefined;
2144
2517
  /**
2145
- * Verify Response from v2 2FA flow
2518
+ * Reads a upgrade challenge out of the ADR-2 `403` body. Used as a fallback
2519
+ * for `/auth/session/exchange`, whose JSON body is the documented SDK contract
2520
+ * even though it also sets the standard header.
2146
2521
  */
2147
- export interface TwoFactorVerifyResponseV2 extends TwoFactorParentAnswer {
2148
- access_token?: string;
2149
- refresh_token?: string;
2150
- id_token?: string;
2151
- /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
2152
- code?: string;
2153
- }
2522
+ export declare const parseChallengeBody: (body: unknown, status: number) => UpgradeChallenge | undefined;
2523
+ /** The bar a challenge demanded, or an elevation reached, on both axes. */
2524
+ type AssuranceBar = {
2525
+ /** The raw winning `acr_values` list, for display and diagnostics. */
2526
+ acrValues?: string;
2527
+ /** The parsed bar. `undefined` = unknown, or not constrained on this axis. */
2528
+ level?: number;
2529
+ /** The freshness constraint, when that is what was demanded. */
2530
+ maxAge?: number;
2531
+ };
2532
+ /** The reasons the SDK can decline to act on a challenge, or act on a suspect one. */
2533
+ type UpgradeDiagnosticReason = 'no-channel' | 'header-required-but-absent' | 'channels-disagree' | 'channels-unorderable' | 'zero-constraint-ignored' | 'challenge-out-of-scope' | 'elevated-insufficient' | 'replay-unsupported';
2154
2534
  /**
2155
- * Registered Two-Factor Method
2535
+ * One diagnostic record.
2536
+ *
2537
+ * A diagnostic is the only observable signal of the response-rewriting and the
2538
+ * misconfiguration this design warns about, so it routes through a callback
2539
+ * whose DEFAULT sink is `console.warn` — never `debug`, which is invisible in
2540
+ * every default configuration. A deployment where step-up silently never fires
2541
+ * must be distinguishable from one where it was never required.
2156
2542
  */
2157
- export interface RegisteredTwoFactorMethod {
2158
- id?: string;
2159
- method: TwoFactorMethod;
2160
- name?: string;
2161
- user_id?: string;
2162
- app_id?: string;
2163
- /** `true` when this passkey also signs the user in as the first factor. */
2164
- is_passkey_for_1fa?: boolean;
2165
- created_at?: string;
2166
- updated_at?: string;
2167
- last_used_at?: string;
2168
- }
2543
+ type UpgradeDiagnostic = {
2544
+ status: number;
2545
+ /**
2546
+ * The request's URL. The parser does not know it — it is handed a status, a
2547
+ * header reader and a body — so it emits `''` and the core, which owns the
2548
+ * request context, fills it in before forwarding to the sink.
2549
+ */
2550
+ url: string;
2551
+ reason: UpgradeDiagnosticReason;
2552
+ detail?: {
2553
+ obtained?: AssuranceBar;
2554
+ required?: AssuranceBar;
2555
+ /** Raw channel inputs, including values discarded as unorderable. */
2556
+ header?: string;
2557
+ body?: string;
2558
+ /** Which field was discarded, for `'zero-constraint-ignored'`. */
2559
+ field?: 'acr_values' | 'max_age';
2560
+ /** Which operation, for per-waiter reasons. */
2561
+ method?: string;
2562
+ /** A human-readable sentence naming the fix. The default sink prints it. */
2563
+ message?: string;
2564
+ };
2565
+ };
2566
+ /** Where diagnostics go. `console.warn` is the default sink, not the only one. */
2567
+ type UpgradeDiagnosticSink = (diagnostic: UpgradeDiagnostic) => void;
2169
2568
  /**
2170
- * Alternative Method Request
2569
+ * Resolves a upgrade challenge from a response, from either channel.
2570
+ *
2571
+ * The SHIPPED export: same name, same three parameters, same return, published
2572
+ * in `@passflow/core@0.14.1`. It is now a thin delegate over
2573
+ * `readUpgradeChallenge`, so there is one merge rule rather than two parsers
2574
+ * that can drift — but it discards the diagnostics, which is why a caller that
2575
+ * needs them (the core) calls the sibling directly.
2576
+ *
2577
+ * Returns `undefined` for every response that is not a upgrade challenge —
2578
+ * including ordinary `401`s, which callers must keep treating as "session
2579
+ * expired".
2171
2580
  */
2172
- export interface TwoFactorAlternativeRequest {
2173
- challenge_id: string;
2174
- method: TwoFactorMethod;
2175
- }
2176
- export interface CLIAuthStatusResponse {
2177
- status: 'pending' | 'completed' | 'expired' | 'failed';
2178
- expires_at?: string;
2179
- challenge?: Record<string, unknown>;
2180
- access_token?: string;
2181
- refresh_token?: string;
2182
- user_id?: string;
2183
- expires_in?: number;
2184
- error?: string;
2185
- }
2186
- export interface CLIAuthCompleteRequest {
2187
- session_id: string;
2188
- access_token: string;
2189
- refresh_token: string;
2190
- user_id: string;
2191
- expires_in: number;
2192
- }
2581
+ export declare const parseUpgradeChallenge: (status: number, getHeader: (name: string) => string | undefined | null, body?: unknown) => UpgradeChallenge | undefined;
2193
2582
  /**
2194
2583
  * Handles a challenge the Passflow instance itself received, resolving with a
2195
2584
  * replayed response once the session has been elevated.
@@ -2213,6 +2602,12 @@ type AxiosRefreshHandler = (request: {
2213
2602
  trigger: 'pre-request';
2214
2603
  allowStale: boolean;
2215
2604
  }) => Promise<Tokens | undefined>;
2605
+ /**
2606
+ * Produces the `X-Passflow-Anti-Bot` value of a covered request. Installed by `Passflow` on its
2607
+ * auth client. Resolves `undefined` when the app is not `human_only`: the request then goes out
2608
+ * without the header, as it always has.
2609
+ */
2610
+ type AxiosAntiBotHandler = (mark: AntiBotMark) => Promise<AntiBotHeader | undefined>;
2216
2611
  declare class AxiosClient {
2217
2612
  private instance;
2218
2613
  protected storageManager: StorageManager;
@@ -2239,6 +2634,8 @@ declare class AxiosClient {
2239
2634
  private upgradeHandler?;
2240
2635
  /** Set by `Passflow` (its refresh controller). Absent on a client built standalone. */
2241
2636
  private refreshHandler?;
2637
+ /** Set by `Passflow` on its auth client. Absent elsewhere: no request is marked there. */
2638
+ private antiBotHandler?;
2242
2639
  /**
2243
2640
  * Passflow's own API as an interception scope, resolved ONCE here from
2244
2641
  * `PassflowConfig.url` so no wrapper or adapter ever derives it. `null` when
@@ -2267,7 +2664,12 @@ declare class AxiosClient {
2267
2664
  * Without a handler (an API client built standalone, outside `Passflow`) no refresh runs: every
2268
2665
  * call sends the stored bearer as it is, and an expired one gets the server's 401.
2269
2666
  */
2270
- setRefreshHandler(handler: AxiosRefreshHandler | undefined): void;
2667
+ setRefreshHandler(handler: AxiosRefreshHandler | undefined): void;
2668
+ /**
2669
+ * Installs (or clears) the anti-bot handler. Only requests marked with `withAntiBot` consult it;
2670
+ * every other request is unchanged.
2671
+ */
2672
+ setAntiBotHandler(handler: AxiosAntiBotHandler | undefined): void;
2271
2673
  /**
2272
2674
  * Re-issues a request after an elevation. Exposed for the upgrade handler,
2273
2675
  * which owns the replay-once decision; the marker preventing a second
@@ -2312,6 +2714,29 @@ export declare class AuthAPI {
2312
2714
  protected axiosClient: AxiosClient;
2313
2715
  constructor(config: PassflowConfig, storageManager?: StorageManager, deviceService?: DeviceService);
2314
2716
  setAppId(appId: string): void;
2717
+ /** Installs (or clears) the handler that produces the anti-bot value of covered calls. */
2718
+ setAntiBotHandler(handler: AxiosAntiBotHandler | undefined): void;
2719
+ /**
2720
+ * A built-in anti-bot challenge for this app. `identifier` is used by the server for difficulty
2721
+ * only. Rejects only with a `PassflowError`.
2722
+ */
2723
+ antiBotChallenge(payload: {
2724
+ identifier?: string;
2725
+ }): Promise<AntiBotChallenge>;
2726
+ /**
2727
+ * A built-in anti-bot challenge for the device verification page, for the app of `user_code`.
2728
+ * Same-origin only, with the page's CSRF token. Rejects only with a `PassflowError`.
2729
+ */
2730
+ deviceAntiBotChallenge(payload: {
2731
+ user_code: string;
2732
+ identifier?: string;
2733
+ }, csrfToken: string): Promise<AntiBotChallenge>;
2734
+ /**
2735
+ * Starts a federated sign-in with a POST, which can carry the anti-bot and agent-tool headers,
2736
+ * and answers the provider's URL to navigate to. Sent with credentials, so the browser keeps the
2737
+ * challenge cookie the answer sets.
2738
+ */
2739
+ federatedStart(provider: string, body: PassflowFederatedStartBody, options?: PassflowAuthOptions): Promise<PassflowFederatedStartResponse>;
2315
2740
  /**
2316
2741
  * Refreshes the session, optionally committing an assurance upgrade.
2317
2742
  *
@@ -2328,8 +2753,8 @@ export declare class AuthAPI {
2328
2753
  * invalidate the session over a mistyped digit.
2329
2754
  */
2330
2755
  refreshToken(refreshToken: string, scopes: string[], accessToken?: string, upgrade?: UpgradeRefreshField): Promise<PassflowAuthorizationResponse>;
2331
- signIn(payload: PassflowSignInPayload, deviceId: string, os: OS): Promise<PassflowAuthorizationResponse>;
2332
- signUp(payload: PassflowSignUpPayload): Promise<PassflowAuthorizationResponse>;
2756
+ signIn(payload: PassflowSignInPayload, deviceId: string, os: OS, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2757
+ signUp(payload: PassflowSignUpPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2333
2758
  /**
2334
2759
  * Redeems the code a PKCE sign-in answered with for the tokens it stands for.
2335
2760
  *
@@ -2338,9 +2763,9 @@ export declare class AuthAPI {
2338
2763
  */
2339
2764
  pkceExchange(code: string, verifier: string): Promise<PassflowAuthorizationResponse>;
2340
2765
  /** Rejects only with a `PassflowError`, because its body can hold the poll secret. */
2341
- passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, deviceId: string, os: OS): Promise<PassflowPasswordlessResponse>;
2766
+ passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, deviceId: string, os: OS, options?: PassflowAuthOptions): Promise<PassflowPasswordlessResponse>;
2342
2767
  /** Rejects only with a `PassflowError`, because its body holds the OTP. */
2343
- passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload): Promise<PassflowValidationResponse>;
2768
+ passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload, options?: PassflowAuthOptions): Promise<PassflowValidationResponse>;
2344
2769
  /**
2345
2770
  * Polls a magic-link sign-in waiting for approval from another device. Sent with credentials:
2346
2771
  * the trusted-device cookie is read when an approved row answers with its code. It rejects only
@@ -2367,12 +2792,12 @@ export declare class AuthAPI {
2367
2792
  validateEmailCode(payload: PassflowEmailCodePayload): Promise<PassflowAuthorizationResponse>;
2368
2793
  logOut(deviceId?: string, refreshToken?: string, isAdmin?: boolean): Promise<PassflowLogoutResponse>;
2369
2794
  validateSession(): Promise<PassflowSessionValidationResponse>;
2370
- sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload): Promise<PassflowSuccessResponse>;
2795
+ sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload, options?: PassflowAuthOptions): Promise<PassflowSuccessResponse>;
2371
2796
  resetPassword(newPassword: string, scopes: string[], resetToken?: string, codeChallenge?: string): Promise<PassflowAuthorizationResponse>;
2372
- passkeyRegisterStart(payload: PassflowPasskeyRegisterStartPayload, deviceId: string, os: OS, isAdmin?: boolean): Promise<PassflowPasskeyStart>;
2373
- passkeyRegisterComplete(passkeyData: RegistrationResponseJSON, deviceId: string, challengeId: string, isAdmin?: boolean): Promise<PassflowAuthorizationResponse>;
2374
- passkeyAuthenticateStart(payload: PassflowPasskeyAuthenticateStartPayload, deviceId: string, os: OS, isAdmin?: boolean): Promise<PassflowPasskeyStart>;
2375
- passkeyAuthenticateComplete(passkeyData: AuthenticationResponseJSON, deviceId: string, challengeId: string, isAdmin?: boolean): Promise<PassflowAuthorizationResponse>;
2797
+ passkeyRegisterStart(payload: PassflowPasskeyRegisterStartPayload, deviceId: string, os: OS, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowPasskeyStart>;
2798
+ passkeyRegisterComplete(passkeyData: RegistrationResponseJSON, deviceId: string, challengeId: string, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2799
+ passkeyAuthenticateStart(payload: PassflowPasskeyAuthenticateStartPayload, deviceId: string, os: OS, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowPasskeyStart>;
2800
+ passkeyAuthenticateComplete(passkeyData: AuthenticationResponseJSON, deviceId: string, challengeId: string, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2376
2801
  passkeyValidate(otp: string, deviceId: string, challengeId: string, isAdmin?: boolean, appId?: string): Promise<PassflowValidationResponse>;
2377
2802
  }
2378
2803
  export declare class CLIAuthAPI {
@@ -2890,6 +3315,12 @@ export declare const APP_ID_HEADER_KEY = "X-Passflow-Clientid";
2890
3315
  export declare const AUTHORIZATION_HEADER_KEY = "Authorization";
2891
3316
  export declare const DEVICE_ID_HEADER_KEY = "X-Passflow-DeviceId";
2892
3317
  export declare const DEVICE_TYPE_HEADER_KEY = "X-Passflow-DeviceType";
3318
+ /** The anti-bot value of a covered sign-in request on a `human_only` app. */
3319
+ export declare const ANTI_BOT_HEADER_KEY = "X-Passflow-Anti-Bot";
3320
+ /** Set to `1` on requests an agent tool sends (`PassflowAuthOptions.agentTool`). */
3321
+ export declare const AGENT_TOOL_HEADER_KEY = "X-Passflow-Agent-Tool";
3322
+ /** The `action` a token provider receives; a reCAPTCHA score key must be executed with it. */
3323
+ export declare const ANTI_BOT_ACTION = "passflow_auth";
2893
3324
  /**
2894
3325
  * SDK version from package.json.
2895
3326
  * Useful for debugging and logging version information.
@@ -3640,242 +4071,6 @@ interface RefreshController {
3640
4071
  readonly ended: boolean;
3641
4072
  dispose(): void;
3642
4073
  }
3643
- /**
3644
- * Passflow event types
3645
- */
3646
- export declare enum PassflowEvent {
3647
- SignIn = "signin",
3648
- SignInStart = "signin:start",
3649
- Register = "register",
3650
- RegisterStart = "register:start",
3651
- /** A sign-up, sign-in or password change is waiting for the email to be proven (no session yet). */
3652
- EmailVerificationRequired = "email-verification:required",
3653
- SignOut = "signout",
3654
- SessionRestored = "session:restored",
3655
- SessionExpired = "session:expired",
3656
- Error = "error",
3657
- Refresh = "refresh",
3658
- RefreshStart = "refresh:start",
3659
- TokenCacheExpired = "token-cache-expired",
3660
- TwoFactorRequired = "2fa:required",
3661
- TwoFactorSetupStarted = "2fa:setup_started",
3662
- TwoFactorEnabled = "2fa:enabled",
3663
- TwoFactorDisabled = "2fa:disabled",
3664
- TwoFactorVerified = "2fa:verified",
3665
- TwoFactorRecoveryUsed = "2fa:recovery_used",
3666
- TwoFactorRecoveryCodesLow = "2fa:recovery_low",
3667
- TwoFactorRecoveryCodesExhausted = "2fa:recovery_exhausted",
3668
- TwoFactorSetupMagicLinkValidated = "2fa:magic_link_validated",
3669
- TwoFactorSetupMagicLinkFailed = "2fa:magic_link_failed",
3670
- TwoFactorChallengeReceived = "two_factor_challenge_received",
3671
- TwoFactorMethodSwitched = "two_factor_method_switched",
3672
- /**
3673
- * @deprecated The server keeps device trust in a cookie and the SDK no longer emits this event.
3674
- */
3675
- TwoFactorDeviceTrusted = "two_factor_device_trusted",
3676
- /** Token refresh entered a transient-failure episode (once per episode, per tab). */
3677
- RefreshFailing = "refresh:failing",
3678
- /** The transient-failure episode ended with a successful refresh or adoption. */
3679
- RefreshRecovered = "refresh:recovered"
3680
- }
3681
- /**
3682
- * The SDK operation that failed (`ErrorPayload.operation`). The SDK sets it on every `Error` it
3683
- * emits, so a subscriber can tell a failed sign-in from a failed refresh without parsing messages.
3684
- */
3685
- type PassflowOperation = 'sign-in' | 'sign-up' | 'passwordless.start' | 'passwordless.complete' | 'passwordless.wait' | 'passwordless.approval' | 'password-reset.send' | 'password-reset.complete' | 'email-verification.complete' | 'passkey.register' | 'passkey.authenticate' | 'federated.popup' | 'federated.redirect' | 'auth-redirect.url' | 'auth-redirect' | 'redirect.check' | 'auth.is-authenticated' | 'session.check' | 'session.list' | 'session.revoke' | 'session.revoke-others' | 'tokens.get' | 'tokens.load' | 'tokens.from-url' | 'oidc.redirect' | 'refresh' | 'upgrade.commit' | 'log-out' | 'reset' | 'settings.app' | 'settings.all' | 'settings.password-policy' | 'settings.passkey' | 'passkey.list' | 'passkey.rename' | 'passkey.delete' | 'passkey.add' | 'tenant.create' | 'invitation.join' | 'invitation.request-link' | 'invitation.list' | 'invitation.delete' | 'invitation.resend' | 'invitation.get-link' | '2fa.status' | '2fa.setup.begin' | '2fa.setup.confirm' | '2fa.enrollment.read' | '2fa.enrollment.setup-link' | '2fa.verify' | '2fa.recovery.use' | '2fa.disable' | '2fa.recovery.regenerate' | '2fa.methods.available' | '2fa.methods.registered' | '2fa.method.setup.start' | '2fa.method.setup.complete' | '2fa.method.remove' | '2fa.challenge.request' | '2fa.challenge.verify' | '2fa.method.switch' | '2fa.trusted-devices.list' | '2fa.trusted-devices.revoke';
3686
- /**
3687
- * Error payload interface for structured error information
3688
- */
3689
- interface ErrorPayload {
3690
- message: string;
3691
- code?: string | number;
3692
- details?: unknown;
3693
- originalError?: unknown;
3694
- /** The operation that failed. Always set by the SDK. */
3695
- operation?: PassflowOperation;
3696
- /** For operation `refresh` | `upgrade.commit`: what asked for the refresh. */
3697
- source?: RefreshTrigger;
3698
- /** For operation `refresh` | `upgrade.commit`: how the failure was classified and what follows. */
3699
- refresh?: RefreshErrorInfo;
3700
- }
3701
- /** An `Error` payload as the SDK reports it: `operation` is required. */
3702
- type OperationErrorPayload = ErrorPayload & {
3703
- operation: PassflowOperation;
3704
- };
3705
- /** Which call produced an `EmailVerificationRequired` event. */
3706
- type PassflowEmailVerificationOperation = 'sign-up' | 'sign-in' | 'reset-password';
3707
- /**
3708
- * Event-specific payload types
3709
- */
3710
- type PassflowEventPayload = {
3711
- [PassflowEvent.SignIn]: {
3712
- tokens?: Tokens;
3713
- parsedTokens?: ParsedTokens;
3714
- /** `'other-tab'` only when an ended tab revives on a new session found in storage. Absent on this tab's own sign-in. */
3715
- origin?: EventOrigin;
3716
- /**
3717
- * `'federated-landing'`: a federated redirect landed here and this instance exchanged its code.
3718
- * `'tokens-in-url'`: tokens received in this page's URL were verified and saved.
3719
- * `'oidc-landing'`: hosted sign-in returned an authorization code here and this instance redeemed it.
3720
- */
3721
- source?: 'federated-landing' | 'tokens-in-url' | 'oidc-landing';
3722
- /** For `source: 'tokens-in-url'`: the `state` the URL carried with the tokens, when it had one. */
3723
- state?: string;
3724
- };
3725
- [PassflowEvent.SignInStart]: {
3726
- email?: string;
3727
- provider?: string;
3728
- };
3729
- [PassflowEvent.Register]: {
3730
- tokens?: Tokens;
3731
- parsedTokens?: ParsedTokens;
3732
- };
3733
- [PassflowEvent.RegisterStart]: {
3734
- email?: string;
3735
- };
3736
- [PassflowEvent.EmailVerificationRequired]: {
3737
- /** The address the code or link went to, when the SDK knows it. */
3738
- email?: string;
3739
- /** Present when a code was emailed; absent when a link was emailed instead. */
3740
- challengeId?: string;
3741
- operation: PassflowEmailVerificationOperation;
3742
- };
3743
- [PassflowEvent.SignOut]: {
3744
- /** `sub` of the session that ended, when known. */
3745
- userId?: string;
3746
- /** Always set by the SDK. `'other-tab'`: another tab signed out, or shared storage was emptied. */
3747
- origin?: EventOrigin;
3748
- };
3749
- [PassflowEvent.SessionRestored]: {
3750
- id: string;
3751
- email?: string;
3752
- username?: string;
3753
- [key: string]: unknown;
3754
- };
3755
- [PassflowEvent.SessionExpired]: {
3756
- reason: SessionExpiredReason;
3757
- /** Always set by the SDK. */
3758
- origin?: EventOrigin;
3759
- };
3760
- [PassflowEvent.Error]: ErrorPayload;
3761
- [PassflowEvent.Refresh]: {
3762
- tokens?: Tokens;
3763
- parsedTokens?: ParsedTokens;
3764
- /**
3765
- * Always set by the SDK. `'refresh'`: this tab's request; `'upgrade'`: this tab's step-up
3766
- * commit; `'adopted'`: tokens this tab did not request (another tab's, or found in storage).
3767
- */
3768
- source?: 'refresh' | 'upgrade' | 'adopted';
3769
- };
3770
- [PassflowEvent.RefreshStart]: {
3771
- tokenId?: string;
3772
- };
3773
- [PassflowEvent.TokenCacheExpired]: {
3774
- isExpired: boolean;
3775
- };
3776
- [PassflowEvent.TwoFactorRequired]: {
3777
- email: string;
3778
- challengeId: string;
3779
- tfaToken: string;
3780
- };
3781
- [PassflowEvent.TwoFactorSetupStarted]: {
3782
- secret: string;
3783
- method?: TwoFactorMethod;
3784
- };
3785
- [PassflowEvent.TwoFactorEnabled]: {
3786
- recoveryCodes: string[];
3787
- clearRecoveryCodes: () => void;
3788
- };
3789
- [PassflowEvent.TwoFactorDisabled]: Record<string, never>;
3790
- [PassflowEvent.TwoFactorVerified]: {
3791
- tokens?: Tokens;
3792
- };
3793
- /** `remainingCodes` is undefined when the server did not send the count. */
3794
- [PassflowEvent.TwoFactorRecoveryUsed]: {
3795
- tokens?: Tokens;
3796
- remainingCodes?: number;
3797
- };
3798
- [PassflowEvent.TwoFactorRecoveryCodesLow]: {
3799
- tokens?: Tokens;
3800
- remainingCodes: number;
3801
- };
3802
- [PassflowEvent.TwoFactorRecoveryCodesExhausted]: {
3803
- tokens?: Tokens;
3804
- };
3805
- [PassflowEvent.TwoFactorSetupMagicLinkValidated]: {
3806
- userId: string;
3807
- appId?: string | null;
3808
- expiresIn: number;
3809
- sessionToken: string;
3810
- };
3811
- [PassflowEvent.TwoFactorSetupMagicLinkFailed]: {
3812
- error: {
3813
- code: 'INVALID_TOKEN' | 'EXPIRED_TOKEN' | 'REVOKED_TOKEN' | 'ALREADY_USED' | 'RATE_LIMITED' | 'SERVER_ERROR';
3814
- message: string;
3815
- retryAfter?: number;
3816
- };
3817
- };
3818
- [PassflowEvent.TwoFactorChallengeReceived]: {
3819
- challengeId: string;
3820
- method: TwoFactorMethod;
3821
- alternativeMethods: TwoFactorMethod[];
3822
- };
3823
- [PassflowEvent.TwoFactorMethodSwitched]: {
3824
- challengeId: string;
3825
- method: TwoFactorMethod;
3826
- alternativeMethods: TwoFactorMethod[];
3827
- };
3828
- [PassflowEvent.TwoFactorDeviceTrusted]: Record<string, never>;
3829
- [PassflowEvent.RefreshFailing]: {
3830
- /** Epoch ms of the episode's first transient failure. */
3831
- since: number;
3832
- /** Epoch ms of the shared pending retry, when known. */
3833
- nextRetryAt?: number;
3834
- /** `'this-tab'` when this tab's own request failed. */
3835
- origin: EventOrigin;
3836
- };
3837
- [PassflowEvent.RefreshRecovered]: {
3838
- /** Same value as the `RefreshFailing` that opened the episode. */
3839
- since: number;
3840
- /** `'this-tab'`: own request succeeded; `'other-tab'`: adopted another tab's tokens. */
3841
- origin: EventOrigin;
3842
- };
3843
- };
3844
- /**
3845
- * Passflow subscriber interface
3846
- */
3847
- interface PassflowSubscriber {
3848
- onAuthChange<E extends PassflowEvent>(eventType: E, payload?: PassflowEventPayload[E]): void;
3849
- }
3850
- /**
3851
- * Store for managing Passflow event subscriptions
3852
- */
3853
- declare class PassflowStore {
3854
- private subscribers;
3855
- /**
3856
- * Subscribe to authentication events
3857
- * @param subscriber The subscriber to register
3858
- * @param events Optional specific events to subscribe to
3859
- */
3860
- subscribe(subscriber: PassflowSubscriber, events?: PassflowEvent[]): void;
3861
- /**
3862
- * Unsubscribe from authentication events
3863
- * @param subscriber The subscriber to unregister
3864
- * @param events Optional specific events to unsubscribe from
3865
- */
3866
- unsubscribe(subscriber: PassflowSubscriber, events?: PassflowEvent[]): void;
3867
- /**
3868
- * Notify subscribers of an event
3869
- * @param eventType The type of event that occurred
3870
- * @param payload Event-specific payload data
3871
- */
3872
- notify<E extends PassflowEvent>(eventType: E, payload?: PassflowEventPayload[E]): void;
3873
- /**
3874
- * Notify subscribers of an error, at most once per error object (`notifyError` in `error-report.ts`).
3875
- * @returns whether the event was emitted
3876
- */
3877
- notifyError(payload: OperationErrorPayload): boolean;
3878
- }
3879
4074
  export declare class TokenCacheService {
3880
4075
  private storageManager;
3881
4076
  private subscribeStore;
@@ -4036,7 +4231,7 @@ export declare class AuthService {
4036
4231
  /**
4037
4232
  * Stores an authentication response: token storage, session state, CSRF token. In BFF mode it
4038
4233
  * forwards the tokens to the BFF server first. Starts no session: a cookie-mode refresh applies
4039
- * its answer through here too.
4234
+ * its answer through here too. `replace` marks a new session: see `StorageManager.saveTokens()`.
4040
4235
  */
4041
4236
  private applyAuthResponse;
4042
4237
  /** A registration that leaves the user signed in: `Register`, then `SignIn` with the same payload. */
@@ -4123,10 +4318,10 @@ export declare class AuthService {
4123
4318
  * Forward tokens to BFF server for httpOnly cookie storage
4124
4319
  */
4125
4320
  private forwardTokensToBFF;
4126
- signIn(payload: PassflowSignInPayload): Promise<PassflowAuthorizationResponse>;
4127
- signUp(payload: PassflowSignUpPayload): Promise<PassflowAuthorizationResponse>;
4128
- passwordlessSignIn(payload: PassflowPasswordlessSignInPayload): Promise<PassflowPasswordlessResponse>;
4129
- passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload): Promise<PassflowValidationResponse>;
4321
+ signIn(payload: PassflowSignInPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4322
+ signUp(payload: PassflowSignUpPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4323
+ passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, options?: PassflowAuthOptions): Promise<PassflowPasswordlessResponse>;
4324
+ passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload, options?: PassflowAuthOptions): Promise<PassflowValidationResponse>;
4130
4325
  /**
4131
4326
  * Waits for the magic-link sign-in this tab started to be approved on another device, polling
4132
4327
  * every 3 s until its expiry. Network errors, 429, 5xx and unreadable answers keep polling.
@@ -4259,13 +4454,27 @@ export declare class AuthService {
4259
4454
  * when the answer arrives, before anything is applied: see `assertSessionPin`.
4260
4455
  */
4261
4456
  refreshToken(upgrade?: UpgradeRefreshField, pin?: UpgradeSessionPin): Promise<PassflowAuthorizationResponse>;
4262
- sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload): Promise<PassflowSuccessResponse>;
4457
+ sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload, options?: PassflowAuthOptions): Promise<PassflowSuccessResponse>;
4263
4458
  resetPassword(newPassword: string, scopes?: string[], token?: string): Promise<PassflowAuthorizationResponse>;
4264
- passkeyRegister(payload: PassflowPasskeyRegisterStartPayload): Promise<PassflowAuthorizationResponse>;
4265
- passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload): Promise<PassflowAuthorizationResponse>;
4459
+ passkeyRegister(payload: PassflowPasskeyRegisterStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4460
+ passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4461
+ /**
4462
+ * Whether a federated start goes out as a POST (`AuthAPI.federatedStart`) rather than as a
4463
+ * navigation to `createFederatedAuthUrl`: on a `human_only` app, whose start must carry the
4464
+ * anti-bot header, and for an agent tool, whose start must carry its own header. A header cannot
4465
+ * ride a navigation. An unknown bot mode keeps the navigation.
4466
+ */
4467
+ private usesFederatedPost;
4468
+ /** The body of a POST federated start: the same fields the GET start sends as query parameters. */
4469
+ private federatedStartBody;
4470
+ /**
4471
+ * The GET start URL. A `human_only` app refuses a start by navigation (403
4472
+ * `error.api.anti_bot.required`); `federatedAuthWithPopup` and `federatedAuthWithRedirect` POST
4473
+ * the start there instead.
4474
+ */
4266
4475
  createFederatedAuthUrl(payload: PassflowFederatedAuthExtendedPayload): string;
4267
- federatedAuthWithPopup(payload: PassflowFederatedAuthPayload): Promise<void>;
4268
- federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload): void;
4476
+ federatedAuthWithPopup(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): Promise<void>;
4477
+ federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): void;
4269
4478
  /**
4270
4479
  * Takes the slot for a `?code=` landing and exchanges the code in the background. `SignIn`,
4271
4480
  * `TwoFactorRequired` or an `Error` with operation `federated.redirect` reports the outcome.
@@ -5778,6 +5987,7 @@ export declare class Passflow {
5778
5987
  private invitationService;
5779
5988
  private tokenCacheService;
5780
5989
  private twoFactorService;
5990
+ private antiBot;
5781
5991
  tenant: TenantService;
5782
5992
  twoFactor: TwoFactorService;
5783
5993
  /**
@@ -6163,7 +6373,7 @@ export declare class Passflow {
6163
6373
  * }
6164
6374
  * ```
6165
6375
  */
6166
- signIn(payload: PassflowSignInPayload): Promise<PassflowAuthorizationResponse>;
6376
+ signIn(payload: PassflowSignInPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6167
6377
  /**
6168
6378
  * Register a new user account with email and password.
6169
6379
  *
@@ -6191,7 +6401,7 @@ export declare class Passflow {
6191
6401
  * }
6192
6402
  * ```
6193
6403
  */
6194
- signUp(payload: PassflowSignUpPayload): Promise<PassflowAuthorizationResponse>;
6404
+ signUp(payload: PassflowSignUpPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6195
6405
  /**
6196
6406
  * Initiate passwordless authentication by sending a magic link or OTP.
6197
6407
  *
@@ -6211,7 +6421,7 @@ export declare class Passflow {
6211
6421
  * console.log('Magic link sent:', response.success);
6212
6422
  * ```
6213
6423
  */
6214
- passwordlessSignIn(payload: PassflowPasswordlessSignInPayload): Promise<PassflowPasswordlessResponse>;
6424
+ passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, options?: PassflowAuthOptions): Promise<PassflowPasswordlessResponse>;
6215
6425
  /**
6216
6426
  * Complete passwordless authentication by verifying the OTP or token.
6217
6427
  *
@@ -6235,7 +6445,7 @@ export declare class Passflow {
6235
6445
  * }
6236
6446
  * ```
6237
6447
  */
6238
- passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload): Promise<PassflowValidationResponse>;
6448
+ passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload, options?: PassflowAuthOptions): Promise<PassflowValidationResponse>;
6239
6449
  /**
6240
6450
  * Waits for a magic-link sign-in this tab started to be approved on another device, then
6241
6451
  * finishes it here. Polls every 3 s until the challenge expires; network errors, 429 and 5xx keep
@@ -6339,6 +6549,30 @@ export declare class Passflow {
6339
6549
  * @throws {PassflowError} `error.app.redirect.url.not.registered` when refused, or a request error
6340
6550
  */
6341
6551
  checkRedirectUrl(url: string): Promise<string>;
6552
+ /**
6553
+ * Sets the token provider for an app in `human_only` bot mode that uses its own anti-bot
6554
+ * provider (Turnstile, hCaptcha, reCAPTCHA). Before each covered sign-in request the SDK calls it
6555
+ * with `{ action: 'passflow_auth', operation }` and sends the token it resolves with in
6556
+ * `X-Passflow-Anti-Bot`. Not called on a `bot_friendly` app, nor with the built-in check.
6557
+ * `undefined` removes it.
6558
+ *
6559
+ * @example
6560
+ * ```typescript
6561
+ * passflow.setAntiBotTokenProvider(() => getTurnstileToken());
6562
+ * ```
6563
+ */
6564
+ setAntiBotTokenProvider(provider: AntiBotTokenProvider | undefined): void;
6565
+ /**
6566
+ * A fresh `X-Passflow-Anti-Bot` value for a request the SDK does not send itself:
6567
+ * `POST /auth/session/exchange`, `/oidc/device/authenticate`, `/oidc/device/passkey/start`.
6568
+ * `undefined` when the app is not `human_only`: send no header then. A value is accepted once.
6569
+ *
6570
+ * The device page has no app id: it passes `settings` from `GET /oidc/device/info` and
6571
+ * `device: { userCode, csrfToken }`, and this instance must have `url` set to the page's origin.
6572
+ *
6573
+ * @throws {PassflowError} When the challenge, the solve or the token provider fails
6574
+ */
6575
+ antiBotToken(request: AntiBotTokenRequest): Promise<string | undefined>;
6342
6576
  private handleError;
6343
6577
  /**
6344
6578
  * Sign out the current user and clear all tokens.
@@ -6388,7 +6622,7 @@ export declare class Passflow {
6388
6622
  * });
6389
6623
  * ```
6390
6624
  */
6391
- federatedAuthWithPopup(payload: PassflowFederatedAuthPayload): void;
6625
+ federatedAuthWithPopup(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): void;
6392
6626
  /**
6393
6627
  * Initiate federated authentication (OAuth) with a full-page redirect.
6394
6628
  *
@@ -6406,7 +6640,7 @@ export declare class Passflow {
6406
6640
  * });
6407
6641
  * ```
6408
6642
  */
6409
- federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload): void;
6643
+ federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): void;
6410
6644
  /**
6411
6645
  * Reset the SDK state by clearing all tokens and optionally throwing an error.
6412
6646
  *
@@ -6486,7 +6720,7 @@ export declare class Passflow {
6486
6720
  * }
6487
6721
  * ```
6488
6722
  */
6489
- sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload): Promise<PassflowSuccessResponse>;
6723
+ sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload, options?: PassflowAuthOptions): Promise<PassflowSuccessResponse>;
6490
6724
  /**
6491
6725
  * Reset password using a reset token (typically from URL after clicking email link).
6492
6726
  *
@@ -6594,7 +6828,7 @@ export declare class Passflow {
6594
6828
  * }
6595
6829
  * ```
6596
6830
  */
6597
- passkeyRegister(payload: PassflowPasskeyRegisterStartPayload): Promise<PassflowAuthorizationResponse>;
6831
+ passkeyRegister(payload: PassflowPasskeyRegisterStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6598
6832
  /**
6599
6833
  * Authenticate a user with a passkey (WebAuthn).
6600
6834
  *
@@ -6615,11 +6849,16 @@ export declare class Passflow {
6615
6849
  * }
6616
6850
  * ```
6617
6851
  */
6618
- passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload): Promise<PassflowAuthorizationResponse>;
6852
+ passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6619
6853
  /**
6620
6854
  * Manually set tokens (useful after custom authentication flows).
6621
6855
  * This will save tokens to storage, update cache, and trigger SignIn event.
6622
6856
  *
6857
+ * The tokens replace the stored session: in JSON mode a refresh token, ID token or scope list
6858
+ * that is not passed is removed from storage. Pass every token you want to keep; read the
6859
+ * current ones with `getTokens()`. In cookie and BFF modes only the ID token is stored, and the
6860
+ * stored one stays when none is passed.
6861
+ *
6623
6862
  * @param tokensData - Tokens object to set
6624
6863
  * @param tokensData.access_token - JWT access token
6625
6864
  * @param tokensData.refresh_token - Optional refresh token
@@ -7341,4 +7580,4 @@ export declare function isValidPhoneNumber(phone: string): boolean;
7341
7580
  * @returns true if valid username format, false otherwise
7342
7581
  */
7343
7582
  export declare function isValidUsername(username: string): boolean;
7344
- export type { AssuranceBar, AuthCallbackResult, BodyKind, ChallengeChannel, CreateClientConfig, CurrentUrlInfo, ErrorPayload, EventOrigin, FetchLike, FetchMiddleware, GroupMembership, InvitationToken, M2MClientConfig, M2MErrorCode, M2MErrorResponse, M2MRateLimitInfo, M2MTokenCache, M2MTokenClaims, M2MTokenRequestInfo, M2MTokenRequestOptions, M2MTokenResponse, OidcErrorCode, OpenAuthUrlOptions, OperationErrorPayload, PassflowEmailVerificationOperation, PassflowEventPayload, PassflowOperation, PassflowRefreshErrorOptions, PassflowSubscriber, PasskeySupport, PlatformAdapter, PlatformStorage, RawUserMembership, RefreshChannel, RefreshClock, RefreshCoordination, RefreshCoordinator, RefreshErrorInfo, RefreshFailureKind, RefreshLockManager, RefreshLockOptions, RefreshTrigger, RegisterOptions, ReplayPolicy, RequestSnapshot, ResponseInterceptorHost, RetryStrategy, SessionExpiredReason, SnapshotHeader, Tenant, TenantMembership, Token, UpgradeAssertContext, UpgradeAssertion, UpgradeChallenge, UpgradeCommitInterruptedReason, UpgradeControllerOptions, UpgradeDiagnostic, UpgradeDiagnosticReason, UpgradeDiagnosticSink, UpgradeElevation, UpgradeEnableOptions, UpgradeEndpoint, UpgradeErrorKind, UpgradeFacade, UpgradeFactor, UpgradeFactorInput, UpgradeFactorType, UpgradeFlightState, UpgradeFlightSummary, UpgradeOptions, UpgradePrepared, UpgradePromptHandler, UpgradePromptRequest, UpgradePromptResult, UpgradeProof, UpgradeReplayInfo, UpgradeResult, UpgradeSessionPin, UpgradeTransport, UpgradeTransportErrorInit, UpgradeWaiterSummary, UserMembership, Waiter, WaiterEntry, WaiterOutcome, WaiterReport, WithAuthOptions };
7583
+ export type { AntiBotAppSettings, AntiBotDeviceContext, AntiBotOperation, AntiBotTokenContext, AntiBotTokenProvider, AntiBotTokenRequest, AssuranceBar, AuthCallbackResult, BodyKind, ChallengeChannel, CreateClientConfig, CurrentUrlInfo, ErrorPayload, EventOrigin, FetchLike, FetchMiddleware, GroupMembership, InvitationToken, M2MClientConfig, M2MErrorCode, M2MErrorResponse, M2MRateLimitInfo, M2MTokenCache, M2MTokenClaims, M2MTokenRequestInfo, M2MTokenRequestOptions, M2MTokenResponse, OidcErrorCode, OpenAuthUrlOptions, OperationErrorPayload, PassflowEmailVerificationOperation, PassflowEventPayload, PassflowOperation, PassflowRefreshErrorOptions, PassflowSubscriber, PasskeySupport, PlatformAdapter, PlatformStorage, RawUserMembership, RefreshChannel, RefreshClock, RefreshCoordination, RefreshCoordinator, RefreshErrorInfo, RefreshFailureKind, RefreshLockManager, RefreshLockOptions, RefreshTrigger, RegisterOptions, ReplayPolicy, RequestSnapshot, ResponseInterceptorHost, RetryStrategy, SessionExpiredReason, SnapshotHeader, Tenant, TenantMembership, Token, UpgradeAssertContext, UpgradeAssertion, UpgradeChallenge, UpgradeCommitInterruptedReason, UpgradeControllerOptions, UpgradeDiagnostic, UpgradeDiagnosticReason, UpgradeDiagnosticSink, UpgradeElevation, UpgradeEnableOptions, UpgradeEndpoint, UpgradeErrorKind, UpgradeFacade, UpgradeFactor, UpgradeFactorInput, UpgradeFactorType, UpgradeFlightState, UpgradeFlightSummary, UpgradeOptions, UpgradePrepared, UpgradePromptHandler, UpgradePromptRequest, UpgradePromptResult, UpgradeProof, UpgradeReplayInfo, UpgradeResult, UpgradeSessionPin, UpgradeTransport, UpgradeTransportErrorInit, UpgradeWaiterSummary, UserMembership, Waiter, WaiterEntry, WaiterOutcome, WaiterReport, WithAuthOptions };