@auth0/auth0-server-js 1.15.0 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { ActClaim, AuthorizationDetails, ExchangeProfileOptions, DiscoveryCacheOptions, TelemetryConfig, AuthClient, ListAuthenticatorsOptions, RequestOptions, AuthenticatorResponse, EnrollAuthenticatorOptions, EnrollmentResponse, ChallengeOptions, ChallengeResponse, MfaVerifyOptions, PasskeySignupChallengeOptions, PasskeySignupChallengeResponse, PasskeyLoginChallengeOptions, PasskeyLoginChallengeResponse, GetTokenByPasskeyOptions, SignUpOptions, SignUpResult, ChangePasswordOptions, ApiResponse, GetUserInfoOptions, UserInfoResponse, TokenResponse } from '@auth0/auth0-auth-js';
2
- export { ActClaim, ApiResponse, AuthenticatorResponse, AuthenticatorType, ChallengeOptions, ChallengeResponse, ChangePasswordError, ChangePasswordOptions, DiscoveryCacheOptions, EnrollAuthenticatorOptions, EnrollEmailOptions, EnrollOobOptions, EnrollOtpOptions, EnrollmentResponse, EnterpriseConnectNotSupportedError, FullResponseOption, GetUserInfoOptions, IsFederatedDomainOptions, ListAuthenticatorsOptions, MfaChallengeError, MfaEnrollmentError, MfaFactorType, MfaListAuthenticatorsError, MfaRequirements, MfaVerifyError, MfaVerifyOobOptions, MfaVerifyOptions, MfaVerifyOtpOptions, MfaVerifyRecoveryCodeOptions, MissingClientAuthError, OobChannel, OobEnrollmentResponse, OrganizationValidationError, OtpEnrollmentResponse, PasskeyChallengeError, PasskeyLoginChallengeOptions as PasskeyChallengeOptions, PasskeyLoginChallengeResponse as PasskeyChallengeResponse, PasskeyCreationOptions, PasskeyCredentialResponse, PasskeyGetTokenError, GetTokenByPasskeyOptions as PasskeyGetTokenOptions, PasskeyRegisterError, PasskeySignupChallengeOptions as PasskeyRegisterOptions, PasskeySignupChallengeResponse as PasskeyRegisterResponse, PasskeyRequestOptions, PasswordlessStartError, PasswordlessVerifyError, RequestOptions, SignUpError, SignUpOptions, SignUpResult, TelemetryConfig, TokenExchangeError, TokenResponse, TokenRevocationError, UserInfoError, UserInfoResponse, isFederatedDomain, isMfaRequiredError } from '@auth0/auth0-auth-js';
1
+ import { ActClaim, AuthorizationDetails, ExchangeProfileOptions, DiscoveryCacheOptions, TelemetryConfig, ListAuthenticatorsOptions, RequestOptions, AuthenticatorResponse, EnrollAuthenticatorOptions, EnrollmentResponse, ChallengeOptions, ChallengeResponse, MfaVerifyOptions, PasskeySignupChallengeOptions, PasskeySignupChallengeResponse, PasskeyLoginChallengeOptions, PasskeyLoginChallengeResponse, GetTokenByPasskeyOptions, SignUpOptions, SignUpResult, ChangePasswordOptions, AuthClient, ApiResponse, GetUserInfoOptions, UserInfoResponse, TokenResponse } from '@auth0/auth0-auth-js';
2
+ export { ActClaim, AnonymousSessionError, ApiResponse, AuthenticatorResponse, AuthenticatorType, ChallengeOptions, ChallengeResponse, ChangePasswordError, ChangePasswordOptions, DiscoveryCacheOptions, EnrollAuthenticatorOptions, EnrollEmailOptions, EnrollOobOptions, EnrollOtpOptions, EnrollmentResponse, EnterpriseConnectNotSupportedError, FullResponseOption, GetUserInfoOptions, IsFederatedDomainOptions, ListAuthenticatorsOptions, MfaChallengeError, MfaEnrollmentError, MfaFactorType, MfaListAuthenticatorsError, MfaRequirements, MfaVerifyError, MfaVerifyOobOptions, MfaVerifyOptions, MfaVerifyOtpOptions, MfaVerifyRecoveryCodeOptions, MissingClientAuthError, OobChannel, OobEnrollmentResponse, OrganizationValidationError, OtpEnrollmentResponse, PasskeyChallengeError, PasskeyLoginChallengeOptions as PasskeyChallengeOptions, PasskeyLoginChallengeResponse as PasskeyChallengeResponse, PasskeyCreationOptions, PasskeyCredentialResponse, PasskeyGetTokenError, GetTokenByPasskeyOptions as PasskeyGetTokenOptions, PasskeyRegisterError, PasskeySignupChallengeOptions as PasskeyRegisterOptions, PasskeySignupChallengeResponse as PasskeyRegisterResponse, PasskeyRequestOptions, PasswordlessStartError, PasswordlessVerifyError, RequestOptions, SignUpError, SignUpOptions, SignUpResult, TelemetryConfig, TokenExchangeError, TokenResponse, TokenRevocationError, UserInfoError, UserInfoResponse, isFederatedDomain, isMfaRequiredError } from '@auth0/auth0-auth-js';
3
3
  import { JWTPayload } from 'jose';
4
4
 
5
5
  /**
@@ -35,6 +35,13 @@ interface ServerClientOptions<TStoreOptions = unknown> {
35
35
  discoveryCache?: DiscoveryCacheOptions;
36
36
  transactionIdentifier?: string;
37
37
  stateIdentifier?: string;
38
+ /**
39
+ * Identifier (and cookie name, for cookie-backed stores) used for the anonymous session.
40
+ *
41
+ * Default: `__a0_anon`. This is the SDK's own store on your application's domain. It is
42
+ * unrelated to the `auth0_anon` cookie Auth0 sets on the Auth0 domain.
43
+ */
44
+ anonymousSessionIdentifier?: string;
38
45
  /**
39
46
  * Optional, custom Fetch implementation to use.
40
47
  */
@@ -45,6 +52,44 @@ interface ServerClientOptions<TStoreOptions = unknown> {
45
52
  * When `enterpriseConnect: true`, the state store is not needed (Auth0 does not manage a session).
46
53
  */
47
54
  stateStore?: StateStore<TStoreOptions>;
55
+ /**
56
+ * Store for anonymous sessions. Required to use the `anonymous` sub-client; accessing
57
+ * `serverClient.anonymous` without it throws `InvalidConfigurationError`.
58
+ *
59
+ * Pass a {@link StatelessAnonymousStore} for the cookie-backed default.
60
+ */
61
+ anonymousStore?: AnonymousStore<TStoreOptions>;
62
+ /**
63
+ * Whether the anonymous session is discarded once the visitor logs in. Default: `true`.
64
+ *
65
+ * An anonymous session holds a bearer credential for the anonymous identity that stays
66
+ * valid for 30 days by default. Once the visitor has authenticated, that credential has
67
+ * no purpose: leaving it behind keeps a cookie on every request and lets
68
+ * `anonymous.getAccessToken()` keep minting anonymous tokens for someone who is logged
69
+ * in. So every method that establishes a user session drops the anonymous session
70
+ * afterwards.
71
+ *
72
+ * The drop is best-effort and happens after the user session is written, so it can never
73
+ * fail a login.
74
+ *
75
+ * Set this to `false` when you need the anonymous identity on a later request — for
76
+ * example to merge a guest cart in a background job — and call
77
+ * `serverClient.anonymous.logout()` yourself once you are done with it. With the default
78
+ * `true`, read `serverClient.anonymous.getSession()` **before** completing the login:
79
+ *
80
+ * ```typescript
81
+ * const anonymousSession = await serverClient.anonymous.getSession(storeOptions);
82
+ * await serverClient.completeInteractiveLogin(url, storeOptions);
83
+ * if (anonymousSession?.sub) {
84
+ * await mergeGuestCart(anonymousSession.sub);
85
+ * }
86
+ * ```
87
+ *
88
+ * Has no effect when no `anonymousStore` is configured. `serverClient.logout()` clears the
89
+ * anonymous session regardless of this setting; see {@link ServerClient.logout} for the one
90
+ * resolver-mode exception.
91
+ */
92
+ clearAnonymousSessionOnLogin?: boolean;
48
93
  /**
49
94
  * Indicates whether the SDK should use the mTLS endpoints if they are available.
50
95
  *
@@ -132,6 +177,83 @@ interface ConnectionTokenSet {
132
177
  connection: string;
133
178
  loginHint?: string;
134
179
  }
180
+ /**
181
+ * An anonymous access token as held in the anonymous store.
182
+ *
183
+ * Auth0 may grant fewer scopes than requested for an anonymous caller. `scope` is what
184
+ * was actually granted — always check it before using the token. `requestedScope` is
185
+ * an internal cache key and is not meaningful to application code.
186
+ */
187
+ interface AnonymousTokenSet extends TokenSet {
188
+ }
189
+ /**
190
+ * An anonymous session, as exposed to the application by
191
+ * {@link ServerAnonymousClient.getSession}.
192
+ *
193
+ * Deliberately does NOT carry the anonymous session token. That token is a long-lived
194
+ * bearer credential for the anonymous identity and is kept inside the SDK's anonymous
195
+ * store, in the same way the refresh token of a user session is never handed to
196
+ * application code by `getAccessToken()`.
197
+ */
198
+ interface AnonymousSessionData {
199
+ /**
200
+ * The anonymous identity, in the form `anon@<uuid>`. This is the `sub` claim of every
201
+ * anonymous access token minted for this session, so it is the key to use for anything
202
+ * you store for the visitor before they log in (a guest cart, for instance).
203
+ *
204
+ * Captured from the first anonymous access token at creation. `undefined` when that token
205
+ * could not be read, which happens when the resource server has token encryption
206
+ * (`token_encryption`) enabled: the access token is then an encrypted JWE and nothing
207
+ * outside the API can read its claims. For such an audience the anonymous `sub` is not
208
+ * obtainable through this SDK, so treat it as optional in any merge path.
209
+ */
210
+ sub?: string;
211
+ /**
212
+ * The metadata attached to the anonymous identity at creation, as it was sent to Auth0.
213
+ *
214
+ * Kept here so the application does not have to shadow what it just supplied. Metadata is
215
+ * write-once, so this value cannot go stale.
216
+ */
217
+ metadata?: Record<string, string>;
218
+ /**
219
+ * Unix timestamp (seconds) at which this anonymous session was created by the SDK.
220
+ *
221
+ * The cookie lifetime is anchored to this value, so renewing an access token never
222
+ * extends the anonymous session.
223
+ */
224
+ createdAt: number;
225
+ /**
226
+ * Unix timestamp (seconds) at which the anonymous session itself expires (30 days by
227
+ * default, tenant-configurable).
228
+ *
229
+ * Currently always `undefined`: Auth0 returns the remaining session lifetime as
230
+ * `session_expires_in` on every anonymous token response, but `@auth0/auth0-auth-js`
231
+ * does not surface it yet. Until it does, the store falls back to a configured
232
+ * lifetime measured from {@link AnonymousSessionData.createdAt}.
233
+ */
234
+ sessionTokenExpiresAt?: number;
235
+ /**
236
+ * Anonymous access tokens held for this session, cached per audience and requested scope.
237
+ */
238
+ tokenSets: AnonymousTokenSet[];
239
+ /**
240
+ * The Auth0 domain the anonymous session was created against. Used in resolver
241
+ * (multi-tenant) mode to make sure a session is never reused across tenants.
242
+ */
243
+ domain?: string;
244
+ [key: string]: unknown;
245
+ }
246
+ /**
247
+ * The anonymous session as persisted by an {@link AnonymousStore}. Adds the session
248
+ * token, which never leaves the SDK.
249
+ */
250
+ interface AnonymousStateData extends AnonymousSessionData {
251
+ /**
252
+ * The opaque handle for the anonymous identity, returned once by Auth0 at creation
253
+ * and never reissued. Used to re-mint anonymous access tokens.
254
+ */
255
+ sessionToken: string;
256
+ }
135
257
  interface InternalStateData {
136
258
  sid: string;
137
259
  createdAt: number;
@@ -194,6 +316,19 @@ interface StateStore<TStoreOptions = unknown> extends AbstractDataStore<StateDat
194
316
  }
195
317
  interface TransactionStore<TStoreOptions = unknown> extends AbstractDataStore<TransactionData, TStoreOptions> {
196
318
  }
319
+ /**
320
+ * Store for anonymous sessions.
321
+ *
322
+ * Separate from the state store on purpose: an anonymous session is not a user session.
323
+ * Writing one into the state store would make `getSession()` and `getUser()` return
324
+ * something for a visitor who has not logged in, which every framework integration reads
325
+ * as "authenticated".
326
+ *
327
+ * Use {@link StatelessAnonymousStore} for the cookie-backed default, or implement this
328
+ * interface to keep anonymous sessions in your own backend.
329
+ */
330
+ interface AnonymousStore<TStoreOptions = unknown> extends AbstractDataStore<AnonymousStateData, TStoreOptions> {
331
+ }
197
332
  interface EncryptedStoreOptions {
198
333
  /**
199
334
  * The secret(s) to use for encryption and decryption. Can be a single string or an array of strings for secret rotation support.
@@ -650,24 +785,9 @@ interface MfaVerifyResponse {
650
785
  /** A new recovery code (only returned when verifying with a recovery code) */
651
786
  recoveryCode?: string;
652
787
  }
653
- /**
654
- * @internal
655
- * Options for constructing a ServerMfaClient.
656
- */
657
- interface ServerMfaClientOptions<TStoreOptions = unknown> {
658
- authClient: AuthClient;
659
- domain: string;
660
- stateStore: StateStore<TStoreOptions>;
661
- stateStoreIdentifier: string;
662
- defaultAudience: string;
663
- }
664
788
 
665
789
  declare class ServerMfaClient<TStoreOptions = unknown> {
666
790
  #private;
667
- /**
668
- * @internal
669
- */
670
- constructor(options: ServerMfaClientOptions<TStoreOptions>);
671
791
  /**
672
792
  * Lists all MFA authenticators enrolled by the user.
673
793
  *
@@ -707,30 +827,8 @@ declare class ServerMfaClient<TStoreOptions = unknown> {
707
827
  verify(options: MfaVerifyOptions, storeOptions?: TStoreOptions, requestOptions?: RequestOptions): Promise<MfaVerifyResponse>;
708
828
  }
709
829
 
710
- /**
711
- * @internal
712
- * Options for constructing a ServerPasskeyClient.
713
- *
714
- * Unlike the MFA client, the passkey client resolves the domain per call so it
715
- * keeps working in resolver (multi-tenant) mode. It therefore receives the
716
- * parent client's `resolveDomain` and `getAuthClient` helpers instead of a
717
- * fixed domain/authClient.
718
- */
719
- interface ServerPasskeyClientOptions<TStoreOptions = unknown> {
720
- resolveDomain: (storeOptions?: TStoreOptions) => Promise<string>;
721
- getAuthClient: (domain: string) => AuthClient;
722
- stateStore: StateStore<TStoreOptions>;
723
- stateStoreIdentifier: string;
724
- defaultScope?: string;
725
- defaultAudience?: string;
726
- }
727
-
728
830
  declare class ServerPasskeyClient<TStoreOptions = unknown> {
729
831
  #private;
730
- /**
731
- * @internal
732
- */
733
- constructor(options: ServerPasskeyClientOptions<TStoreOptions>);
734
832
  /**
735
833
  * Requests a passkey signup challenge for a new user.
736
834
  *
@@ -799,27 +897,8 @@ declare class ServerPasskeyClient<TStoreOptions = unknown> {
799
897
  getToken(options: GetTokenByPasskeyOptions, storeOptions?: TStoreOptions, requestOptions?: RequestOptions): Promise<PasskeyGetTokenResult>;
800
898
  }
801
899
 
802
- /**
803
- * @internal
804
- * Options for constructing a ServerDatabaseClient.
805
- *
806
- * Like the passkey client, the database client resolves the domain per call so
807
- * it keeps working in resolver (multi-tenant) mode. It therefore receives the
808
- * parent client's `resolveDomain` and `getAuthClient` helpers instead of a
809
- * fixed domain/authClient. Unlike the MFA/passkey clients, it never touches the
810
- * state store — signup and change-password write no session.
811
- */
812
- interface ServerDatabaseClientOptions<TStoreOptions = unknown> {
813
- resolveDomain: (storeOptions?: TStoreOptions) => Promise<string>;
814
- getAuthClient: (domain: string) => AuthClient;
815
- }
816
-
817
900
  declare class ServerDatabaseClient<TStoreOptions = unknown> {
818
901
  #private;
819
- /**
820
- * @internal
821
- */
822
- constructor(options: ServerDatabaseClientOptions<TStoreOptions>);
823
902
  /**
824
903
  * Registers a new user in a database connection.
825
904
  *
@@ -852,6 +931,211 @@ declare class ServerDatabaseClient<TStoreOptions = unknown> {
852
931
  changePassword(options: ChangePasswordOptions, storeOptions?: TStoreOptions, requestOptions?: RequestOptions): Promise<string>;
853
932
  }
854
933
 
934
+ /**
935
+ * Options for creating an anonymous session.
936
+ */
937
+ interface CreateAnonymousSessionOptions {
938
+ /**
939
+ * The API audience the anonymous access token should be scoped to.
940
+ * Defaults to `authorizationParams.audience` on the `ServerClient`.
941
+ */
942
+ audience?: string;
943
+ /**
944
+ * Space-separated scopes to request. Does not fall back to `authorizationParams.scope`
945
+ * (that value targets logged-in users and doesn't apply to anonymous identities).
946
+ */
947
+ scope?: string;
948
+ /**
949
+ * Up to 1024 bytes of string key-value metadata to attach to the anonymous identity.
950
+ * The limit applies to the JSON-serialized object, so keys, quotes, and punctuation all
951
+ * count. Set once at creation — Auth0 rejects metadata on any subsequent call. If the
952
+ * session expires and a new one is created, the old metadata is gone. Exceeding the limit
953
+ * throws an `AnonymousSessionError` with code `invalid_request`.
954
+ */
955
+ metadata?: Record<string, string>;
956
+ }
957
+ /**
958
+ * Options for retrieving an anonymous access token.
959
+ */
960
+ interface GetAnonymousAccessTokenOptions {
961
+ /**
962
+ * The API audience the anonymous access token should be scoped to.
963
+ * Defaults to `authorizationParams.audience` on the `ServerClient`.
964
+ */
965
+ audience?: string;
966
+ /**
967
+ * Space-separated scopes to request. Does not fall back to `authorizationParams.scope`.
968
+ */
969
+ scope?: string;
970
+ }
971
+
972
+ /**
973
+ * Client for Auth0 Anonymous Sessions on the server.
974
+ *
975
+ * An anonymous session gives a visitor who has not logged in a stable identity
976
+ * (`anon@<uuid>`) and an access token, so your API can serve them personalised data
977
+ * before they authenticate. Reach it through `serverClient.anonymous`, which requires an
978
+ * `anonymousStore` on the `ServerClient`.
979
+ *
980
+ * How it is stored
981
+ * ----------------
982
+ * The anonymous session token is a long-lived bearer credential for the anonymous
983
+ * identity, so this client keeps it in the anonymous store and never returns it. The
984
+ * application only ever receives access tokens, exactly as it does for a user session.
985
+ *
986
+ * The anonymous store is separate from the state store on purpose. An anonymous visitor
987
+ * must not show up as a logged-in user, so `serverClient.getSession()` and
988
+ * `serverClient.getUser()` keep returning `undefined` while an anonymous session is
989
+ * active.
990
+ *
991
+ * Lifecycle
992
+ * ---------
993
+ * - {@link ServerAnonymousClient.createSession} is the only thing that creates a session.
994
+ * Nothing here creates one implicitly, so an expired session surfaces as an error
995
+ * instead of silently swapping the visitor onto a new anonymous identity (and silently
996
+ * dropping their metadata).
997
+ * - {@link ServerAnonymousClient.getAccessToken} returns a cached token, or re-mints one
998
+ * from the stored session token.
999
+ * - {@link ServerAnonymousClient.logout} discards the session locally.
1000
+ * - Logging in ends the anonymous session. Every method that establishes a user session
1001
+ * drops it afterwards, as does `serverClient.logout()`. Read `getSession()` **before**
1002
+ * completing the login when you need the anonymous identity to merge data, or set
1003
+ * `clearAnonymousSessionOnLogin: false` on the `ServerClient` to keep it and call
1004
+ * `logout()` yourself.
1005
+ *
1006
+ * Linking an anonymous session to the user created at login
1007
+ * ---------------------------------------------------------
1008
+ * `startInteractiveLogin()` links an active anonymous session to the user at login
1009
+ * automatically. When `anonymousStore` is configured and a session is in the store, the
1010
+ * `ServerClient` mints a short-lived Session Transfer Ticket before the redirect and appends
1011
+ * it to the `/authorize` URL as `anon_transfer_token`. Auth0 redeems the ticket during
1012
+ * authorization and makes the anonymous session available to Actions as
1013
+ * `event.anonymous_session`. No extra configuration is required.
1014
+ *
1015
+ * The ticket is valid for 30 seconds and is fail-open: if minting fails or the ticket
1016
+ * expires before `/authorize` processes it, login continues without linking the anonymous
1017
+ * session.
1018
+ *
1019
+ * The logins that do not go through `/authorize` cannot carry the ticket:
1020
+ * `passkey.getToken()`, `completePasswordless()`, `completePasswordlessMagicLink()`,
1021
+ * `loginBackchannel()`, and `loginWithCustomTokenExchange()`. Auth0 ignores any anonymous
1022
+ * session on those endpoints. For those flows, do the merge in your own application using
1023
+ * the anonymous `sub`.
1024
+ *
1025
+ * @example
1026
+ * ```typescript
1027
+ * // Give a visitor an anonymous identity on their first request.
1028
+ * let session = await serverClient.anonymous.getSession(storeOptions);
1029
+ * if (!session) {
1030
+ * await serverClient.anonymous.createSession(
1031
+ * { audience: 'https://api.example.com', metadata: { landing: 'pricing' } },
1032
+ * storeOptions
1033
+ * );
1034
+ * }
1035
+ *
1036
+ * // On any later request, get a valid token for your API.
1037
+ * try {
1038
+ * const { accessToken } = await serverClient.anonymous.getAccessToken(
1039
+ * { audience: 'https://api.example.com' },
1040
+ * storeOptions
1041
+ * );
1042
+ * } catch (error) {
1043
+ * if (error instanceof AnonymousSessionExpiredError) {
1044
+ * await serverClient.anonymous.createSession({ audience: 'https://api.example.com' }, storeOptions);
1045
+ * }
1046
+ * }
1047
+ * ```
1048
+ */
1049
+ declare class ServerAnonymousClient<TStoreOptions = unknown> {
1050
+ #private;
1051
+ /**
1052
+ * Creates an anonymous session and stores it, returning the first anonymous access token.
1053
+ *
1054
+ * Replaces any anonymous session already stored for this visitor. Metadata can only be
1055
+ * attached here, because Auth0 rejects a request that carries both metadata and an
1056
+ * existing session.
1057
+ *
1058
+ * The anonymous identity (`sub`) is read off the first access token and stored alongside
1059
+ * the metadata, so {@link ServerAnonymousClient.getSession} can hand both back without the
1060
+ * application decoding a token. It stays `undefined` for an audience with token encryption
1061
+ * (`token_encryption`) enabled, whose access token is an encrypted JWE only the API can
1062
+ * read.
1063
+ *
1064
+ * @param options Optional audience, scope and metadata for the new session.
1065
+ * @param storeOptions Optional options used to pass to the anonymous store (and to resolve the domain in resolver mode).
1066
+ *
1067
+ * @throws {AnonymousSessionError} If Auth0 rejected the request. Common codes are
1068
+ * `feature_not_enabled` (the tenant flag is off), `unauthorized_client` (the client is
1069
+ * not enabled for anonymous sessions), `invalid_target` (the resource server does not
1070
+ * allow anonymous access), `invalid_request` (metadata over 1024 bytes, or not all
1071
+ * strings) and `access_denied`. `code` is `server_error` when Auth0 answers with a body
1072
+ * that is not JSON.
1073
+ *
1074
+ * Only call this once you have established the visitor has no anonymous session (check
1075
+ * {@link ServerAnonymousClient.getSession} first), rather than on every request.
1076
+ *
1077
+ * @returns The anonymous access token for the requested audience.
1078
+ */
1079
+ createSession(options?: CreateAnonymousSessionOptions, storeOptions?: TStoreOptions): Promise<TokenSet>;
1080
+ /**
1081
+ * Returns an anonymous access token for the stored anonymous session, fetching a fresh
1082
+ * one from Auth0 when the cached one has expired.
1083
+ *
1084
+ * Tokens are cached per audience and scope, so requesting a second audience returns a
1085
+ * second token for the same anonymous identity without replacing the first.
1086
+ *
1087
+ * Auth0 may grant fewer scopes than requested — a scope the anonymous identity is not
1088
+ * entitled to is silently dropped and the response is still a success. Always check
1089
+ * `tokenSet.scope` before calling your API; do not assume the token carries every scope
1090
+ * you asked for.
1091
+ *
1092
+ * This never creates a session. If the anonymous session has expired, the stored session
1093
+ * is deleted and `AnonymousSessionExpiredError` is thrown, so a visitor is never moved
1094
+ * onto a fresh anonymous identity behind your back.
1095
+ *
1096
+ * @param options Optional audience and scope for the requested token.
1097
+ * @param storeOptions Optional options used to pass to the anonymous store (and to resolve the domain in resolver mode).
1098
+ *
1099
+ * @throws {MissingAnonymousSessionError} When there is no anonymous session stored, or the stored one belongs to another Auth0 domain (resolver mode).
1100
+ * @throws {AnonymousSessionExpiredError} When the anonymous session has expired or Auth0 rejected the session token. The stored session is deleted first.
1101
+ *
1102
+ * @returns The anonymous access token for the requested audience.
1103
+ */
1104
+ getAccessToken(options?: GetAnonymousAccessTokenOptions, storeOptions?: TStoreOptions): Promise<TokenSet>;
1105
+ /**
1106
+ * Returns the stored anonymous session, or `undefined` when there is none.
1107
+ *
1108
+ * Two common uses:
1109
+ * - **Gate `createSession`** — call this first; only create a session when the result is `undefined`.
1110
+ * - **Read identity for a merge** — `sub` and `metadata` are available here without decoding a token.
1111
+ *
1112
+ * This is a local read of the store with no request to Auth0. It cannot tell you whether
1113
+ * Auth0 still considers the session valid — only {@link ServerAnonymousClient.getAccessToken} can.
1114
+ * The session token is never included in the result.
1115
+ *
1116
+ * @param storeOptions Optional options used to pass to the anonymous store (and to resolve the domain in resolver mode).
1117
+ *
1118
+ * @returns The anonymous session, or `undefined` when there is none for this visitor (or it belongs to another Auth0 domain in resolver mode).
1119
+ */
1120
+ getSession(storeOptions?: TStoreOptions): Promise<AnonymousSessionData | undefined>;
1121
+ /**
1122
+ * Clears the anonymous session from the store.
1123
+ *
1124
+ * Does not call `POST /anonymous/logout` — that endpoint only clears the `auth0_anon`
1125
+ * browser cookie, which your server never holds. Any access tokens already issued remain
1126
+ * valid until they expire (~2 hours by default).
1127
+ *
1128
+ * You rarely need to call this directly: every method that establishes a user session
1129
+ * clears the anonymous session automatically (unless `clearAnonymousSessionOnLogin: false`
1130
+ * is set), and `serverClient.logout()` clears it too. Call this to explicitly reset a
1131
+ * visitor's anonymous identity, or to clean up after your own post-login merge logic when
1132
+ * automatic clearing is disabled.
1133
+ *
1134
+ * @param storeOptions Optional options used to pass to the anonymous store.
1135
+ */
1136
+ logout(storeOptions?: TStoreOptions): Promise<void>;
1137
+ }
1138
+
855
1139
  declare class ServerClient<TStoreOptions = unknown> {
856
1140
  #private;
857
1141
  /**
@@ -902,6 +1186,35 @@ declare class ServerClient<TStoreOptions = unknown> {
902
1186
  * request resolves the intended tenant.
903
1187
  */
904
1188
  get database(): ServerDatabaseClient<TStoreOptions>;
1189
+ /**
1190
+ * The anonymous session client, for giving a visitor who has not logged in a stable
1191
+ * identity and an access token for your API.
1192
+ *
1193
+ * Provides `createSession()` to establish the anonymous identity, `getAccessToken()` to
1194
+ * obtain and renew anonymous access tokens, `getSession()` to check whether a visitor
1195
+ * already has one, and `logout()` to discard it.
1196
+ *
1197
+ * Requires `anonymousStore` on the `ServerClient`, and a tenant and client configured for
1198
+ * anonymous sessions. Anonymous sessions are kept in that store, never in the state
1199
+ * store, so `getSession()` and `getUser()` still report no user while one is active.
1200
+ *
1201
+ * The anonymous session ends when the visitor logs in: every login method clears it once
1202
+ * the user session is written, unless you set `clearAnonymousSessionOnLogin: false`.
1203
+ * {@link ServerClient.logout} clears it too.
1204
+ *
1205
+ * For `/authorize` flows, `startInteractiveLogin()` links the anonymous session to
1206
+ * the user automatically via a Session Transfer Ticket — no extra configuration needed.
1207
+ * For logins that bypass `/authorize` (passkey, passwordless, backchannel, custom token
1208
+ * exchange), the anonymous session is not linked. Read `anonymous.getSession()` before
1209
+ * the login to get the anonymous `sub` for a manual merge, or set
1210
+ * `clearAnonymousSessionOnLogin: false` and clear it yourself afterwards.
1211
+ *
1212
+ * Like `passkey` and `database`, this works in both static and resolver (multi-tenant)
1213
+ * domain modes.
1214
+ *
1215
+ * @throws {InvalidConfigurationError} When no `anonymousStore` is configured.
1216
+ */
1217
+ get anonymous(): ServerAnonymousClient<TStoreOptions>;
905
1218
  constructor(options: ServerClientOptions<TStoreOptions>);
906
1219
  /**
907
1220
  * Starts the Enterprise Connect login flow. Performs WebFinger domain discovery
@@ -1202,6 +1515,29 @@ declare class ServerClient<TStoreOptions = unknown> {
1202
1515
  revokeRefreshToken(options?: RevokeRefreshTokenOptions, storeOptions?: TStoreOptions, requestOptions?: RequestOptions): Promise<void>;
1203
1516
  /**
1204
1517
  * Logs the user out and returns a URL to redirect the user-agent to after they log out.
1518
+ *
1519
+ * Clears the anonymous session as well, whenever an `anonymousStore` is configured. Logging
1520
+ * out means the visitor is done, so leaving a 30-day anonymous credential behind in a
1521
+ * cookie would be surprising, and `anonymous.getAccessToken()` would keep working right
1522
+ * after the user logged out. This happens even when there is no user session to clear: a
1523
+ * visitor who only ever had an anonymous session can log out. Unlike the automatic clearing
1524
+ * at login, it is not affected by `clearAnonymousSessionOnLogin`, which exists so an
1525
+ * application can finish its post-login work.
1526
+ *
1527
+ * In resolver (multi-tenant) mode the one exception is a stored user session belonging to a
1528
+ * different Auth0 domain than the request resolves to. Nothing local is cleared in that
1529
+ * case, anonymous session included, exactly as today: that state belongs to another tenant.
1530
+ *
1531
+ * The anonymous session is only ever cleared locally. The SDK does not call
1532
+ * `POST /anonymous/logout`: that endpoint exists to clear the `auth0_anon` cookie in a
1533
+ * browser, and it revokes nothing server-side. Your server never holds that cookie, so
1534
+ * calling it would achieve nothing. If the visitor's browser created an anonymous session
1535
+ * of its own (through `@auth0/auth0-spa-js`, for example), that cookie is not covered by
1536
+ * this SDK and has to be cleared from the browser.
1537
+ *
1538
+ * Anonymous access tokens already handed out stay valid until they expire; there is no
1539
+ * anonymous session to revoke them against.
1540
+ *
1205
1541
  * @param options Options used to configure the logout process.
1206
1542
  * @param storeOptions Optional options used to pass to the Transaction and State Store.
1207
1543
  * @param requestOptions Optional per-request options (signal, headers, customFetch). Applied to the token revocation ONLY. Building the logout URL is local string work and issues no request, so nothing here can affect it.
@@ -1462,6 +1798,99 @@ declare class StatelessStateStore<TStoreOptions> extends AbstractSessionStore<TS
1462
1798
  private getCookieKeys;
1463
1799
  }
1464
1800
 
1801
+ /**
1802
+ * Abstract class that can be used to implement an Encrypted JWT Anonymous Session Store,
1803
+ * using the 'A256CBC-HS512' encryption algorithm.
1804
+ *
1805
+ * Extend this when you want the SDK's encryption but your own persistence (Redis, a
1806
+ * database, and so on). For the cookie-backed default, use `StatelessAnonymousStore`.
1807
+ */
1808
+ declare abstract class AbstractAnonymousStore<TStoreOptions = unknown> extends AbstractStore<AnonymousStateData, TStoreOptions> implements AnonymousStore<TStoreOptions> {
1809
+ constructor(options: EncryptedStoreOptions);
1810
+ }
1811
+
1812
+ /**
1813
+ * Default lifetime of an anonymous session, in seconds (30 days).
1814
+ *
1815
+ * Matches the Auth0 default for `sessions.anonymous.lifetime_in_minutes`. Override it with
1816
+ * {@link StatelessAnonymousStoreOptions.sessionTokenLifetime} when your tenant is configured
1817
+ * differently.
1818
+ */
1819
+ declare const DEFAULT_ANONYMOUS_SESSION_LIFETIME: number;
1820
+ /**
1821
+ * Cookie attributes for the anonymous session cookie.
1822
+ *
1823
+ * This is your application's own cookie on your own domain. It is not the `auth0_anon`
1824
+ * cookie, which Auth0 sets on the Auth0 domain and controls itself.
1825
+ */
1826
+ interface AnonymousCookieOptions {
1827
+ /**
1828
+ * The sameSite attribute of the anonymous session cookie.
1829
+ *
1830
+ * Default: `lax`. `lax` is enough: this cookie is only ever read by your own server on
1831
+ * requests to your own site.
1832
+ */
1833
+ sameSite?: 'strict' | 'lax' | 'none';
1834
+ /**
1835
+ * The secure attribute of the anonymous session cookie.
1836
+ *
1837
+ * Default: `true`. Set it to `false` only for local development over plain HTTP.
1838
+ */
1839
+ secure?: boolean;
1840
+ /**
1841
+ * The path attribute of the anonymous session cookie.
1842
+ *
1843
+ * Default: `/`.
1844
+ */
1845
+ path?: string;
1846
+ }
1847
+ interface StatelessAnonymousStoreOptions extends EncryptedStoreOptions {
1848
+ /**
1849
+ * Lifetime of an anonymous session in seconds, used to work out the cookie's `Max-Age`.
1850
+ *
1851
+ * Default: 30 days, matching the Auth0 default. This should match
1852
+ * `sessions.anonymous.lifetime_in_minutes` on your tenant. It is only a client-side
1853
+ * bound: Auth0 is the authority on when the anonymous session token stops working, and a
1854
+ * request made after that point fails with `AnonymousSessionExpiredError` regardless of
1855
+ * what is configured here.
1856
+ */
1857
+ sessionTokenLifetime?: number;
1858
+ /**
1859
+ * The options for the anonymous session cookie.
1860
+ */
1861
+ cookie?: AnonymousCookieOptions;
1862
+ }
1863
+ /**
1864
+ * Stateless anonymous session store.
1865
+ *
1866
+ * Keeps the whole anonymous session in an encrypted, `HttpOnly` cookie on your application's
1867
+ * domain, chunked across several cookies when needed, so it needs no server-side storage.
1868
+ * Pass it as `anonymousStore` on the `ServerClient`, alongside `StatelessStateStore`.
1869
+ *
1870
+ * The cookie's `Max-Age` is anchored to the moment the anonymous session was created, so
1871
+ * renewing an access token does not extend it. Auth0 never reissues an anonymous session
1872
+ * token, so a rolling expiry here would keep a 30-day session alive forever.
1873
+ *
1874
+ * @example
1875
+ * ```typescript
1876
+ * const serverClient = new ServerClient({
1877
+ * domain: '<AUTH0_DOMAIN>',
1878
+ * clientId: '<AUTH0_CLIENT_ID>',
1879
+ * clientSecret: '<AUTH0_CLIENT_SECRET>',
1880
+ * transactionStore: new CookieTransactionStore({ secret }, cookieHandler),
1881
+ * stateStore: new StatelessStateStore({ secret }, cookieHandler),
1882
+ * anonymousStore: new StatelessAnonymousStore({ secret }, cookieHandler),
1883
+ * });
1884
+ * ```
1885
+ */
1886
+ declare class StatelessAnonymousStore<TStoreOptions> extends AbstractAnonymousStore<TStoreOptions> {
1887
+ #private;
1888
+ constructor(options: StatelessAnonymousStoreOptions, cookieHandler: CookieHandler<TStoreOptions>);
1889
+ set(identifier: string, anonymousStateData: AnonymousStateData, removeIfExists?: boolean, options?: TStoreOptions): Promise<void>;
1890
+ get(identifier: string, options?: TStoreOptions): Promise<AnonymousStateData | undefined>;
1891
+ delete(identifier: string, options?: TStoreOptions): Promise<void>;
1892
+ }
1893
+
1465
1894
  /**
1466
1895
  * Codes carried on the `code` field of a `TokenExchangeError` raised by the Session
1467
1896
  * Transfer Token (STT) flow. These are specific to Custom Token Exchange Impersonation
@@ -1536,6 +1965,37 @@ declare class IssuerValidationError extends Error {
1536
1965
  code: string;
1537
1966
  constructor(message: string);
1538
1967
  }
1968
+ /**
1969
+ * Error thrown when an anonymous session is required but none is stored for this visitor.
1970
+ *
1971
+ * Anonymous sessions are never created implicitly. Call
1972
+ * `serverClient.anonymous.createSession()` first, and use
1973
+ * `serverClient.anonymous.getSession()` to check whether a visitor already has one.
1974
+ */
1975
+ declare class MissingAnonymousSessionError extends Error {
1976
+ code: string;
1977
+ constructor(message?: string);
1978
+ }
1979
+ /**
1980
+ * Error thrown when the anonymous session has expired or was rejected by Auth0, so no new
1981
+ * anonymous access token can be minted for it.
1982
+ *
1983
+ * The stored anonymous session is deleted before this is thrown. Call
1984
+ * `serverClient.anonymous.createSession()` to start a new one. Any metadata attached to
1985
+ * the previous anonymous identity is gone: metadata is set once, at creation.
1986
+ *
1987
+ * Recovering from this is not free. `@auth0/auth0-auth-js` answers an expired session token
1988
+ * by creating a replacement anonymous identity rather than reporting the expiry, so by the
1989
+ * time this error is raised Auth0 has already minted an identity the SDK deliberately
1990
+ * discards (storing it would move the visitor onto an identity they never asked for, without
1991
+ * their metadata). The `createSession()` that recovers is therefore a second call to Auth0,
1992
+ * and under concurrency every in-flight request pays it. Handle this once, on a path the
1993
+ * visitor actually needs a token on, rather than in a retry loop.
1994
+ */
1995
+ declare class AnonymousSessionExpiredError extends Error {
1996
+ code: string;
1997
+ constructor(message?: string);
1998
+ }
1539
1999
  /**
1540
2000
  * Error thrown when the session has passed its upstream IdP-asserted
1541
2001
  * `session_expiry` ceiling (IPSIE SL1). The user must re-authenticate.
@@ -1545,4 +2005,4 @@ declare class SessionExpiredError extends Error {
1545
2005
  constructor(message?: string);
1546
2006
  }
1547
2007
 
1548
- export { type AbstractDataStore, AbstractStateStore, AbstractTransactionStore, type AccessTokenForConnectionOptions, type AuthorizationParameters, BackchannelLogoutError, type BuildSessionTransferRedirectOptions, type CompletePasswordlessEmailOptions, type CompletePasswordlessOptions, type CompletePasswordlessResult, type CompletePasswordlessSmsOptions, type ConnectionTokenSet, type CookieHandler, type CookieSerializeOptions, CookieTransactionStore, type CustomTokenExchangeOptions, type DomainResolver, type EncryptedStoreOptions, type GetAccessTokenOptions, type InternalStateData, InvalidConfigurationError, IssuerValidationError, type LoginBackchannelOptions, type LoginBackchannelResult, type LoginWithCustomTokenExchangeOptions, type LoginWithCustomTokenExchangeResult, type LogoutOptions, type LogoutTokenClaims, type MfaVerifyResponse, MissingRequiredArgumentError, MissingSessionError, MissingTransactionError, type PasskeyGetTokenResult, type RequestSessionTransferTokenOptions, type RevokeRefreshTokenOptions, ServerClient, type ServerClientOptions, ServerDatabaseClient, ServerMfaClient, ServerPasskeyClient, type SessionConfiguration, type SessionCookieOptions, type SessionData, SessionExpiredError, type SessionStore, type SessionTransferActor, type SessionTransferTokenResult, type StartEnterpriseLoginOptions, type StartInteractiveLoginOptions, StartLinkUserError, type StartLinkUserOptions, type StartPasswordlessEmailCodeOptions, type StartPasswordlessEmailLinkOptions, type StartPasswordlessOptions, type StartPasswordlessSmsOptions, type StartUnlinkUserOptions, type StateData, type StateStore, StatefulStateStore, type StatefulStateStoreOptions, StatelessStateStore, TokenExchangeErrorCode, type TokenSet, type TransactionData, type TransactionStore, type UserClaims };
2008
+ export { AbstractAnonymousStore, type AbstractDataStore, AbstractStateStore, AbstractTransactionStore, type AccessTokenForConnectionOptions, type AnonymousCookieOptions, type AnonymousSessionData, AnonymousSessionExpiredError, type AnonymousStateData, type AnonymousStore, type AnonymousTokenSet, type AuthorizationParameters, BackchannelLogoutError, type BuildSessionTransferRedirectOptions, type CompletePasswordlessEmailOptions, type CompletePasswordlessOptions, type CompletePasswordlessResult, type CompletePasswordlessSmsOptions, type ConnectionTokenSet, type CookieHandler, type CookieSerializeOptions, CookieTransactionStore, type CreateAnonymousSessionOptions, type CustomTokenExchangeOptions, DEFAULT_ANONYMOUS_SESSION_LIFETIME, type DomainResolver, type EncryptedStoreOptions, type GetAccessTokenOptions, type GetAnonymousAccessTokenOptions, type InternalStateData, InvalidConfigurationError, IssuerValidationError, type LoginBackchannelOptions, type LoginBackchannelResult, type LoginWithCustomTokenExchangeOptions, type LoginWithCustomTokenExchangeResult, type LogoutOptions, type LogoutTokenClaims, type MfaVerifyResponse, MissingAnonymousSessionError, MissingRequiredArgumentError, MissingSessionError, MissingTransactionError, type PasskeyGetTokenResult, type RequestSessionTransferTokenOptions, type RevokeRefreshTokenOptions, ServerAnonymousClient, ServerClient, type ServerClientOptions, ServerDatabaseClient, ServerMfaClient, ServerPasskeyClient, type SessionConfiguration, type SessionCookieOptions, type SessionData, SessionExpiredError, type SessionStore, type SessionTransferActor, type SessionTransferTokenResult, type StartEnterpriseLoginOptions, type StartInteractiveLoginOptions, StartLinkUserError, type StartLinkUserOptions, type StartPasswordlessEmailCodeOptions, type StartPasswordlessEmailLinkOptions, type StartPasswordlessOptions, type StartPasswordlessSmsOptions, type StartUnlinkUserOptions, type StateData, type StateStore, StatefulStateStore, type StatefulStateStoreOptions, StatelessAnonymousStore, type StatelessAnonymousStoreOptions, StatelessStateStore, TokenExchangeErrorCode, type TokenSet, type TransactionData, type TransactionStore, type UserClaims };