@passflow/core 0.33.0 → 0.34.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;
@@ -404,14 +404,6 @@ declare class StorageManager {
404
404
  tokenKeys(): string[];
405
405
  private getKeyForTokenType;
406
406
  }
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
407
  /**
416
408
  * Synchronous key-value storage interface.
417
409
  * Compatible with localStorage (web) and react-native-mmkv (RN).
@@ -589,6 +581,13 @@ interface PlatformAdapter {
589
581
  * In redirect mode on web, the promise may never resolve.
590
582
  */
591
583
  openAuthUrl(url: string, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
584
+ /**
585
+ * Optional. Opens the auth window now, while the user's click still allows it, and navigates it
586
+ * when `url` resolves; closes it and rejects with the same error if `url` rejects. Used for a
587
+ * federated start that must be POSTed first (an app in `human_only` bot mode). Without it the
588
+ * SDK waits for the URL and calls `openAuthUrl`.
589
+ */
590
+ openPendingAuthUrl?(url: Promise<string>, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
592
591
  /**
593
592
  * Optional passkey support. If the platform does not support passkeys,
594
593
  * this property is undefined. The SDK checks for undefined before calling.
@@ -662,8 +661,8 @@ export declare class WebAdapter implements PlatformAdapter {
662
661
  * document.addEventListener('visibilitychange', handler) where document.hidden
663
662
  * (token-cache-service.ts:134-145, complementary to onForeground)
664
663
  *
665
- * NOTE: Not currently called by the SDK. Included in the interface for
666
- * React Native adapter compatibility (future use).
664
+ * NOTE: The SDK does not call it. It is part of the `PlatformAdapter` interface
665
+ * so an adapter for another platform, such as React Native, can offer it.
667
666
  */
668
667
  onBackground(callback: () => void): () => void;
669
668
  /**
@@ -689,6 +688,15 @@ export declare class WebAdapter implements PlatformAdapter {
689
688
  * (auth-service.ts:813)
690
689
  */
691
690
  openAuthUrl(url: string, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
691
+ /**
692
+ * Opens a blank popup at once, inside the user's click, and sends it to `url` once that
693
+ * resolves. A blocked popup falls back to a full-page redirect to the URL; a rejected `url`
694
+ * closes the popup and rejects with the same error. Other modes wait for the URL and behave as
695
+ * `openAuthUrl`.
696
+ */
697
+ openPendingAuthUrl(url: Promise<string>, options?: OpenAuthUrlOptions): Promise<AuthCallbackResult>;
698
+ /** Polls the popup until it returns to `expectedReturnOrigin`, closes, or times out. */
699
+ private watchPopup;
692
700
  /**
693
701
  * Replaces:
694
702
  * startRegistration({ optionsJSON: publicKey }) from @simplewebauthn/browser
@@ -729,6 +737,97 @@ export declare class WebAdapter implements PlatformAdapter {
729
737
  * Exported so consuming code can reference it without allocating a new instance.
730
738
  */
731
739
  export declare const webAdapter: WebAdapter;
740
+ /**
741
+ * Public types of multi-tab-safe token refresh.
742
+ *
743
+ * @module refresh/types
744
+ */
745
+ /** Options of one lock request: exclusive mode only, as the SDK uses `navigator.locks`. */
746
+ interface RefreshLockOptions {
747
+ ifAvailable?: boolean;
748
+ steal?: boolean;
749
+ signal?: AbortSignal;
750
+ }
751
+ /** The part of `navigator.locks` (LockManager) the SDK uses: exclusive mode only. */
752
+ interface RefreshLockManager {
753
+ request(name: string, options: RefreshLockOptions, callback: (lock: unknown) => unknown): Promise<unknown>;
754
+ }
755
+ /** The part of BroadcastChannel the SDK uses. Must not deliver an instance's own posts to itself. */
756
+ interface RefreshChannel {
757
+ postMessage(message: unknown): void;
758
+ addEventListener(type: 'message', listener: (event: {
759
+ data: unknown;
760
+ }) => void): void;
761
+ removeEventListener(type: 'message', listener: (event: {
762
+ data: unknown;
763
+ }) => void): void;
764
+ close(): void;
765
+ }
766
+ /** Time source for every refresh timer of one instance (heartbeat, silence, retry, waits). */
767
+ interface RefreshClock {
768
+ /** Epoch ms. */
769
+ now(): number;
770
+ /** Runs `fn` after `ms`; returns the cancel. */
771
+ setTimeout(fn: () => void, ms: number): () => void;
772
+ /** `[0, 1)` for backoff jitter. Default `Math.random`. */
773
+ random?(): number;
774
+ }
775
+ /** Transports for the cross-tab protocol, supplied by tests, Electron or custom hosts. */
776
+ interface RefreshCoordinator {
777
+ locks: RefreshLockManager;
778
+ /** One per Passflow instance; closed by `dispose()`. */
779
+ channel: RefreshChannel;
780
+ /** Default: `crypto.randomUUID()` or a random string. */
781
+ tabId?: string;
782
+ /** Another tab wrote the shared token storage. Called once at construction; returns unsubscribe. */
783
+ onStorageChange?: (listener: () => void) => () => void;
784
+ /** Default: `Date.now` / `setTimeout` / `Math.random`. */
785
+ clock?: RefreshClock;
786
+ }
787
+ /** How tabs of this origin coordinate token refresh (`PassflowConfig.refreshCoordination`). */
788
+ type RefreshCoordination = 'web-locks' | 'none' | RefreshCoordinator;
789
+ /** What asked for a refresh (`ErrorPayload.source`). */
790
+ type RefreshTrigger =
791
+ /** `Passflow.refreshToken()` / `AuthService.refreshToken()` */
792
+ 'refresh-token' |
793
+ /** `TokenCacheService.getTokensWithRefresh()` */
794
+ 'token-check' |
795
+ /** `getTokens(true)` / `session({ doRefresh: true })` */
796
+ 'session' |
797
+ /** An SDK API call whose access token expires within 30 s */
798
+ 'pre-request' |
799
+ /** Step-up commit */
800
+ 'upgrade' |
801
+ /** The scheduled retry, with no new caller */
802
+ 'retry' |
803
+ /** The held-tab send */
804
+ 'held';
805
+ /** How a failed `/auth/refresh` is read (architecture §2.6). */
806
+ type RefreshFailureKind = 'transient' | 'blocked' | 'auth';
807
+ /** Refresh details on `ErrorPayload` for operations `refresh` and `upgrade.commit`. */
808
+ interface RefreshErrorInfo {
809
+ classification: RefreshFailureKind;
810
+ /** A retry is scheduled (transient, or auth with strikes left). */
811
+ willRetry: boolean;
812
+ /** Epoch ms of the retry, when `willRetry`. */
813
+ nextRetryAt?: number;
814
+ /** Auth failures since the last success, after this one. */
815
+ strikes: number;
816
+ /** Resolved `refreshStrikes`. */
817
+ maxStrikes: number;
818
+ }
819
+ /** Whether an event was caused by this tab's own action or learnt from another tab. */
820
+ type EventOrigin = 'this-tab' | 'other-tab';
821
+ /** Why a session ended (`SessionExpired.reason`). */
822
+ type SessionExpiredReason =
823
+ /** `refreshStrikes` auth failures (this tab, or another tab of the lineage). */
824
+ 'refresh_failed' |
825
+ /** `error.token.blocked` and no successor within 20 s; this tab only. */
826
+ 'successor_timeout' |
827
+ /** Storage now holds another user's tokens. */
828
+ 'identity_changed' |
829
+ /** Legacy members, never emitted. */
830
+ 'token_invalid' | 'logged_out';
732
831
  /** Factor types the upgrade protocol understands, named as `upgrade.type` on the wire. */
733
832
  type UpgradeFactorType = 'totp' | 'recovery_codes' | 'passkey' | 'email_otp' | 'sms_otp';
734
833
  /** The prepare round's result — `POST /auth/upgrade/begin`, normalised to camelCase. */
@@ -811,549 +910,345 @@ export declare const passkeyFactor: UpgradeFactor;
811
910
  export declare const DEFAULT_UPGRADE_FACTORS: readonly UpgradeFactor[];
812
911
  /** Indexes a factor list by type for lookup during a challenge. */
813
912
  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";
913
+ export type RequestOptions<D> = {
914
+ data?: D;
915
+ config?: AxiosRequestConfig;
916
+ };
917
+ export declare enum RequestMethod {
918
+ GET = "get",
919
+ POST = "post",
920
+ PUT = "put",
921
+ PATCH = "patch",
922
+ DELETE = "delete"
923
+ }
924
+ export declare enum PassflowEndpointPaths {
925
+ signin = "/auth/login",
926
+ signup = "/auth/register",
927
+ pkceExchange = "/auth/pkce_exchange",
928
+ redirectCheck = "/auth/redirect/check",
929
+ signInWithProvider = "/auth/federated/start/",
930
+ passwordless = "/auth/passwordless/start",
931
+ passwordlessComplete = "/auth/passwordless/complete",
932
+ passwordlessStatus = "/auth/passwordless/status",
933
+ passwordlessApprovalInfo = "/auth/passwordless/approval/info",
934
+ passwordlessApprovalDecide = "/auth/passwordless/approval/decide",
935
+ logout = "/user/logout",
936
+ refresh = "/auth/refresh",
937
+ validateSession = "/user/me",
938
+ sendPasswordResetEmail = "/auth/password/reset",
939
+ resetPassword = "/auth/password/change",
940
+ appSettings = "/app/settings",
941
+ passkeyRegisterStart = "/auth/passkey/register/start",
942
+ passkeyRegisterComplete = "/auth/passkey/register/complete",
943
+ passkeyAuthenticateStart = "/auth/passkey/authenticate/start",
944
+ passkeyAuthenticateComplete = "/auth/passkey/authenticate/complete",
945
+ passkeyValidate = "/auth/validate",
946
+ settingsAll = "/settings",
947
+ settingsPasswordPolicy = "/settings/password",
948
+ settingsPasskey = "/settings/passkey",
949
+ userPasskey = "/user/passkey",
950
+ addUserPasskey = "/user/passkey/add/start",
951
+ completeAddUserPasskey = "/user/passkey/add/complete",
952
+ userSessions = "/user/sessions",
953
+ userSessionsRevokeOthers = "/user/sessions/revoke-others",
954
+ joinInvitation = "/user/tenant/join",
955
+ tenantPath = "/user/tenant",
956
+ invitationsPath = "/user/tenant/:tenantID/invitations",
957
+ requestInvitation = "/user/invite",
958
+ invitationDelete = "/user/invite/:invitationID",
959
+ invitationResend = "/user/invite/:invitationID/resend",
960
+ invitationGetLink = "/user/invite/:invitationID/link",
961
+ twoFactor = "/user/2fa",
962
+ twoFactorStatus = "/user/2fa/status",
963
+ twoFactorSetupBegin = "/user/2fa/setup/begin",
964
+ twoFactorSetupConfirm = "/user/2fa/setup/confirm",
965
+ twoFactorVerify = "/auth/2fa/verify",
966
+ twoFactorRecovery = "/auth/2fa/recovery",
967
+ twoFactorRegenerateCodes = "/user/2fa/recovery-codes/regenerate",
968
+ twoFactorSetupMagicLink = "/auth/2fa-setup", // :token param appended in API call
969
+ twoFactorEnrollment = "/auth/2fa/enrollment",
970
+ twoFactorEnrollmentEmailLink = "/auth/2fa/enrollment/email-link",
971
+ twoFactorEnrollmentBegin = "/auth/2fa/setup/begin",
972
+ twoFactorEnrollmentConfirm = "/auth/2fa/setup/confirm",
973
+ TwoFactorMethodsAvailable = "/v2/user/2fa/methods/available",
974
+ TwoFactorMethodsRegistered = "/v2/user/2fa/methods",
975
+ TwoFactorSetupStart = "/v2/user/2fa/setup/start",
976
+ TwoFactorSetupComplete = "/v2/user/2fa/setup/complete",
977
+ TwoFactorMethodRemove = "/v2/user/2fa/methods/:id",
978
+ TwoFactorChallenge = "/v2/auth/2fa/challenge",
979
+ TwoFactorVerifyV2 = "/v2/auth/2fa/verify",
980
+ TwoFactorAlternative = "/v2/auth/2fa/alternative",
981
+ TwoFactorTrustedDevices = "/v2/user/2fa/trusted-devices",
982
+ TwoFactorTrustedDeviceRevoke = "/v2/user/2fa/trusted-devices/:id",
983
+ cliAuthStatus = "/cli/auth/status/:sessionId",
984
+ cliAuthComplete = "/cli/auth/complete",
985
+ upgradeStart = "/auth/upgrade/start",
986
+ hostedUpgradeStart = "/auth/session/upgrade/start",
987
+ hostedUpgrade = "/auth/session/upgrade",
988
+ antiBotChallenge = "/auth/anti-bot/challenge",
989
+ deviceAntiBotChallenge = "/oidc/device/anti-bot/challenge"
990
+ }
991
+ export declare enum PassflowAdminEndpointPaths {
992
+ passkeyRegisterStart = "/admin/auth/passkey/register/start",
993
+ passkeyRegisterComplete = "/admin/auth/passkey/register/complete",
994
+ passkeyAuthenticateStart = "/admin/auth/passkey/authenticate/start",
995
+ passkeyAuthenticateComplete = "/admin/auth/passkey/authenticate/complete",
996
+ passkeyValidate = "/admin/auth/validate",
997
+ logout = "/admin/auth/logout"
998
+ }
818
999
  /**
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.
1000
+ * BFF (Backend-for-Frontend) configuration for secure token storage.
1001
+ * When enabled, tokens are sent to the BFF server which stores them in httpOnly cookies.
825
1002
  */
826
- type UpgradeChallenge = {
1003
+ export type TokenExchangeConfig = {
827
1004
  /**
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.
1005
+ * Enable token exchange mode. When true, authorization code is sent to your server
1006
+ * for token exchange instead of being exchanged directly from the browser.
834
1007
  */
835
- acrValues?: string;
1008
+ enabled: boolean;
836
1009
  /**
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.
1010
+ * URL to send authorization code for server-side token exchange.
1011
+ * Your server exchanges the code for tokens and stores them in httpOnly cookies.
1012
+ * @example '/api/auth/callback'
843
1013
  */
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;
1014
+ callbackUrl: string;
849
1015
  /**
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).
1016
+ * URL to call for token refresh. BFF reads refresh_token from httpOnly cookie
1017
+ * and returns new tokens (also stored in cookies).
1018
+ * @example '/api/auth/refresh'
852
1019
  */
853
- availableFactors?: UpgradeFactorType[];
1020
+ refreshUrl?: string;
854
1021
  /**
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.
1022
+ * URL to call for logout. BFF clears httpOnly cookies.
1023
+ * @example '/api/auth/logout'
859
1024
  */
860
- signInRequired?: boolean;
1025
+ logoutUrl?: string;
861
1026
  /**
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.
1027
+ * URL to check authentication status (whether httpOnly cookies are valid).
1028
+ * @example '/api/auth/status'
868
1029
  */
869
- channels?: ChallengeChannel[];
1030
+ statusUrl?: string;
870
1031
  };
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.
1032
+ /** @deprecated Use TokenExchangeConfig instead */
1033
+ export type BFFConfig = TokenExchangeConfig;
1034
+ export type PassflowConfig = {
1035
+ url?: string;
1036
+ appId?: string;
1037
+ scopes?: string[];
1038
+ createTenantForNewUser?: boolean;
1039
+ parseQueryParams?: boolean;
1040
+ /**
1041
+ * Leaves a federated `?code=` landing alone in the constructor and in `handleTokensRedirect`,
1042
+ * so that only `completeFederatedLanding()` takes it. For hosts that build the instance during
1043
+ * render and may discard it. Token and `#tfa_token` landings are not affected.
1044
+ */
1045
+ deferFederatedLanding?: boolean;
1046
+ keyStoragePrefix?: string;
1047
+ /**
1048
+ * Token exchange configuration for secure server-side token handling.
1049
+ * When enabled, authorization code is sent to your server which exchanges it
1050
+ * for tokens and stores them in httpOnly cookies. Tokens never touch the browser.
1051
+ */
1052
+ tokenExchange?: TokenExchangeConfig;
1053
+ /**
1054
+ * Platform adapter for cross-platform compatibility.
1055
+ * Defaults to WebAdapter (browser APIs) if not provided.
1056
+ * Pass a custom adapter to support React Native or other platforms.
1057
+ */
1058
+ platform?: PlatformAdapter;
1059
+ /**
1060
+ * Assurance upgrade (step-up) configuration. Construction-time only: the
1061
+ * prompt handler is deliberately NOT here, because it is a lifetime-scoped
1062
+ * resource that has to be torn down, which configuration cannot express.
1063
+ */
1064
+ upgrade?: PassflowUpgradeConfig;
1065
+ /**
1066
+ * How tabs of this origin coordinate token refresh.
1067
+ * - `'web-locks'` (default): a Web Lock plus a BroadcastChannel, on a browser page whose
1068
+ * `platform.storage` is shared by every tab (the default web adapter's localStorage) and that
1069
+ * has `navigator.locks` and `BroadcastChannel`. Elsewhere it falls back to `'none'`; on a
1070
+ * browser page with shared storage the fallback writes one `[passflow]` warning, at the first
1071
+ * refresh.
1072
+ * - `'none'`: no cross-tab coordination. Single flight within this instance, compare-and-set
1073
+ * save, per-instance retries.
1074
+ * - a `RefreshCoordinator` object: the same protocol as `'web-locks'` over the transports
1075
+ * you supply (tests, Electron, custom hosts). Never falls back.
1076
+ */
1077
+ refreshCoordination?: RefreshCoordination;
1078
+ /**
1079
+ * Authentication failures of `/auth/refresh` counted since the last successful refresh or
1080
+ * adoption, after which the session ends. Transient failures in between neither add a strike nor
1081
+ * reset the count. Default 3. A non-integer is floored; a value below 1 or not a finite number
1082
+ * uses the default.
1083
+ */
1084
+ refreshStrikes?: number;
1085
+ /**
1086
+ * Same-origin URL of the anti-bot worker script shipped as `@passflow/core/anti-bot-worker.js`,
1087
+ * for example `'/anti-bot-worker.js'`. Used only by apps in `human_only` bot mode with the
1088
+ * built-in check. Without it the proof of work runs on the main thread.
1089
+ */
1090
+ antiBotWorkerUrl?: string;
1091
+ };
1092
+ export type PassflowUpgradeConfig = {
1093
+ /** Relying-party id forwarded verbatim to `POST /auth/upgrade/start` for passkey upgrades. */
1094
+ relyingPartyId?: string;
1095
+ /** Overrides the factor set offered during an upgrade. Defaults to what this SDK can complete. */
1096
+ factors?: readonly UpgradeFactor[];
1097
+ };
1098
+ /**
1099
+ * Passflow's own API, as an interception scope — "domain 1".
876
1100
  *
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.
1101
+ * A challenge arriving from here is handled with zero configuration, because
1102
+ * `url` is an input the SDK already takes and whatever it points at is
1103
+ * unambiguously ours.
880
1104
  */
881
- export declare const parseChallengeHeader: (header: string | undefined | null, status: number) => UpgradeChallenge | undefined;
1105
+ export type UpgradeDomain = {
1106
+ /** The API origin, e.g. `https://api.passflow.dev`. */
1107
+ origin: string;
1108
+ /** The path prefix when `url` carries one, normalised without a trailing slash. */
1109
+ pathPrefix?: string;
1110
+ };
882
1111
  /**
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.
1112
+ * Resolves domain 1 from `PassflowConfig.url`.
1113
+ *
1114
+ * `url` is OPTIONAL, and the absent case is specified rather than guessed: the
1115
+ * domain is EMPTY (`null`), and nothing throws. Throwing would break apps that
1116
+ * never enabled step-up, and substituting a default origin — `PASSFLOW_CLOUD_URL`,
1117
+ * the document origin, the origin the first 401 came from — would be the SDK
1118
+ * inferring a trust boundary it has no information about. An empty domain is not
1119
+ * silent: the first parseable challenge on an attached surface must raise a
1120
+ * diagnostic naming `url` as the fix.
1121
+ *
1122
+ * Note this deliberately does NOT mirror `AxiosClient`'s `url || PASSFLOW_CLOUD_URL`
1123
+ * fallback. That fallback decides where to send our own traffic; this decides
1124
+ * whose 401s may drive a security prompt, and the two questions do not share an
1125
+ * answer.
886
1126
  */
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;
1127
+ export declare const resolveUpgradeDomain: (url?: string) => UpgradeDomain | null;
1128
+ /** The raw `POST /auth/upgrade/start` body, snake_case exactly as the server sends it. */
1129
+ export type UpgradeStartWire = {
1130
+ challenge_id: string;
1131
+ method: string;
1132
+ /** RFC 3339. The server enforces the TTL; the SDK carries this for display only. */
1133
+ expires_at: string;
1134
+ /** WebAuthn assertion options, present only for a passkey upgrade. */
1135
+ webauthn?: PublicKeyCredentialRequestOptionsJSON;
1136
+ /** Masked delivery target (`j***@x.com`), present only for email / SMS OTP. */
1137
+ code_sent_to?: string;
896
1138
  };
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
1139
  /**
900
- * One diagnostic record.
1140
+ * The `upgrade` field of `POST /auth/refresh` — the commit round.
1141
+ * Also the whole body of `POST /auth/session/upgrade`.
901
1142
  *
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.
1143
+ * The server types `assertion` as `json.RawMessage`, so a new factor can extend
1144
+ * the payload without a wire-format change.
907
1145
  */
908
- type UpgradeDiagnostic = {
909
- status: number;
1146
+ export type UpgradeRefreshField = {
1147
+ type: string;
1148
+ assertion: UpgradeAssertion;
1149
+ };
1150
+ export type PassflowAuthorizationResponse = Tokens & {
910
1151
  /**
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.
1152
+ * The authorization code a PKCE app answers with in place of tokens. The SDK
1153
+ * redeems it, so a response handed back to a caller never carries one.
914
1154
  */
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
- };
1155
+ code?: string;
1156
+ /** Where the server sends the user next; a password reset answers with its link's redirect. */
1157
+ redirect_url?: string;
1158
+ challenge_id?: string;
1159
+ tfa_token?: string;
1160
+ token_delivery?: 'json_body' | 'cookie' | 'mobile';
1161
+ cookies?: string[];
1162
+ csrf_token?: string;
1163
+ /** `true` when the server needs the email proven before this sign-in finishes. No tokens come with it. */
1164
+ email_verification_required?: boolean;
1165
+ /** Human-readable text from the server, e.g. "We sent a code to a***@example.com." */
1166
+ message?: string;
930
1167
  };
931
- /** Where diagnostics go. `console.warn` is the default sink, not the only one. */
932
- type UpgradeDiagnosticSink = (diagnostic: UpgradeDiagnostic) => void;
933
1168
  /**
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".
1169
+ * A sign-up, sign-in or password change that waits for the email to be proven.
1170
+ * With `challenge_id`: a code was emailed, finish with `Passflow.verifyEmailCode`.
1171
+ * Without: the code budget is spent and a link was emailed instead.
1172
+ * `message` is what the server sent; a malformed answer may leave it out.
945
1173
  */
946
- export declare const parseUpgradeChallenge: (status: number, getHeader: (name: string) => string | undefined | null, body?: unknown) => UpgradeChallenge | undefined;
1174
+ export type PassflowEmailVerificationStep = {
1175
+ email_verification_required: true;
1176
+ message: string;
1177
+ challenge_id?: string;
1178
+ };
1179
+ /** The emailed code for a `PassflowEmailVerificationStep` that carried a `challenge_id`. */
1180
+ export type PassflowEmailCodePayload = {
1181
+ challenge_id: string;
1182
+ otp: string;
1183
+ };
947
1184
  /**
948
- * Public types of multi-tab-safe token refresh.
949
- *
950
- * @module refresh/types
1185
+ * Whether an auth answer is an email verification step rather than a session. Only the
1186
+ * `email_verification_required` flag is checked, so an answer with the flag is never taken
1187
+ * for a session.
951
1188
  */
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;
1189
+ export declare const isEmailVerificationStep: (response: unknown) => response is PassflowEmailVerificationStep;
1190
+ export type PassflowValidationResponse = Tokens & {
1191
+ redirect_url: string;
1192
+ challenge_id?: string;
1193
+ tfa_token?: string;
1194
+ /** PKCE app: the code to redeem with the verifier, in place of tokens. */
1195
+ code?: string;
1196
+ };
1197
+ export type PassflowSuccessResponse = {
1198
+ result: 'ok';
1199
+ };
1200
+ export type PassflowLogoutResponse = {
1201
+ status: 'ok';
1202
+ };
1203
+ export interface PassflowSessionValidationResponse {
1204
+ valid: boolean;
1205
+ user?: {
1206
+ id: string;
1207
+ email?: string;
1208
+ username?: string;
1209
+ [key: string]: unknown;
1210
+ };
1211
+ expires_at?: number;
957
1212
  }
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
- });
1213
+ export type PassflowResponseError = {
1214
+ error: {
1215
+ id: string;
1216
+ message: string;
1217
+ status: number;
1218
+ location: string;
1219
+ time: string;
1220
+ };
1221
+ };
1222
+ /** Id of the error a call rejects with when the Passflow API cannot be reached or its gateway answers 502, 503 or 504. */
1223
+ export declare const SERVICE_UNAVAILABLE_ERROR_ID = "error.service.unavailable";
1224
+ /** Message of the {@link SERVICE_UNAVAILABLE_ERROR_ID} error. */
1225
+ export declare const SERVICE_UNAVAILABLE_MESSAGE = "Passflow is temporarily unavailable. Please try again in a moment.";
1226
+ export declare class PassflowError extends Error {
1227
+ id: string;
1228
+ message: string;
1229
+ status: number;
1230
+ location: string;
1231
+ time: string;
1232
+ /** Declared here rather than inherited: `Error.cause` is ES2022 and this build targets ES2021 libs. */
1233
+ readonly cause?: unknown;
1234
+ constructor(error: PassflowResponseError['error'], options?: {
1235
+ cause?: unknown;
1236
+ });
1354
1237
  }
1355
1238
  /** Id of the 403 a password sign-in answers with when the user must change the password first. */
1356
1239
  export declare const PASSWORD_CHANGE_REQUIRED_ERROR_ID = "error.api.password.change.required";
1240
+ /** The covered request carried no `X-Passflow-Anti-Bot` header on a `human_only` app (403). */
1241
+ export declare const ANTI_BOT_REQUIRED_ERROR_ID = "error.api.anti_bot.required";
1242
+ /** The anti-bot value was wrong, expired or used before (403). The built-in check is resent once. */
1243
+ export declare const ANTI_BOT_FAILED_ERROR_ID = "error.api.anti_bot.failed";
1244
+ /** The server could not check the anti-bot value right now (503, `Retry-After`). */
1245
+ export declare const ANTI_BOT_UNAVAILABLE_ERROR_ID = "error.api.anti_bot.unavailable";
1246
+ /** A `human_only` app uses its own provider and `setAntiBotTokenProvider()` was not called. */
1247
+ export declare const ANTI_BOT_PROVIDER_MISSING_ERROR_ID = "error.anti_bot.provider_missing";
1248
+ /** The token provider rejected or returned an empty string. */
1249
+ export declare const ANTI_BOT_PROVIDER_FAILED_ERROR_ID = "error.anti_bot.provider_failed";
1250
+ /** The built-in proof of work could not be solved: no Web Crypto, a worker error, or no number found. */
1251
+ export declare const ANTI_BOT_SOLVE_FAILED_ERROR_ID = "error.anti_bot.solve_failed";
1357
1252
  /** The sign-in was refused until the user changes the password; no token comes with it. */
1358
1253
  export declare class PassflowPasswordChangeRequiredError extends PassflowError {
1359
1254
  constructor(error: PassflowResponseError['error'], options?: {
@@ -1589,6 +1484,60 @@ export type AppSettings = {
1589
1484
  login_app_theme: LoginWebAppTheme;
1590
1485
  login_app_settings?: unknown;
1591
1486
  token_delivery_method?: TokenDeliveryMethod;
1487
+ /** Absent on servers that do not report it, which means `bot_friendly`. */
1488
+ bot_mode?: BotMode;
1489
+ /** Only when `human_only`. Absent on a `human_only` app means the built-in check. */
1490
+ anti_bot?: AntiBotSettings;
1491
+ };
1492
+ /** `human_only`: every sign-in start must carry an anti-bot value in `X-Passflow-Anti-Bot`. */
1493
+ export type BotMode = 'bot_friendly' | 'human_only';
1494
+ /** `builtin` is Passflow's proof of work; the others are the customer's own provider. */
1495
+ export type AntiBotProviderName = 'builtin' | 'turnstile' | 'hcaptcha' | 'recaptcha';
1496
+ export type AntiBotSettings = {
1497
+ provider: AntiBotProviderName;
1498
+ /** The provider's public site key, for a widget. Absent for `builtin`. */
1499
+ site_key?: string;
1500
+ };
1501
+ /**
1502
+ * `POST /auth/anti-bot/challenge` and `POST /oidc/device/anti-bot/challenge`. The answer is the
1503
+ * integer `number` in `[0, max]` with `hex(SHA-256(salt + ":" + number)) === challenge`.
1504
+ */
1505
+ export type AntiBotChallenge = {
1506
+ algorithm: 'SHA-256';
1507
+ app: string;
1508
+ exp: number;
1509
+ max: number;
1510
+ salt: string;
1511
+ challenge: string;
1512
+ signature: string;
1513
+ };
1514
+ /** The decoded `X-Passflow-Anti-Bot` value of the built-in check. */
1515
+ export type AntiBotSolution = Omit<AntiBotChallenge, 'algorithm'> & {
1516
+ number: number;
1517
+ };
1518
+ /** Options of one sign-in call. */
1519
+ export type PassflowAuthOptions = {
1520
+ /**
1521
+ * Sends `X-Passflow-Agent-Tool: 1`. Set only by agent tool actions; the server then refuses a
1522
+ * device parent. A federated start with it is sent as a POST, because a header cannot ride a
1523
+ * navigation.
1524
+ */
1525
+ agentTool?: boolean;
1526
+ };
1527
+ /** `POST /auth/federated/start/{provider}`: the same fields the GET start takes as query parameters. */
1528
+ export type PassflowFederatedStartBody = {
1529
+ device?: string;
1530
+ redirect_url: string;
1531
+ scopes: string[];
1532
+ create_tenant?: boolean;
1533
+ invite_token?: string;
1534
+ parent_challenge_id?: string;
1535
+ code_challenge?: string;
1536
+ code_challenge_method?: 'S256';
1537
+ state?: string;
1538
+ };
1539
+ export type PassflowFederatedStartResponse = {
1540
+ auth_url: string;
1592
1541
  };
1593
1542
  /**
1594
1543
  * A write-only app secret that the admin API clears by name with
@@ -2025,171 +1974,604 @@ export type TwoFactorVerifyResponse = Tokens & TwoFactorParentAnswer & {
2025
1974
  code?: string;
2026
1975
  };
2027
1976
  /**
2028
- * Options for the call that completes a sign-in with its second factor.
1977
+ * Options for the call that completes a sign-in with its second factor.
1978
+ */
1979
+ export type TwoFactorCompletionOptions = {
1980
+ /**
1981
+ * Ask the server to trust this device, so later sign-ins from it skip the
1982
+ * second factor where the app allows that. The server keeps the trust in
1983
+ * an HttpOnly cookie; nothing is stored by the SDK.
1984
+ */
1985
+ trustDevice?: boolean;
1986
+ };
1987
+ /**
1988
+ * A device the user trusted to stand in for their second factor on this app.
1989
+ */
1990
+ export type TwoFactorTrustedDevice = {
1991
+ id: string;
1992
+ user_agent?: string;
1993
+ created_at: string;
1994
+ last_used_at?: string;
1995
+ expires_at: string;
1996
+ /** True for the device the request came from. */
1997
+ current: boolean;
1998
+ };
1999
+ /** GET /v2/user/2fa/trusted-devices */
2000
+ export type TwoFactorTrustedDevicesResponse = {
2001
+ devices: TwoFactorTrustedDevice[];
2002
+ };
2003
+ export type TwoFactorRecoveryResponse = Tokens & {
2004
+ success?: true;
2005
+ /** Codes left after this one. The server may leave it out. */
2006
+ remaining_recovery_codes?: number;
2007
+ /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
2008
+ code?: string;
2009
+ };
2010
+ export type TwoFactorDisableResponse = {
2011
+ disabled: true;
2012
+ };
2013
+ export type TwoFactorRegenerateResponse = {
2014
+ recovery_codes: string[];
2015
+ };
2016
+ /**
2017
+ * Two-Factor magic link error codes
2018
+ */
2019
+ export type TwoFactorSetupMagicLinkErrorCode = 'INVALID_TOKEN' | 'EXPIRED_TOKEN' | 'REVOKED_TOKEN' | 'ALREADY_USED' | 'RATE_LIMITED' | 'SERVER_ERROR';
2020
+ /**
2021
+ * Two-Factor magic link error details
2022
+ */
2023
+ export type TwoFactorSetupMagicLinkError = {
2024
+ code: TwoFactorSetupMagicLinkErrorCode;
2025
+ message: string;
2026
+ retryAfter?: number;
2027
+ };
2028
+ /**
2029
+ * Response from magic link validation endpoint
2030
+ * Backend returns scoped session token for 2FA setup operations
2031
+ */
2032
+ export type TwoFactorSetupMagicLinkValidationResponse = {
2033
+ success: boolean;
2034
+ sessionToken?: string;
2035
+ userId?: string;
2036
+ expiresIn?: number;
2037
+ appId?: string | null;
2038
+ error?: TwoFactorSetupMagicLinkError;
2039
+ };
2040
+ /**
2041
+ * Internal session state for magic link 2FA setup
2042
+ * Stored in memory only, not persisted across page reloads
2043
+ */
2044
+ export type TwoFactorSetupMagicLinkSession = {
2045
+ sessionToken: string;
2046
+ userId: string;
2047
+ appId?: string | null;
2048
+ scope: '2fa_setup';
2049
+ timestamp: number;
2050
+ expiresAt: number;
2051
+ };
2052
+ /**
2053
+ * Two-Factor method types
2054
+ */
2055
+ export type TwoFactorMethod = 'totp' | 'email_otp' | 'sms_otp' | 'passkey' | 'push_fcm' | 'push_webpush' | 'recovery_codes';
2056
+ /**
2057
+ * Challenge Request for v2 2FA flow
2058
+ */
2059
+ export interface TwoFactorChallengeRequest {
2060
+ first_factor_method?: string;
2061
+ trust_device?: boolean;
2062
+ }
2063
+ /**
2064
+ * Challenge Response from v2 2FA flow
2065
+ */
2066
+ export interface TwoFactorChallengeResponse {
2067
+ challenge_id: string;
2068
+ method: TwoFactorMethod;
2069
+ /** Other methods the user can switch to. Absent from the answer to a switch. */
2070
+ alternative_methods?: TwoFactorMethod[];
2071
+ expires_at: string;
2072
+ code_sent_to?: string;
2073
+ webauthn_options?: unknown;
2074
+ /** Digits in the TOTP code. TOTP challenges only. */
2075
+ totp_digits?: 6 | 8;
2076
+ /** Seconds per TOTP step. TOTP challenges only. */
2077
+ totp_period?: number;
2078
+ /**
2079
+ * Whether this sign-in may ask to trust the device (`trust_device`), as the app allows.
2080
+ * Absent from servers older than the flag; treat absent as unknown.
2081
+ */
2082
+ device_trust_available?: boolean;
2083
+ }
2084
+ /**
2085
+ * Verify Request for v2 2FA flow
2086
+ */
2087
+ export interface TwoFactorVerifyRequestV2 {
2088
+ challenge_id: string;
2089
+ method: TwoFactorMethod;
2090
+ response: string;
2091
+ trust_device?: boolean;
2092
+ }
2093
+ /**
2094
+ * Verify Response from v2 2FA flow
2095
+ */
2096
+ export interface TwoFactorVerifyResponseV2 extends TwoFactorParentAnswer {
2097
+ access_token?: string;
2098
+ refresh_token?: string;
2099
+ id_token?: string;
2100
+ /** On a PKCE app; `TwoFactorService` redeems it, so its callers never see one. */
2101
+ code?: string;
2102
+ }
2103
+ /**
2104
+ * Registered Two-Factor Method
2105
+ */
2106
+ export interface RegisteredTwoFactorMethod {
2107
+ id?: string;
2108
+ method: TwoFactorMethod;
2109
+ name?: string;
2110
+ user_id?: string;
2111
+ app_id?: string;
2112
+ /** `true` when this passkey also signs the user in as the first factor. */
2113
+ is_passkey_for_1fa?: boolean;
2114
+ created_at?: string;
2115
+ updated_at?: string;
2116
+ last_used_at?: string;
2117
+ }
2118
+ /**
2119
+ * Alternative Method Request
2120
+ */
2121
+ export interface TwoFactorAlternativeRequest {
2122
+ challenge_id: string;
2123
+ method: TwoFactorMethod;
2124
+ }
2125
+ export interface CLIAuthStatusResponse {
2126
+ status: 'pending' | 'completed' | 'expired' | 'failed';
2127
+ expires_at?: string;
2128
+ challenge?: Record<string, unknown>;
2129
+ access_token?: string;
2130
+ refresh_token?: string;
2131
+ user_id?: string;
2132
+ expires_in?: number;
2133
+ error?: string;
2134
+ }
2135
+ export interface CLIAuthCompleteRequest {
2136
+ session_id: string;
2137
+ access_token: string;
2138
+ refresh_token: string;
2139
+ user_id: string;
2140
+ expires_in: number;
2141
+ }
2142
+ /** The covered call an anti-bot value is produced for. */
2143
+ type AntiBotOperation = 'sign-in' | 'sign-up' | 'passwordless.start' | 'passkey.register' | 'passkey.authenticate' | 'password-reset.send' | 'federated.start' | 'session.exchange' | 'device.authenticate' | 'device.passkey.start';
2144
+ /** What a token provider is asked for. `action` is always `'passflow_auth'`. */
2145
+ type AntiBotTokenContext = {
2146
+ action: 'passflow_auth';
2147
+ operation: AntiBotOperation;
2148
+ };
2149
+ /**
2150
+ * The customer's own anti-bot provider (Turnstile, hCaptcha, reCAPTCHA): resolves with a token
2151
+ * the server verifies with that provider. A function with no parameters is accepted too.
2152
+ */
2153
+ type AntiBotTokenProvider = (context: AntiBotTokenContext) => Promise<string>;
2154
+ /** The device verification page's context for `POST /oidc/device/anti-bot/challenge`. */
2155
+ type AntiBotDeviceContext = {
2156
+ userCode: string;
2157
+ csrfToken: string;
2158
+ };
2159
+ /** The bot mode and provider an anti-bot value is produced for. */
2160
+ type AntiBotAppSettings = Pick<AppSettings, 'bot_mode' | 'anti_bot'>;
2161
+ type AntiBotTokenRequest = {
2162
+ operation: AntiBotOperation;
2163
+ /** Email, username or phone, sent with the challenge request; used by the server for difficulty only. */
2164
+ identifier?: string;
2165
+ /** Bot mode and provider when not this app's `/app/settings` (the device page: `/oidc/device/info`). */
2166
+ settings?: AntiBotAppSettings;
2167
+ device?: AntiBotDeviceContext;
2168
+ };
2169
+ declare class DeviceService {
2170
+ private storageManager;
2171
+ /** The id this service minted; used when the storage keeps nothing (server rendering). */
2172
+ private mintedDeviceId;
2173
+ constructor(storageManager?: StorageManager);
2174
+ getDeviceId(): string;
2175
+ generateUniqueDeviceId(): string;
2176
+ }
2177
+ /**
2178
+ * Passflow event types
2029
2179
  */
2030
- export type TwoFactorCompletionOptions = {
2180
+ export declare enum PassflowEvent {
2181
+ SignIn = "signin",
2182
+ SignInStart = "signin:start",
2183
+ Register = "register",
2184
+ RegisterStart = "register:start",
2185
+ /** A sign-up, sign-in or password change is waiting for the email to be proven (no session yet). */
2186
+ EmailVerificationRequired = "email-verification:required",
2187
+ SignOut = "signout",
2188
+ SessionRestored = "session:restored",
2189
+ SessionExpired = "session:expired",
2190
+ Error = "error",
2191
+ Refresh = "refresh",
2192
+ RefreshStart = "refresh:start",
2193
+ TokenCacheExpired = "token-cache-expired",
2194
+ TwoFactorRequired = "2fa:required",
2195
+ TwoFactorSetupStarted = "2fa:setup_started",
2196
+ TwoFactorEnabled = "2fa:enabled",
2197
+ TwoFactorDisabled = "2fa:disabled",
2198
+ TwoFactorVerified = "2fa:verified",
2199
+ TwoFactorRecoveryUsed = "2fa:recovery_used",
2200
+ TwoFactorRecoveryCodesLow = "2fa:recovery_low",
2201
+ TwoFactorRecoveryCodesExhausted = "2fa:recovery_exhausted",
2202
+ TwoFactorSetupMagicLinkValidated = "2fa:magic_link_validated",
2203
+ TwoFactorSetupMagicLinkFailed = "2fa:magic_link_failed",
2204
+ TwoFactorChallengeReceived = "two_factor_challenge_received",
2205
+ TwoFactorMethodSwitched = "two_factor_method_switched",
2031
2206
  /**
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.
2207
+ * @deprecated The server keeps device trust in a cookie and the SDK no longer emits this event.
2035
2208
  */
2036
- trustDevice?: boolean;
2037
- };
2209
+ TwoFactorDeviceTrusted = "two_factor_device_trusted",
2210
+ /** Token refresh entered a transient-failure episode (once per episode, per tab). */
2211
+ RefreshFailing = "refresh:failing",
2212
+ /** The transient-failure episode ended with a successful refresh or adoption. */
2213
+ RefreshRecovered = "refresh:recovered",
2214
+ /** A `human_only` app's covered call started producing its anti-bot value (a proof of work, or the provider's token). */
2215
+ AntiBotSolving = "anti-bot:solving",
2216
+ /** The anti-bot value is ready; the covered request goes out next. */
2217
+ AntiBotSolved = "anti-bot:solved"
2218
+ }
2038
2219
  /**
2039
- * A device the user trusted to stand in for their second factor on this app.
2220
+ * The SDK operation that failed (`ErrorPayload.operation`). The SDK sets it on every `Error` it
2221
+ * emits, so a subscriber can tell a failed sign-in from a failed refresh without parsing messages.
2040
2222
  */
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
- };
2223
+ 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
2224
  /**
2068
- * Two-Factor magic link error codes
2225
+ * Error payload interface for structured error information
2069
2226
  */
2070
- export type TwoFactorSetupMagicLinkErrorCode = 'INVALID_TOKEN' | 'EXPIRED_TOKEN' | 'REVOKED_TOKEN' | 'ALREADY_USED' | 'RATE_LIMITED' | 'SERVER_ERROR';
2227
+ interface ErrorPayload {
2228
+ message: string;
2229
+ code?: string | number;
2230
+ details?: unknown;
2231
+ originalError?: unknown;
2232
+ /** The operation that failed. Always set by the SDK. */
2233
+ operation?: PassflowOperation;
2234
+ /** For operation `refresh` | `upgrade.commit`: what asked for the refresh. */
2235
+ source?: RefreshTrigger;
2236
+ /** For operation `refresh` | `upgrade.commit`: how the failure was classified and what follows. */
2237
+ refresh?: RefreshErrorInfo;
2238
+ }
2239
+ /** An `Error` payload as the SDK reports it: `operation` is required. */
2240
+ type OperationErrorPayload = ErrorPayload & {
2241
+ operation: PassflowOperation;
2242
+ };
2243
+ /** Which call produced an `EmailVerificationRequired` event. */
2244
+ type PassflowEmailVerificationOperation = 'sign-up' | 'sign-in' | 'reset-password';
2071
2245
  /**
2072
- * Two-Factor magic link error details
2246
+ * Event-specific payload types
2073
2247
  */
2074
- export type TwoFactorSetupMagicLinkError = {
2075
- code: TwoFactorSetupMagicLinkErrorCode;
2076
- message: string;
2077
- retryAfter?: number;
2248
+ type PassflowEventPayload = {
2249
+ [PassflowEvent.SignIn]: {
2250
+ tokens?: Tokens;
2251
+ parsedTokens?: ParsedTokens;
2252
+ /** `'other-tab'` only when an ended tab revives on a new session found in storage. Absent on this tab's own sign-in. */
2253
+ origin?: EventOrigin;
2254
+ /**
2255
+ * `'federated-landing'`: a federated redirect landed here and this instance exchanged its code.
2256
+ * `'tokens-in-url'`: tokens received in this page's URL were verified and saved.
2257
+ * `'oidc-landing'`: hosted sign-in returned an authorization code here and this instance redeemed it.
2258
+ */
2259
+ source?: 'federated-landing' | 'tokens-in-url' | 'oidc-landing';
2260
+ /** For `source: 'tokens-in-url'`: the `state` the URL carried with the tokens, when it had one. */
2261
+ state?: string;
2262
+ };
2263
+ [PassflowEvent.SignInStart]: {
2264
+ email?: string;
2265
+ provider?: string;
2266
+ };
2267
+ [PassflowEvent.Register]: {
2268
+ tokens?: Tokens;
2269
+ parsedTokens?: ParsedTokens;
2270
+ };
2271
+ [PassflowEvent.RegisterStart]: {
2272
+ email?: string;
2273
+ };
2274
+ [PassflowEvent.EmailVerificationRequired]: {
2275
+ /** The address the code or link went to, when the SDK knows it. */
2276
+ email?: string;
2277
+ /** Present when a code was emailed; absent when a link was emailed instead. */
2278
+ challengeId?: string;
2279
+ operation: PassflowEmailVerificationOperation;
2280
+ };
2281
+ [PassflowEvent.SignOut]: {
2282
+ /** `sub` of the session that ended, when known. */
2283
+ userId?: string;
2284
+ /** Always set by the SDK. `'other-tab'`: another tab signed out, or shared storage was emptied. */
2285
+ origin?: EventOrigin;
2286
+ };
2287
+ [PassflowEvent.SessionRestored]: {
2288
+ id: string;
2289
+ email?: string;
2290
+ username?: string;
2291
+ [key: string]: unknown;
2292
+ };
2293
+ [PassflowEvent.SessionExpired]: {
2294
+ reason: SessionExpiredReason;
2295
+ /** Always set by the SDK. */
2296
+ origin?: EventOrigin;
2297
+ };
2298
+ [PassflowEvent.Error]: ErrorPayload;
2299
+ [PassflowEvent.Refresh]: {
2300
+ tokens?: Tokens;
2301
+ parsedTokens?: ParsedTokens;
2302
+ /**
2303
+ * Always set by the SDK. `'refresh'`: this tab's request; `'upgrade'`: this tab's step-up
2304
+ * commit; `'adopted'`: tokens this tab did not request (another tab's, or found in storage).
2305
+ */
2306
+ source?: 'refresh' | 'upgrade' | 'adopted';
2307
+ };
2308
+ [PassflowEvent.RefreshStart]: {
2309
+ tokenId?: string;
2310
+ };
2311
+ [PassflowEvent.TokenCacheExpired]: {
2312
+ isExpired: boolean;
2313
+ };
2314
+ [PassflowEvent.TwoFactorRequired]: {
2315
+ email: string;
2316
+ challengeId: string;
2317
+ tfaToken: string;
2318
+ };
2319
+ [PassflowEvent.TwoFactorSetupStarted]: {
2320
+ secret: string;
2321
+ method?: TwoFactorMethod;
2322
+ };
2323
+ [PassflowEvent.TwoFactorEnabled]: {
2324
+ recoveryCodes: string[];
2325
+ clearRecoveryCodes: () => void;
2326
+ };
2327
+ [PassflowEvent.TwoFactorDisabled]: Record<string, never>;
2328
+ [PassflowEvent.TwoFactorVerified]: {
2329
+ tokens?: Tokens;
2330
+ };
2331
+ /** `remainingCodes` is undefined when the server did not send the count. */
2332
+ [PassflowEvent.TwoFactorRecoveryUsed]: {
2333
+ tokens?: Tokens;
2334
+ remainingCodes?: number;
2335
+ };
2336
+ [PassflowEvent.TwoFactorRecoveryCodesLow]: {
2337
+ tokens?: Tokens;
2338
+ remainingCodes: number;
2339
+ };
2340
+ [PassflowEvent.TwoFactorRecoveryCodesExhausted]: {
2341
+ tokens?: Tokens;
2342
+ };
2343
+ [PassflowEvent.TwoFactorSetupMagicLinkValidated]: {
2344
+ userId: string;
2345
+ appId?: string | null;
2346
+ expiresIn: number;
2347
+ sessionToken: string;
2348
+ };
2349
+ [PassflowEvent.TwoFactorSetupMagicLinkFailed]: {
2350
+ error: {
2351
+ code: 'INVALID_TOKEN' | 'EXPIRED_TOKEN' | 'REVOKED_TOKEN' | 'ALREADY_USED' | 'RATE_LIMITED' | 'SERVER_ERROR';
2352
+ message: string;
2353
+ retryAfter?: number;
2354
+ };
2355
+ };
2356
+ [PassflowEvent.TwoFactorChallengeReceived]: {
2357
+ challengeId: string;
2358
+ method: TwoFactorMethod;
2359
+ alternativeMethods: TwoFactorMethod[];
2360
+ };
2361
+ [PassflowEvent.TwoFactorMethodSwitched]: {
2362
+ challengeId: string;
2363
+ method: TwoFactorMethod;
2364
+ alternativeMethods: TwoFactorMethod[];
2365
+ };
2366
+ [PassflowEvent.TwoFactorDeviceTrusted]: Record<string, never>;
2367
+ [PassflowEvent.RefreshFailing]: {
2368
+ /** Epoch ms of the episode's first transient failure. */
2369
+ since: number;
2370
+ /** Epoch ms of the shared pending retry, when known. */
2371
+ nextRetryAt?: number;
2372
+ /** `'this-tab'` when this tab's own request failed. */
2373
+ origin: EventOrigin;
2374
+ };
2375
+ [PassflowEvent.RefreshRecovered]: {
2376
+ /** Same value as the `RefreshFailing` that opened the episode. */
2377
+ since: number;
2378
+ /** `'this-tab'`: own request succeeded; `'other-tab'`: adopted another tab's tokens. */
2379
+ origin: EventOrigin;
2380
+ };
2381
+ [PassflowEvent.AntiBotSolving]: {
2382
+ operation: AntiBotOperation;
2383
+ provider: AntiBotProviderName;
2384
+ };
2385
+ [PassflowEvent.AntiBotSolved]: {
2386
+ operation: AntiBotOperation;
2387
+ provider: AntiBotProviderName;
2388
+ };
2078
2389
  };
2079
2390
  /**
2080
- * Response from magic link validation endpoint
2081
- * Backend returns scoped session token for 2FA setup operations
2391
+ * Passflow subscriber interface
2082
2392
  */
2083
- export type TwoFactorSetupMagicLinkValidationResponse = {
2084
- success: boolean;
2085
- sessionToken?: string;
2086
- userId?: string;
2087
- expiresIn?: number;
2088
- appId?: string | null;
2089
- error?: TwoFactorSetupMagicLinkError;
2090
- };
2393
+ interface PassflowSubscriber {
2394
+ onAuthChange<E extends PassflowEvent>(eventType: E, payload?: PassflowEventPayload[E]): void;
2395
+ }
2091
2396
  /**
2092
- * Internal session state for magic link 2FA setup
2093
- * Stored in memory only, not persisted across page reloads
2397
+ * Store for managing Passflow event subscriptions
2094
2398
  */
2095
- export type TwoFactorSetupMagicLinkSession = {
2096
- sessionToken: string;
2097
- userId: string;
2098
- appId?: string | null;
2099
- scope: '2fa_setup';
2100
- timestamp: number;
2101
- expiresAt: number;
2399
+ declare class PassflowStore {
2400
+ private subscribers;
2401
+ /**
2402
+ * Subscribe to authentication events
2403
+ * @param subscriber The subscriber to register
2404
+ * @param events Optional specific events to subscribe to
2405
+ */
2406
+ subscribe(subscriber: PassflowSubscriber, events?: PassflowEvent[]): void;
2407
+ /**
2408
+ * Unsubscribe from authentication events
2409
+ * @param subscriber The subscriber to unregister
2410
+ * @param events Optional specific events to unsubscribe from
2411
+ */
2412
+ unsubscribe(subscriber: PassflowSubscriber, events?: PassflowEvent[]): void;
2413
+ /**
2414
+ * Notify subscribers of an event
2415
+ * @param eventType The type of event that occurred
2416
+ * @param payload Event-specific payload data
2417
+ */
2418
+ notify<E extends PassflowEvent>(eventType: E, payload?: PassflowEventPayload[E]): void;
2419
+ /**
2420
+ * Notify subscribers of an error, at most once per error object (`notifyError` in `error-report.ts`).
2421
+ * @returns whether the event was emitted
2422
+ */
2423
+ notifyError(payload: OperationErrorPayload): boolean;
2424
+ }
2425
+ /** A value for `X-Passflow-Anti-Bot`; `builtin` tells whether a `failed` answer may be resent once. */
2426
+ type AntiBotHeader = {
2427
+ value: string;
2428
+ builtin: boolean;
2102
2429
  };
2103
2430
  /**
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
2431
+ * Axios copies this object into each request's config (and each resend's), so the interceptors
2432
+ * may write `builtin` and `retried` on it.
2109
2433
  */
2110
- export interface TwoFactorChallengeRequest {
2111
- first_factor_method?: string;
2112
- trust_device?: boolean;
2113
- }
2434
+ type AntiBotMark = {
2435
+ operation: AntiBotOperation;
2436
+ identifier?: string;
2437
+ /** Set by the request interceptor: the value came from the built-in check. */
2438
+ builtin?: boolean;
2439
+ /** Set by the response interceptor before the one resend after `anti_bot.failed`. */
2440
+ retried?: boolean;
2441
+ };
2442
+ /** The error code RFC 9470 §3 defines for an insufficient authentication event. */
2443
+ export declare const INSUFFICIENT_USER_AUTHENTICATION = "insufficient_user_authentication";
2444
+ /** The ADR-2 error code `/auth/session/exchange` returns in its 403 body. */
2445
+ export declare const UPGRADE_REQUIRED = "upgrade_required";
2114
2446
  /**
2115
- * Challenge Response from v2 2FA flow
2447
+ * What the server demands before it will serve the original request.
2448
+ *
2449
+ * Both fields are optional because the two middlewares challenge on different
2450
+ * axes: RequireAuthLevel names an `acrValues` and omits `maxAge`, while
2451
+ * RequireFreshAuth does the reverse. A challenge carrying neither is still
2452
+ * valid — it means "re-prove a factor" without further qualification.
2116
2453
  */
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;
2454
+ type UpgradeChallenge = {
2129
2455
  /**
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.
2456
+ * Required authentication context class (`acr`), e.g. `'2'`.
2457
+ *
2458
+ * After a two-channel merge this is the raw list of the channel that SET THE
2459
+ * BAR, with the header preferred on a numeric tie. A channel that contributed
2460
+ * no level never supplies it — showing `"2gold"` as the bar would
2461
+ * misrepresent what the server demanded.
2132
2462
  */
2133
- device_trust_available?: boolean;
2134
- }
2463
+ acrValues?: string;
2464
+ /**
2465
+ * The parsed bar: `max` over each channel's `min` participating level
2466
+ * (§13.2.1a). `undefined` means unknown or unconstrained on this axis.
2467
+ *
2468
+ * Optional, and absent from the single-channel parsers' output, so
2469
+ * `parseChallengeHeader` / `parseChallengeBody` keep the exact shape they
2470
+ * ship with. `readUpgradeChallenge` always sets it when a level was parsed.
2471
+ */
2472
+ requiredLevel?: number;
2473
+ /** Maximum permitted age of the authentication event, in seconds. */
2474
+ maxAge?: number;
2475
+ /** The status that carried the challenge: 401 (protected resource) or 403 (session exchange). */
2476
+ status: number;
2477
+ /**
2478
+ * The factors this user can use, in the order to offer them, from the `403` body's
2479
+ * `available_factors`. Absent when the server does not send it (older servers, the header channel).
2480
+ */
2481
+ availableFactors?: UpgradeFactorType[];
2482
+ /**
2483
+ * The `403` body's `sign_in_required`: `true` when only a fresh sign-in can meet
2484
+ * the challenge, `false` when a step-up could but `availableFactors` names none
2485
+ * this account has (for example a device-bound passkey for AAL3). Absent from
2486
+ * older servers.
2487
+ */
2488
+ signInRequired?: boolean;
2489
+ /**
2490
+ * Every channel that PARSED AS A CHALLENGE in any field — not only the
2491
+ * channels that won a comparison. An opaque header contributes no constraint
2492
+ * yet must still be counted, because only something that saw and discarded it
2493
+ * can report it. `length === 2` means "both channels carried a challenge".
2494
+ *
2495
+ * Set by `readUpgradeChallenge`; absent from the single-channel parsers.
2496
+ */
2497
+ channels?: ChallengeChannel[];
2498
+ };
2499
+ /** Which wire channel a challenge was read from. */
2500
+ type ChallengeChannel = 'header' | 'body';
2135
2501
  /**
2136
- * Verify Request for v2 2FA flow
2502
+ * Reads a upgrade challenge out of a `WWW-Authenticate` header, or returns
2503
+ * `undefined` when the header is absent or describes some other failure.
2504
+ *
2505
+ * The header must both use the `Bearer` scheme and carry
2506
+ * `error="insufficient_user_authentication"`. A bare `WWW-Authenticate: Bearer`
2507
+ * (what an expired token produces) is deliberately NOT a upgrade challenge.
2137
2508
  */
2138
- export interface TwoFactorVerifyRequestV2 {
2139
- challenge_id: string;
2140
- method: TwoFactorMethod;
2141
- response: string;
2142
- trust_device?: boolean;
2143
- }
2509
+ export declare const parseChallengeHeader: (header: string | undefined | null, status: number) => UpgradeChallenge | undefined;
2144
2510
  /**
2145
- * Verify Response from v2 2FA flow
2511
+ * Reads a upgrade challenge out of the ADR-2 `403` body. Used as a fallback
2512
+ * for `/auth/session/exchange`, whose JSON body is the documented SDK contract
2513
+ * even though it also sets the standard header.
2146
2514
  */
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
- }
2515
+ export declare const parseChallengeBody: (body: unknown, status: number) => UpgradeChallenge | undefined;
2516
+ /** The bar a challenge demanded, or an elevation reached, on both axes. */
2517
+ type AssuranceBar = {
2518
+ /** The raw winning `acr_values` list, for display and diagnostics. */
2519
+ acrValues?: string;
2520
+ /** The parsed bar. `undefined` = unknown, or not constrained on this axis. */
2521
+ level?: number;
2522
+ /** The freshness constraint, when that is what was demanded. */
2523
+ maxAge?: number;
2524
+ };
2525
+ /** The reasons the SDK can decline to act on a challenge, or act on a suspect one. */
2526
+ type UpgradeDiagnosticReason = 'no-channel' | 'header-required-but-absent' | 'channels-disagree' | 'channels-unorderable' | 'zero-constraint-ignored' | 'challenge-out-of-scope' | 'elevated-insufficient' | 'replay-unsupported';
2154
2527
  /**
2155
- * Registered Two-Factor Method
2528
+ * One diagnostic record.
2529
+ *
2530
+ * A diagnostic is the only observable signal of the response-rewriting and the
2531
+ * misconfiguration this design warns about, so it routes through a callback
2532
+ * whose DEFAULT sink is `console.warn` — never `debug`, which is invisible in
2533
+ * every default configuration. A deployment where step-up silently never fires
2534
+ * must be distinguishable from one where it was never required.
2156
2535
  */
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
- }
2536
+ type UpgradeDiagnostic = {
2537
+ status: number;
2538
+ /**
2539
+ * The request's URL. The parser does not know it — it is handed a status, a
2540
+ * header reader and a body — so it emits `''` and the core, which owns the
2541
+ * request context, fills it in before forwarding to the sink.
2542
+ */
2543
+ url: string;
2544
+ reason: UpgradeDiagnosticReason;
2545
+ detail?: {
2546
+ obtained?: AssuranceBar;
2547
+ required?: AssuranceBar;
2548
+ /** Raw channel inputs, including values discarded as unorderable. */
2549
+ header?: string;
2550
+ body?: string;
2551
+ /** Which field was discarded, for `'zero-constraint-ignored'`. */
2552
+ field?: 'acr_values' | 'max_age';
2553
+ /** Which operation, for per-waiter reasons. */
2554
+ method?: string;
2555
+ /** A human-readable sentence naming the fix. The default sink prints it. */
2556
+ message?: string;
2557
+ };
2558
+ };
2559
+ /** Where diagnostics go. `console.warn` is the default sink, not the only one. */
2560
+ type UpgradeDiagnosticSink = (diagnostic: UpgradeDiagnostic) => void;
2169
2561
  /**
2170
- * Alternative Method Request
2562
+ * Resolves a upgrade challenge from a response, from either channel.
2563
+ *
2564
+ * The SHIPPED export: same name, same three parameters, same return, published
2565
+ * in `@passflow/core@0.14.1`. It is now a thin delegate over
2566
+ * `readUpgradeChallenge`, so there is one merge rule rather than two parsers
2567
+ * that can drift — but it discards the diagnostics, which is why a caller that
2568
+ * needs them (the core) calls the sibling directly.
2569
+ *
2570
+ * Returns `undefined` for every response that is not a upgrade challenge —
2571
+ * including ordinary `401`s, which callers must keep treating as "session
2572
+ * expired".
2171
2573
  */
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
- }
2574
+ export declare const parseUpgradeChallenge: (status: number, getHeader: (name: string) => string | undefined | null, body?: unknown) => UpgradeChallenge | undefined;
2193
2575
  /**
2194
2576
  * Handles a challenge the Passflow instance itself received, resolving with a
2195
2577
  * replayed response once the session has been elevated.
@@ -2213,6 +2595,12 @@ type AxiosRefreshHandler = (request: {
2213
2595
  trigger: 'pre-request';
2214
2596
  allowStale: boolean;
2215
2597
  }) => Promise<Tokens | undefined>;
2598
+ /**
2599
+ * Produces the `X-Passflow-Anti-Bot` value of a covered request. Installed by `Passflow` on its
2600
+ * auth client. Resolves `undefined` when the app is not `human_only`: the request then goes out
2601
+ * without the header, as it always has.
2602
+ */
2603
+ type AxiosAntiBotHandler = (mark: AntiBotMark) => Promise<AntiBotHeader | undefined>;
2216
2604
  declare class AxiosClient {
2217
2605
  private instance;
2218
2606
  protected storageManager: StorageManager;
@@ -2239,6 +2627,8 @@ declare class AxiosClient {
2239
2627
  private upgradeHandler?;
2240
2628
  /** Set by `Passflow` (its refresh controller). Absent on a client built standalone. */
2241
2629
  private refreshHandler?;
2630
+ /** Set by `Passflow` on its auth client. Absent elsewhere: no request is marked there. */
2631
+ private antiBotHandler?;
2242
2632
  /**
2243
2633
  * Passflow's own API as an interception scope, resolved ONCE here from
2244
2634
  * `PassflowConfig.url` so no wrapper or adapter ever derives it. `null` when
@@ -2268,6 +2658,11 @@ declare class AxiosClient {
2268
2658
  * call sends the stored bearer as it is, and an expired one gets the server's 401.
2269
2659
  */
2270
2660
  setRefreshHandler(handler: AxiosRefreshHandler | undefined): void;
2661
+ /**
2662
+ * Installs (or clears) the anti-bot handler. Only requests marked with `withAntiBot` consult it;
2663
+ * every other request is unchanged.
2664
+ */
2665
+ setAntiBotHandler(handler: AxiosAntiBotHandler | undefined): void;
2271
2666
  /**
2272
2667
  * Re-issues a request after an elevation. Exposed for the upgrade handler,
2273
2668
  * which owns the replay-once decision; the marker preventing a second
@@ -2312,6 +2707,29 @@ export declare class AuthAPI {
2312
2707
  protected axiosClient: AxiosClient;
2313
2708
  constructor(config: PassflowConfig, storageManager?: StorageManager, deviceService?: DeviceService);
2314
2709
  setAppId(appId: string): void;
2710
+ /** Installs (or clears) the handler that produces the anti-bot value of covered calls. */
2711
+ setAntiBotHandler(handler: AxiosAntiBotHandler | undefined): void;
2712
+ /**
2713
+ * A built-in anti-bot challenge for this app. `identifier` is used by the server for difficulty
2714
+ * only. Rejects only with a `PassflowError`.
2715
+ */
2716
+ antiBotChallenge(payload: {
2717
+ identifier?: string;
2718
+ }): Promise<AntiBotChallenge>;
2719
+ /**
2720
+ * A built-in anti-bot challenge for the device verification page, for the app of `user_code`.
2721
+ * Same-origin only, with the page's CSRF token. Rejects only with a `PassflowError`.
2722
+ */
2723
+ deviceAntiBotChallenge(payload: {
2724
+ user_code: string;
2725
+ identifier?: string;
2726
+ }, csrfToken: string): Promise<AntiBotChallenge>;
2727
+ /**
2728
+ * Starts a federated sign-in with a POST, which can carry the anti-bot and agent-tool headers,
2729
+ * and answers the provider's URL to navigate to. Sent with credentials, so the browser keeps the
2730
+ * challenge cookie the answer sets.
2731
+ */
2732
+ federatedStart(provider: string, body: PassflowFederatedStartBody, options?: PassflowAuthOptions): Promise<PassflowFederatedStartResponse>;
2315
2733
  /**
2316
2734
  * Refreshes the session, optionally committing an assurance upgrade.
2317
2735
  *
@@ -2328,8 +2746,8 @@ export declare class AuthAPI {
2328
2746
  * invalidate the session over a mistyped digit.
2329
2747
  */
2330
2748
  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>;
2749
+ signIn(payload: PassflowSignInPayload, deviceId: string, os: OS, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2750
+ signUp(payload: PassflowSignUpPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2333
2751
  /**
2334
2752
  * Redeems the code a PKCE sign-in answered with for the tokens it stands for.
2335
2753
  *
@@ -2338,9 +2756,9 @@ export declare class AuthAPI {
2338
2756
  */
2339
2757
  pkceExchange(code: string, verifier: string): Promise<PassflowAuthorizationResponse>;
2340
2758
  /** Rejects only with a `PassflowError`, because its body can hold the poll secret. */
2341
- passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, deviceId: string, os: OS): Promise<PassflowPasswordlessResponse>;
2759
+ passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, deviceId: string, os: OS, options?: PassflowAuthOptions): Promise<PassflowPasswordlessResponse>;
2342
2760
  /** Rejects only with a `PassflowError`, because its body holds the OTP. */
2343
- passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload): Promise<PassflowValidationResponse>;
2761
+ passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload, options?: PassflowAuthOptions): Promise<PassflowValidationResponse>;
2344
2762
  /**
2345
2763
  * Polls a magic-link sign-in waiting for approval from another device. Sent with credentials:
2346
2764
  * the trusted-device cookie is read when an approved row answers with its code. It rejects only
@@ -2367,12 +2785,12 @@ export declare class AuthAPI {
2367
2785
  validateEmailCode(payload: PassflowEmailCodePayload): Promise<PassflowAuthorizationResponse>;
2368
2786
  logOut(deviceId?: string, refreshToken?: string, isAdmin?: boolean): Promise<PassflowLogoutResponse>;
2369
2787
  validateSession(): Promise<PassflowSessionValidationResponse>;
2370
- sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload): Promise<PassflowSuccessResponse>;
2788
+ sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload, options?: PassflowAuthOptions): Promise<PassflowSuccessResponse>;
2371
2789
  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>;
2790
+ passkeyRegisterStart(payload: PassflowPasskeyRegisterStartPayload, deviceId: string, os: OS, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowPasskeyStart>;
2791
+ passkeyRegisterComplete(passkeyData: RegistrationResponseJSON, deviceId: string, challengeId: string, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2792
+ passkeyAuthenticateStart(payload: PassflowPasskeyAuthenticateStartPayload, deviceId: string, os: OS, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowPasskeyStart>;
2793
+ passkeyAuthenticateComplete(passkeyData: AuthenticationResponseJSON, deviceId: string, challengeId: string, isAdmin?: boolean, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
2376
2794
  passkeyValidate(otp: string, deviceId: string, challengeId: string, isAdmin?: boolean, appId?: string): Promise<PassflowValidationResponse>;
2377
2795
  }
2378
2796
  export declare class CLIAuthAPI {
@@ -2890,6 +3308,12 @@ export declare const APP_ID_HEADER_KEY = "X-Passflow-Clientid";
2890
3308
  export declare const AUTHORIZATION_HEADER_KEY = "Authorization";
2891
3309
  export declare const DEVICE_ID_HEADER_KEY = "X-Passflow-DeviceId";
2892
3310
  export declare const DEVICE_TYPE_HEADER_KEY = "X-Passflow-DeviceType";
3311
+ /** The anti-bot value of a covered sign-in request on a `human_only` app. */
3312
+ export declare const ANTI_BOT_HEADER_KEY = "X-Passflow-Anti-Bot";
3313
+ /** Set to `1` on requests an agent tool sends (`PassflowAuthOptions.agentTool`). */
3314
+ export declare const AGENT_TOOL_HEADER_KEY = "X-Passflow-Agent-Tool";
3315
+ /** The `action` a token provider receives; a reCAPTCHA score key must be executed with it. */
3316
+ export declare const ANTI_BOT_ACTION = "passflow_auth";
2893
3317
  /**
2894
3318
  * SDK version from package.json.
2895
3319
  * Useful for debugging and logging version information.
@@ -3640,242 +4064,6 @@ interface RefreshController {
3640
4064
  readonly ended: boolean;
3641
4065
  dispose(): void;
3642
4066
  }
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
4067
  export declare class TokenCacheService {
3880
4068
  private storageManager;
3881
4069
  private subscribeStore;
@@ -4123,10 +4311,10 @@ export declare class AuthService {
4123
4311
  * Forward tokens to BFF server for httpOnly cookie storage
4124
4312
  */
4125
4313
  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>;
4314
+ signIn(payload: PassflowSignInPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4315
+ signUp(payload: PassflowSignUpPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4316
+ passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, options?: PassflowAuthOptions): Promise<PassflowPasswordlessResponse>;
4317
+ passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload, options?: PassflowAuthOptions): Promise<PassflowValidationResponse>;
4130
4318
  /**
4131
4319
  * Waits for the magic-link sign-in this tab started to be approved on another device, polling
4132
4320
  * every 3 s until its expiry. Network errors, 429, 5xx and unreadable answers keep polling.
@@ -4259,13 +4447,27 @@ export declare class AuthService {
4259
4447
  * when the answer arrives, before anything is applied: see `assertSessionPin`.
4260
4448
  */
4261
4449
  refreshToken(upgrade?: UpgradeRefreshField, pin?: UpgradeSessionPin): Promise<PassflowAuthorizationResponse>;
4262
- sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload): Promise<PassflowSuccessResponse>;
4450
+ sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload, options?: PassflowAuthOptions): Promise<PassflowSuccessResponse>;
4263
4451
  resetPassword(newPassword: string, scopes?: string[], token?: string): Promise<PassflowAuthorizationResponse>;
4264
- passkeyRegister(payload: PassflowPasskeyRegisterStartPayload): Promise<PassflowAuthorizationResponse>;
4265
- passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload): Promise<PassflowAuthorizationResponse>;
4452
+ passkeyRegister(payload: PassflowPasskeyRegisterStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4453
+ passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
4454
+ /**
4455
+ * Whether a federated start goes out as a POST (`AuthAPI.federatedStart`) rather than as a
4456
+ * navigation to `createFederatedAuthUrl`: on a `human_only` app, whose start must carry the
4457
+ * anti-bot header, and for an agent tool, whose start must carry its own header. A header cannot
4458
+ * ride a navigation. An unknown bot mode keeps the navigation.
4459
+ */
4460
+ private usesFederatedPost;
4461
+ /** The body of a POST federated start: the same fields the GET start sends as query parameters. */
4462
+ private federatedStartBody;
4463
+ /**
4464
+ * The GET start URL. A `human_only` app refuses a start by navigation (403
4465
+ * `error.api.anti_bot.required`); `federatedAuthWithPopup` and `federatedAuthWithRedirect` POST
4466
+ * the start there instead.
4467
+ */
4266
4468
  createFederatedAuthUrl(payload: PassflowFederatedAuthExtendedPayload): string;
4267
- federatedAuthWithPopup(payload: PassflowFederatedAuthPayload): Promise<void>;
4268
- federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload): void;
4469
+ federatedAuthWithPopup(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): Promise<void>;
4470
+ federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): void;
4269
4471
  /**
4270
4472
  * Takes the slot for a `?code=` landing and exchanges the code in the background. `SignIn`,
4271
4473
  * `TwoFactorRequired` or an `Error` with operation `federated.redirect` reports the outcome.
@@ -5778,6 +5980,7 @@ export declare class Passflow {
5778
5980
  private invitationService;
5779
5981
  private tokenCacheService;
5780
5982
  private twoFactorService;
5983
+ private antiBot;
5781
5984
  tenant: TenantService;
5782
5985
  twoFactor: TwoFactorService;
5783
5986
  /**
@@ -6163,7 +6366,7 @@ export declare class Passflow {
6163
6366
  * }
6164
6367
  * ```
6165
6368
  */
6166
- signIn(payload: PassflowSignInPayload): Promise<PassflowAuthorizationResponse>;
6369
+ signIn(payload: PassflowSignInPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6167
6370
  /**
6168
6371
  * Register a new user account with email and password.
6169
6372
  *
@@ -6191,7 +6394,7 @@ export declare class Passflow {
6191
6394
  * }
6192
6395
  * ```
6193
6396
  */
6194
- signUp(payload: PassflowSignUpPayload): Promise<PassflowAuthorizationResponse>;
6397
+ signUp(payload: PassflowSignUpPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6195
6398
  /**
6196
6399
  * Initiate passwordless authentication by sending a magic link or OTP.
6197
6400
  *
@@ -6211,7 +6414,7 @@ export declare class Passflow {
6211
6414
  * console.log('Magic link sent:', response.success);
6212
6415
  * ```
6213
6416
  */
6214
- passwordlessSignIn(payload: PassflowPasswordlessSignInPayload): Promise<PassflowPasswordlessResponse>;
6417
+ passwordlessSignIn(payload: PassflowPasswordlessSignInPayload, options?: PassflowAuthOptions): Promise<PassflowPasswordlessResponse>;
6215
6418
  /**
6216
6419
  * Complete passwordless authentication by verifying the OTP or token.
6217
6420
  *
@@ -6235,7 +6438,7 @@ export declare class Passflow {
6235
6438
  * }
6236
6439
  * ```
6237
6440
  */
6238
- passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload): Promise<PassflowValidationResponse>;
6441
+ passwordlessSignInComplete(payload: PassflowPasswordlessSignInCompletePayload, options?: PassflowAuthOptions): Promise<PassflowValidationResponse>;
6239
6442
  /**
6240
6443
  * Waits for a magic-link sign-in this tab started to be approved on another device, then
6241
6444
  * finishes it here. Polls every 3 s until the challenge expires; network errors, 429 and 5xx keep
@@ -6339,6 +6542,30 @@ export declare class Passflow {
6339
6542
  * @throws {PassflowError} `error.app.redirect.url.not.registered` when refused, or a request error
6340
6543
  */
6341
6544
  checkRedirectUrl(url: string): Promise<string>;
6545
+ /**
6546
+ * Sets the token provider for an app in `human_only` bot mode that uses its own anti-bot
6547
+ * provider (Turnstile, hCaptcha, reCAPTCHA). Before each covered sign-in request the SDK calls it
6548
+ * with `{ action: 'passflow_auth', operation }` and sends the token it resolves with in
6549
+ * `X-Passflow-Anti-Bot`. Not called on a `bot_friendly` app, nor with the built-in check.
6550
+ * `undefined` removes it.
6551
+ *
6552
+ * @example
6553
+ * ```typescript
6554
+ * passflow.setAntiBotTokenProvider(() => getTurnstileToken());
6555
+ * ```
6556
+ */
6557
+ setAntiBotTokenProvider(provider: AntiBotTokenProvider | undefined): void;
6558
+ /**
6559
+ * A fresh `X-Passflow-Anti-Bot` value for a request the SDK does not send itself:
6560
+ * `POST /auth/session/exchange`, `/oidc/device/authenticate`, `/oidc/device/passkey/start`.
6561
+ * `undefined` when the app is not `human_only`: send no header then. A value is accepted once.
6562
+ *
6563
+ * The device page has no app id: it passes `settings` from `GET /oidc/device/info` and
6564
+ * `device: { userCode, csrfToken }`, and this instance must have `url` set to the page's origin.
6565
+ *
6566
+ * @throws {PassflowError} When the challenge, the solve or the token provider fails
6567
+ */
6568
+ antiBotToken(request: AntiBotTokenRequest): Promise<string | undefined>;
6342
6569
  private handleError;
6343
6570
  /**
6344
6571
  * Sign out the current user and clear all tokens.
@@ -6388,7 +6615,7 @@ export declare class Passflow {
6388
6615
  * });
6389
6616
  * ```
6390
6617
  */
6391
- federatedAuthWithPopup(payload: PassflowFederatedAuthPayload): void;
6618
+ federatedAuthWithPopup(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): void;
6392
6619
  /**
6393
6620
  * Initiate federated authentication (OAuth) with a full-page redirect.
6394
6621
  *
@@ -6406,7 +6633,7 @@ export declare class Passflow {
6406
6633
  * });
6407
6634
  * ```
6408
6635
  */
6409
- federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload): void;
6636
+ federatedAuthWithRedirect(payload: PassflowFederatedAuthPayload, options?: PassflowAuthOptions): void;
6410
6637
  /**
6411
6638
  * Reset the SDK state by clearing all tokens and optionally throwing an error.
6412
6639
  *
@@ -6486,7 +6713,7 @@ export declare class Passflow {
6486
6713
  * }
6487
6714
  * ```
6488
6715
  */
6489
- sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload): Promise<PassflowSuccessResponse>;
6716
+ sendPasswordResetEmail(payload: PassflowSendPasswordResetEmailPayload, options?: PassflowAuthOptions): Promise<PassflowSuccessResponse>;
6490
6717
  /**
6491
6718
  * Reset password using a reset token (typically from URL after clicking email link).
6492
6719
  *
@@ -6594,7 +6821,7 @@ export declare class Passflow {
6594
6821
  * }
6595
6822
  * ```
6596
6823
  */
6597
- passkeyRegister(payload: PassflowPasskeyRegisterStartPayload): Promise<PassflowAuthorizationResponse>;
6824
+ passkeyRegister(payload: PassflowPasskeyRegisterStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6598
6825
  /**
6599
6826
  * Authenticate a user with a passkey (WebAuthn).
6600
6827
  *
@@ -6615,7 +6842,7 @@ export declare class Passflow {
6615
6842
  * }
6616
6843
  * ```
6617
6844
  */
6618
- passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload): Promise<PassflowAuthorizationResponse>;
6845
+ passkeyAuthenticate(payload: PassflowPasskeyAuthenticateStartPayload, options?: PassflowAuthOptions): Promise<PassflowAuthorizationResponse>;
6619
6846
  /**
6620
6847
  * Manually set tokens (useful after custom authentication flows).
6621
6848
  * This will save tokens to storage, update cache, and trigger SignIn event.
@@ -7341,4 +7568,4 @@ export declare function isValidPhoneNumber(phone: string): boolean;
7341
7568
  * @returns true if valid username format, false otherwise
7342
7569
  */
7343
7570
  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 };
7571
+ 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 };