declare const TEST_API_URL = "https://test.stytch.com"; declare const LIVE_API_URL = "https://api.stytch.com"; declare const CLIENTSIDE_SERVICES_IFRAME_URL = "https://js.stytch.com/clientside-services/index.html"; declare const STYTCH_DFP_BACKEND_URL = "https://telemetry.stytch.com"; declare const STYTCH_DFP_CDN_URL = "https://elements.stytch.com"; declare const STYTCH_SESSION_COOKIE = "stytch_session"; declare const STYTCH_SESSION_JWT_COOKIE = "stytch_session_jwt"; declare const POWERED_BY_STYTCH_IMG_URL = "https://public-assets.stytch.com/et_powered_by_stytch_logo.png"; declare const GOOGLE_ONE_TAP_HOST = "https://accounts.google.com/gsi"; declare const GOOGLE_ONE_TAP_SCRIPT_URL = "https://accounts.google.com/gsi/client"; declare const DEFAULT_SESSION_DURATION_MINUTES = 30; declare const DEFAULT_OTP_EXPIRATION_MINUTES = 5; declare const MULTIPLE_STYTCH_CLIENTS_DETECTED_WARNING: string; /** * Configuration for a Stytch project. This represents aspects of project * configuration that are controlled via the Stytch dashboard, but affect SDK * behavior. You can extend from this type for improved type safety when * creating your own project configuration. * * To specify a default project configuration for your entire project, augment * {@link Stytch.DefaultProjectConfiguration} via declaration merging. For more * advanced use cases, many types accept `StytchProjectConfiguration` as a * generic type parameter directly. * * This type is equivalent to the `Stytch.ProjectConfiguration` type, which is * defined in the `Stytch` namespace for convenience. * * @example * interface MyProjectConfiguration extends ProjectConfiguration { * OpaqueTokens: true; * } * * const client = new StytchClient(...); */ interface StytchProjectConfiguration { /** * Whether sensitive tokens are omitted from response bodies. Set this to true * when HttpOnly cookies are enforced for the project. */ OpaqueTokens: boolean; } type StytchProjectConfigurationInput = Partial; type BooleanOption = TInput extends true ? TTrue : TInput extends false ? TFalse : TTrue | TFalse; type ReadProjectConfig = TUserConfig[TKey] extends StytchProjectConfiguration[TKey] ? TUserConfig[TKey] : TDefaultValue; type ExtractOpaqueTokens = ReadProjectConfig<"OpaqueTokens", TProjectConfiguration>; type AllowedOpaqueTokens = ExtractOpaqueTokens; type OpaqueTokensNeverConfig = { OpaqueTokens: false; }; type OpaqueTokensNever = false; type IfOpaqueTokens = BooleanOption; type RedactedToken = ""; type Redacted = { [K in keyof T]: V; }; type Cacheable = T & { /** * If true, indicates that the value returned is from the application cache * and a state refresh is in progress. */ fromCache: boolean; }; type StringLiteralFromEnum = `${T}`; type EnumOrStringLiteral = T | StringLiteralFromEnum; declare function loadESModule(url: string, moduleFromGlobalScope: () => T): Promise; declare const VERTICAL_B2B = "B2B"; declare const VERTICAL_CONSUMER = "CONSUMER"; type Vertical = typeof VERTICAL_B2B | typeof VERTICAL_CONSUMER; declare const WILDCARD_ACTION = "*"; type RBACPolicyRole = { role_id: string; description: string; permissions: { resource_id: string; actions: string[]; }[]; }; type RBACPolicyScope = { scope: string; description: string; permissions: { resource_id: string; actions: string[]; }[]; }; type RBACPolicyResource = { resource_id: string; description: string; actions: string[]; }; type RBACPolicyRaw = { roles: RBACPolicyRole[]; resources: RBACPolicyResource[]; scopes: RBACPolicyScope[]; }; /** * RBACPolicy represents an instance of a parsed Stytch RBAC policy object * It contains methods for computing outcomes for various permissions questions */ declare class RBACPolicy { roles: RBACPolicyRole[]; resources: RBACPolicyResource[]; private rolesByID; constructor(roles: RBACPolicyRole[], resources: RBACPolicyResource[]); static fromJSON(input: RBACPolicyRaw): RBACPolicy; /** * Merges organization custom roles with this project policy. * Custom roles are additive - they add additional roles on top of the base project policy. * Resources remain from the project policy, roles are combined. * @param customRoles Array of custom organization roles to add * @returns A new RBACPolicy instance with merged roles */ mergeWithCustomRoles(customRoles: RBACPolicyRole[]): RBACPolicy; /** * isAuthorized returns whether or not a user with a specific set of roles can perform a desired action * @example * const canDoIt = policy.callerIsAuthorized(roles, 'files', 'create') * console.log(canDoIt) // true */ callerIsAuthorized(memberRoles: string[], resourceId: string, action: string): boolean; /** * allPermissions generates a map that allows quick lookup of all the permissions available to the user * @example * const perms = policy.allPermissions(roles) * console.log(perms.files.create) // true * console.log(perms.files.delete) // false */ allPermissionsForCaller(memberRoles: string[]): Record>; } type BootstrapData = { projectName: string | null; displayWatermark: boolean; cnameDomain: string | null; emailDomains: string[]; captchaSettings: { enabled: false; } | { enabled: true; siteKey: string; }; pkceRequiredForEmailMagicLinks: boolean; pkceRequiredForPasswordResets: boolean; pkceRequiredForOAuth: boolean; pkceRequiredForSso: boolean; slugPattern: string | null; createOrganizationEnabled: boolean; passwordConfig: { ludsComplexity: number; ludsMinimumCount: number; } | null; runDFPProtectedAuth: boolean; dfpProtectedAuthMode?: DFPProtectedAuthMode; rbacPolicy: RBACPolicyRaw | null; siweRequiredForCryptoWallets: boolean; vertical: Vertical | null; }; type EnvironmentOptions = { endpoints?: { liveAPIURL: string; testAPIURL: string; dfpBackendURL: string; clientsideServicesIframeURL: string; }; }; type InternalStytchClientOptions = StytchClientOptions & EnvironmentOptions; type SessionUpdateOptions = { /** * If the authenticate method was called with session_duration_minutes, this property will * be set. This is mainly used for the keepSessionAlive option. */ sessionDurationMinutes?: number; }; declare const getLiveApiURL: (opts: InternalStytchClientOptions | undefined) => string; declare const getTestApiURL: (opts: InternalStytchClientOptions | undefined) => string; declare const checkPublicToken: (publicToken: unknown) => void; declare const checkNotSSR: (clientName: "StytchUIClient" | "StytchHeadlessClient") => void; declare const checkB2BNotSSR: (clientName: "StytchB2BUIClient" | "StytchB2BHeadlessClient") => void; // List of Alpha-2 country codes to display in the drop down for phone number entry in our pre-built UI components. // // This list contains all allowed country codes, in alphabetical order, with the exception of the US, which is placed first as it is // the default and our most common user country. // // This list was built by pulling all countries from https://www.iban.com/country-codes and then removing countries that are not on our // unsupported countries (https://app.launchdarkly.com/default/production/features/default-banned-countries-for-phone-validation/targeting). // // Other useful links are the IBAN Alpha-2 code list (https://www.iban.com/country-codes) and Twilio's per-country notes // (https://www.twilio.com/en-us/guidelines/ag/sms). Just substitute the country code in that URL! // // This list is served to any customer, regardless of whether they are on the default country allowlist (only US and Canada) or they allow // all countries. This means that users may be able to choose a country that is not allowed for a customer and receive an error. This should // be improved in the future: ODEVX-34. declare const COUNTRIES_LIST: { readonly US: "1"; readonly AX: "358"; readonly AS: "1684"; readonly AG: "1268"; readonly AI: "1264"; readonly AR: "54"; readonly AT: "43"; readonly AU: "61"; readonly BE: "32"; readonly BJ: "229"; readonly BO: "591"; readonly BR: "55"; readonly IO: "246"; readonly BN: "673"; readonly BG: "359"; readonly BF: "226"; readonly CM: "237"; readonly CA: "1"; readonly BQ: "599"; readonly CF: "236"; readonly CL: "56"; readonly CX: "61"; readonly CC: "61"; readonly CO: "57"; readonly CD: "243"; readonly CK: "682"; readonly CR: "506"; readonly HR: "385"; readonly CZ: "420"; readonly DK: "45"; readonly DO: "1829"; readonly EC: "593"; readonly SV: "503"; readonly EE: "372"; readonly SZ: "268"; readonly FK: "500"; readonly FI: "358"; readonly FR: "33"; readonly GF: "594"; readonly DE: "49"; readonly GH: "233"; readonly GR: "30"; readonly GD: "1473"; readonly GT: "502"; readonly GG: "44"; readonly GW: "245"; readonly GY: "592"; readonly HU: "36"; readonly IS: "354"; readonly IN: "91"; readonly IE: "353"; readonly IM: "44"; readonly IT: "39"; readonly JM: "1876"; readonly JP: "81"; readonly KZ: "7"; readonly KE: "254"; readonly KI: "686"; readonly KR: "82"; readonly LV: "371"; readonly LT: "370"; readonly LU: "352"; readonly MO: "853"; readonly MT: "356"; readonly MH: "692"; readonly MR: "222"; readonly MU: "230"; readonly YT: "262"; readonly MX: "52"; readonly MC: "377"; readonly ME: "382"; readonly NR: "674"; readonly NL: "31"; readonly NZ: "64"; readonly NI: "505"; readonly NF: "672"; readonly NO: "47"; readonly PA: "507"; readonly PY: "595"; readonly PE: "51"; readonly PN: "870"; readonly PL: "48"; readonly PT: "351"; readonly PR: "1"; readonly RO: "40"; readonly BL: "590"; readonly SH: "290"; readonly KN: "1869"; readonly LC: "1758"; readonly MF: "590"; readonly PM: "508"; readonly SM: "378"; readonly ST: "239"; readonly SC: "248"; readonly SX: "599"; readonly SK: "421"; readonly SI: "386"; readonly ZA: "27"; readonly SS: "211"; readonly ES: "34"; readonly SR: "597"; readonly SJ: "47"; readonly SE: "46"; readonly CH: "41"; readonly TW: "886"; readonly TZ: "255"; readonly TK: "690"; readonly TO: "676"; readonly TT: "1868"; readonly TR: "90"; readonly UA: "380"; readonly GB: "44"; readonly UM: "1"; readonly UY: "598"; readonly VA: "379"; readonly EH: "212"; }; type CountryCode = keyof typeof COUNTRIES_LIST; declare const getDFPBackendURL: (opts: InternalStytchClientOptions | undefined) => string; declare const getDFPCdnURL: (opts: InternalStytchClientOptions | undefined) => string; /* eslint-disable no-console */ /* eslint-disable @typescript-eslint/no-explicit-any */ /** * An ultralightweight wrapper around console.log. * In the future, the logger might be passed in from the customer, * or the level might be configurable. */ declare const logger: { debug: (...args: any[]) => boolean; log: (...args: any[]) => void; warn: (...args: any[]) => void; error: (...args: any[]) => void; }; /** * Moves the first item that matches the predicate to the front of the array. * Returns a tuple of [reorderedArray, foundMatch] where foundMatch indicates * whether a matching item was found and moved. * * Note: Returns false if the array has only one item, but does return true even if the * item is found at index 0. This is behavior matches user expectation that you can't * really reorder an array of length 1. */ declare function moveToFront(array: T[], predicate: (item: T) => boolean): [ reorderedArray: T[], foundMatch: boolean ]; // TODO: This weird structure is because export * seems to produce a type structure // that consuming packages downstream had issues with. Not entirely sure why, // I assume it's a TS bug that will be solved in the future? declare const arrayUtils: { moveToFront: typeof moveToFront; }; declare const isTestPublicToken: (token: string) => boolean; /** * Normalizes an es5 promise with a .then(onSuccess, onFailure) signature to * the es6 .then().catch() signature */ declare const normalizePromiseLike: (prom: PromiseLike) => Promise; declare const createEventId: () => string; declare const createAppSessionId: () => string; declare const createPersistentId: () => string; declare const validate: (methodName: string) => { isObject: (fieldName: string, value: object) => any; isOptionalObject: (fieldName: string, value: object | undefined) => any; isString: (fieldName: string, value: string) => any; isOptionalString: (fieldName: string, value: string | undefined) => any; isStringArray: (fieldName: string, value: string[]) => any; isOptionalStringArray: (fieldName: string, value: string[] | undefined) => any; isNumber: (fieldName: string, value: number) => any; isOptionalNumber: (fieldName: string, value: number | undefined) => any; isBoolean: (fieldName: string, value: boolean) => any; isOptionalBoolean: (fieldName: string, value: boolean | undefined) => any; }; declare const isPhoneMethod: (selectionMethod: string) => boolean; declare const isEmailMethod: (selectionMethod: string) => boolean; declare const removeResponseCommon: ({ request_id, status_code, ...rest }: T) => Omit; type WithUser = T & { __user: User & ResponseCommon; }; declare const omitUser: (resp: T & { __user: User; }) => T; // Factors interface EmailFactor { delivery_method: "email" | "embedded"; type: string; last_authenticated_at: string; email_factor: { email_id: string; email_address: string; }; } interface PhoneNumberFactor { delivery_method: "sms" | "whatsapp"; type: string; last_authenticated_at: string; phone_number_factor: { phone_id: string; phone_number: string; }; } interface GoogleOAuthFactor { delivery_method: "oauth_google"; type: string; last_authenticated_at: string; google_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface MicrosoftOAuthFactor { delivery_method: "oauth_microsoft"; type: string; last_authenticated_at: string; microsoft_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface AppleOAuthFactor { delivery_method: "oauth_apple"; type: string; last_authenticated_at: string; apple_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface GithubOAuthFactor { delivery_method: "oauth_github"; type: string; last_authenticated_at: string; github_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface GitLabOAuthFactor { delivery_method: "oauth_gitlab"; type: string; last_authenticated_at: string; gitlab_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface FacebookOAuthFactor { delivery_method: "oauth_facebook"; type: string; last_authenticated_at: string; facebook_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface DiscordOAuthFactor { delivery_method: "oauth_discord"; type: string; last_authenticated_at: string; discord_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface SalesforceOAuthFactor { delivery_method: "oauth_salesforce"; type: string; last_authenticated_at: string; salesforce_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface SlackOAuthFactor { delivery_method: "oauth_slack"; type: string; last_authenticated_at: string; slack_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface AmazonOAuthFactor { delivery_method: "oauth_amazon"; type: string; last_authenticated_at: string; amazon_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface BitbucketOAuthFactor { delivery_method: "oauth_bitbucket"; type: string; last_authenticated_at: string; bitbucket_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface LinkedInOAuthFactor { delivery_method: "oauth_linkedin"; type: string; last_authenticated_at: string; linkedin_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface CoinbaseOAuthFactor { delivery_method: "oauth_coinbase"; type: string; last_authenticated_at: string; coinbase_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface TwitchOAuthFactor { delivery_method: "oauth_twitch"; type: string; last_authenticated_at: string; twitch_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface TwitterOAuthFactor { delivery_method: "oauth_twitter"; type: string; last_authenticated_at: string; twitter_oauth_factor: { id: string; provider_subject: string; }; } interface TikTokOAuthFactor { delivery_method: "oauth_tiktok"; type: string; last_authenticated_at: string; tiktok_oauth_factor: { id: string; provider_subject: string; }; } interface FigmaOAuthFactor { delivery_method: "oauth_figma"; type: string; last_authenticated_at: string; figma_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface SnapchatOAuthFactor { delivery_method: "oauth_snapchat"; type: string; last_authenticated_at: string; snapchat_oauth_factor: { id: string; provider_subject: string; }; } interface YahooOAuthFactor { delivery_method: "oauth_yahoo"; type: string; last_authenticated_at: string; yahoo_oauth_factor: { id: string; email_id: string; provider_subject: string; }; } interface WebAuthnFactor { delivery_method: "webauthn_registration"; type: string; last_authenticated_at: string; webauthn_factor: { webauthn_registration_id: string; domain: string; user_agent: string; }; } interface AuthenticatorAppFactor { delivery_method: "authenticator_app"; type: string; last_authenticated_at: string; authenticator_app_factor: { totp_id: string; }; } interface RecoveryCodeFactor { delivery_method: "recovery_code"; type: string; last_authenticated_at: string; recovery_code_factor: { totp_recovery_code_id: string; }; } interface CryptoWalletFactor { delivery_method: "crypto_wallet"; type: string; last_authenticated_at: string; crypto_wallet_factor: { crypto_wallet_id: string; crypto_wallet_address: string; crypto_wallet_type: string; }; } interface PasswordFactor { delivery_method: "knowledge"; type: string; last_authenticated_at: string; } interface BiometricFactor { delivery_method: "biometric"; type: string; last_authenticated_at: string; biometric_factor: { biometric_registration_id: string; }; } interface AccessTokenExchangeFactor { delivery_method: "oauth_access_token_exchange"; type: string; last_authenticated_at: string; oauth_access_token_exchange_factor: { client_id: string; }; } type AuthenticationFactor = EmailFactor | PhoneNumberFactor | GoogleOAuthFactor | MicrosoftOAuthFactor | AppleOAuthFactor | GithubOAuthFactor | GitLabOAuthFactor | FacebookOAuthFactor | DiscordOAuthFactor | SalesforceOAuthFactor | SlackOAuthFactor | AmazonOAuthFactor | BitbucketOAuthFactor | LinkedInOAuthFactor | CoinbaseOAuthFactor | TwitchOAuthFactor | TwitterOAuthFactor | TikTokOAuthFactor | SnapchatOAuthFactor | FigmaOAuthFactor | YahooOAuthFactor | WebAuthnFactor | AuthenticatorAppFactor | RecoveryCodeFactor | CryptoWalletFactor | PasswordFactor | BiometricFactor | AccessTokenExchangeFactor; type Session = { attributes: { ip_address: string; user_agent: string; }; /** * All the authentication factors that have been associated with the current session. * @example * const userIsMFAd = session.authentication_factors.length > 2; */ authentication_factors: AuthenticationFactor[]; /** * The timestamp of the session's expiration. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ expires_at: string; /** * The timestamp of the last time the session was accessed. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ last_accessed_at: string; /** * Globally unique UUID that identifies a specific session in the Stytch API. */ session_id: string; /** * The timestamp of the session's creation. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ started_at: string; /** * Globally unique UUID that identifies a specific user in the Stytch API. */ user_id: string; /** * A map of the custom claims associated with the session. * Custom claims can only be set from the server, they cannot be set using the clientside SDKs. * After claims have been added to a session, call {@link IHeadlessSessionClient#authenticate stytch.session.authenticate} to refresh the session state clientside. * See our {@link https://stytch.com/docs/sessions#using-sessions_custom-claims guide} for more information. * If no claims are set, this field will be null. */ custom_claims: null | Record; /** * A list of the roles associated with the session. */ roles: string[]; }; type SessionAuthenticateOptions = Partial; type SessionAuthenticateResponse = AuthenticateResponse; type SessionAccessTokenExchangeOptions = SessionDurationOptions & { /** * The Connected Apps access token. */ access_token: string; }; type SessionAccessTokenExchangeResponse = AuthenticateResponse; type SessionRevokeOptions = { /** * When true, clear the user and session object in the local storage, even in the event of a network failure revoking the session. * When false, the user and session object will not be cleared in the event that the SDK cannot contact the Stytch servers. * The user and session object will always be cleared when the session revoke call succeeds. * Defaults to false */ forceClear?: boolean; }; type SessionRevokeResponse = ResponseCommon; type SessionAttestOptions = { /** * The ID of the token profile used to validate the JWT string. */ profile_id: string; /** * JWT string. */ token: string; } & Partial & Partial; type SessionAttestResponse = AuthenticateResponse; type SessionOnChangeCallback = (session: Session | null) => void; type SessionTokens = { /** * An opaque session token. * Session tokens need to be authenticated via the {@link https://stytch.com/docs/api/session-auth SessionsAuthenticate} * endpoint before a user takes any action that requires authentication * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_tokens our documentation} for more information. */ session_token: string; /** * A JSON Web Token that contains standard claims about the user as well as information about the Stytch session * Session JWTs can be authenticated locally without an API call. * A session JWT is signed by project-specific keys stored by Stytch. * You can retrieve your project's public keyset via our {@link https://stytch.com/docs/api/jwks-get GetJWKS} endpoint * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_jwts our documentation} for more information. */ session_jwt: string; }; type SessionTokensUpdate = { /** * An opaque session token. * Session tokens need to be authenticated via the {@link https://stytch.com/docs/api/session-auth SessionsAuthenticate} * endpoint before a user takes any action that requires authentication * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_tokens our documentation} for more information. */ session_token: string; /** * A JSON Web Token that contains standard claims about the user as well as information about the Stytch session * Session JWTs can be authenticated locally without an API call. * A session JWT is signed by project-specific keys stored by Stytch. * You can retrieve your project's public keyset via our {@link https://stytch.com/docs/api/jwks-get GetJWKS} endpoint * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_jwts our documentation} for more information. */ session_jwt?: string | null; }; type SessionInfo = Cacheable<{ /** * The session object, or null if no session exists. */ session: Session | null; }>; interface IHeadlessSessionClient { /** * The SDK provides the `session.getSync` method to retrieve the current session. * The `session.onChange` method can be used to listen to session changes. * * If logged in, `session.getSync` returns the in-memory session object. Otherwise, it returns `null`. * @example * const sess = stytch.session.getSync(); * const hasWebAuthn = sess.authentication_factors.find( * factor => factor.delivery_method === 'webauthn_registration' * ); * @returns The user's active {@link Session} object or `null` */ getSync(): Session | null; /** * The `session.getInfo` method is similar to `session.getSync`, but it returns an object containing the `session` object and a `fromCache` boolean. * If `fromCache` is true, the session object is from the cache and a state refresh is in progress. */ getInfo(): SessionInfo; /** * Returns the `session_token` and `session_jwt` values associated with the logged-in user's active session. * * Session tokens are only available if: * - There is an active session, and * - The session is _not_ managed via HttpOnly cookies. * * If either of these conditions is not met, `getTokens` will return `null`. * * Note that the Stytch SDK stores the `session_token` and `session_jwt` values as session cookies in the user's browser. * Those cookies will be automatically included in any request that your frontend makes to a service (such as your backend) that shares the domain set on the cookies, so in most cases, you will not need to explicitly retrieve the `session_token` and `session_jwt` values using the `getTokens()` method. * However, we offer this method to serve some unique use cases where explicitly retrieving the tokens is necessary. * * @example * const {session_jwt} = stytch.session.getTokens(); * fetch('https://api.example.com, { * headers: new Headers({ * 'Authorization': 'Bearer ' + session_jwt, * credentials: 'include', * }), * }) * */ getTokens(): IfOpaqueTokens, never, SessionTokens | null>; /** * The `session.onChange` method takes in a callback that gets called whenever the session object changes. * It returns an unsubscribe method for you to call when you no longer want to listen for such changes. * * In React, the `@stytch/react` library provides the `useStytchSession` hook that implements these methods for you to easily access the session and listen for changes. * * @example * stytch.session.onChange((sess) => { * if(!sess) { * // The user has been logged out! * window.location.href = 'https://example.com/login' * } * }) * @param callback - {@link SessionOnChangeCallback} */ onChange(callback: SessionOnChangeCallback): UnsubscribeFunction; /** * Wraps Stytch's {@link https://stytch.com/docs/api/session-auth Authenticate} Session endpoint and validates that the session issued to the user is still valid. * The SDK will invoke this method automatically in the background. * You probably won't need to call this method directly. * It's recommended to use `session.getSync` and `session.onChange` instead. * * @example * stytch.session.authenticate({ * // Extend the session for another 60 minutes * session_duration_minutes: 60 * }) * @param options - {@link SessionAuthenticateOptions} * @returns A {@link SessionAuthenticateResponse} */ authenticate(options?: SessionAuthenticateOptions): Promise>; /** * Wraps Stytch's {@link https://stytch.com/docs/api/connected-app-access-token-exchange Exchange Access Token} endpoint and exchanges a Connected Apps token for a Session for the original User. * @example * stytch.session.exchangeAccessToken({ * access_token: 'eyJh...', * session_duration_minutes: 60 * }) * @param options - {@link SessionAccessTokenExchangeOptions} * @returns A {@link SessionAccessTokenExchangeResponse} */ exchangeAccessToken(options: SessionAccessTokenExchangeOptions): Promise>; /** * Wraps Stytch's {@link https://stytch.com/docs/api/session-revoke Revoke} Session endpoint and revokes the user's current session. This method should be used to log out a user. * * While calling this method, we clear the user and session objects from local storage * unless the SDK cannot contact the Stytch servers. This behavior can be overriden by using the optional param object. * * @param options - {@link SessionRevokeOptions} * @example * stytch.session.revoke() * .then(() => window.location.href = 'https://example.com/login'); * @returns A {@link SessionRevokeResponse} */ revoke(options?: SessionRevokeOptions): Promise; /** * Update a user's session tokens to hydrate a front-end session from the backend. * For example, if you log your users in with one of our backend SDKs, you can pass the resulting `session_token` and `session_jwt` to this method to prime the frontend SDK with a valid set of tokens. * You must then make an {@link https://stytch.com/docs/api/session-auth authenticate} call to authenticate the session tokens and retrieve the user's current session. * * @param tokens - The session tokens to update to */ updateSession(tokens: SessionTokensUpdate): void; /** * Wraps Stytch's {@link https://stytch.com/docs/api/attest-session Attest} Session endpoint and gets a Stytch session from a trusted JWT. * * @param data - {@link SessionAttestOptions} * @returns A {@link SessionAttestResponse} */ attest(data: SessionAttestOptions): Promise>; } type ResponseCommon = { /** * Globally unique UUID that is returned with every API call. * This value is important to log for debugging purposes; * Stytch may ask for this value to help identify a specific API call when helping you debug an issue. */ request_id: string; /** * The HTTP status code of the response. * Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, * 3XX values are redirects, 4XX are client errors, and 5XX are server errors. */ status_code: number; }; type User = { /** * The timestamp of the user's creation. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ created_at: string; /** * The `crypto_wallets` array contains a list of all crypto wallets that a user has linked via Stytch. */ crypto_wallets: { /** * Globally unique UUID that identifies a specific crypto wallet in the Stytch API. * The `crypto_wallet_id` is used when you need to operate on a specific user's crypto wallet, e.g. to remove the crypto wallet from the Stytch user. */ crypto_wallet_id: string; /** * The `crypto_wallet_address` is the actual blockchain address of this user's crypto wallet. */ crypto_wallet_address: string; /** * The `crypto_wallet_type` is the blockchain that the user's crypto wallet operates on, e.g. Ethereum, Solana, etc. */ crypto_wallet_type: string; /** * The `verified` boolean denotes whether or not this method has been successfully authenticated by the user. */ verified: boolean; }[]; /** * The `emails` array contains an array of `email` objects for the user. */ emails: { /** * The email address. */ email: string; /** * Globally unique UUID that identifies a specific email address in the Stytch API. * The `email_id` is used when you need to operate on a specific user's email address, * e.g. to delete the email address from the Stytch user. */ email_id: string; /** * The `verified` boolean denotes whether or not this method has been successfully authenticated by the user. */ verified: boolean; }[]; name: { first_name: string; last_name: string; middle_name: string; }; /** * A JSON object containing application-specific metadata. * This field can only be updated by a direct API integration. * Use it to store fields that a user should not be allowed to edit without backend validation - such as `role` or `subscription_status`. * See our {@link https://stytch.com/docs/api/metadata metadata reference} for complete details. */ trusted_metadata: Record; /** * A JSON object containing application-specific metadata. * Use it to store fields that a user can be allowed to edit directly without backend validation - such as `display_theme` or `preferred_locale`. * See our {@link https://stytch.com/docs/api/metadata metadata reference} for complete details. */ untrusted_metadata: Record; /** * The `phone_numbers` array contains an array of phone number objects for the user. */ phone_numbers: { /** * A phone number. */ phone_number: string; /** * Globally unique UUID that identifies a specific phone number in the Stytch API. * The `phone_id` is used when you need to operate on a specific user's phone number, * e.g. to delete the phone number from the Stytch user. */ phone_id: string; /** * The `verified` boolean denotes whether or not this method has been successfully authenticated by the user. */ verified: boolean; }[]; /** * The `providers` array contains an array of provider objects for the user, i.e. which OAuth providers the user has used to link their account. */ providers: { /** * Globally unique UUID that identifies singluar registration of a user with an OAuth identity provider in the Stytch API. */ oauth_user_registration_id: string; /** * The `provider_subject` field is the unique identifier used to identify the user within a given OAuth provider. * Also commonly called the "sub" or "Subject field" in OAuth protocols. */ provider_subject: string; /** * The `type` field denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Facebook, GitHub etc. */ provider_type: string; /** * If available, the `profile_picture_url` is a url of the user's profile picture set in OAuth identity the provider that the user has authenticated with, e.g. Facebook profile picture. */ profile_picture_url: string; /** * If available, the `locale` is the user's locale set in the OAuth identity provider that the user has authenticated with. */ locale: string; }[]; /** * The `password` object is returned for users with a password. */ password: null | { /** * Globally unique UUID that identifies a specific password in the Stytch API. */ password_id: string; /** * The `requires_reset` field indicates whether the user will need to reset their password to use it in the future. * See {@link https://stytch.com/docs/api/password-authenticate the API docs} for explanations of scenarios where * this might be required. */ requires_reset: boolean; }; /** * The `status` value denotes whether or not a user has successfully logged in at least once with any available login method. * Possible values are `active` and `pending`. */ status: "active" | "pending"; /** * The `totps` array contains a list of all TOTP instances for a given user in the Stytch API. */ totps: { /** * Globally unique UUID that identifies a specific TOTP instance in the Stytch API. * The `totp_id` is used when you need to operate on a specific user's TOTP instance, e.g. to delete the TOTP instance from the Stytch user. */ totp_id: string; /** * The `verified` boolean denotes whether or not this method has been successfully authenticated by the user. */ verified: boolean; }[]; /** * Globally unique UUID that identifies a specific user in the Stytch API. * The user_id critical to perform operations on a user in our API, like Get user, Delete user, etc, * so be sure to preserve this value. */ user_id: string; /** * The `webauthn_registrations` array contains a list of all WebAuthn registrations for a given user in the Stytch API. */ webauthn_registrations: WebAuthnRegistration[]; /** * The `biometric_registrations` array contains a list of all Biometric registrations for a given user in the Stytch API. */ biometric_registrations: { /** * Globally unique UUID that identifies a specific Biometric registration in the Stytch API. * The `biometric_registration_id` is used when you need to operate on a specific user's Biometric registration, * e.g. to delete the Biometric instance from the Stytch user. */ biometric_registration_id: string; /** * The `verified` boolean denotes whether or not this method has been successfully authenticated by the user. */ verified: boolean; }[]; /** * The `roles` array contains a list of all roles assigned to a given user in the Stytch API. */ roles: string[]; /** * The external ID of the user. */ external_id?: string; }; type WebAuthnRegistration = { /** * The `domain` on which a WebAuthn registration was started. * This will be the domain of your app. */ domain: string; /** * The `user_agent` of the user's browser or device. */ user_agent: string; /** * The `authenticator_type` string displays the requested authenticator type of the WebAuthn device. * The two valid types are "platform" and "cross-platform". * If no value is present, the WebAuthn device was created without an authenticator type preference. */ authenticator_type: string; /** * The `verified` boolean denotes whether or not this method has been successfully authenticated by the user. */ verified: boolean; /** * Globally unique UUID that identifies a specific WebAuthn registration in the Stytch API. * The `webauthn_registration_id` is used when you need to operate on a specific user's WebAuthn registration, * e.g. to delete the WebAuthn instance from the Stytch user. */ webauthn_registration_id: string; /** * The name of the WebAuthn device. We randomly generate the field to begin with but you can update it to a * custom value via the {@link https://stytch.com/docs/api/webauthn-update WebAuthnUpdate} endpoint. */ name: string; }; type SessionTokens$0 = { /** * An opaque session token. * Session tokens need to be authenticated via the {@link https://stytch.com/docs/api/session-auth SessionsAuthenticate} * endpoint before a user takes any action that requires authentication * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_tokens our documentation} for more information. */ session_token: string; /** * A JSON Web Token that contains standard claims about the user as well as information about the Stytch session * Session JWTs can be authenticated locally without an API call. * A session JWT is signed by project-specific keys stored by Stytch. * You can retrieve your project's public keyset via our {@link https://stytch.com/docs/api/jwks-get GetJWKS} endpoint * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_jwts our documentation} for more information. */ session_jwt: string; }; type AuthenticateResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific user in the Stytch API. * The user_id critical to perform operations on a user in our API, like Get user, Delete user, etc, * so be sure to preserve this value. */ user_id: string; /** * The Session object created. * See {@link Session} for details. */ session: Session; /** * The user object affected by this API call. * See the {@link https://stytch.com/docs/api/get-user Get user} endpiont for complete response field detail. */ user: User; } & IfOpaqueTokens, Redacted, SessionTokens$0>; type DeleteResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific user in the Stytch API. * The user_id critical to perform operations on a user in our API, like Get user, Delete user, etc, * so be sure to preserve this value. */ user_id: string; }; type SessionDurationOptions = { /** * Set the session lifetime to be this many minutes from now. * This will return both an opaque `session_token` and `session_jwt` for this session, which will automatically be stored in the browser cookies. * The `session_jwt` will have a fixed lifetime of five minutes regardless of the underlying session duration, and will be automatically refreshed by the SDK in the background over time. * This value must be a minimum of 5 and may not exceed the maximum session duration minutes value set in the * {@link https://stytch.com/dashboard/sdk-configuration SDK Configuration } page of the Stytch dashboard. */ session_duration_minutes: number; }; type UnsubscribeFunction = () => void; type StytchClientOptions = { cookieOptions?: { /** * The name of the cookie containing the opaque Stytch session token. * Defaults to `stytch_session` */ opaqueTokenCookieName?: string; /** * The name of the cookie containing the opaque Stytch session token. * Defaults to `stytch_session_jwt` */ jwtCookieName?: string; /** * The name of the cookie containing the Stytch intermediate session token. * Defaults to `stytch_intermediate_session_token` */ istCookieName?: string; /** * What HTTP path the cookies should be available on. * Equal to configuring the `;path=${}` param in the set-cookie directive. * Defaults to unset. */ path?: string; /** * What domain the cookies should be available on. * Equal to configuring the `;domain=${}` param in the set-cookie directive. * The domain _must_ match the domain of the Javascript origin the SDK is running on. * Also requires setting availableToSubdomains: true to have any effect. * Defaults to unset. */ domain?: string; /** * Whether to make the cookies available to subdomains. * When true, equivalent to configuring the `;domain=${window.location.host}` directive * When false, equivalent to leaving the directive unset * Defaults to false. */ availableToSubdomains?: boolean; }; /** * The custom domain to use for Stytch API calls. Defaults to * `api.stytch.com`. */ customBaseUrl?: string; /** * The custom domain to use for DFP Protected Auth. You must contact Stytch support to set up the domain * prior to using it in the SDK. */ dfppaUrl?: string; /** * The custom domain to use for the DFP Protected Auth CDN to load the telemetry.js script. */ dfpCdnUrl?: string; /** * @deprecated dfppaDomain and dfpCdnDomain are now configured as dfppaUrl and dfpCdnUrl directly under StytchClientOptions * apiDomain and testApiDomain are now configured using customBaseUrl directly under StytchClientOptions */ endpointOptions?: { /** * The custom domain to use for Stytch API calls. Defaults to * `api.stytch.com`. * * This value is only used for live projects, not test projects. */ apiDomain?: string; /** * The custom domain to use for Stytch API calls. Defaults to * `test.stytch.com`. * * This value is only used for test projects, not live projects. */ testApiDomain?: string; /** * The custom domain to use for DFP Protected Auth. You must contact Stytch support to set up the domain * prior to using it in the SDK. */ dfppaDomain?: string; /** * The custom domain to use for the DFP Protected Auth CDN to load the telemetry.js script. */ dfpCdnDomain?: string; }; /** * If true, the session will be automatically extended when the user has the * application open. */ keepSessionAlive?: boolean; }; type ConsumerState = { user?: User; session?: Session; }; type locale = "en" | "es" | "pt-br" | string; type MemberEmailUpdateDeliveryMethod = "EMAIL_MAGIC_LINK" | "EMAIL_OTP"; type DeviceAttributeDetails = { is_new: boolean; first_seen_at?: string; // ISO 8601 timestamp string last_seen_at?: string; // ISO 8601 timestamp string }; type SDKDeviceHistory = { ip_address?: string; ip_address_details?: DeviceAttributeDetails; ip_geo_city?: string; ip_geo_region?: string; ip_geo_country?: string; ip_geo_country_details?: DeviceAttributeDetails; }; type ConnectedAppPublic = { client_id: string; client_type: string; client_name: string; client_description: string; client_logo_url?: string; }; type ScopeResult = { scope: string; is_grantable: boolean; description: string; }; type OAuthGetURLOptions = { /** * The URL that Stytch redirects to after the OAuth flow is completed for a user that already exists. * This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /oauth/authenticate endpoint and finishes the login. * The URL should be configured as a Login URL in the Stytch Dashboard's Redirect URL page. * If the field is not specified, the default in the Dashboard is used. */ login_redirect_url?: string; /** * The URL that Stytch redirects to after the OAuth flow is completed for a user that does not yet exist. * This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /oauth/authenticate endpoint and finishes the login. * The URL should be configured as a Sign Up URL in the Stytch Dashboard's Redirect URL page. * If the field is not specified, the default in the Dashboard is used. */ signup_redirect_url?: string; /** * An optional list of custom scopes that you'd like to request from the user in addition to the ones Stytch requests by default. * @example Google Custom Scopes * ['https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/firebase'] * * @example Facebook Custom Scopes * ['public_profile', 'instagram_shopping_tag_products'] */ custom_scopes?: string[]; /** * An optional mapping of provider specific values to pass through to the OAuth provider * @example Google authorization parameters * {"prompt": "select_account", "login_hint": "example@stytch.com"} */ provider_params?: Record; /** * An optional token to pre-associate an OAuth flow with an existing Stytch User */ oauth_attach_token?: string; }; type OAuthAuthenticateOptions = SessionDurationOptions; type OAuthAuthenticateResponse = AuthenticateResponse & { /** * The `provider_subject` field is the unique identifier used to identify the user within a given OAuth provider. * Also commonly called the "sub" or "Subject field" in OAuth protocols. */ provider_subject: string; /** * The `type` field denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Facebook, GitHub etc. */ provider_type: string; /** * If available, the `profile_picture_url` is a url of the user's profile picture set in OAuth identity the provider that the user has authenticated with, e.g. Facebook profile picture. */ profile_picture_url: string; /** * If available, the `locale` is the user's locale set in the OAuth identity provider that the user has authenticated with. */ locale: string; /** * The `provider_values` object lists relevant identifiers, values, and scopes for a given OAuth provider. * For example this object will include a provider's `access_token` that you can use to access the provider's API for a given user. * Note that these values will vary based on the OAuth provider in question, e.g. `id_token` may not be returned by all providers. */ provider_values: { /** * The `access_token` that you may use to access the user's data in the provider's API. */ access_token: string; /** * The `id_token` returned by the OAuth provider. * ID Tokens are JWTs that contain structured information about a user. * The exact content of each ID Token varies from provider to provider. * ID Tokens are returned from OAuth providers that conform to the {@link https://openid.net/foundation/ OpenID Connect} specification, which is based on OAuth. */ id_token: string; /** * The `refresh_token` that you may use to refresh a user's session within the provider's API. */ refresh_token: string; /** * The OAuth scopes included for a given provider. * See each provider's section above to see which scopes are included by default and how to add custom scopes. */ scopes: string[]; /** * The timestamp when the Session expires. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. 2021-12-29T12:33:09Z. */ expires_at: string; }; }; type OAuthStartFailureReason = "User Canceled" | "Authentication Failed" | "Invalid Platform"; type OAuthStartResponse = void | { success: true; } | { success: false; reason: OAuthStartFailureReason; error?: Error; }; /** * Methods for interacting with an individual OAuth provider. */ interface IOAuthProvider { /** * Start an OAuth flow by redirecting the browser to one of Stytch's {@link https://stytch.com/docs/api/oauth-google-start oauth start} endpoints. * If enabled, this method will also generate a PKCE code_verifier and store it in localstorage on the device (See the {@link https://stytch.com/docs/oauth#guides_pkce PKCE OAuth guide} for details). * If your application is configured to use a custom subdomain with Stytch, it will be used automatically. * @example * const loginWithGoogle = useCallback(()=> { * stytch.oauth.google.start({ * login_redirect_url: 'https://example.com/oauth/callback', * signup_redirect_url: 'https://example.com/oauth/callback', * custom_scopes: ['https://www.googleapis.com/auth/gmail.compose'] * }) * }, [stytch]); * return ( * * ); * * @param options - An {@link OAuthGetURLOptions} object * * @returns OAuthStartResponse - In browsers, the browser is redirected during this function call and will return void. You should not attempt to run any code after calling this function. In React Native applications, an external browser is opened, and this method will return the result of the browser/native authentication attempt. * * @throws A `StytchSDKUsageError` when called with invalid input. */ start(options?: OAuthGetURLOptions): Promise; } type OAuthAttachResponse = ResponseCommon & { oauth_attach_token: string; }; interface IHeadlessOAuthClient { google: IOAuthProvider; microsoft: IOAuthProvider; apple: IOAuthProvider; github: IOAuthProvider; gitlab: IOAuthProvider; facebook: IOAuthProvider; discord: IOAuthProvider; salesforce: IOAuthProvider; slack: IOAuthProvider; amazon: IOAuthProvider; bitbucket: IOAuthProvider; linkedin: IOAuthProvider; coinbase: IOAuthProvider; twitch: IOAuthProvider; twitter: IOAuthProvider; tiktok: IOAuthProvider; snapchat: IOAuthProvider; figma: IOAuthProvider; yahoo: IOAuthProvider; /** * The authenticate method wraps the {@link https://stytch.com/docs/api/oauth-authenticate authenticate} OAuth API endpoint which validates the OAuth token passed in. * * @example * const token = new URLSearchParams(window.location.search).get('token'); * stytch.oauth.authenticate(token, { * session_duration_minutes: 60 * }).then(...) * * @param token - The token to authenticate * @param options - {@link OAuthAuthenticateOptions} * * @returns A {@link OAuthAuthenticateResponse} indicating the token has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(token: string, options: OAuthAuthenticateOptions): Promise>; /** * The attach method wraps the {@link https://stytch.com/docs/api/oauth-attach attach} OAuth API endpoint and generates an OAuth Attach Token to pre-associate an OAuth flow with an existing Stytch User. * * You must have an active Stytch session to use this endpoint. * Pass the returned oauth_attach_token to the same provider's OAuth Start endpoint to treat this OAuth flow as a * login for that user instead of a signup * * @param provider - The OAuth provider's name. * * @returns A {@link OAuthAttachResponse} containing a single-use token for connecting the Stytch User selection from this request to the corresponding OAuth Start request. */ attach(provider: string): Promise; } type UserOnChangeCallback = (user: User | null) => void; type UserUpdateOptions = { /** * The name of the user. If at least one name field is passed, all name fields will be updated. */ name?: { /** * The first name of the user. Replaces an existing first name, if it exists. */ first_name?: string; /** * The middle name(s) of the user. Replaces an existing middle name, if it exists. */ middle_name?: string; /** * The last name of the user. Replaces an existing last name, if it exists. */ last_name?: string; }; /** * A JSON object containing application-specific metadata. * Use it to store fields that a user can be allowed to edit directly without backend validation - such as `display_theme` or `preferred_locale`. * See our {@link https://stytch.com/docs/api/metadata metadata reference} for complete details. */ untrusted_metadata?: Record; }; type UserUpdateResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific user in the Stytch API. */ user_id: string; /** * The updated emails for the user. */ emails: User["emails"]; /** * The updated phone numbers for the user. */ phone_numbers: User["phone_numbers"]; /** * The updated crypto wallets for the user. */ crypto_wallets: User["crypto_wallets"]; }; type UserInfo = Cacheable<{ /** * The user object, or null if no user exists. */ user: User | null; }>; type UserGetConnectedAppsResponse = ResponseCommon & { connected_apps: { connected_app_id: string; name: string; description: string; client_type: string; logo_url?: string; scopes_granted: string; }[]; }; interface IHeadlessUserClient { /** * The asynchronous method, `user.get`, wraps the {@link https://stytch.com/docs/api/get-user get user} endpoint. * It fetches the user's data and refreshes the cached object if changes are detected. * The Stytch SDK will invoke this method automatically in the background, so you probably won't need to call this method directly. * * @returns A {@link User} object, or null if no user exists. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ get(): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/update-user update user} endpoint. Use this method to change the user's name, untrusted metadata, and attributes. * * You can listen for successful user updates anywhere in the codebase with the `stytch.user.onChange()` method or `useStytchUser()` hook if you are using React. * * **Note:** If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk#resources_multi-factor-authentication Multi-factor authentication} section for more details. * * @example * ``` * const updateName = useCallback(() => { * stytchClient.user.update({ * name: { * first_name: 'Jane', * last_name: 'Doe', * }, * }); * }, [stytchClient]); * ``` * * @param options - {@link UserUpdateOptions} * * @returns A {@link UserUpdateResponse} indicating the user has been updated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ update(options: UserUpdateOptions): Promise; /** * The `user.getSync` is a synchronous method for getting a user. This is the recommended approach. You can listen to changes with the `onChange` method. * If logged in, this returns the cached user object, otherwise it returns null. This method does not refresh the user's data. * * @returns A {@link User} object, or null if no user exists. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ getSync(): User | null; /** * The `user.getInfo` method is similar to `user.getSync`, but it returns an object containing the `user` object and a `fromCache` boolean. * If `fromCache` is true, the user object is from the cache and a state refresh is in progress. */ getInfo(): UserInfo; /** * The `user.onChange` method takes in a callback that gets called whenever the user object changes. It returns an unsubscribe method for you to call when you no longer want to listen for such changes. * * In React, the `@stytch/react` library provides the `useStytchUser` hook that implements these methods for you to easily access the user and listen for changes. * * @param callback - Gets called whenever the user object changes. See {@link UserOnChangeCallback}. * * @returns An {@link UnsubscribeFunction} for you to call when you no longer want to listen for changes in the user object. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ onChange(callback: UserOnChangeCallback): UnsubscribeFunction; /** * Wraps Stytch's {@link https://stytch.com/docs/api/delete-user-email delete user email} endpoint. * This methods cannot be used to remove all factors from a user. A user must have at least one email, phone number, or OAuth provider associated with their account at all times, otherwise they will not be able to log in again. * Note: If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk#resources_multi-factor-authentication Multi-factor authentication} section for more details. * * @param emailId - ID of the email to be deleted. * * @returns A {@link DeleteResponse} that indicates the user email has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteEmail(emailId: string): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/delete-user-phone-number delete phone number} endpoint. * This methods cannot be used to remove all factors from a user. A user must have at least one email, phone number, or OAuth provider associated with their account at all times, otherwise they will not be able to log in again. * Note: If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk#resources_multi-factor-authentication Multi-factor authentication} section for more details. * * @param phoneId - ID of the phone number to be deleted. * * @returns A {@link DeleteResponse} that indicates the user phone number has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deletePhoneNumber(phoneId: string): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/delete-user-totp delete TOTP} endpoint. * Note: If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk#resources_multi-factor-authentication Multi-factor authentication} section for more details. * * @param totpId - ID of the TOTP registration to be deleted. * * @returns A {@link DeleteResponse} that indicates the user TOTP registration has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteTOTP(totpId: string): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/delete-user-oauth-registration delete OAuth} endpoint. * Note: If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk#resources_multi-factor-authentication Multi-factor authentication} section for more details. * * @param oauthUserRegistrationId - ID of the OAuth registration to be deleted. * * @returns A {@link DeleteResponse} that indicates the user OAuth registration has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteOAuthRegistration(oauthUserRegistrationId: string): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/delete-user-crypto-wallet delete crypto wallet} endpoint. * Note: If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk#resources_multi-factor-authentication Multi-factor authentication} section for more details. * * @param cryptoWalletId - ID of the crypto wallet to be deleted. * * @returns A {@link DeleteResponse} that indicates the user crypto wallet has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteCryptoWallet(cryptoWalletId: string): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/delete-user-webauthn-registration delete WebAuthn} endpoint. * Note: If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk#resources_multi-factor-authentication Multi-factor authentication} section for more details. * * @param webAuthnId - ID of the WebAuthn registration to be deleted. * * @returns A {@link DeleteResponse} that indicates the user WebAuthn registration has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteWebauthnRegistration(webAuthnId: string): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/delete-user-biometric-registration delete biometric} endpoint. * * @param biometricRegistrationId - ID of the biometric registration to be deleted. * * @returns A {@link DeleteResponse} that indicates the user Biometric registration has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteBiometricRegistration(biometricRegistrationId: string): Promise; /** * The User Get Connected Apps method wraps the {@link https://stytch.com/docs/api/connected-app-user-get-all User Get Connected Apps} API endpoint. * The `user_id` will be automatically inferred from the logged-in user's session. * * This method retrieves a list of Connected Apps that the user has completed an authorization flow with successfully. * If the user revokes a Connected App's access (e.g. via the `revokeConnectedApp` method) then the Connected App will * no longer be returned in this endpoint's response. * * @returns A {@link UserGetConnectedAppsResponse} containing a list of the user's connected apps * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ getConnectedApps(): Promise; /** * The User Revoke Connected App method wraps the {@link https://stytch.com/docs/api/connected-app-user-revoke User Revoke Connected App} API endpoint. * The `user_id` will be automatically inferred from the logged-in user's session. * * This method revokes a Connected App's access to the user and revokes all active tokens that have been * created on the user's behalf. New tokens cannot be created until the user completes a new authorization * flow with the Connected App. * * Note that after calling this method, the user will be forced to grant consent in subsequent authorization * flows with the Connected App. * * @param connectedAppId - ID of the Connected App to revoke. * @returns A {@link ResponseCommon} indicating that the Connected App's access has been revoked. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ revokedConnectedApp(connectedAppId: string): Promise; } type MagicLinksBaseOptions = { /** * The url the user clicks from the sign-up email magic link. * This should be a url that your app receives and parses and subsequently send an api request to authenticate the magic link and sign-up the user. * If this value is not passed, the default sign-up redirect URL that you set in your Dashboard is used. * If you have not set a default sign-up redirect URL, an error is returned. */ signup_magic_link_url?: string; /** * Set the expiration for the sign-up email magic link, in minutes. * By default, it expires in 1 week. * The minimum expiration is 5 minutes and the maximum is 10080 minutes (7 days). */ signup_expiration_minutes?: number; /** * The url the user clicks from the login email magic link. * This should be a url that your app receives and parses and subsequently send an API request to authenticate the magic link and log in the user. * If this value is not passed, the default login redirect URL that you set in your Dashboard is used. * If you have not set a default login redirect URL, an error is returned. */ login_magic_link_url?: string; /** * Set the expiration for the login email magic link, in minutes. * By default, it expires in 1 hour. * The minimum expiration is 5 minutes and the maximum is 10080 minutes (7 days). */ login_expiration_minutes?: number; /** * The email template ID to use for login emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Magic link Login custom HTML template. */ login_template_id?: string; /** * The email template ID to use for sign-up emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Magic link Sign-up custom HTML template. */ signup_template_id?: string; /** * Used to determine which language to use when sending the user this delivery method. Parameter is a [IETF BCP 47 language tag](https://www.w3.org/International/articles/language-tags/), e.g. `"en"`. * * Currently supported languages are English (`"en"`), Spanish (`"es"`), and Brazilian Portuguese (`"pt-br"`); if no value is provided, the copy defaults to English. */ locale?: locale; }; type MagicLinksLoginOrCreateOptions = MagicLinksBaseOptions; type MagicLinksSendOptions = MagicLinksBaseOptions; type MagicLinksLoginOrCreateResponse = ResponseCommon; type MagicLinksSendResponse = ResponseCommon; type MagicLinksAuthenticateOptions = SessionDurationOptions; // AuthenticateMagicResponse type MagicLinksAuthenticateResponse = AuthenticateResponse & { /** * The ID of the method used to send a magic link. */ method_id: string; }; interface IHeadlessMagicLinksClient { email: { /** * The Login or create method wraps the {@link https://stytch.com/docs/api/log-in-or-create-user-by-email Login or Create} Email Magic Link API endpoint. * * See the {@link https://stytch.com/docs/sdks/javascript-sdk#email-magic-links_methods_send Stytch Docs} for a complete reference. * * @example * stytch.magicLinks.email.loginOrCreate('sandbox@stytch.com', { * login_magic_link_url: 'https://example.com/authenticate', * login_expiration_minutes: 60, * signup_magic_link_url: 'https://example.com/authenticate', * signup_expiration_minutes: 60, * }); * * @param email - The email of the user to send the invite magic link to. * @param options - {@link MagicLinksLoginOrCreateOptions} * * @returns A {@link MagicLinksLoginOrCreateResponse} indicating that the email has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ loginOrCreate(email: string, options?: MagicLinksLoginOrCreateOptions): Promise; /** * The Send method wraps the {@link https://stytch.com/docs/api/send-by-email send} Email Magic Link API endpoint. * This method requires that the user already exist within Stytch before a magic link may be sent. * This method is useful for gating your login flow to only pre-created users, e.g. an invite or waitlist. * * This method is also used when you need to add an email address to an existing Stytch User. * If there is a currently valid Stytch session, and the user inputs an email address that does not match one on their Stytch User object, upon successful authentication the new email address will be appended to the `emails` array. * Note, this does expose a potential account enumeration vector, see our article on {@link https://stytch.com/docs/resources/platform/account-enumeration preventing account enumeration} for more details. * * See the {@link https://stytch.com/docs/sdks/javascript-sdk#email-magic-links_methods_send Stytch Docs} for a complete reference. * * @example * stytch.magicLinks.email.send('sandbox@stytch.com', { * login_magic_link_url: 'https://example.com/authenticate', * login_expiration_minutes: 60, * signup_magic_link_url: 'https://example.com/authenticate', * signup_expiration_minutes: 60, * }); * * @param email - The email of the user to send the invite magic link to. * @param options - {@link MagicLinksSendOptions} * * @returns A {@link MagicLinksSendResponse} indicating that the email has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ send(email: string, options?: MagicLinksSendOptions): Promise; }; /** * The Authenticate method wraps the {@link https://stytch.com/docs/api/authenticate-magic-link authenticate} * Magic Link API endpoint which validates the magic link token passed in. * * See the {@link https://stytch.com/docs/sdks/javascript-sdk#email-magic-links_methods_authenticate Stytch Docs} for a complete reference. * * @example * const currentLocation = new URL(window.location.href); * const token = currentLocation.searchParams.get('token'); * stytch.magicLinks.authenticate(token, { * session_duration_minutes: 60, * }); * * @param token - The magic link token from the token query parameter in the URL. * @param options - {@link MagicLinksLoginOrCreateOptions} * * @returns A {@link MagicLinksAuthenticateResponse} indicating that magic link has been authenticated and the user is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(token: string, options: MagicLinksAuthenticateOptions): Promise>; } type OTPCodeOptions = { /** * Set the expiration for the one-time passcode, in minutes. The minimum expiration is 1 minute and the maximum is 10 minutes. The default expiration is 2 minutes. */ expiration_minutes: number; /** * Used to determine which language to use when sending the user this delivery method. Parameter is a [IETF BCP 47 language tag](https://www.w3.org/International/articles/language-tags/), e.g. `"en"`. * * Currently supported languages are English (`"en"`), Spanish (`"es"`), and Brazilian Portuguese (`"pt-br"`); if no value is provided, the copy defaults to English. */ locale?: locale; }; type OTPCodeSMSOptions = OTPCodeOptions & { /** * Indicates whether the SMS message should include autofill metadata */ enable_autofill?: boolean; /** * Indicates how long the autofill session should be valid. Defaults to 5 minutes */ autofill_session_duration_minutes?: number; }; type OTPCodeEmailOptions = OTPCodeOptions & { /** * The email template ID to use for login emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a OTP Login custom HTML template. */ login_template_id?: string; /** * The email template ID to use for sign-up emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a OTP Sign-up custom HTML template. */ signup_template_id?: string; }; type OTPAuthenticateOptions = { /** * Set the session lifetime to be this many minutes from now. * This value must be a minimum of 5 and may not exceed the `maximum session duration minutes` value set in the {@link https://stytch.com/dashboard/sdk-configuration SDK Configuration} page of the Stytch dashboard. * A successful authentication will continue to extend the session this many minutes. */ session_duration_minutes: number; }; type OTPsBaseResponse = ResponseCommon & { /** * The ID of the method used to send a one-time passcode. */ method_id: string; }; type OTPsLoginOrCreateResponse = OTPsBaseResponse; type OTPsSendResponse = OTPsBaseResponse; type OTPsAuthenticateResponse = AuthenticateResponse & { /** * The ID of the method used to send a one-time passcode. */ method_id: string; /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; interface IHeadlessOTPsClient { sms: { /** * Wraps Stytch's {@link https://stytch.com/docs/api/log-in-or-create-user-by-sms login_or_create} via SMS API endpoint. Call this method to send an SMS passcode to new or existing users. * * @example * ``` * const sendPasscode = useCallback(() => { * stytchClient.otps.sms.loginOrCreate('+12025550162', { * expiration_minutes: 5, * }); * }, [stytchClient]); * ``` * * @param phone_number - The phone number of the user to send a one-time passcode. The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see {@link https://stytch.com/docs/testing Testing} for more detail. * @param options - {@link OTPCodeOptions} * * @returns A {@link OTPsLoginOrCreateResponse} indicating the one-time passcode has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ loginOrCreate(phone_number: string, options?: OTPCodeSMSOptions): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/send-otp-by-sms send} via SMS API endpoint. Call this method to send an SMS passcode to existing users. * * @example * ``` * const sendPasscode = useCallback(() => { * stytchClient.otps.sms.send('+12025550162', { * expiration_minutes: 5, * }); * }, [stytchClient]); * ``` * * @param phone_number - The phone number of the user to send a one-time passcode. The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see {@link https://stytch.com/docs/testing Testing} for more detail. * @param options - {@link OTPCodeOptions} * * @returns A {@link OTPsSendResponse} indicating the one-time passcode has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ send(phone_number: string, options?: OTPCodeSMSOptions): Promise; }; whatsapp: { /** * Wraps Stytch's {@link https://stytch.com/docs/api/whatsapp-login-or-create login_or_create} via WhatsApp API endpoint. Call this method to send a WhatsApp passcode to new or existing users. * * @example * ``` * const sendPasscode = useCallback(() => { * stytchClient.otps.whatsapp.loginOrCreate('+12025550162', { * expiration_minutes: 5, * }); * }, [stytchClient]); * ``` * * @param phone_number - The phone number of the user to send a one-time passcode. The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see {@link https://stytch.com/docs/testing Testing} for more detail. * @param options - {@link OTPCodeOptions} * * @returns A {@link OTPsLoginOrCreateResponse} indicating the one-time passcode has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ loginOrCreate(phone_number: string, options?: OTPCodeOptions): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/whatsapp-send send} via WhatsApp API endpoint. Call this method to send an WhatsApp passcode to existing users. * * @example * ``` * const sendPasscode = useCallback(() => { * stytchClient.otps.whatsapp.send('+12025550162', { * expiration_minutes: 5, * }); * }, [stytchClient]); * ``` * * @param phone_number - The phone number of the user to send a one-time passcode. The phone number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, see {@link https://stytch.com/docs/testing Testing} for more detail. * @param options - {@link OTPCodeOptions} * * @returns A {@link OTPsSendResponse} indicating the one-time passcode has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ send(phone_number: string, options?: OTPCodeOptions): Promise; }; email: { /** * Wraps Stytch's {@link https://stytch.com/docs/api/log-in-or-create-user-by-email login_or_create} via email API endpoint. Call this method to send an email passcode to new or existing users. * * @example * ``` * const sendPasscode = useCallback(() => { * stytchClient.otps.email.loginOrCreate('sandbox@stytch.com', { * expiration_minutes: 5, * }); * }, [stytchClient]); * ``` * * @param email - The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test this endpoint, see {@link https://stytch.com/docs/testing Testing} for more detail. * @param options - {@link OTPCodeEmailOptions} * * @returns A {@link OTPsLoginOrCreateResponse} indicating the one-time passcode has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ loginOrCreate(email: string, options?: OTPCodeEmailOptions): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/send-otp-by-email send} via Email API endpoint. Call this method to send an email passcode to existing users. * * @example * ``` * const sendPasscode = useCallback(() => { * stytchClient.otps.email.send('sandbox@stytch.com', { * expiration_minutes: 5, * }); * }, [stytchClient]); * ``` * * @param email - The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test this endpoint, see {@link https://stytch.com/docs/testing Testing} for more detail. * @param options - {@link OTPCodeEmailOptions} * * @returns A {@link OTPsSendResponse} indicating the one-time passcode has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ send(email: string, options?: OTPCodeEmailOptions): Promise; }; /** * The Authenticate method wraps the {@link https://stytch.com/docs/api/authenticate-otp authenticate} one-time passcode API method which validates the code passed in. * * @example * ``` * const [code, setCode] = useState(''); * * const method_id = "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0" * // returned from calling loginOrCreate for OTPs on SMS, WhatsApp or Email * * const authenticate = useCallback((e) => { * e.preventDefault(); * stytchClient.otps.authenticate(code, method_id, { * session_duration_minutes: 60, * }); * }, [stytchClient, code]); * * const handleChange = useCallback((e) => { * setCode(e.target.value); * }, []); * ``` * * @param otp - The code to authenticate. * @param method_id - The ID of the method used to send a one-time passcode. * @param options - {@link OTPAuthenticateOptions} * * @returns A {@link OTPsAuthenticateResponse} indicating the one-time passcode method has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(otp: string, method_id: string, options?: OTPAuthenticateOptions): Promise>; } type SIWEParams = { /** * An RFC 3986 URI referring to the resource that is the subject of the signing. Defaults to window.location.origin */ uri?: string; /** * The EIP-155 Chain ID to which the session is bound, and the network where Contract Accounts MUST be resolved. * Defaults to 1. */ chain_id?: string; /** * The time when the message was generated. Defaults to the current time. * Must conform to the RFC 3339 standard in UTC, e.g. 2021-12-29T12:33:09Z. */ issued_at?: string; /** * A human-readable ASCII assertion that the user will sign. Must not include '\n'. */ statement?: string; /** * The time when the signed authentication message will become valid. Defaults to the current time. * Must conform to the RFC 3339 standard in UTC, e.g. 2021-12-29T12:33:09Z. */ not_before?: string; /** * A system-specific identifier that may be used to uniquely refer to the sign-in request. */ message_request_id?: string; /** * A list of information or references to information the user wishes to have resolved as part of authentication. * Every resource must be a valid RFC 3986 URI. */ resources?: string[]; }; type CryptoWalletAuthenticateStartOptions = { /** * The address to authenticate. */ crypto_wallet_address: string; /** * The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. */ crypto_wallet_type: string; /** * Parameters for the Sign In With Ethereum (SIWE) protocol. Only used if you have toggled on the * siweRequiredForCryptoWallets parameter in your SDK configuration and if the crypto_wallet_type is `ethereum`. */ siwe_params?: SIWEParams; }; type CryptoWalletAuthenticateStartResponse = ResponseCommon & { /** * The challenge to be signed by the user's wallet. */ challenge: string; }; type CryptoWalletAuthenticateOptions = SessionDurationOptions & { /** * The address to authenticate. */ crypto_wallet_address: string; /** * The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. */ crypto_wallet_type: string; /** * The signature from the message. */ signature: string; }; // CryptoWalletsAuthenticateResponse type CryptoWalletAuthenticateResponse = AuthenticateResponse & { /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; interface IHeadlessCryptoWalletClient { /** * Wraps Stytch's {@link https://stytch.com/docs/api/crypto-wallet-authenticate-start Crypto Wallet Authenticate Start} endpoint. Call this method to prompt the user to sign a challenge using their crypto wallet. * * For Ethereum crypto wallets, the challenge will follow the Sign In With Ethereum (SIWE) protocol if you have toggled **SIWE Enabled** in the {@link https://stytch.com/dashboard/sdk-configuration SDK Configuration page}. The domain and URI will be inferred automatically, but you may optionally override the URI. * * Load the challenge data by calling `cryptoWallets.authenticateStart()`. * * You'll then pass this challenge to the user's wallet for signing. You can do so by using the crypto provider's built-in API and by including the `crypto_wallet_address` and `challenge` that is provided from `cryptoWallets.authenticateStart()`. See [Ethereum's EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) for an example of Ethereum's provider API. * * * @example * ``` * // Request user's address * const [crypto_wallet_address] = await ethereum.request({ * method: 'eth_requestAccounts', * }); * * // Ask Stytch to generate a challenge for the user * const { challenge } = await stytch.cryptoWallets.authenticateStart({ * crypto_wallet_address: crypto_wallet_address, * crypto_wallet_type: 'ethereum', * }); * ``` * @param options - {@link CryptoWalletAuthenticateStartOptions} * * @returns A {@link CryptoWalletAuthenticateStartResponse} containing a challenge to be passed to the user's wallet for signing. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticateStart(options: CryptoWalletAuthenticateStartOptions): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/crypto-wallet-authenticate authenticate} crypto wallet endpoint. Call this method after the user signs the challenge to validate the signature. * If this method succeeds and the user is not already logged in, the user will be logged in, granted an active session, and the {@link https://stytch.com/docs/sdks/javascript-sdk/resources/cookies-and-session-management session cookies} will be minted and stored in the browser. * If the user is already logged in, the crypto wallet will be added to the `user.crypto_wallets[]` array and associated with user's existing session as an `authentication_factor`. * * See [Ethereum's EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) for an example of Ethereum's provider API. * * @example * ``` * // Ask the user to sign the challenge * const signature = await ethereum.request({ * method: 'personal_sign', * params: [challenge, crypto_wallet_address], * }); * * // Authenticate the signature * stytch.cryptoWallets.authenticate({ * crypto_wallet_address: crypto_wallet_address, * crypto_wallet_type: 'ethereum', * signature: signature, * session_duration_minutes: 60, * }); * ``` * * @param options - {@link CryptoWalletAuthenticateOptions} * * @returns A {@link CryptoWalletAuthenticateResponse} indicating the user has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(options: CryptoWalletAuthenticateOptions): Promise>; } type TOTPCreateOptions = { /** * The expiration for the TOTP instance. If the newly created TOTP is not authenticated within this time frame the TOTP will be unusable. Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 1440. */ expiration_minutes: number; }; type TOTPCreateResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific TOTP registration in the Stytch API. */ totp_id: string; /** * The TOTP secret key shared between the authenticator app and the server used to generate TOTP codes. */ secret: string; /** * The QR code image encoded in base64. */ qr_code: string; /** * The recovery codes used to authenticate the user without an authenticator app. */ recovery_codes: string[]; }; type TOTPAuthenticateOptions = SessionDurationOptions & { /** * The TOTP code to authenticate. The TOTP code should consist of 6 digits. */ totp_code: string; }; // TOTPsAuthenticateResponse type TOTPAuthenticateResponse = AuthenticateResponse & { /** * Globally unique UUID that identifies a specific TOTP registration in the Stytch API. */ totp_id: string; /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; type TOTPRecovery = { /** * Globally unique UUID that identifies a specific TOTP registration in the Stytch API. */ totp_id: string; /** * Indicates whether or not the TOTP registration has been verified by the user. */ verified: boolean; /** * The recovery codes for the TOTP registration. */ recovery_codes: string[]; }; type TOTPRecoveryCodesResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific user in the Stytch API. */ user_id: string; /** * See {@link TOTPRecovery}. */ totps: TOTPRecovery; }; type TOTPRecoverOptions = SessionDurationOptions & { /** * The recovery code to authenticate. */ recovery_code: string; }; // TOTPsRecoverResponse type TOTPRecoverResponse = AuthenticateResponse & { /** * Globally unique UUID that identifies a specific TOTP registration in the Stytch API. */ totp_id: string; /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; interface IHeadlessTOTPClient { /** * Wraps Stytch's {@link https://stytch.com/docs/api/totp-create Create} endpoint. Call this method to create a new TOTP instance for a user. The user can use the authenticator application of their choice to scan the QR code or enter the secret. * * You can listen for successful user updates anywhere in the codebase with the `stytch.user.onChange()` method or `useStytchUser()` hook if you are using React. * * **Note:** If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk/resources/mfa Multi-factor Authentication} section for more details. * * @example * ``` * stytchClient.totps.create({ expiration_minutes: 60 }); * ``` * * @param options - {@link TOTPCreateOptions} * * @returns A {@link TOTPCreateResponse} indicating a new TOTP instance has been created. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ create(options: TOTPCreateOptions): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/totp-authenticate Authenticate} endpoint. Call this method to authenticate a TOTP code entered by a user. * * @example * ``` * stytch.totps.authenticate({ totp_code: '123456', session_duration_minutes: 60 }); * ``` * * @param options - {@link TOTPAuthenticateOptions} * * @returns A {@link TOTPAuthenticateResponse} indicating the TOTP code has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(options: TOTPAuthenticateOptions): Promise>; /** * Wraps Stytch's {@link https://stytch.com/docs/api/totp-get-recovery-codes Recovery Codes} endpoint. Call this method to retrieve the recovery codes for a TOTP instance tied to a user. * * You can listen for successful user updates anywhere in the codebase with the `stytch.user.onChange()` method or `useStytchUser()` hook if you are using React. * * **Note:** If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk/resources/mfa Multi-factor authentication} section for more details. * * @example * ``` * stytchClient.totps.recoveryCodes(); * ``` * * @returns A {@link TOTPRecoveryCodesResponse} containing the TOTP recovery codes tied to the user. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ recoveryCodes(): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/api/totp-recover Recover} endpoint. Call this method to authenticate a recovery code for a TOTP instance. * * @example * ``` * stytch.totps.recover({ recovery_code: 'xxxx-xxxx-xxxx', session_duration_minutes: 60 }); * ``` * * @param options - {@link TOTPRecoverOptions} * * @returns A {@link TOTPRecoverResponse} indicating the TOTP recovery code has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ recover(options: TOTPRecoverOptions): Promise>; } type WebAuthnRegisterStartOptions = SessionDurationOptions & { /** * The domain for the WebAuthn registration. * @default window.location.hostname */ domain?: string; /** * The requested authenticator type of the WebAuthn device. The two valid values are `platform` and `cross-platform`. If no value passed, we assume both values are allowed. */ authenticator_type?: "platform" | "cross-platform"; /** * Whether the flow should be optimized for Passkeys. */ is_passkey?: boolean; /** * The desired ID for the `user` key in the `public_key_credential_creation_options` response field. The default is the User's ID. */ override_id?: string; /** * The desired name for the `user` key in the `public_key_credential_creation_options` response field. The default is the User's name, email, or phone number. */ override_name?: string; /** * The desired display_name for the `user` key in the `public_key_credential_creation_options` response field. The default is the User's name, email, or phone number. */ override_display_name?: string; /** * If true, will encode credentials using base64 URL encoding instead of base64 standard encoding. Defaults to false. */ use_base64_url_encoding?: boolean; }; type WebAuthnRegisterResponse = AuthenticateResponse & { /** * A unique ID that identifies a specific WebAuthn registration. */ webauthn_registration_id: string; }; type WebAuthnAuthenticateStartOptions = SessionDurationOptions & { /** * The domain for the WebAuthn registration. */ domain?: string; /** * Whether the flow should be optimized for Passkeys. */ is_passkey?: boolean; /** * Whether to use conditional mediation (autofill) in the authentication flow. */ conditional_mediation?: boolean; /** * An optional `AbortSignal` to allow aborting the authentication process. */ signal?: AbortSignal; }; type WebAuthnAuthenticateResponse = AuthenticateResponse & { /** * A unique ID that identifies a specific WebAuthn registration. */ webauthn_registration_id: string; /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; type WebAuthnUpdateOptions = { /** * A unique ID that identifies a specific WebAuthn registration. */ webauthn_registration_id: string; /** * A readable name for the registration. */ name: string; }; type WebAuthnUpdateResponse = ResponseCommon & { /** * The webauthn registration object. */ webauthn_registration: WebAuthnRegistration; }; interface IHeadlessWebAuthnClient { /** * Wraps Stytch's {@link https://stytch.com/docs/api/webauthn-register-start register_start} and {@link https://stytch.com/docs/api/webauthn-register register} WebAuthn endpoints and the [navigator.credentials](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create) web API. Call this method to prompt the user to enroll a new WebAuthn factor and save the factor in Stytch. * * Call `webauthn.register` inside an event callback triggered by a user gesture. * * You can listen for successful user updates anywhere in the codebase with the `stytch.user.onChange()` method or `useStytchUser()` hook if you are using React. * * **Note:** If a user has enrolled another MFA method, this method will require MFA. See the {@link https://stytch.com/docs/sdks/javascript-sdk/resources/mfa Multi-factor authentication} section for more details. * * @example * ``` * const registerWebAuthn = useCallback(() => { * stytchClient.register({ * domain: 'subdomain.example.com', * authenticator_type: 'platform' * }); * }, [stytchClient]); * ``` * * @param options - {@link WebAuthnRegisterStartOptions} * * @returns A {@link WebAuthnRegisterResponse} indicating WebAuthn has been registered. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ register(options?: WebAuthnRegisterStartOptions): Promise>; /** * Wraps Stytch's {@link https://stytch.com/docs/api/webauthn-authenticate-start authenticate_start} and {@link https://stytch.com/docs/api/webauthn-authenticate authenticate} WebAuthn endpoints and the [navigator.credentials](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create) web API. Call this method to prompt the user to enroll a new WebAuthn factor and save the factor in Stytch. * * Call `webauthn.authenticate` inside an event callback triggered by a user gesture. * * You can listen for successful user updates anywhere in the codebase with the `stytch.user.onChange()` method or `useStytchUser()` hook if you are using React. * * @example * ``` * const authenticateWebAuthn = useCallback(() => { * stytchClient.webauthn.authenticate({ * domain: 'subdomain.example.com', * session_duration_minutes: 60, * }); * }, [stytchClient]); * ``` * * @param options - {@link WebAuthnAuthenticateStartOptions} * * @returns A {@link WebAuthnAuthenticateResponse} indicating the WebAuthn registration has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(options: WebAuthnAuthenticateStartOptions): Promise | null>; /** * Allows a WebAuthn registration to be updated with a different name. */ update(options: WebAuthnUpdateOptions): Promise; /** * Determines if the browser supports autofill. If it does, we recommend using `conditional_mediation` when authenticating. */ browserSupportsAutofill(): Promise; } type PasswordCreateOptions = SessionDurationOptions & { /** * The email of the new user. */ email: string; /** * The password for the new user. */ password: string; }; // PasswordsCreateResponse type PasswordCreateResponse = AuthenticateResponse & { /** * Globally unique UUID that identifies a specific email address in the Stytch API. * The `email_id` is used when you need to operate on a specific user's email address, * e.g. to delete the email address from the Stytch user. */ email_id: string; /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; type PasswordAuthenticateOptions = SessionDurationOptions & { /** * The email of the user. */ email: string; /** * The password for the user. */ password: string; }; // PasswordsAuthenticateResponse type PasswordAuthenticateResponse = AuthenticateResponse & { /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; type PasswordResetByEmailStartOptions = { /** * The email of the user that requested the password reset. */ email: string; /** * The url that the user clicks from the password reset email to skip resetting their password and directly login. * This should be a url that your app receives, parses, and subsequently sends an API request to the magic link authenticate endpoint to complete the login process without reseting their password. * If this value is not passed, the login redirect URL that you set in your Dashboard is used. * If you have not set a default login redirect URL, an error is returned. */ login_redirect_url?: string; /** * Set the expiration for the login email magic link, in minutes. * By default, it expires in 1 hour. * The minimum expiration is 5 minutes and the maximum is 10080 minutes (7 days). */ login_expiration_minutes?: number; /** * The url that the user clicks from the password reset email to finish the reset password flow. * This should be a url that your app receives and parses before showing your app's reset password page. * After the user submits a new password to your app, it should send an API request to complete the password reset process. * If this value is not passed, the default reset password redirect URL that you set in your Dashboard is used. * If you have not set a default reset password redirect URL, an error is returned. */ reset_password_redirect_url?: string; /** * Set the expiration for the password reset, in minutes. * By default, it expires in 30 minutes. * The minimum expiration is 5 minutes and the maximum is 7 days (10080 mins). */ reset_password_expiration_minutes?: number; /** * The email template ID to use for password reset. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Passwords reset custom HTML template. */ reset_password_template_id?: string; /** * Used to determine which language to use when sending the user this delivery method. Parameter is a [IETF BCP 47 language tag](https://www.w3.org/International/articles/language-tags/), e.g. `"en"`. * * Currently supported languages are English (`"en"`), Spanish (`"es"`), and Brazilian Portuguese (`"pt-br"`); if no value is provided, the copy defaults to English. */ locale?: string; }; type PasswordResetByEmailStartResponse = ResponseCommon; type PasswordResetByEmailOptions = SessionDurationOptions & { /** * The token to authenticate. */ token: string; /** * The new password for the user. */ password: string; }; // PasswordsEmailResetResponse type PasswordResetByEmailResponse = AuthenticateResponse & { /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; type PasswordResetByExistingPasswordOptions = SessionDurationOptions & { /** * The user's email. */ email: string; /** * The user's existing password. */ existing_password: string; /** * The new password for the user. */ new_password: string; }; // PasswordsExistingPasswordResetResponse type PasswordResetByExistingPasswordResponse = AuthenticateResponse & { /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; type PasswordResetBySessionOptions = SessionDurationOptions & { /** * The new password for the user. */ password: string; }; // PasswordsSessionResetResponse type PasswordResetBySessionResponse = AuthenticateResponse & { /** * The device history of the user. */ user_device?: SDKDeviceHistory; }; type PasswordStrengthCheckOptions = { /** * The email associated with the password. Provide this for a more accurate strength check. */ email?: string; /** * The password to strength check. */ password: string; }; type PasswordStrengthCheckResponse = ResponseCommon & { /** * Whether or not the password is considered valid and secure. * Read more about password validity {@link https://stytch.com/docs/api/password-strength-check in our docs}. */ valid_password: boolean; /** * The score of the password as determined by {@link https://github.com/dropbox/zxcvbn zxcvbn}. */ score: number; /** * Determines if the password has been breached using {@link https://haveibeenpwned.com/ HaveIBeenPwned}. */ breached_password: boolean; /** * Will return true if breach detection will be evaluated. By default this option is enabled. * This option can be disabled by contacting support@stytch.com. If this value is false then * breached_password will always be false as well. */ breach_detection_on_create: boolean; /** * The strength policy type enforced, either `zxcvbn` or `luds`. */ strength_policy: "luds" | "zxcvbn"; /** * Feedback for how to improve the password's strength using {@link https://github.com/dropbox/zxcvbn zxcvbn}. */ feedback: { suggestions: string[]; warning: string; /** * Contains which LUDS properties are fulfilled by the password and which are missing to convert * an invalid password into a valid one. You'll use these fields to provide feedback to the user * on how to improve the password. */ luds_requirements: { has_digit: boolean; has_lower_case: boolean; has_symbol: boolean; has_upper_case: boolean; missing_characters: number; missing_complexity: number; }; }; }; interface IHeadlessPasswordClient { /** * The Create method wraps the {@link https://stytch.com/docs/api/password-create Create} Password API endpoint. * If a user with this email already exists in the project, this API will return an error. * Existing passwordless users who wish to create a password need to go through the reset password flow. * * This endpoint will return an error if the password provided does not meet our strength requirements, * which you can check beforehand with the {@link https://stytch.com/docs/api/password-strength-check Strength Check} Password API endpoint. * * If this method succeeds, the user will be logged in, granted an active session, and the * {@link https://stytch.com/docs/sdks/javascript-sdk/resources/cookies-and-session-management session cookies} will be minted and stored in the browser. * * @example * const {valid_password} = await stytch.passwords.strengthCheck({ email, password }); * if (valid_password) { * stytch.passwords.create({ email, password, session_duration_minutes: 60 }); * } * * @param options - {@link PasswordCreateOptions} * * @returns A {@link PasswordCreateResponse} indicating the user has been created and that the user is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ create(options: PasswordCreateOptions): Promise>; /** * The Authenticate method wraps the {@link https://stytch.com/docs/api/password-authenticate Authenticate} Password API endpoint. * This endpoint verifies that the user has a password currently set, and that the entered password is correct. * * There are cases where this endpoint will return a `reset_password` error even if the password entered is correct. * View our {@link https://stytch.com/docs/api/password-authenticate API Docs} for complete details. * * @example * stytch.passwords.authenticate({ * email: 'sandbox@stytch.com', * password: 'aVerySecurePassword', * session_duration_minutes: 60 * }); * * @param options - {@link PasswordAuthenticateOptions} * * @returns A {@link PasswordAuthenticateResponse} indicating the password is valid and that the user is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(options: PasswordAuthenticateOptions): Promise>; /** * The resetByEmailStart method wraps the {@link https://stytch.com/docs/api/password-email-reset-start Reset By Email Start} Password API endpoint. * This endpoint initiates a password reset for the email address provided. * This will trigger an email to be sent to the address, containing a magic link that will allow them to set a new password and authenticate. * * @example * stytch.passwords.resetByEmailStart({ * email: 'sandbox@stytch.com', * reset_password_redirect_url: 'https://example.com/login/reset', * reset_password_expiration_minutes: 10, * login_redirect_url: 'https://example.com/login/authenticate', * }); * * @param options - {@link PasswordResetByEmailStartOptions} * * @returns A {@link PasswordResetByEmailStartResponse} indicating the password is valid and that the user is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetByEmailStart(options: PasswordResetByEmailStartOptions): Promise; /** * The resetByEmail method wraps the {@link https://stytch.com/docs/api/password-email-reset Reset By Email} Password API endpoint. * This endpoint the user’s password and authenticate them. * This endpoint checks that the magic link token is valid, hasn't expired, or already been used. * The provided password needs to meet our password strength requirements, which can be checked in advance with the {@link https://stytch.com/docs/api/password-strength-check Strength Check} Password API endpoint. * * @example * const currentLocation = new URL(window.location.href); * const token = currentLocation.searchParams.get('token'); * stytch.passwords.resetByEmail({ * token, * email: 'sandbox@stytch.com', * password: 'aVerySecurePassword', * session_duration_minutes: 60 * }); * * @param options - {@link PasswordResetByEmailOptions} * * @returns A {@link PasswordResetByEmailResponse} indicating the password is valid and that the user is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetByEmail(options: PasswordResetByEmailOptions): Promise>; /** * The `strengthCheck` method wraps the {@link https://stytch.com/docs/api/password-strength-check Strength Check} Password API endpoint. * * This method allows you to check whether or not the user’s provided password is valid, and to provide feedback to the user on how to increase the strength of their password. * All passwords must pass the strength requirements to be accepted as valid. * * @example * const {valid_password, feedback} = await stytch.passwords.strengthCheck({ email, password }); * if (!valid_password) { * throw new Error('Password is not strong enough: ' + feedback.warning); * } * * @param options - {@link PasswordStrengthCheckOptions} * * @returns A {@link PasswordStrengthCheckResponse} containing password strength feedback. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ strengthCheck(options: PasswordStrengthCheckOptions): Promise; /** * The resetByExistingPassword method wraps the {@link https://stytch.com/docs/api/password-existing-password-reset Reset By Existing Password} API endpoint. * * @example * stytch.passwords.resetByExistingPassword({ * email: 'sandbox@stytch.com', * existing_password: 'aVerySecurePassword', * new_password: 'aVerySecureNewPassword' * }); * * @param options - {@link PasswordResetByExistingPasswordOptions} * * @returns A {@link PasswordResetByExistingPasswordResponse} indicating the password is valid and that the user is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetByExistingPassword(options: PasswordResetByExistingPasswordOptions): Promise>; /** * The resetBySession method wraps the {@link https://stytch.com/docs/api/password-session-reset Reset By Session} API endpoint. * * @example * stytch.passwords.resetBySession({ * password: 'aVerySecurePassword' * }); * * @param options - {@link PasswordResetBySessionOptions} * * @returns A {@link PasswordResetBySessionResponse} indicating the password is valid and that the user is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetBySession(options: PasswordResetBySessionOptions): Promise>; } // Authentication Factors interface B2BEmailFactor { delivery_method: "email"; type: string; last_authenticated_at: string; email_factor: { email_id: string; email_address: string; }; sequence_order: "PRIMARY"; } interface B2BPhoneNumberFactor { delivery_method: "sms" | "whatsapp"; type: string; last_authenticated_at: string; phone_number_factor: { phone_id: string; phone_number: string; }; sequence_order: "SECONDARY"; } interface B2BGoogleOAuthFactor { delivery_method: "oauth_google"; type: string; last_authenticated_at: string; google_oauth_factor: { id: string; email_id: string; provider_subject: string; }; sequence_order: "PRIMARY"; } interface B2BMicrosoftOAuthFactor { delivery_method: "oauth_microsoft"; type: string; last_authenticated_at: string; microsoft_oauth_factor: { id: string; email_id: string; provider_subject: string; }; sequence_order: "PRIMARY"; } interface B2BHubSpotOAuthFactor { delivery_method: "oauth_hubspot"; type: string; last_authenticated_at: string; hubspot_oauth_factor: { id: string; email_id: string; provider_subject: string; provider_tenant_id?: string; }; sequence_order: "PRIMARY"; } interface B2BSlackOAuthFactor { delivery_method: "oauth_slack"; type: string; last_authenticated_at: string; slack_oauth_factor: { id: string; email_id: string; provider_subject: string; provider_tenant_id?: string; }; sequence_order: "PRIMARY"; } interface B2BGitHubOAuthFactor { delivery_method: "oauth_github"; type: string; last_authenticated_at: string; github_oauth_factor: { id: string; email_id: string; provider_subject: string; provider_tenant_ids?: string[]; }; sequence_order: "PRIMARY"; } type B2BAuthenticationFactor = B2BEmailFactor | B2BPhoneNumberFactor | B2BGoogleOAuthFactor | B2BMicrosoftOAuthFactor | B2BHubSpotOAuthFactor | B2BSlackOAuthFactor | B2BGitHubOAuthFactor; type MemberResponseCommon = ResponseCommon & { /** * Globally unique UUID that identifies a specific member in the Stytch API. * The member_id critical to perform operations on a member in our API * so be sure to preserve this value. */ member_id: string; /** * The Member object. * See {@link Member} for details. */ member: Member; /** * The Organization object. * See {@link Organization} for details. */ organization: Organization; }; interface MemberSession { /** * Globally unique UUID that identifies a specific member session in the Stytch API. */ member_session_id: string; /** * Globally unique UUID that identifies a specific member in the Stytch API. * The member_id critical to perform operations on a member in our API * so be sure to preserve this value. */ member_id: string; /** * Globally unique UUID that identifies an organization in the Stytch API. */ organization_id: string; /** * The timestamp of the session's creation. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ started_at: string; /** * The timestamp of the last time the session was accessed. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ last_accessed_at: string; /** * The timestamp of the session's expiration. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ expires_at: string; /** * All the authentication factors that have been associated with the current member session. */ authentication_factors: B2BAuthenticationFactor[]; /** * A map of the custom claims associated with the session. * Custom claims can only be set from the server, they cannot be set using the clientside SDKs. * After claims have been added to a session, call {@link IHeadlessB2BSessionClient#authenticate stytch.session.authenticate} to refresh the session state clientside. * See our {@link https://stytch.com/docs/sessions#using-sessions_custom-claims guide} for more information. * If no claims are set, this field will be null. */ custom_claims?: Record; /** * A list of the roles associated with the session. * Members may inherit certain roles depending on the factors in their session. * For example, some roles may only be active if the member logged in from a specific SAML IDP. */ roles: string[]; /** * The slug of the organization that the member belongs to. */ organization_slug: string; } interface SSORegistration { connection_id: string; external_id: string; registration_id: string; sso_attributes: Record; } interface OAuthRegistration { /** * Globally unique UUID that identifies a specific member OAuth registration in the Stytch API. */ member_oauth_registration_id: string; /** * The `provider_subject` field is the unique identifier used to identify the user within a given OAuth provider. * Also commonly called the "sub" or "Subject field" in OAuth protocols. */ provider_subject: string; /** * The `type` field denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Facebook, GitHub etc. */ provider_type: string; /** * If available, the `profile_picture_url` is a url of the user's profile picture set in OAuth identity the provider that the user has authenticated with, e.g. Facebook profile picture. */ profile_picture_url: string | null; /** * If available, the `locale` is the user's locale set in the OAuth identity provider that the user has authenticated with. */ locale: string | null; /** * A list of known tenants associated with the provider. */ provider_tenants: { /** * The ID of the tenant assigned by the provider. */ tenant_id: string; /** * The name of the tenant. */ tenant_name: string; }[]; } type RoleSource = { type: "direct_assignment"; details: Record; } | { type: "email_assignment"; details: { email_domain: string; }; } | { type: "sso_connection"; details: { connection_id: string; }; } | { type: "sso_connection_group"; details: { connection_id: string; group: string; }; } | { type: "scim_connection_group"; details: { connection_id: string; group_id: string; }; }; interface MemberRole { role_id: string; sources: RoleSource[]; } interface RetiredEmailAddress { email_id?: string; email_address?: string; } interface Member { /** * Globally unique UUID that identifies an organization in the Stytch API. */ organization_id: string; /** * Globally unique UUID that identifies a specific member in the Stytch API. * The member_id critical to perform operations on a member in our API * so be sure to preserve this value. */ member_id: string; /** * The email address of the member. */ email_address: string; /** * Whether the member's email address is verified. */ email_address_verified: boolean; /** * A list of retired email addresses associated with the Member, if any exist. */ retired_email_addresses: RetiredEmailAddress[]; /** * The `status` value denotes whether or not a user has successfully logged in at least once with any available login method. */ status: string; /** * The name of the member */ name: string; /** * A JSON object containing application-specific metadata. * This field can only be updated by a direct API integration. * Use it to store fields that a member should not be allowed to edit without backend validation - such as `role` or `subscription_status`. * See our {@link https://stytch.com/docs/api/metadata metadata reference} for complete details. */ trusted_metadata: Record; /** * A JSON object containing application-specific metadata. * Use it to store fields that a member can be allowed to edit directly without backend validation - such as `display_theme` or `preferred_locale`. * See our {@link https://stytch.com/docs/api/metadata metadata reference} for complete details. */ untrusted_metadata: Record; /** * The timestamp of the Member's creation. Values conform to the RFC 3339 standard and are expressed in * UTC, e.g. `2021-12-29T12:33:09Z`. */ created_at: string; /** * The timestamp of when the Member was last updated. Values conform to the RFC 3339 standard and are * expressed in UTC, e.g. `2021-12-29T12:33:09Z`. */ updated_at: string; sso_registrations: SSORegistration[]; /** * Identifies the Member as a break glass user - someone who has permissions to authenticate into an Organization by bypassing the Organization's settings. * A break glass account is typically used for emergency purposes to gain access outside of normal authentication procedures. */ is_breakglass: boolean; /** * Whether or not the Member has the `stytch_admin` Role. This Role is automatically granted to Members * who create an Organization through the discovery flow. See the * {@link https://stytch.com/docs/b2b/guides/rbac/stytch-default RBAC guide} for more details on this Role. */ is_admin: boolean; /** * Returned if the member has a registered password */ member_password_id: string; /** * If true, the member must complete a secondary authentication flow, such as SMS OTP, along with their * primary authentication factor in order to log in and attain a member session. */ mfa_enrolled: boolean; /** * Returned if the member has a phone number. */ mfa_phone_number: string; /** * Whether the member's phone number is verified. */ mfa_phone_number_verified: boolean; /** * A list of the member's roles and their sources */ roles: MemberRole[]; /** * The member's default MFA method. */ default_mfa_method: string; /** * Globally unique UUID that identifies a TOTP instance. */ totp_registration_id: string; /** * A list of OAuth registrations for the member. */ oauth_registrations: OAuthRegistration[]; /** * The external ID of the member. */ external_id?: string; } type B2BSessionTokens = { /** * An opaque session token. * Session tokens need to be authenticated via the {@link https://stytch.com/docs/b2b/api/authenticate-session SessionsAuthenticate} * endpoint before a member takes any action that requires authentication. * If the project is configured to use HttpOnly cookies, this field will always be empty. * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_tokens our documentation} for more information. */ session_token: string; /** * A JSON Web Token that contains standard claims about the user as well as information about the Stytch session * Session JWTs can be authenticated locally without an API call. * A session JWT is signed by project-specific keys stored by Stytch. * If the project is configured to use HttpOnly cookies, this field will always be empty. * See {@link https://stytch.com/docs/sessions#session-tokens-vs-JWTs_jwts our documentation} for more information. */ session_jwt: string; }; type B2BAuthenticateResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific member in the Stytch API. * The member_id critical to perform operations on a member in our API * so be sure to preserve this value. */ member_id: string; /** * The Member Session object. * See {@link MemberSession} for details. */ member_session: MemberSession; /** * The Member object. * See {@link Member} for details. */ member: Member; /** * The Organization object. * See {@link Organization} for details. */ organization: Organization; } & IfOpaqueTokens, Redacted, B2BSessionTokens>; type B2BAuthenticateResponseWithMFA = Omit, "member_session"> & ({ /** * The Member Session object. * See {@link MemberSession} for details. */ member_session: MemberSession; /** * Returns true if the member is fully authenticated, in which case a member session is returned. * Returns false if the member still needs to complete a secondary authentication requirement, * in which case an intermediate_session_token is returned. */ member_authenticated: true; /** * The intermediate_session_token can be passed into a secondary authentication endpoint, such as OTP authenticate, * in order to receive a member session. The intermediate_session_token can also be used with discovery endpoints * to join a different organization or create a new organization. * If the project is configured to use HttpOnly cookies, this field will always be empty. */ intermediate_session_token: ""; /** * Contains information about the member's options for completing MFA, if applicable. */ mfa_required: null; /** * Contains information about the member's requirements for verifying their email, if applicable. */ primary_required: null; } | { /** * The Member Session object. * See {@link MemberSession} for details. */ member_session: null; /** * Returns true if the member is fully authenticated, in which case a member session is returned. * Returns false if the member still needs to complete a secondary authentication requirement, * in which case an intermediate_session_token is returned. */ member_authenticated: false; /** * The intermediate_session_token can be passed into a secondary authentication endpoint, such as OTP authenticate, * in order to receive a member session. The intermediate_session_token can also be used with discovery endpoints * to join a different organization or create a new organization. * If the project is configured to use HttpOnly cookies, this field will always be empty. */ intermediate_session_token: IfOpaqueTokens, RedactedToken, string>; /** * Contains information about the member's options for completing MFA, if applicable. */ mfa_required: MfaRequired | null; /** * Contains information about the member's requirements for verifying their email, if applicable. */ primary_required: PrimaryRequired | null; }); type B2BAllowedAuthMethods = "sso" | "magic_link" | "password" | "google_oauth" | "microsoft_oauth" | "hubspot_oauth" | "slack_oauth" | "github_oauth" | "email_otp"; type B2BAllowedMFAMethods = "sms_otp" | "totp"; interface SSOActiveConnection { connection_id: string; display_name: string; identity_provider: string; } interface Organization { /** * Globally unique UUID that identifies an organization in the Stytch API. */ organization_id: string; /** * The name of the organization. */ organization_name: string; /** * The slug of the organization. */ organization_slug: string; /** * The external ID of the organization. */ organization_external_id?: string; /** * A URL of the organization's logo. */ organization_logo_url: string; /** * A JSON object containing application-specific metadata. * This field can only be updated by a direct API integration. */ trusted_metadata: Record; /** * The organization's custom RBAC roles. * Custom roles are additive to the project's base RBAC policy. */ custom_roles?: RBACPolicyRole[]; /** * The default connection used for SSO when there are multiple active connections. */ sso_default_connection_id: string | null; /** * The authentication setting that controls the JIT provisioning of Members when authenticating via SSO. * The accepted values are: * ALL_ALLOWED – new Members will be automatically provisioned upon successful authentication via any of the Organization's sso_active_connections. * RESTRICTED – only new Members with SSO logins that comply with sso_jit_provisioning_allowed_connections can be provisioned upon authentication. * NOT_ALLOWED – disable JIT provisioning via SSO. */ sso_jit_provisioning: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * An array of connection_ids that reference SAML Connection objects. * Only these connections will be allowed to JIT provision Members via SSO when sso_jit_provisioning is set to RESTRICTED. */ sso_jit_provisioning_allowed_connections: string[]; /** * An array of active SSO Connection references. */ sso_active_connections: SSOActiveConnection[]; /** * An active SCIM Connection reference. */ scim_active_connection: { connection_id: string; display_name: string; } | null; /** * An array of email domains that allow invites or JIT provisioning for new Members. * This list is enforced when either email_invites or email_jit_provisioning is set to RESTRICTED. * Common domains such as gmail.com are not allowed. */ email_allowed_domains: string[]; /** * The authentication setting that controls how a new Member can be provisioned by authenticating via Email Magic Link. * The accepted values are: * ALL_ALLOWED - any new Member can be provisioned via Email Magic Link. * RESTRICTED – only new Members with verified emails that comply with email_allowed_domains can be provisioned upon authentication via Email Magic Link. * NOT_ALLOWED – disable JIT provisioning via Email Magic Link. */ email_jit_provisioning: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The authentication setting that controls how a new Member can be invited to an organization by email. * The accepted values are: * ALL_ALLOWED – any new Member can be invited to join via email. * RESTRICTED – only new Members with verified emails that comply with email_allowed_domains can be invited via email. * NOT_ALLOWED – disable email invites. */ email_invites: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The authentication setting that controls how a new Member can be provisioned by authenticating via OAuth, when the OAuth provider does not guarantee the validity of the email. * The accepted values are: * RESTRICTED – only Members coming from an OAuth Tenant are in allowed_oauth_tenants are allowed to JIT provision. * NOT_ALLOWED – disable JIT provisioning via OAuth. */ oauth_tenant_jit_provisioning: "RESTRICTED" | "NOT_ALLOWED"; /** * A JSON object of allowed OAuth Tenants to be used with oauth_tenant_jit_provisioning. * Records are provided with the provider, e.g. "hubspot", as the key, and a list of tenants, e.g. ['HubID1234', 'HubID2345'], as the value. */ allowed_oauth_tenants: Record; /** * The setting that controls which authentication methods can be used by Members of an Organization. * The accepted values are: * ALL_ALLOWED – the default setting which allows all authentication methods to be used. * RESTRICTED – only methods that comply with allowed_auth_methods can be used for authentication. This setting does not apply to Members with is_breakglass set to true. */ auth_methods: "ALL_ALLOWED" | "RESTRICTED"; /** * An array of allowed authentication methods. * This list is enforced when auth_methods is set to RESTRICTED. * The list's accepted values are: sso, magic_link, password, google_oauth, microsoft_oauth, hubspot_oauth, slack_oauth, github_oauth, and email_otp. */ allowed_auth_methods?: B2BAllowedAuthMethods[]; /** * The setting that controls which mfa methods can be used by Members of an Organization. * The accepted values are: * ALL_ALLOWED – the default setting which allows all MFA methods to be used. * RESTRICTED – only methods that comply with allowed_mfa_methods can be used for MFA. This setting does not apply to Members with is_breakglass set to true. */ mfa_methods?: "ALL_ALLOWED" | "RESTRICTED"; /** * An array of allowed MFA methods. * This list is enforced when mfa_methods is set to RESTRICTED. * The list's accepted values are: sms_otp and totp. */ allowed_mfa_methods?: B2BAllowedMFAMethods[]; /** * The setting that controls the MFA policy for all Members in the Organization. The accepted values are: * REQUIRED_FOR_ALL – All Members within the Organization will be required to complete MFA every time they wish to log in. * OPTIONAL – The default value. The Organization does not require MFA by default for all Members. Members will be required to complete MFA only if their mfa_enrolled status is set to true */ mfa_policy: "OPTIONAL" | "REQUIRED_FOR_ALL"; /** * An array of implicit role assignments granted to members in this organization whose emails match the domain. */ rbac_email_implicit_role_assignments?: { role_id: string; domain: string; }[]; /** * The setting that controls an Organization's policy towards allowing First Party Connected Apps to interact with its Members. * The accepted values are: * ALL_ALLOWED - any Connected App in the Project may interact with the Organization's Members. * RESTRICTED – only Connected Apps set in the allowlist (`allowed_first_party_connected_apps`) are permitted. * NOT_ALLOWED – no Connected Apps are allowed. */ first_party_connected_apps_allowed_type?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The IDs of First Party Connected Apps that are allowed to interact with an Organization's Members. This value is only * used if `first_party_connected_apps_allowed_type` is set to 'RESTRICTED'. */ allowed_first_party_connected_apps?: string[]; /** * The setting that controls an Organization's policy towards allowing Third Party Connected Apps to interact with its Members. * The accepted values are: * ALL_ALLOWED - any Connected App in the Project may interact with the Organization's Members. * RESTRICTED – only Connected Apps set in the allowlist (`allowed_first_party_connected_apps`) are permitted. * NOT_ALLOWED – no Connected Apps are allowed. */ third_party_connected_apps_allowed_type?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The IDs of Third Party Connected Apps that are allowed to interact with an Organization's Members. This value is only used * if `first_party_connected_apps_allowed_type` is set to 'RESTRICTED'. */ allowed_third_party_connected_apps?: string[]; } type B2BState = { member?: Member; organization?: Organization; session?: MemberSession; }; interface DiscoveredOrganization { organization: Organization; membership: { type: "eligible_to_join_by_email_domain"; details: { domain: string; }; member: null; } | { type: "active_member" | "pending_member" | "invited_member"; details: null; member: Member; } | { type: "eligible_to_join_by_oauth_tenant"; details: { provider: string; tenant: string; }; member: null; }; member_authenticated: boolean; primary_required: PrimaryRequired | null; mfa_required: MfaRequired | null; } interface MfaRequired { member_options: MemberOptions | null; /** * Equal to 'sms_otp' if an OTP code was sent to the member's phone number. */ secondary_auth_initiated: "sms_otp" | null; } interface PrimaryRequired { allowed_auth_methods: string[]; } interface MemberOptions { mfa_phone_number: string; } interface X509Certificate { certificate_id: string; certificate: string; issuer: string; created_at: string; expires_at: string; updated_at: string; } interface EncryptionPrivateKey { private_key_id: string; private_key: string; created_at: string; } interface SAMLConnection { /** * Globally unique UUID that identifies a specific Organization. */ organization_id: string; /** * Globally unique UUID that identifies a specific SAML Connection. */ connection_id: string; /** * The status of the connection. * The possible values are `pending` or `active`. * See the {@link https://stytch.com/docs/b2b/api/update-saml-connection Update SAML Connection} endpoint for more details. */ status: string; /** * An object that represents the attributes used to identify a Member. * This object will map the IdP-defined User attributes to Stytch-specific values. * Required attributes: `email` and one of `full_name` or `first_name` and `last_name`. */ attribute_mapping: Record; /** * A globally unique name for the IdP. This will be provided by the IdP. */ idp_entity_id: string; /** * A human-readable display name for the connection. */ display_name: string; /** * The URL for which assertions for login requests will be sent. This will be provided by the IdP. */ idp_sso_url: string; /** * The URL of the Assertion Consumer Service. * This value will be passed to the IdP to redirect the Member back to Stytch after a sign-in attempt. * Read our {@link https://stytch.com/docs/b2b/api/saml-overview SAML Overview} for more info. */ acs_url: string; /** * The URL of the Audience Restriction. * This value will indicate that Stytch is the intended audience of an assertion. * Read our {@link https://stytch.com/docs/b2b/api/saml-overview SAML Overview} for more info. */ audience_uri: string; /** * A list of X.509 certificates Stytch will use to sign its assertion requests. Certificates should be uploaded to the IdP. */ signing_certificates: X509Certificate[]; /** * A list of X.509 certificates Stytch will use to validate an assertion callback. Certificates should be populated from the IdP. */ verification_certificates: X509Certificate[]; /** * An array of implicit role assignments granted to members in this organization who log in with this SAML connection. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ saml_connection_implicit_role_assignments: { role_id: string; }[]; /** * An array of implicit role assignments granted to members in this organization who log in with this SAML connection * and belong to the specified group. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ saml_group_implicit_role_assignments: { role_id: string; group: string; }[]; /** * The identity provider of this connection. For SAML, the accepted values are `generic`, `okta`, `microsoft-entra`, and 'google-workspace'. */ identity_provider: string; /** * A list of encryption private keys used to decrypt encrypted SAML assertions. */ saml_encryption_private_keys: EncryptionPrivateKey[]; } interface OIDCConnection { /** * Globally unique UUID that identifies a specific Organization. */ organization_id: string; /** * Globally unique UUID that identifies a specific OIDC Connection. */ connection_id: string; /** * The status of the connection. * The possible values are `pending` or `active`. * See the {@link https://stytch.com/docs/b2b/api/update-oidc-connection Update OIDC Connection} endpoint for more details. */ status: string; /** * A human-readable display name for the connection. */ display_name: string; /** * The callback URL for this OIDC connection. This value will be passed to the IdP to redirect the Member back to Stytch after a sign-in attempt. */ redirect_url: string; /** * A case-sensitive `https://` URL that uniquely identifies the IdP. This will be provided by the IdP. */ issuer: string; /** * The OAuth2.0 client ID used to authenticate login attempts. This will be provided by the IdP. */ client_id: string; /** * The secret belonging to the OAuth2.0 client used to authenticate login attempts. This will be provided by the IdP. */ client_secret: string; /** * The location of the URL that starts an OAuth login at the IdP. This will be provided by the IdP. */ authorization_url: string; /** * The location of the URL that issues OAuth2.0 access tokens and OIDC ID tokens. This will be provided by the IdP. */ token_url: string; /** * The location of the IDP's UserInfo Endpoint. This will be provided by the IdP. */ userinfo_url: string; /** * The location of the IdP's JSON Web Key Set, used to verify credentials issued by the IdP. This will be provided by the IdP. */ jwks_url: string; /** * The identity provider of this connection. For OIDC, the accepted values are `generic`, `okta`, and `microsoft-entra`. */ identity_provider: string; /** * A space-separated list of custom scopes that will be requested on each SSOStart call. The total set of scopes will be the union of: the OIDC scopes `openid email profile`, the scopes requested in the `custom_scopes` query parameter on each SSOStart call, and the scopes listed in the OIDC Connection object. */ custom_scopes: string; /** * An object that represents the attributes used to identify a Member. This object will map the IdP-defined User attributes to Stytch-specific values, which will appear on the member's Trusted Metadata. */ attribute_mapping: Record; } interface ExternalConnection { /** * Globally unique UUID that identifies a specific Organization. */ organization_id: string; /** * Globally unique UUID that identifies a specific Connection. */ connection_id: string; /** * Globally unique UUID that identifies a specific External Organization. */ external_organization_id: string; /** * Globally unique UUID that identifies a specific External Connection. */ external_connection_id: string; /** * The status of the connection. * External connections are always `active`. * See the {@link https://stytch.com/docs/b2b/api/update-external-connection Update External Connection} endpoint for more details. */ status: string; /** * A human-readable display name for the connection. */ display_name: string; /** * An array of implicit role assignments granted to members in this organization who log in with this external connection. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ external_connection_implicit_role_assignments: { role_id: string; }[]; /** * An array of implicit role assignments granted to members in this organization who log in with this external connection * and belong to the specified group. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ external_group_implicit_role_assignments: { role_id: string; group: string; }[]; } type B2BSessionAuthenticateResponse = B2BAuthenticateResponse; type B2BSessionRevokeOptions = { /** * When true, clear the user and session object in the local storage, even in the event of a network failure revoking the session. * When false, the user and session object will not be cleared in the event that the SDK cannot contact the Stytch servers. * The user and session object will always be cleared when the session revoke call succeeds. * Defaults to false */ forceClear?: boolean; }; type B2BSessionRevokeForMemberOptions = { /** * The ID of the Member whose sessions should be revoked. */ member_id: string; }; type B2BSessionRevokeForMemberResponse = ResponseCommon; type B2BSessionOnChangeCallback = (session: MemberSession | null) => void; type B2BSessionExchangeOptions = SessionDurationOptions & { /** * The ID of the organization that the new session should belong to. */ organization_id: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; type B2BSessionExchangeResponse = B2BAuthenticateResponseWithMFA; type B2BSessionAccessTokenExchangeOptions = SessionDurationOptions & { /** * The Connected Apps access token. */ access_token: string; }; type B2BSessionAccessTokenExchangeResponse = B2BAuthenticateResponse; type MemberSessionInfo = Cacheable<{ /** * The session object, or null if no session exists. */ session: MemberSession | null; }>; type B2BSessionAttestOptions = SessionDurationOptions & { /** * The ID of the organization that the new session should belong to. */ organization_id?: string; /** * The ID of the token profile used to validate the JWT string. */ profile_id: string; /** * JWT string. */ token: string; } & Partial; type B2BSessionAttestResponse = B2BAuthenticateResponse; interface IHeadlessB2BSessionClient { /** * If logged in, the `session.getSync` method returns the cached session object. Otherwise it returns `null`. * * @example * const memberSession = stytch.session.getSync(); * @returns The user's active {@link MemberSession} object or `null` */ getSync(): MemberSession | null; /** * The `session.getInfo` method is similar to `session.getSync`, but it returns an object containing the `session` object and a `fromCache` boolean. * If `fromCache` is true, the session object is from the cache and a state refresh is in progress. */ getInfo(): MemberSessionInfo; /** * Returns the `session_token` and `session_jwt` values associated with the logged-in user's active session. * * Session tokens are only available if: * - There is an active session, and * - The session is _not_ managed via HttpOnly cookies. * * If either of these conditions is not met, `getTokens` will return `null`. * * Note that the Stytch SDK stores the `session_token` and `session_jwt` values as session cookies in the user's browser. * Those cookies will be automatically included in any request that your frontend makes to a service (such as your backend) that shares the domain set on the cookies, so in most cases, you will not need to explicitly retrieve the `session_token` and `session_jwt` values using the `getTokens()` method. * However, we offer this method to serve some unique use cases where explicitly retrieving the tokens may be necessary. * * @example * const {session_jwt} = stytch.session.getTokens(); * fetch('https://api.example.com, { * headers: new Headers({ * 'Authorization': 'Bearer ' + session_jwt, * credentials: 'include', * }), * }) * */ getTokens(): IfOpaqueTokens, never, SessionTokens$0 | null>; /** * The `session.onChange` method takes in a callback that gets called whenever the Member Session object changes. * It returns an unsubscribe method for you to call when you no longer want to listen for such changes. * * The `useStytchMemberSession` hook is available in `@stytch/react` or `@stytch/nextjs`. It implements these methods for you to easily access the session and listen for changes. * @example * stytch.session.onChange((memberSession) => { * if(!memberSession) { * // The member has been logged out! * window.location.href = 'https://example.com/login' * } * }) * @param callback - {@link B2BSessionOnChangeCallback} */ onChange(callback: B2BSessionOnChangeCallback): UnsubscribeFunction; /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/authenticate-session authenticate } Session endpoint and validates that the session issued to the user is still valid. * The SDK will invoke this method automatically in the background. You probably won't need to call this method directly. * It's recommended to use `session.getSync` and `session.onChange` instead. * @example * stytch.session.authenticate({ * // Extend the session for another 60 minutes * session_duration_minutes: 60 * }) * @param options - {@link SessionAuthenticateOptions} * @returns A {@link B2BSessionAuthenticateResponse} object */ authenticate(options?: SessionAuthenticateOptions): Promise>; /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/revoke-session revoke} Session endpoint and revokes the user's current session. * This method should be used to log out a user. While calling this method, we clear the user and session objects from local storage * unless the SDK cannot contact the Stytch servers. This behavior can be overriden by using the optional param object. * * @param options - {@link B2BSessionRevokeOptions} * * @example * stytch.session.revoke() * .then(() => window.location.href = 'https://example.com/login'); * @returns A {@link SessionRevokeResponse} */ revoke(options?: B2BSessionRevokeOptions): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/revoke-session revoke} Session endpoint and revokes all Sessions for a given Member. * * @rbac action="revoke-sessions", resource="stytch.member" * * @param options - {@link B2BSessionRevokeForMemberOptions} * * @example * stytch.session.revokeForMember({ member_id: 'member-id-123' }); * @returns A {@link B2BSessionRevokeForMemberResponse} */ revokeForMember(options: B2BSessionRevokeForMemberOptions): Promise; /** * Update a user's session tokens to hydrate a front-end session from the backend. * For example, if you log your users in with one of our backend SDKs, you can pass the resulting `session_token` and `session_jwt` to this method to prime the frontend SDK with a valid set of tokens. * You must then make an {@link https://stytch.com/docs/api/session-auth authenticate} call to authenticate the session tokens and retrieve the user's current session. * * @param tokens - The session tokens to update to */ updateSession(tokens: SessionTokensUpdate): void; /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/exchange-session Exchange Session} endpoint and exchanges the member's current session for a session in the specified Organization. * @example * stytch.session.exchange({ * organization_id: 'organization-123', * session_duration_minutes: 60 * }) * @param options - {@link B2BSessionExchangeOptions} * @returns A {@link B2BSessionExchangeResponse} */ exchange(options: B2BSessionExchangeOptions): Promise>; /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/connected-app-access-token-exchange Exchange Access Token} endpoint and exchanges a Connected Apps token for a Session for the original Member. * @example * stytch.session.exchangeAccessToken({ * access_token: 'eyJh...', * session_duration_minutes: 60 * }) * @param options - {@link B2BSessionExchangeOptions} * @returns A {@link B2BSessionExchangeResponse} */ exchangeAccessToken(options: B2BSessionAccessTokenExchangeOptions): Promise>; /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/attest-session Attest} Session endpoint and gets a Stytch session from a trusted JWT. * @example * stytch.session.attest({ * organization_id: 'organization-123', * profile_id: 'profile-123', * token: 'eyJh...', * session_duration_minutes: 60 * }) * @param data - {@link B2BSessionAttestOptions} * @returns A {@link B2BSessionAttestResponse} */ attest(data: B2BSessionAttestOptions): Promise>; } type B2BDiscoveryOrganizationsResponse = ResponseCommon & { /** * The email corresponding to the intermediate_session_token, session_token, or session_jwt that was passed in */ email_address: string; discovered_organizations: DiscoveredOrganization[]; /** * The organization_id that the intermediate_session_token is associated with, if any. This field will be null * if a session_token or session_jwt is passed in. */ organization_id_hint: string | null; }; type B2BDiscoveryOrganizationsCreateOptions = SessionDurationOptions & { /** * The name of the new Organization. If the name is not specified, a name will be created based on the email * that was used in the discovery flow. */ organization_name?: string; /** * The unique URL slug of the new Organization. If the slug is not specified, a slug will be created based on the * email that was used in the discovery flow. */ organization_slug?: string; /** * The image URL of the new Organization. */ organization_logo_url?: string; /** * The authentication setting that controls the JIT provisioning of Members to the new Organization * when authenticating via SSO. The accepted values are: ALL_ALLOWED, RESTRICTED, and NOT_ALLOWED. */ sso_jit_provisioning?: string; /** * An array of email domains that allow invites or JIT provisioning for new Members to the new Organization. * This list is enforced when email_invites, email_jit_provisioning, or sso_jit_provisioning are set to RESTRICTED. */ email_allowed_domains?: string[]; /** * The authentication setting that controls how a new Member can be provisioned to the new Organization by * authenticating via Email Magic Link. The accepted values are RESTRICTED and NOT_ALLOWED. */ email_jit_provisioning?: string; /** * The authentication setting that controls how a new Member can be invited to the new Organization via * Email Magic Link. The accepted values are: ALL_ALLOWED, RESTRICTED, and NOT_ALLOWED. */ email_invites?: string; /** * The authentication setting that controls how a new Member can be provisioned by authenticating via OAuth, when the OAuth provider does not guarantee the validity of the email. * The accepted values are: * RESTRICTED – only Members coming from an OAuth Tenant are in allowed_oauth_tenants are allowed to JIT provision. * NOT_ALLOWED – disable JIT provisioning via OAuth. */ oauth_tenant_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; /** * A JSON object of allowed OAuth Tenants to be used with oauth_tenant_jit_provisioning. * Records are provided with the provider, e.g. "hubspot", as the key, and a list of tenants, e.g. ['HubID1234', 'HubID2345'], as the value. */ allowed_oauth_tenants?: Record; /** * Determines whether authenticating to the Organization should be restricted to specific authentication methods. * The accepted values are: ALL_ALLOWED, RESTRICTED, and NOT_ALLOWED. */ auth_methods?: string; /** * An array of authentication methods that Members are allowed to use to authenticate to the Organization. * This list is enforced when auth_methods is set to RESTRICTED. * The accepted values are 'sso', 'magiclink', 'password', 'google_oauth', 'microsoft_oauth', 'hubspot_oauth', 'slack_oauth', and 'github_oauth'. */ allowed_auth_methods?: B2BAllowedAuthMethods[]; /** * The MFA policy of the organization. If 'REQUIRED_FOR_ALL', all members (including the new one that will be created * through this endpoint) will be required to complete MFA when logging in to the organization. If 'OPTIONAL', * members will only be required to complete MFA if their mfa_enrolled field is set to true. * The accepted values are 'REQUIRED_FOR_ALL' and 'OPTIONAL'. */ mfa_policy?: string; }; type B2BDiscoveryOrganizationsCreateResponse = B2BAuthenticateResponseWithMFA; type B2BDiscoveryIntermediateSessionsExchangeOptions = SessionDurationOptions & { /** * The id of the Organization that the new Member is joining. */ organization_id: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; type B2BDiscoveryIntermediateSessionsExchangeResponse = B2BAuthenticateResponseWithMFA; interface IHeadlessB2BDiscoveryClient { organizations: { /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/list-discovered-organizations list discovered Organizations} endpoint. * If there is a current Member Session, the SDK will call the endpoint with the session token. * Otherwise, the SDK will use the intermediate session token. * If neither a Member Session nor an intermediate session token is present, this method will fail. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/discovery#list-discovered-organizations Stytch Docs} for a complete reference. * * @example * stytch.discovery.organizations.list(); * * @returns A {@link B2BDiscoveryOrganizationsResponse} containing the email address associated with the session * factor passed in, and a list of discovered organizations associated with the email. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ list(): Promise; /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/create-organization-via-discovery create Organization via discovery} endpoint. * This method will fail if there is no intermediate session token present. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/discovery#create-organization-via-discovery Stytch Docs} for a complete reference. * * @example * stytch.discovery.organizations.create({ * organization_name: 'my-great-organization', * organization_slug: 'my-great-organization', * sso_jit_provisioning: 'ALL_ALLOWED', * session_duration_minutes: 60, * }); * * @param data - {@link B2BDiscoveryOrganizationsCreateOptions} * * @returns A {@link B2BDiscoveryOrganizationsCreateResponse} indicating that the intermediate session token * has been authenticated, a new Organization has been created, and the Member has been created and is logged in * to the new Organization * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ create(data: B2BDiscoveryOrganizationsCreateOptions): Promise>; }; intermediateSessions: { /** * Wraps Stytch's {@link https://stytch.com/docs/b2b/api/exchange-intermediate-session exchange intermediate session} endpoint. * This method will fail if there is no intermediate session token present. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/discovery#exchange-intermediate-session Stytch Docs} for a complete reference. * * @example * stytch.discovery.intermediateSessions.exchange({ * organization_id: 'organization-test-123', * session_duration_minutes: 60, * }); * * @param data - {@link B2BDiscoveryIntermediateSessionsExchangeOptions} * * @returns A {@link B2BDiscoveryIntermediateSessionsExchangeResponse} indicating that the intermediate session token * has been authenticated and the member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ exchange(data: B2BDiscoveryIntermediateSessionsExchangeOptions): Promise>; }; } type B2BDiscoveryAuthenticateResponse = ResponseCommon & { /** * The intermediate session token. This token does not belong to a specific instance of a member, * but may be exchanged for a member session or used to create a new organization. * If the project is configured to use HttpOnly cookies, this field will always be empty. */ intermediate_session_token: IfOpaqueTokens, RedactedToken, string>; /** * The email of the end user who is logging in */ email_address: string; discovered_organizations: DiscoveredOrganization[]; }; type B2BMagicLinksInviteOptions = { /** * The email address of the end user to whom the invite will be sent. */ email_address: string; /** * The URL that the Member clicks from the invite Email Magic Link. * This URL should be an endpoint in the backend server that verifies the request by querying * Stytch's authenticate endpoint and finishes the invite flow. * If this value is not passed, the default `invite_redirect_url` that you set in your Dashboard is used. * If you have not set a default `invite_redirect_url`, an error is returned. */ invite_redirect_url?: string; /** * Use a custom template for invite emails. * By default, it will use your default email template. * The template must be a template using our built-in customizations or a custom HTML email for Magic Links - Invite. */ invite_template_id?: string; /** * The name of the Member. */ name?: string; /** * A JSON object containing application-specific metadata. * Use it to store fields that a member can be allowed to edit directly without backend validation - such as `display_theme` or `preferred_locale`. * See our {@link https://stytch.com/docs/api/metadata metadata reference} for complete details. */ untrusted_metadata?: Record; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * Roles to explicitly assign to this Member. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ roles?: string[]; /** * The expiration time, in minutes. If not accepted within this time frame, the invite will need to be resent. * Defaults to 10080 (1 week) with a minimum of 5 and a maximum of 10080. */ invite_expiration_minutes?: number; }; type B2BMagicLinksInviteResponse = MemberResponseCommon; type B2BMagicLinkLoginOrSignupOptions = { /** * The email of the member logging in or signing up */ email_address: string; /** * The id of the organization the member belongs to */ organization_id: string; /** * The url the user clicks from the login email magic link. * This should be a url that your app receives and parses and subsequently send an API request to authenticate the magic link and log in the member. * If this value is not passed, the default login redirect URL that you set in your Dashboard is used. * If you have not set a default login redirect URL, an error is returned. */ login_redirect_url?: string; /** * The url the user clicks from the sign-up email magic link. * This should be a url that your app receives and parses and subsequently send an api request to authenticate the magic link and sign-up the user. * If this value is not passed, the default sign-up redirect URL that you set in your Dashboard is used. * If you have not set a default sign-up redirect URL, an error is returned. */ signup_redirect_url?: string; /** * The email template ID to use for login emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Magic link Login custom HTML template. */ login_template_id?: string; /** * The email template ID to use for sign-up emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Magic link Sign-up custom HTML template. */ signup_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * The expiration time, in minutes, for a login Email Magic Link. If not authenticated within this time frame, the email will need to be resent. * Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 10080 (1 week). */ login_expiration_minutes?: number; /** * The expiration time, in minutes, for a signup Email Magic Link. If not authenticated within this time frame, the email will need to be resent. * Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 10080 (1 week). */ signup_expiration_minutes?: number; }; type B2BMagicLinkLoginOrSignupResponse = ResponseCommon; type B2BMagicLinksAuthenticateOptions = SessionDurationOptions & { /** * The magic link token used to authenticate a member */ magic_links_token: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; type B2BMagicLinksAuthenticateResponse = B2BAuthenticateResponseWithMFA & { /** * The ID of the method used to send a magic link. */ method_id: string; /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; type B2BMagicLinksEmailDiscoverySendOptions = { /** * The email of the member logging in */ email_address: string; /** * The url the user clicks from the login email magic link. * This should be a url that your app receives and parses and subsequently send an API request to authenticate the magic link and log in the member. * If this value is not passed, the default discovery redirect URL that you set in your Dashboard is used. * If you have not set a default discovery redirect URL, an error is returned. */ discovery_redirect_url?: string; /** * The email template ID to use for login emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Magic link Login custom HTML template. */ login_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * The expiration time, in minutes. If not accepted within this time frame, the email will need to be resent. * Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 10080 (1 week). */ discovery_expiration_minutes?: number; }; type B2BMagicLinksEmailDiscoverySendResponse = ResponseCommon; type B2BMagicLinksDiscoveryAuthenticateResponse = B2BDiscoveryAuthenticateResponse; type B2BMagicLinksDiscoveryAuthenticateOptions = { /** * The discovery magic link token used to authenticate an end user */ discovery_magic_links_token: string; }; interface IHeadlessB2BMagicLinksClient { email: { /** * The invite method wraps the {@link https://stytch.com/docs/b2b/api/send-invite-email invite} Email Magic Link API endpoint. * * The `organization_id` will be automatically inferred from the logged-in Member's session. * * To revoke an existing invite, use the {@link https://stytch.com/docs/b2b/sdks/members/delete-member Delete Member} endpoint. This will both delete the invited Member from the target Organization and revoke all existing invite emails. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-magic-links#invite Stytch Docs} for a complete reference. * * @example * stytch.magicLinks.email.invite({ * email_address: 'sandbox@stytch.com', * }); * * @rbac action="create", resource="stytch.member" * * @param data - {@link B2BMagicLinksInviteOptions} * * @returns A {@link B2BMagicLinksInviteResponse} indicating that the email has been sent. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ invite(data: B2BMagicLinksInviteOptions): Promise; /** * The `loginOrSignup` method wraps the {@link https://stytch.com/docs/b2b/api/send-login-signup-email login or signup} Email magic link API endpoint. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-magic-links#login-or-signup Stytch Docs} for a complete reference. * * @example * stytch.magicLinks.email.loginOrSignup({ * email_address: 'sandbox@stytch.com', * organization_id: 'organization-test-123', * }); * * @param data - {@link B2BMagicLinkLoginOrSignupOptions} * * @returns A {@link B2BMagicLinkLoginOrSignupResponse} indicating that the email has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ loginOrSignup(data: B2BMagicLinkLoginOrSignupOptions): Promise; discovery: { /** * The Send Discovery Email method wraps the {@link https://stytch.com/docs/b2b/api/send-discovery-email send discovery email} API endpoint. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-magic-links#send-discovery-email Stytch Docs} for a complete reference. * * @example * stytch.magicLinks.email.discovery.send({ * email_address: 'sandbox@stytch.com', * }); * * @param data - {@link B2BMagicLinksEmailDiscoverySendOptions} * * @returns A {@link B2BMagicLinksEmailDiscoverySendResponse} indicating that the email has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ send(data: B2BMagicLinksEmailDiscoverySendOptions): Promise; }; }; /** * The Authenticate method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-magic-link authenticate} magic link API endpoint which validates the magic link token passed in. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-magic-links#authenticate Stytch Docs} for a complete reference. * * @example * stytch.magicLinks.authenticate({ * magic_link_token: 'token', * session_duration_minutes: 60, * }); * * @param data - {@link B2BMagicLinksAuthenticateOptions} * * @returns A {@link B2BMagicLinksAuthenticateResponse} indicating that magic link has been authenticated and the member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(data: B2BMagicLinksAuthenticateOptions): Promise>; discovery: { /** * The Authenticate Discovery Magic Link method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-discovery-magic-link authenticate} discovery magic link API endpoint, which validates the discovery magic link token passed in. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-magic-links#authenticate-discovery-magic-link Stytch Docs} for a complete reference. * * @example * stytch.magicLinks.discovery.authenticate({ * discovery_magic_link_token: 'token', * }); * * @param data - {@link B2BMagicLinksDiscoveryAuthenticateOptions} * * @returns A {@link B2BMagicLinksDiscoveryAuthenticateResponse} indicating that the magic link has been authenticated. * The response will contain the intermediate_session_token, the email address that the magic link was sent to, * and a list of discovered organizations that are associated with the email address. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(data: B2BMagicLinksDiscoveryAuthenticateOptions): Promise>; }; } type B2BMemberOnChangeCallback = (member: Member | null) => void; type B2BMemberUpdateOptions = { /** * The name of the Member. Replaces the existing name, if it exists. */ name?: string; /** * A JSON object containing application-specific metadata. * Use it to store fields that a Member can be allowed to edit directly without backend validation - such as `display_theme` or `preferred_locale`. * See our {@link https://stytch.com/docs/api/metadata metadata reference} for complete details. */ untrusted_metadata?: Record; /** * Sets whether the Member is enrolled in MFA. * If true, the Member must complete an MFA step whenever they wish to log in to their Organization. * If false, the Member only needs to complete an MFA step if the Organization's MFA policy is set to REQUIRED_FOR_ALL. */ mfa_enrolled?: boolean; /** * Sets the Member's phone number. Throws an error if the Member already has a phone number. */ mfa_phone_number?: string; /** * Sets the Member's default MFA method. Valid values are 'sms_otp' and 'totp'. * This value will determine * 1. Which MFA method the Member is prompted to use when logging in * 2. Whether An SMS will be sent automatically after completing the first leg of authentication */ default_mfa_method?: "sms_otp" | "totp"; }; type B2BMemberUnlinkRetiredEmailRequest = { /** * ID of the retired email to be deleted. At least one of email id or email address must be provided. */ email_id?: string; /** * Address of the retired email to be deleted. At least one of email id or email address must be provided. */ email_address?: string; }; type B2BMemberStartEmailUpdateRequest = { /** * The new email address to be set (after verification) for the Member. */ email_address: string; /** * The url the user is redirected to after clicking the login email magic link. * This should be a url that your app receives and parses and subsequently send an API request to authenticate the magic link and log in the member. * If this value is not passed, the default login redirect URL that you set in your Dashboard is used. * If you have not set a default login redirect URL, an error is returned. */ login_redirect_url?: string; /** * The email template ID to use for magic linkemails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Magic link Login custom HTML template. */ login_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * The delivery method to use when sending the email, either EMAIL_MAGIC_LINK or EMAIL_OTP. By default, EMAIL_MAGIC_LINK is used. */ delivery_method?: MemberEmailUpdateDeliveryMethod; }; type B2BMemberStartEmailUpdateResponse = MemberResponseCommon; type B2BMemberGetConnectedAppsResponse = ResponseCommon & { connected_apps: { connected_app_id: string; name: string; description: string; client_type: string; logo_url?: string; scopes_granted: string; }[]; }; type B2BMemberRevokeConnectedAppOptions = { connected_app_id: string; }; type B2BMemberRevokeConnectedAppResponse = ResponseCommon; type B2BMemberUpdateResponse = MemberResponseCommon; type B2BMemberDeleteMFAPhoneNumberResponse = MemberResponseCommon; type B2BMemberDeletePasswordResponse = MemberResponseCommon; type B2BMemberDeleteMFATOTPResponse = MemberResponseCommon; type B2BMemberUnlinkRetiredEmailResponse = MemberResponseCommon; type MemberInfo = Cacheable<{ /** * The member object, or null if no member exists. */ member: Member | null; }>; interface IHeadlessB2BSelfClient { /** * The asynchronous method, `member.get`, wraps the {@link https://stytch.com/docs/b2b/api/search-members search member} endpoint. * It fetches the Member's data and refreshes the cached object if changes are detected. * The Stytch SDK will invoke this method automatically in the background, so you probably won't need to call this method directly. * * @returns A {@link Member} object, or null if no member exists. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ get(): Promise; /** * If logged in, the `member.getSync` method returns the cached Member object. * Otherwise it returns `null`. * This method does not refresh the Member's data. * * @returns A {@link Member} object, or null if no user exists. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ getSync(): Member | null; /** * The `member.getInfo` method is similar to `member.getSync`, but it returns an object containing the `member` object and a `fromCache` boolean. * If `fromCache` is true, the Member object is from the cache and a state refresh is in progress. */ getInfo(): MemberInfo; /** * The `member.onChange` method takes in a callback that gets called whenever the Member object changes. * It returns an unsubscribe method for you to call when you no longer want to listen for such changes. * * @param callback - Gets called whenever the member object changes. See {@link B2BMemberOnChangeCallback}. * * @returns An {@link UnsubscribeFunction} for you to call when you no longer want to listen for changes in the member object. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ onChange(callback: B2BMemberOnChangeCallback): UnsubscribeFunction; /** * The Update Member method wraps the {@link https://stytch.com/docs/b2b/api/update-member Update Member} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method can be used to update any Member in the logged-in Member's Organization. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#update-self Stytch Docs} for a complete reference. * * @example * stytch.self.update({ * mfa_enrolled: true, * phone_number: '+12025550162', * }); * * @rbac action="requested", resource="stytch.self" * * @param data - {@link B2BMemberUpdateOptions} * * @returns A {@link B2BMemberUpdateResponse} indicating that the member has been updated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ update(data: B2BMemberUpdateOptions): Promise; /** * The Delete Self MFA phone number method wraps the {@link https://stytch.com/docs/b2b/api/delete-member-mfa-phone-number Delete Member MFA phone number} API endpoint. * The `organization_id` and `member_id` will be automatically inferred from the logged-in Member's session. * This method can only be used to delete the logged-in Member's MFA phone number. * * To change a Member's phone number, you must first call this endpoint to delete the existing phone number. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#delete-self-mfa-phone-number Stytch Docs} for a complete reference. * * @rbac action="update.info.delete.mfa-phone", resource="stytch.self" * * @returns A {@link B2BMemberDeleteMFAPhoneNumberResponse} indicating that the member's phone number has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteMFAPhoneNumber(): Promise; /** * The Delete Self password method wraps the {@link https://stytch.com/docs/b2b/api/delete-member-password Delete Member password} API endpoint. * The `organization_id` and `member_id` will be automatically inferred from the logged-in Member's session. * This method can only be used to delete the logged-in Member's password. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#delete-self-password Stytch Docs} for a complete reference. * * @rbac action="update.info.delete.password", resource="stytch.self" * * @returns A {@link B2BMemberDeletePasswordResponse} indicating that the member's phone number has been deleted. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deletePassword(passwordId: string): Promise; /** * The Delete Self MFA totp method wraps the {@link https://stytch.com/docs/b2b/api/delete-member-mfa-totp Delete Member MFA TOTP} API endpoint. * The `organization_id` and `member_id` will be automatically inferred from the logged-in Member's session. * This method can only be used to delete the logged-in Member's MFA totp. * * To change a Member's totp, you must first call this endpoint to delete the existing totp. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#delete-self-mfa-totp Stytch Docs} for a complete reference. * * @rbac action="update.info.delete.mfa-totp", resource="stytch.self" * * @returns A {@link B2BMemberDeleteMFATOTPResponse} indicating that the member's totp has been deleted. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteMFATOTP(): Promise; /** * The Unlink Self Retired Email Address method wraps the {@link https://stytch.com/docs/b2b/api/unlink-retired-member-email Unlink Retired Email} API endpoint. * The `organization_id` and `member_id` will be automatically inferred from the logged-in Member's session. * This method can only be used to unlink the logged-in Member's retired email. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#unlink-retired-member-email Stytch Docs} for a complete reference. * * @rbac action="update.info.unlink.retired-email", resource="stytch.self" * * @param data - {@link B2BMemberUnlinkRetiredEmailRequest} * @returns A {@link B2BMemberUnlinkRetiredEmailResponse} indicating that the member's retired email has been marked as deleted. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ unlinkRetiredEmail(data: B2BMemberUnlinkRetiredEmailRequest): Promise; /** * The Start Email Update method wraps the {@link https://stytch.com/docs/b2b/api/start-member-email-update Start Member Email Update} API endpoint. * The `organization_id` and `member_id` will be automatically inferred from the logged-in Member's session. * This method can be used to start the self-serve email update process for the logged-in Member. * * See the {@link https://stytch.com/docs/b2b/sdks/members/start-self-email-update Stytch Docs} for a complete reference. * * @rbac action="update.info.email", resource="stytch.self" * * @param data - {@link B2BMemberStartEmailUpdateRequest} * @returns A {@link B2BMemberStartEmailUpdateResponse} indicating that an email update has been started. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ startEmailUpdate(data: B2BMemberStartEmailUpdateRequest): Promise; /** * The Member Get Connected Apps method wraps the {@link https://stytch.com/docs/b2b/api/connected-app-member-get-all Member Get Connected Apps} API endpoint. * The `organization_id` and `member_id` will be automatically inferred from the logged-in Member's session. * * This method retrieves a list of Connected Apps that the Member has completed an authorization flow with successfully. * If the Member revokes a Connected App's access (e.g. via the `revokeConnectedApp` method) then the Connected App will * no longer be returned in this endpoint's response. A Connected App's access may be revoked if the Organization's * allowed Connected App policy changes. * * See the {@link https://stytch.com/docs/b2b/sdks/members/get-self-connected-apps Stytch Docs} for a complete reference. * * @rbac action="get.connected-apps", resource="stytch.self" * * @returns A {@link B2BMemberGetConnectedAppsResponse} indicating that the member's retired email has been marked as deleted. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ getConnectedApps(): Promise; /** * The Member Revoke Connected App method wraps the {@link https://stytch.com/docs/b2b/api/connected-app-member-revoke Member Revoke Connected App} API endpoint. * The `organization_id` and `member_id` will be automatically inferred from the logged-in Member's session. * * This method revokes a Connected App's access to the Member and revokes all active tokens that have been * created on the Member's behalf. New tokens cannot be created until the Member completes a new authorization * flow with the Connected App. * * Note that after calling this method, the Member will be forced to grant consent in subsequent authorization * flows with the Connected App. * * See the {@link https://stytch.com/docs/b2b/sdks/members/revoke-self-connected-app Stytch Docs} for a complete reference. * * @rbac action="revoke.connected-app", resource="stytch.self" * * @param data - {@link B2BMemberRevokeConnectedAppOptions} * @returns A {@link B2BMemberRevokeConnectedAppResponse} indicating that the Connected App's access has been revoked. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ revokeConnectedApp(data: B2BMemberRevokeConnectedAppOptions): Promise; } type B2BOrganizationsUpdateOptions = { /** * The name of the organization */ organization_name?: string; /** * The unique URL slug of the Organization. A minimum of two characters is required. * The slug only accepts alphanumeric characters and the following reserved characters: - . _ ~. */ organization_slug?: string; /** * The image URL of the Organization logo. */ organization_logo_url?: string; /** * The default connection used for SSO when there are multiple active connections. */ sso_default_connection_id?: string; /** * The authentication setting that controls the JIT provisioning of Members when authenticating via SSO. * The accepted values are: * ALL_ALLOWED – new Members will be automatically provisioned upon successful authentication via any of the Organization's sso_active_connections. * RESTRICTED – only new Members with SSO logins that comply with sso_jit_provisioning_allowed_connections can be provisioned upon authentication. * NOT_ALLOWED – disable JIT provisioning via SSO. */ sso_jit_provisioning?: string; /** * An array of connection_ids that reference SAML Connection objects. * Only these connections will be allowed to JIT provision Members via SSO when sso_jit_provisioning is set to RESTRICTED. */ sso_jit_provisioning_allowed_connections?: string[]; /** * An array of email domains that allow invites or JIT provisioning for new Members. * This list is enforced when either email_invites or email_jit_provisioning is set to RESTRICTED. * Common domains such as gmail.com are not allowed. */ email_allowed_domains?: string[]; /** * The authentication setting that controls how a new Member can be provisioned by authenticating via Email Magic Link. * The accepted values are: * ALL_ALLOWED - any new Member can be provisioned via Email Magic Link. * RESTRICTED – only new Members with verified emails that comply with email_allowed_domains can be provisioned upon authentication via Email Magic Link. * NOT_ALLOWED – disable JIT provisioning via Email Magic Link. */ email_jit_provisioning?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The authentication setting that controls how a new Member can be invited to an organization by email. * The accepted values are: * ALL_ALLOWED – any new Member can be invited to join via email. * RESTRICTED – only new Members with verified emails that comply with email_allowed_domains can be invited via email. * NOT_ALLOWED – disable email invites. */ email_invites?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The authentication setting that controls how a new Member can be provisioned by authenticating via OAuth, when the OAuth provider does not guarantee the validity of the email. * The accepted values are: * RESTRICTED – only Members coming from an OAuth Tenant are in allowed_oauth_tenants are allowed to JIT provision. * NOT_ALLOWED – disable JIT provisioning via OAuth. */ oauth_tenant_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; /** * A JSON object of allowed OAuth Tenants to be used with oauth_tenant_jit_provisioning. * Records are provided with the provider, e.g. "hubspot", as the key, and a list of tenants, e.g. ['HubID1234', 'HubID2345'], as the value. */ allowed_oauth_tenants?: Record; /** * The setting that controls which authentication methods can be used by Members of an Organization. * The accepted values are: * ALL_ALLOWED – the default setting which allows all authentication methods to be used. * RESTRICTED – only methods that comply with allowed_auth_methods can be used for authentication. This setting does not apply to Members with is_breakglass set to true. */ auth_methods?: string; /** * An array of allowed authentication methods. * This list is enforced when auth_methods is set to RESTRICTED. * The list's accepted values are: sso, magic_link, password, google_oauth, microsoft_oauth, hubspot_oauth, and slack_oauth. */ allowed_auth_methods?: B2BAllowedAuthMethods[]; /** * The setting that controls which mfa methods can be used by Members of an Organization. * The accepted values are: * ALL_ALLOWED – the default setting which allows all MFA methods to be used. * RESTRICTED – only methods that comply with allowed_mfa_methods can be used for MFA. This setting does not apply to Members with is_breakglass set to true. */ mfa_methods?: "ALL_ALLOWED" | "RESTRICTED"; /** * An array of allowed MFA methods. * This list is enforced when mfa_methods is set to RESTRICTED. * The list's accepted values are: sms_otp and totp. */ allowed_mfa_methods?: B2BAllowedMFAMethods[]; /** * The setting that controls the MFA policy for all Members in the Organization. The accepted values are: * REQUIRED_FOR_ALL – All Members within the Organization will be required to complete MFA every time they wish to log in. * OPTIONAL – The default value. The Organization does not require MFA by default for all Members. Members will be required to complete MFA only if their mfa_enrolled status is set to true */ mfa_policy?: string; /** * An array of implicit role assignments granted to members in this organization whose emails match the domain. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ rbac_email_implicit_role_assignments?: { role_id: string; domain: string; }[]; /** * The setting that controls an Organization's policy towards allowing First Party Connected Apps to interact with its Members. * The accepted values are: * ALL_ALLOWED - any Connected App in the Project may interact with the Organization's Members. * RESTRICTED – only Connected Apps set in the allowlist (`allowed_first_party_connected_apps`) are permitted. * NOT_ALLOWED – no Connected Apps are allowed. */ first_party_connected_apps_allowed_type?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The IDs of First Party Connected Apps that are allowed to interact with an Organization's Members. This value is only * used if `first_party_connected_apps_allowed_type` is set to 'RESTRICTED'. */ allowed_first_party_connected_apps?: string[]; /** * The setting that controls an Organization's policy towards allowing Third Party Connected Apps to interact with its Members. * The accepted values are: * ALL_ALLOWED - any Connected App in the Project may interact with the Organization's Members. * RESTRICTED – only Connected Apps set in the allowlist (`allowed_first_party_connected_apps`) are permitted. * NOT_ALLOWED – no Connected Apps are allowed. */ third_party_connected_apps_allowed_type?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; /** * The IDs of Third Party Connected Apps that are allowed to interact with an Organization's Members. This value is only used * if `first_party_connected_apps_allowed_type` is set to 'RESTRICTED'. */ allowed_third_party_connected_apps?: string[]; }; type B2BOrganizationsUpdateResponse = ResponseCommon & { /** * The Organization object. * See {@link Organization} for details. */ organization: Organization; }; type B2BOrganizationsDeleteResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific Organization. */ organization_id: string; }; type B2BOrganizationsGetBySlugOptions = { /** * The URL slug of the Organization to get. */ organization_slug: string; }; type OrganizationBySlugMatch = Pick; type B2BOrganizationsGetBySlugResponse = ResponseCommon & { /** * The matching organization, or null if no matching organization was found. */ organization: OrganizationBySlugMatch | null; }; type B2BOrganizationsGetConnectedAppsResponse = ResponseCommon & { connected_apps: { connected_app_id: string; name: string; description: string; client_type: string; logo_url?: string; }[]; }; type B2BOrganizationsGetConnectedAppOptions = { connected_app_id: string; }; type B2BOrganizationsGetConnectedAppResponse = ResponseCommon & { connected_app_id: string; name: string; description: string; client_type: string; logo_url?: string; active_members: { member_id: string; granted_scopes: string[]; }[]; }; type B2BOrganizationsMembersCreateOptions = { /** * The email address of the Member. */ email_address: string; /** * The name of the Member. */ name?: string; /** * An arbitrary JSON object of application-specific data. * These fields can be edited directly by the frontend SDK, and should not be used to store critical information. */ untrusted_metadata?: Record; /** * Flag for whether or not to save a Member as pending or active in Stytch. It defaults to false. * If true, new Members will be created with status pending in Stytch's backend. * Their status will remain pending and they will continue to receive signup email templates for every Email Magic Link until that Member authenticates and becomes active. * If false, new Members will be created with status active. */ create_member_as_pending?: boolean; /** * Identifies the Member as a break glass user - someone who has permissions to authenticate into an Organization by bypassing the Organization's settings. * A break glass account is typically used for emergency purposes to gain access outside of normal authentication procedures. */ is_breakglass?: boolean; /** * The Member's phone number. A Member may only have one phone number. */ mfa_phone_number?: string; /** * Sets whether the Member is enrolled in MFA. * If true, the Member must complete an MFA step whenever they wish to log in to their Organization. * If false, the Member only needs to complete an MFA step if the Organization's MFA policy is set to REQUIRED_FOR_ALL. */ mfa_enrolled?: boolean; /** * Roles to explicitly assign to this Member. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ roles?: string[]; }; type B2BOrganizationsMembersCreateResponse = MemberResponseCommon; type B2BOrganizationsMembersUpdateOptions = { /** * Globally unique UUID that identifies a specific Member. */ member_id: string; /** * The name of the Member. */ name?: string; /** * An arbitrary JSON object of application-specific data. * These fields can be edited directly by the frontend SDK, and should not be used to store critical information. */ untrusted_metadata?: Record; /** * Identifies the Member as a break glass user - someone who has permissions to authenticate into an Organization by bypassing the Organization's settings. * A break glass account is typically used for emergency purposes to gain access outside of normal authentication procedures. */ is_breakglass?: boolean; /** * The Member's phone number. A Member may only have one phone number. */ mfa_phone_number?: string; /** * Sets whether the Member is enrolled in MFA. * If true, the Member must complete an MFA step whenever they wish to log in to their Organization. * If false, the Member only needs to complete an MFA step if the Organization's MFA policy is set to REQUIRED_FOR_ALL. */ mfa_enrolled?: boolean; /** * Roles to explicitly assign to this Member. Will completely replace any existing explicitly assigned roles. * If a Role is removed from a Member, and the Member is also implicitly assigned this Role from an SSO connection * or an SSO group, we will by default revoke any existing sessions for the Member that contain any SSO authentication * factors with the affected connection ID. You can preserve these sessions by passing in the * preserve_existing_sessions parameter with a value of true. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ roles?: string[]; /** * Whether to preserve existing sessions when explicit Roles that are revoked are also implicitly assigned by SSO * connection or SSO group. Defaults to false - that is, existing Member Sessions that contain SSO authentication * factors with the affected SSO connection IDs will be revoked. */ preserve_existing_sessions?: boolean; /** * Sets the Member's default MFA method. Valid values are 'sms_otp' and 'totp'. * This value will determine * 1. Which MFA method the Member is prompted to use when logging in * 2. Whether An SMS will be sent automatically after completing the first leg of authentication */ default_mfa_method?: "sms_otp" | "totp"; /** * Updates the Member's `email_address`, if provided. */ email_address?: string; /** * If set to `true`, and an `email_address` is provided, this will unlink the Member's previous email, marking it as * deleted instead of retired at the conclusion of a successful update. Defaults to false. * See our {@link https://stytch.com/docs/b2b/api/unlink-retired-member-email Unlink Retired Email API reference} for more * information about email unlinking. */ unlink_email?: boolean; }; type B2BOrganizationsMembersUpdateResponse = MemberResponseCommon; type SearchQueryOperand = { filter_name: "member_ids"; filter_value: string[]; } | { filter_name: "member_emails"; filter_value: string[]; } | { filter_name: "member_email_fuzzy"; filter_value: string; } | { filter_name: "member_is_breakglass"; filter_value: boolean; } | { filter_name: "statuses"; filter_value: string[]; } | { filter_name: "member_mfa_phone_numbers"; filter_value: string[]; } | { filter_name: "member_mfa_phone_number_fuzzy"; filter_value: string; } | { filter_name: "member_password_exists"; filter_value: boolean; } | { filter_name: "member_roles"; filter_value: string[]; } | { filter_name: string; [key: string]: unknown; }; type B2BOrganizationsMembersSearchOptions = { /** * The cursor field allows you to paginate through your results. * Each result array is limited to 1000 results. * If your query returns more than 1000 results, you will need to paginate the responses using the cursor. * If you receive a response that includes a non-null next_cursor in the results_metadata object, repeat the search call with the next_cursor value set to the cursor field to retrieve the next page of results. * Continue to make search calls until the next_cursor in the response is null. */ cursor?: string; /** * The number of search results to return per page. * The default limit is 100. A maximum of 1000 results can be returned by a single search request. * If the total size of your result set is greater than one page size, you must paginate the response. * See the cursor field. */ limit?: number; /** * The optional query object contains the operator, i.e. AND or OR, and the operands that will filter your results. * Only an operator is required. If you include no operands, no filtering will be applied. * If you include no query object, it will return all Members with no filtering applied. */ query?: { /** * The action to perform on the operands. The accepted value are: * * `AND` – all the operand values provided must match. * * `OR` – the operator will return any matches to at least one of the operand values you supply. */ operator: "OR" | "AND" | string; /** * An array of operand objects that contains all of the filters and values to apply to your search query. */ operands: SearchQueryOperand[]; }; }; type B2BOrganizationsMembersSearchResponse = ResponseCommon & { members: Member[]; /** * The search `results_metadata` object contains metadata relevant to your specific query like `total` and * `next_cursor`. */ results_metadata: { total: number; /** * The `next_cursor` string is returned when your search result contains more than one page of results. * This value is passed into your next search call in the `cursor` field. */ next_cursor?: string; }; /** * A map from `organization_id` to * [Organization object](https://stytch.com/docs/b2b/api/organization-object). The map only contains the * Organizations that the Members belongs to. */ organizations: Record; }; type B2BOrganizationsMembersDeleteResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific Member. */ member_id: string; }; type B2BOrganizationsMembersReactivateResponse = MemberResponseCommon; type B2BOrganizationsMemberDeletePasswordResponse = MemberResponseCommon; type B2BOrganizationsMemberDeleteMFAPhoneNumberResponse = MemberResponseCommon; type B2BOrganizationsMemberDeleteMFATOTPResponse = MemberResponseCommon; type B2BOrganizationsMemberUnlinkRetiredEmailOptions = { /** * Globally unique UUID that identifies a specific Member. */ member_id: string; /** * Unique identifier for the retired email to be deleted. * Either the email_id, or the email_address, or both must be provided. * If both are provided they must reference the same retired email. */ email_id?: string; /** * The retired email address to be deleted * Either the email_id, or the email_address, or both must be provided. * If both are provided they must reference the same retired email. */ email_address?: string; }; type B2BOrganizationsMemberUnlinkRetiredEmailResponse = MemberResponseCommon; type B2BOrganizationsMemberStartEmailUpdateOptions = { /** * Globally unique UUID that identifies a specific Member. */ member_id: string; /** * The new email address to be set (after verification) for the Member. */ email_address: string; /** * The url the user is redirected to after clicking the login email magic link. * This should be a url that your app receives and parses and subsequently send an API request to authenticate the magic link and log in the member. * If this value is not passed, the default login redirect URL that you set in your Dashboard is used. * If you have not set a default login redirect URL, an error is returned. */ login_redirect_url?: string; /** * The email template ID to use for magic linkemails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Magic link Login custom HTML template. */ login_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * The delivery method to use when sending the email, either EMAIL_MAGIC_LINK or EMAIL_OTP. By default, EMAIL_MAGIC_LINK is used. */ delivery_method?: MemberEmailUpdateDeliveryMethod; }; type B2BOrganizationsMemberStartEmailUpdateResponse = MemberResponseCommon; type B2BOrganizationsMemberGetConnectedAppsOptions = { member_id: string; }; type B2BOrganizationsMemberGetConnectedAppsResponse = ResponseCommon & { connected_apps: { connected_app_id: string; name: string; description: string; client_type: string; logo_url?: string; scopes_granted: string; }[]; }; type B2BOrganizationsMemberRevokeConnectedAppOptions = { member_id: string; connected_app_id: string; }; type B2BOrganizationsMemberRevokeConnectedAppResponse = ResponseCommon; type OrganizationInfo = Cacheable<{ /** * The organization object, or null if no organization exists. */ organization: Organization | null; }>; interface IHeadlessB2BOrganizationClient { /** * The asynchronous method, `organization.get`, wraps the {@link https://stytch.com/docs/b2b/api/get-organization get organization} endpoint. * It fetches the Organization's data and refreshes the cached object if changes are detected. * The Stytch SDK will invoke this method automatically in the background, so you probably won't need to call this method directly. * * @returns An {@link Organization} object. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ get(): Promise; /** * If logged in, the `organization.getSync` method returns the cached Organization object. * Otherwise, it returns `null`. * This method does not refresh the Organization's data. * * @returns An {@link Organization} object, or null if no organization exists. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ getSync(): Organization | null; /** * The `organization.getInfo` method is similar to `organization.getSync`, but it returns an object containing the `organization` object and a `fromCache` boolean. * If `fromCache` is true, the Organization object is from the cache and a state refresh is in progress. */ getInfo(): OrganizationInfo; /** * The `organization.onChange` method takes in a callback that gets called whenever the Organization object changes. It returns an unsubscribe method for you to call when you no longer want to listen for such changes. * * @param callback - Gets called whenever the organization object changes. See {@link B2BOrganizationOnChangeCallback}. * * @returns An {@link UnsubscribeFunction} for you to call when you no longer want to listen for changes in the organization object. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ onChange: (callback: (organization: Organization | null) => void) => UnsubscribeFunction; /** * The update organization method wraps the {@link https://stytch.com/docs/b2b/api/update-organization update organization} API endpoint. * This will update the logged-in Member's Organization. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/organizations#update-organization Stytch Docs} for a complete reference. * * @rbac action="requested", resource="stytch.organization" * * @param data - {@link B2BOrganizationsUpdateOptions} * * @returns A {@link B2BOrganizationsUpdateResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ update(data: B2BOrganizationsUpdateOptions): Promise; /** * The Delete Organization method wraps the {@link https://stytch.com/docs/b2b/api/delete-organization delete organization} API endpoint. * This will delete the logged-in Member's Organization. * As a consequence, their Member object will also be deleted, and their session will be revoked. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/organizations#delete-organization Stytch Docs} for a complete reference. * * @rbac action="delete", resource="stytch.organization" * * @returns A {@link B2BOrganizationsDeleteResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ delete(): Promise; /** * The `organization.getBySlug` method can be used to retrieve details about an organization from its slug. * This method may be called even if the Member is not logged in. * * @param data - {@link B2BOrganizationsGetBySlugOptions} * * @returns A {@link B2BOrganizationsGetBySlugResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an¿ error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ getBySlug(data: B2BOrganizationsGetBySlugOptions): Promise; /** * The Get Connected Apps method wraps the {@link https://stytch.com/docs/b2b/api/connected-app-org-get-all Get Connected Apps} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method retrieves a list of Connected Apps that have been installed by the Organization's Members. A Connected App * can be considered to be installed if at least one of the Organization's Members has successfully completed an * authorization flow with the Connected App and no revocation has occurred since that completion. A Connected App may * be uninstalled if the Organization changes its `first_party_connected_apps_allowed_type`or `third_party_connected_apps_allowed_type` * policies. * * See the {@link https://stytch.com/docs/b2b/sdks/organizations/connected-apps-get-all Stytch Docs} for a complete reference. * * @returns A {@link B2BOrganizationsGetConnectedAppsResponse} list of allowed Connected Apps. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ getConnectedApps(): Promise; /** * The Get Connected App method wraps the {@link https://stytch.com/docs/b2b/api/connected-app-org-get Get Connected App} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * * This method retrieves information about the specified Connected App as well as a list of Members in * the Organization who have completed an authorization flow with the Connected App. * * See the {@link https://stytch.com/docs/b2b/sdks/organizations/connected-app-get Stytch Docs} for a complete reference. * * @param data - {@link B2BOrganizationsGetConnectedAppOptions} * @returns A {@link B2BOrganizationsGetConnectedAppResponse} list of allowed Connected Apps. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ getConnectedApp(data: B2BOrganizationsGetConnectedAppOptions): Promise; members: { /** * The Create Member method wraps the {@link https://stytch.com/docs/b2b/api/create-member Create Member} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to create Members in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#create-member Stytch Docs} for a complete reference. * * @param data - {@link B2BOrganizationsMembersCreateOptions} * * @rbac action="create", resource="stytch.member" * * @returns A {@link B2BOrganizationsMembersCreateResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ create(data: B2BOrganizationsMembersCreateOptions): Promise; /** * The Search Members method wraps the {@link https://stytch.com/docs/b2b/api/search-members Search Members} API endpoint. It can be used to search for Members within the logged-in Member's Organization. * * Submitting an empty `query` returns all non-deleted Members within the logged-in Member's Organization. * * *All fuzzy search filters require a minimum of three characters. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#search-members Stytch Docs} for a complete reference. * * @rbac action="search", resource="stytch.member" * * @param data - {@link B2BOrganizationsMembersSearchOptions} * * @returns A {@link B2BOrganizationsMembersSearchResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ search(data: B2BOrganizationsMembersSearchOptions): Promise; /** * The Update Member method wraps the {@link https://stytch.com/docs/b2b/api/update-member Update Member} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method can be used to update any Member in the logged-in Member's Organization. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#update-member Stytch Docs} for a complete reference. * * @param data - {@link B2BOrganizationsMembersUpdateOptions} * * @returns A {@link B2BOrganizationsMembersUpdateResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ update(data: B2BOrganizationsMembersUpdateOptions): Promise; /** * The Delete Member password method wraps the {@link https://stytch.com/docs/b2b/api/delete-member-password Delete Member password} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to delete the passwords of Members in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#delete-member-password Stytch Docs} for a complete reference. * * @rbac action="update.info.delete.password", resource="stytch.member" * * @param passwordId - The ID of the password to be deleted * * @returns A {@link B2BOrganizationsMemberDeletePasswordResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ deletePassword(passwordId: string): Promise; /** * The Delete Member MFA phone number method wraps the {@link https://stytch.com/docs/b2b/api/delete-member-mfa-phone-number Delete Member MFA phone number} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Members's session. * This method cannot be used to delete the phone numbers of Members in other Organizations. * * To change a Member's phone number, you must first call this endpoint to delete the existing phone number. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#delete-member-mfa-phone-number Stytch Docs} for a complete reference. * * @rbac action="update.info.delete.mfa-phone", resource="stytch.member" * * @param memberId - The ID of the member * * @returns A {@link B2BOrganizationsMemberDeleteMFAPhoneNumberResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ deleteMFAPhoneNumber(memberId: string): Promise; /** * The Delete Member method wraps the {@link https://stytch.com/docs/b2b/api/delete-member delete member} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to delete Members in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#delete-member Stytch Docs} for a complete reference. * * @rbac action="delete", resource="stytch.member or stytch.self (depending on target MemberID)" * * @param memberId - The ID of the member to be deleted * * @returns A {@link B2BOrganizationsMembersDeleteResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ delete(memberId: string): Promise; /** * The Reactivate Member method wraps the {@link https://stytch.com/docs/b2b/api/reactivate-member Reactivate Member} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to reactivate Members in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#reactivate-member Stytch Docs} for a complete reference. * * @rbac action="create", resource="stytch.member" * * @param memberId - The ID of the member to be reactivated * * @returns A {@link B2BOrganizationsMembersReactivateResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ reactivate(memberId: string): Promise; /** * The Delete Member TOTP method wraps the {@link https://stytch.com/docs/b2b/api/delete-member-mfa-totp Delete Member TOTP} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to delete totps of Members in other Organizations. * * To change a Member's TOTP, you must first call this endpoint to delete the existing TOTP. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#delete-member-mfa-totp Stytch Docs} for a complete reference. * * @rbac action="update.info.delete.mfa-totp", resource="stytch.member" * * @param memberId - The ID of the member * * @returns A {@link B2BOrganizationsMemberDeleteMFATOTPResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ deleteMFATOTP(memberId: string): Promise; /** * The Unlink Member Retired Email Address method wraps the {@link https://stytch.com/docs/b2b/api/unlink-retired-member-email Unlink Retired Email} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to unlink emails of Members in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/members#unlink-retired-member-email Stytch Docs} for a complete reference. * * @rbac action="update.info.unlink.retired-email", resource="stytch.member" * * @param data - {@link B2BOrganizationsMemberUnlinkRetiredEmailOptions}. * * @returns A {@link B2BOrganizationsMemberUnlinkRetiredEmailResponse} response. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. */ unlinkRetiredEmail(data: B2BOrganizationsMemberUnlinkRetiredEmailOptions): Promise; /** * The Start Email Update method wraps the {@link https://stytch.com/docs/b2b/api/start-member-email-update Start Member Email Update} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to start the self-serve email update process for Members in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/members/start-member-email-update Stytch Docs} for a complete reference. * * @rbac action="update.info.email", resource="stytch.member" * * @param data - {@link B2BOrganizationsMemberStartEmailUpdateOptions} * @returns A {@link B2BOrganizationsMemberStartEmailUpdateResponse} indicating that an email update has been started. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ startEmailUpdate(data: B2BOrganizationsMemberStartEmailUpdateOptions): Promise; /** * The Member Get Connected Apps method wraps the {@link https://stytch.com/docs/b2b/api/connected-app-member-get-all Member Get Connected Apps} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * * This method retrieves a list of Connected Apps that the Member has completed an authorization flow with successfully. * If the Member revokes a Connected App's access (e.g. via the `revokeConnectedApp` method) then the Connected App will * no longer be returned in this endpoint's response. A Connected App's access may be revoked if the Organization's * allowed Connected App policy changes. * * See the {@link https://stytch.com/docs/b2b/sdks/members/get-member-connected-apps Stytch Docs} for a complete reference. * * @rbac action="get.connected-apps", resource="stytch.member" * * @returns A {@link B2BMemberGetConnectedAppsResponse} containing a list of the member's connected apps. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ getConnectedApps(data: B2BOrganizationsMemberGetConnectedAppsOptions): Promise; /** * The Member Revoke Connected App method wraps the {@link https://stytch.com/docs/b2b/api/connected-app-member-revoke Member Revoke Connected App} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * * This method revokes a Connected App's access to the Member and revokes all active tokens that have been * created on the Member's behalf. New tokens cannot be created until the Member completes a new authorization * flow with the Connected App. * * Note that after calling this method, the Member will be forced to grant consent in subsequent authorization * flows with the Connected App. * * See the {@link https://stytch.com/docs/b2b/sdks/members/revoke-member-connected-app Stytch Docs} for a complete reference. * * @rbac action="revoke.connected-app", resource="stytch.member" * * @param data - {@link B2BMemberRevokeConnectedAppOptions} * @returns A {@link B2BMemberRevokeConnectedAppResponse} indicating that the Connected App's access has been revoked. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ revokeConnectedApp(data: B2BOrganizationsMemberRevokeConnectedAppOptions): Promise; }; } type OAuthOrgSelectorOptions = { /** * The id of the organization the member belongs to. */ organization_id: string; /** * The slug of the organization the member belongs to. */ organization_slug?: never; } | { organization_slug: string; organization_id?: never; }; type OAuthStartOptions = OAuthOrgSelectorOptions & { /** * The URL that Stytch redirects to after the OAuth flow is completed for a member that already exists. * This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /oauth/authenticate endpoint and finishes the login. * The URL should be configured as a Login URL in the Stytch Dashboard's Redirect URL page. * If the field is not specified, the default in the Dashboard is used. */ login_redirect_url?: string; /** * The URL that Stytch redirects to after the OAuth flow is completed for a member that does not yet exist. * This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /oauth/authenticate endpoint and finishes the login. * The URL should be configured as a Sign Up URL in the Stytch Dashboard's Redirect URL page. * If the field is not specified, the default in the Dashboard is used. */ signup_redirect_url?: string; /** * An optional list of custom scopes that you'd like to request from the member in addition to the ones Stytch requests by default. * @example Google Custom Scopes * ['https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/firebase'] */ custom_scopes?: string[]; /** * An optional mapping of provider specific values to pass through as query params to the OAuth provider * @example Google authorization parameters * {"prompt": "select_account", "login_hint": "example@stytch.com"} */ provider_params?: Record; }; type B2BOAuthDiscoveryStartOptions = { /** * The URL that Stytch redirects to after the OAuth flow is completed for the member to perform discovery actions. * This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /oauth/discovery/authenticate endpoint and finishes the login. * The URL should be configured as a Discovery URL in the Stytch Dashboard's Redirect URL page. * If the field is not specified, the default in the Dashboard is used. */ discovery_redirect_url?: string; /** * An optional list of custom scopes that you'd like to request from the member in addition to the ones Stytch requests by default. * @example Google Custom Scopes * ['https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/firebase'] */ custom_scopes?: string[]; /** * An optional mapping of provider specific values to pass through to the OAuth provider * @example Google authorization parameters * {"prompt": "select_account", "login_hint": "example@stytch.com"} */ provider_params?: Record; }; type B2BOAuthAuthenticateOptions = SessionDurationOptions & { /** * The oauth token used to authenticate a member */ oauth_token: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; type OAuthDiscoveryAuthenticateOptions = { /** * The oauth token used to finish the discovery flow */ discovery_oauth_token: string; }; type B2BOAuthDiscoveryAuthenticateResponse = B2BDiscoveryAuthenticateResponse; type B2BOAuthAuthenticateResponse = B2BAuthenticateResponseWithMFA & { /** * The `provider_values` object lists relevant identifiers, values, and scopes for a given OAuth provider. * For example this object will include a provider's `access_token` that you can use to access the provider's API for a given member. * Note that these values will vary based on the OAuth provider in question, e.g. `id_token` may not be returned by all providers. */ provider_values: { /** * The `access_token` that you may use to access the member's data in the provider's API. */ access_token: string; /** * The `id_token` returned by the OAuth provider. * ID Tokens are JWTs that contain structured information about a user. * The exact content of each ID Token varies from provider to provider. * ID Tokens are returned from OAuth providers that conform to the {@link https://openid.net/foundation/ OpenID Connect} specification, which is based on OAuth. */ id_token: string; /** * The `refresh_token` that you may use to refresh a member's session within the provider's API. */ refresh_token: string; /** * The OAuth scopes included for a given provider. * See each provider's section above to see which scopes are included by default and how to add custom scopes. */ scopes: string[]; /** * The timestamp when the Session expires. * Values conform to the RFC 3339 standard and are expressed in UTC, e.g. 2021-12-29T12:33:09Z. */ expires_at: string; }; /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; /** * Methods for interacting with an individual OAuth provider. */ interface IOAuthProvider$0 { /** * The `oauth.$provider.start()` methods start OAuth flows by redirecting the browser to one of Stytch's {@link https://stytch.com/docs/b2b/api/oauth-google-start OAuth Start} endpoints. * One of `organization_id` or `slug` is required to specify which organization the user is trying to access. * If the organization that the user is trying to access is not yet known, use the `oauth.$provider.discovery.start()` method instead. * * The method will also generate a PKCE `code_verifier` and store it in local storage on the device (See the {@link https://stytch.com/docs/guides/oauth/adding-pkce PKCE OAuth guide} for details). * If your application is configured to use a custom subdomain with Stytch, it will be used automatically. * * @example * const loginWithGoogle = useCallback(()=> { * stytch.oauth.google.start({ * login_redirect_url: 'https://example.com/oauth/callback', * signup_redirect_url: 'https://example.com/oauth/callback', * organization_id: 'organization-test-123', * custom_scopes: ['https://www.googleapis.com/auth/gmail.compose'] * }) * }, [stytch]); * return ( * * ); * * @param data - An {@link OAuthStartOptions} object * * @returns void - the browser is redirected during this function call. You should not attempt to run any code after calling this function. * * @throws A `StytchSDKUsageError` when called with invalid input. */ start(data: OAuthStartOptions): Promise; discovery: { /** * Start a discovery OAuth login flow by redirecting the browser to Stytch's {@link https://stytch.com/docs/b2b/api/oauth-google-discovery-start OAuth discovery start} endpoint. * If enabled, this method will also generate a pkce_code_verifier and store it in localstorage on the device. * @example * const loginWithGoogle = useCallback(()=> { * stytch.oauth.discovery.start({ * discovery_redirect_url: 'https://example.com/oauth/login', * custom_scopes: 'profile avatar', * }) * }, [stytch]); * return ( * * ); * * @param data - An {@link B2BOAuthDiscoveryStartOptions} object * * @returns void - the browser is redirected during this function call. You should not attempt to run any code after calling this function. * * @throws A `StytchSDKUsageError` when called with invalid input. */ start(data: B2BOAuthDiscoveryStartOptions): Promise; }; } interface IHeadlessB2BOAuthClient { google: IOAuthProvider$0; microsoft: IOAuthProvider$0; hubspot: IOAuthProvider$0; slack: IOAuthProvider$0; github: IOAuthProvider$0; /** * The `authenticate` method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-oauth Authenticate OAuth} API endpoint which validates the OAuth token passed in. * * @example * stytch.oauth.authenticate({ * oauth_token: token, * session_duration_minutes: 60, * }); * * @param data - An {@link OAuthStartOptions} object * * @returns void - the browser is redirected during this function call. You should not attempt to run any code after calling this function. * * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(data: B2BOAuthAuthenticateOptions): Promise>; discovery: { /** * The authenticate method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-discovery-oauth Authenticate Discovery OAuth} API endpoint which validates the OAuth token passed in. * If this method succeeds, the intermediate session token will be stored in the browser as a cookie. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/oauth#discovery-authenticate Stytch Docs} for a complete reference. * * @example * stytch.oauth.discovery.authenticate({ * discovery_oauth_token: 'token', * }); * * @param data - {@link OAuthDiscoveryAuthenticateOptions} * * @returns A {@link B2BOAuthDiscoveryAuthenticateResponse} indicating that the OAuth flow has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(data: OAuthDiscoveryAuthenticateOptions): Promise>; }; } type SSOStartOptions = { /** * The ID of the SSO Connection to use for the login flow * * @example "saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9" */ connection_id: string; /** * The URL that Stytch redirects to after the SSO flow is completed for a user that already exists. * This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /sso/authenticate endpoint and finishes the login. * The URL should be configured as a Login URL in the Stytch Dashboard's Redirect URL page. * If the field is not specified, the default in the Dashboard is used. */ login_redirect_url?: string; /** * The URL that Stytch redirects to after the SSO flow is completed for a user that does not yet exist. * This URL should be an endpoint in the backend server that verifies the request by querying Stytch's /sso/authenticate endpoint and finishes the login. * The URL should be configured as a Sign Up URL in the Stytch Dashboard's Redirect URL page. * If the field is not specified, the default in the Dashboard is used. */ signup_redirect_url?: string; }; type SSOAuthenticateOptions = SessionDurationOptions & { /** * The sso token used to authenticate a member */ sso_token: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; type SSOAuthenticateResponse = B2BAuthenticateResponseWithMFA & { /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; type B2BSSOSAMLCreateConnectionOptions = { /** * A human-readable display name for the connection. */ display_name?: string; /** * The identity provider of this connection. For SAML, the accepted values are `generic`, `okta`, `microsoft-entra`, and 'google-workspace'. */ identity_provider?: string; }; type B2BSSOSAMLCreateConnectionResponse = ResponseCommon & { /** * The SAML Connection object affected by this API call. */ connection: SAMLConnection; }; type B2BSSOSAMLUpdateConnectionOptions = { /** * Globally unique UUID that identifies a specific SAML Connection. */ connection_id: string; /** * A globally unique name for the IdP. This will be provided by the IdP. */ idp_entity_id?: string; /** * A human-readable display name for the connection. */ display_name?: string; /** * An object that represents the attributes used to identify a Member. * This object will map the IdP-defined User attributes to Stytch-specific values. * Required attributes: `email` and one of `full_name` or `first_name` and `last_name`. */ attribute_mapping?: Record; /** * The URL for which assertions for login requests will be sent. This will be provided by the IdP. */ idp_sso_url?: string; /** * A certificate that Stytch will use to verify the sign-in assertion sent by the IdP, * in {@link https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail PEM} format. * See our {@link https://stytch.com/docs/b2b/api/saml-certificates X509 guide} for more info. */ x509_certificate?: string; /** * An array of implicit role assignments granted to members in this organization who log in with this SAML connection. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ saml_connection_implicit_role_assignments?: { role_id: string; }[]; /** * An array of implicit role assignments granted to members in this organization who log in with this SAML connection * and belong to the specified group. * Before adding any group implicit role assignments, you must add a "groups" key to your SAML connection's * attribute_mapping. Make sure that your IdP is configured to correctly send the group information. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ saml_group_implicit_role_assignments?: { role_id: string; group: string; }[]; /** * The identity provider of this connection. For SAML, the accepted values are `generic`, `okta`, `microsoft-entra`, and 'google-workspace'. */ identity_provider?: string; /** * A private key in PEM format that Stytch will use to sign SAML requests. * See our {@link https://stytch.com/docs/b2b/api/saml-certificates X509 guide} for more info. */ signing_private_key?: string; /** * A private key in PEM format that Stytch will use to decrypt encrypted SAML assertions. * See our {@link https://stytch.com/docs/b2b/api/saml-certificates X509 guide} for more info. */ saml_encryption_private_key?: string; }; type B2BSSOSAMLUpdateConnectionResponse = ResponseCommon & { /** * The SAML Connection object affected by this API call. */ connection: SAMLConnection; }; type B2BSSOSAMLUpdateConnectionByURLOptions = { /** * Globally unique UUID that identifies a specific SAML Connection. */ connection_id: string; /** * A URL that points to the IdP metadata. This will be provided by the IdP. */ metadata_url: string; }; type B2BSSOSAMLUpdateConnectionByURLResponse = ResponseCommon & { /** * The SAML Connection object affected by this API call. */ connection: SAMLConnection; }; type B2BSSOSAMLDeleteVerificationCertificateOptions = { /** * Globally unique UUID that identifies a specific SAML Connection. */ connection_id: string; /** * The ID of the certificate to be deleted. */ certificate_id: string; }; type B2BSSOSAMLDeleteVerificationCertificateResponse = ResponseCommon & { /** * The ID of the certificate that was deleted. */ certificate_id: string; }; type B2BSSOSAMLDeleteEncryptionPrivateKeyOptions = { /** * Globally unique UUID that identifies a specific SAML Connection. */ connection_id: string; /** * The ID of the encryption private key to be deleted. */ private_key_id: string; }; type B2BSSOSAMLDeleteEncryptionPrivateKeyResponse = ResponseCommon & { /** * The ID of the encryption private key that was deleted. */ private_key_id: string; }; type B2BSSOCreateExternalConnectionOptions = { /** * A human-readable display name for the connection. */ display_name?: string; /** * External connection organization id */ external_organization_id: string; /** * External connection id */ external_connection_id: string; }; type B2BSSOCreateExternalConnectionResponse = ResponseCommon & { /** * The External Connection object affected by this API call. */ connection: ExternalConnection; }; type B2BSSOUpdateExternalConnectionOptions = { /** * Globally unique UUID that identifies a specific External Connection. */ connection_id: string; /** * A human-readable display name for the connection. */ display_name?: string; /** * An array of implicit role assignments granted to members in this organization who log in with this external connection. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ external_connection_implicit_role_assignments?: { role_id: string; }[]; /** * An array of implicit role assignments granted to members in this organization who log in with this external connection * and belong to the specified group. * Before adding any group implicit role assignments, you must add a "groups" key to the underlying connection's * attribute_mapping. Make sure that your IdP is configured to correctly send the group information. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ external_group_implicit_role_assignments?: { role_id: string; group: string; }[]; }; type B2BSSOUpdateExternalConnectionResponse = ResponseCommon & { /** * The External Connection object affected by this API call. */ connection: ExternalConnection; }; type B2BSSOOIDCCreateConnectionOptions = { /** * A human-readable display name for the connection. */ display_name?: string; /** * The identity provider of this connection. For OIDC, the accepted values are `generic`, `okta`, and `microsoft-entra`. */ identity_provider?: string; }; type B2BSSOOIDCCreateConnectionResponse = ResponseCommon & { /** * The OIDC Connection object affected by this API call. */ connection: OIDCConnection; }; type B2BSSOOIDCUpdateConnectionOptions = { /** * Globally unique UUID that identifies a specific OIDC Connection. */ connection_id: string; /** * A human-readable display name for the connection. */ display_name?: string; /** * A case-sensitive `https://` URL that uniquely identifies the IdP. This will be provided by the IdP. */ issuer?: string; /** * The OAuth2.0 client ID used to authenticate login attempts. This will be provided by the IdP. */ client_id?: string; /** * The secret belonging to the OAuth2.0 client used to authenticate login attempts. This will be provided by the IdP. */ client_secret?: string; /** * The location of the URL that starts an OAuth login at the IdP. This will be provided by the IdP. */ authorization_url?: string; /** * The location of the URL that issues OAuth2.0 access tokens and OIDC ID tokens. This will be provided by the IdP. */ token_url?: string; /** * The location of the IDP's UserInfo Endpoint. This will be provided by the IdP. */ userinfo_url?: string; /** * The location of the IdP's JSON Web Key Set, used to verify credentials issued by the IdP. This will be provided by the IdP. */ jwks_url?: string; /** * The identity provider of this connection. For OIDC, the accepted values are `generic`, `okta`, and `microsoft-entra`. */ identity_provider?: string; /** * A space-separated list of custom scopes that will be requested on each SSOStart call. The total set of scopes will be the union of: the OIDC scopes `openid email profile`, the scopes requested in the `custom_scopes` query parameter on each SSOStart call, and the scopes listed in the OIDC Connection object. */ custom_scopes?: string; /** * An object that represents the attributes used to identify a Member. This object will map the IdP-defined User attributes to Stytch-specific values, which will appear on the member's Trusted Metadata. */ attribute_mapping?: Record; }; type B2BSSOOIDCUpdateConnectionResponse = ResponseCommon & { /** * The OIDC Connection object affected by this API call. */ connection: OIDCConnection; /** * If it is not possible to resolve the well-known metadata document from the OIDC issuer, this field will explain what went wrong if the request is successful otherwise. * In other words, even if the overall request succeeds, there could be relevant warnings related to the connection update. */ warning: string; }; type B2BSSOGetConnectionsResponse = ResponseCommon & { /** * The list of SAML Connections owned by this organization. */ saml_connections: SAMLConnection[]; /** * The list of OIDC Connections owned by this organization. */ oidc_connections: OIDCConnection[]; /** * The list of External Connections owned by this organization. */ external_connections: ExternalConnection[]; }; type B2BSSODeleteConnectionResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific SSO Connection. */ connection_id: string; }; type B2BSSODiscoverConnectionsResponse = ResponseCommon & { connections: SSOActiveConnection[]; }; interface IHeadlessB2BSSOClient { /** * The `sso.start()` method starts an SSO flow by redirecting the browser to Stytch's {@link https://stytch.com/docs/b2b/api/sso-authenticate-start SSO Start} endpoint. * The method will also generate a PKCE `code_verifier` and store it in localstorage on the device. * * @example * const loginWithOkta = useCallback(()=> { * stytch.sso.start({ * connection_id: 'saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9', * login_redirect_url: 'https://example.com/oauth/callback', * signup_redirect_url: 'https://example.com/oauth/callback', * }) * }, [stytch]); * return ( * * ); * * @param data - An {@link SSOStartOptions} object * * @returns void - the browser is redirected during this function call. You should not attempt to run any code after calling this function. * * @throws A `StytchSDKUsageError` when called with invalid input. */ start(data: SSOStartOptions): Promise; /** * The authenticate method wraps the {@link https://stytch.com/docs/b2b/api/sso-authenticate SSO Authenticate} API endpoint which validates the SSO token passed in. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#authenticate Stytch Docs} for a complete reference. * * @example * stytch.sso.authenticate({ * sso_token: 'token', * session_duration_minutes: 60, * }); * * @param data - {@link SSOAuthenticateOptions} * * @returns A {@link SSOAuthenticateResponse} indicating that the SSO flow has been authenticated and the member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(data: SSOAuthenticateOptions): Promise>; /** * The Get SSO Connections method wraps the {@link https://stytch.com/docs/b2b/api/get-sso-connections Get SSO Connections} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to get SSO connections from other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#get-connections Stytch Docs} for a complete reference. * * @example * stytch.sso.getConnections(); * * @rbac action="get", resource="stytch.sso" * * @returns A {@link B2BSSOGetConnectionsResponse} containing the organization's SSO connections * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ getConnections(): Promise; /** * The SSO Discovery method surfaces SSO connections for the end user. It will return all active SSO connections * for an end user or, if no active connections are found, it will return all SSO connections that the end user * could JIT provision into based on the provided email address. * * @example * stytch.sso.discoverConnections('example@stytch.com'); * * @param emailAddress - Email address to return SSO connection IDs for. * * @returns A {@link B2BSSODiscoverConnectionsResponse} containing an array of associated SSO connection IDs. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ discoverConnections(emailAddress: string): Promise; /** * The Delete SSO Connection method wraps the {@link https://stytch.com/docs/b2b/api/delete-sso-connection Delete SSO Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to delete SSO connections in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#delete-connection Stytch Docs} for a complete reference. * * @example * stytch.sso.deleteConnection('saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9'); * * @rbac action="delete", resource="stytch.sso" * * @param connectionId - The ID of the connection to delete * * @returns A {@link B2BSSODeleteConnectionResponse} indicating that the SSO connection has been created. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ deleteConnection(connectionId: string): Promise; saml: { /** * The Create SAML Connection method wraps the {@link https://stytch.com/docs/b2b/api/create-saml-connection Create SAML Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to create SAML connections in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#create-saml-connection Stytch Docs} for a complete reference. * * @example * stytch.sso.saml.createConnection({ * display_name: 'OneLogin SAML Connection', * }); * * @rbac action="create", resource="stytch.sso" * * @param data - {@link B2BSSOSAMLCreateConnectionOptions} * * @returns A {@link B2BSSOSAMLCreateConnectionResponse} indicating that the SSO connection has been created. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ createConnection(data: B2BSSOSAMLCreateConnectionOptions): Promise; /** * The Update SAML Connection method wraps the {@link https://stytch.com/docs/b2b/api/update-saml-connection Update SAML Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to update SAML connections in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#update-saml-connection Stytch Docs} for a complete reference. * * @example * stytch.sso.saml.updateConnection({ * connection_id: 'saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9', * x509_certificate: '-----BEGIN CERTIFICATE----...', * }); * * @rbac action="update", resource="stytch.sso" * * @param data - {@link B2BSSOSAMLUpdateConnectionOptions} * * @returns A {@link B2BSSOSAMLUpdateConnectionResponse} indicating that the SSO connection has been updated. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ updateConnection(data: B2BSSOSAMLUpdateConnectionOptions): Promise; /** * The Update SAML Connection method wraps the {@link https://stytch.com/docs/b2b/api/update-saml-connection Update SAML Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to update SAML connections in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#update-saml-connection-url Stytch Docs} for a complete reference. * * @example * stytch.sso.saml.updateConnectionByURL({ * connection_id: 'saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9', * metadata_url: 'https://idp.example.com/app/51861cbc-d3b9-428b-9761-227f5fb12be9/sso/saml/metadata', * }); * * @rbac action="update", resource="stytch.sso" * * @param data - {@link B2BSSOSAMLUpdateConnectionByURLOptions} * * @returns A {@link B2BSSOSAMLUpdateConnectionByURLResponse} indicating that the SSO connection has been updated. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ updateConnectionByURL(data: B2BSSOSAMLUpdateConnectionByURLOptions): Promise; /** * The Delete SAML Verification Certificate method wraps the {@link https://stytch.com/docs/b2b/api/delete-verification-certificate Delete Verification Certificate} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to delete verification certificates in other Organizations. * * You may need to do this when rotating certificates from your IdP, since Stytch allows a maximum of 5 certificates per connection. There must always be at least one certificate per active connection. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#delete-verification-certificate Stytch Docs} for a complete reference. * * @example * stytch.sso.saml.deleteVerificationCertificate({ * connection_id: 'saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9', * certificate_id: 'saml-verification-key-test-5ccbc642-9373-42b8-928f-c1646c868701', * }); * * @rbac action="update", resource="stytch.sso" * * @param data - {@link B2BSSOSAMLDeleteVerificationCertificateOptions} * * @returns A {@link B2BSSOSAMLDeleteVerificationCertificateResponse} indicating that the Verification Certificate has been deleted. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ deleteVerificationCertificate(data: B2BSSOSAMLDeleteVerificationCertificateOptions): Promise; /** * The Delete SAML Encryption Private Key method wraps the {@link https://stytch.com/docs/b2b/api/delete-encryption-private-key Delete Encryption Private Key} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to delete encryption private keys in other Organizations. * * You may need to do this when rotating encryption private keys from your IdP, since Stytch allows a maximum of 5 private keys per connection. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#delete-encryption-private-key Stytch Docs} for a complete reference. * * @example * stytch.sso.saml.deleteEncryptionPrivateKey({ * connection_id: 'saml-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9', * private_key_id: 'saml-encryption-key-test-5ccbc642-9373-42b8-928f-c1646c868701', * }); * * @rbac action="update", resource="stytch.sso" * * @param data - {@link B2BSSOSAMLDeleteEncryptionPrivateKeyOptions} * * @returns A {@link B2BSSOSAMLDeleteEncryptionPrivateKeyResponse} indicating that the Encryption Private Key has been deleted. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ deleteEncryptionPrivateKey(data: B2BSSOSAMLDeleteEncryptionPrivateKeyOptions): Promise; }; oidc: { /** * The Create OIDC Connection method wraps the {@link https://stytch.com/docs/b2b/api/create-oidc-connection Create OIDC Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to create OIDC connections in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#create-oidc-connection Stytch Docs} for a complete reference. * * @example * stytch.sso.oidc.createConnection({ * display_name: 'OneLogin OIDC Connection', * }); * * @rbac action="create", resource="stytch.sso" * * @param data - {@link B2BSSOOIDCCreateConnectionOptions} * * @returns A {@link B2BSSOOIDCCreateConnectionResponse} indicating that the SSO connection has been created. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ createConnection(data: B2BSSOOIDCCreateConnectionOptions): Promise; /** * The Update OIDC Connection method wraps the {@link https://stytch.com/docs/b2b/api/update-oidc-connection Update OIDC Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to update OIDC connections in other Organizations. * * When the value of `issuer` changes, Stytch will attempt to retrieve the [OpenID Provider Metadata](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata) document found at `${issuer}/.well-known/openid-configuration`. * If the metadata document can be retrieved successfully, Stytch will use it to infer the values of `authorization_url`, `token_url`, `jwks_url`, and `userinfo_url`. * The `client_id` and `client_secret` values cannot be inferred from the metadata document, and *must* be passed in explicitly. * * If the metadata document cannot be retrieved, Stytch will still update the connection using values from the request body. * * If the metadata document can be retrieved, and values are passed in the request body, the explicit values passed in from the request body will take precedence over the values inferred from the metadata document. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#update-oidc-connection Stytch Docs} for a complete reference. * * @example * stytch.sso.oidc.updateConnection({ * connection_id: 'oidc-connection-test-b6c714c2-7413-4b92-a0f1-97aa1085aeff', * client_id: "s6BhdRkqt3", * client_secret: "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4=" * }); * * @rbac action="update", resource="stytch.sso" * * @param data - {@link B2BSSOOIDCUpdateConnectionOptions} * * @returns A {@link B2BSSOOIDCUpdateConnectionResponse} indicating that the SSO connection has been updated. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ updateConnection(data: B2BSSOOIDCUpdateConnectionOptions): Promise; }; external: { /** * The Create External Connection method wraps the {@link https://stytch.com/docs/b2b/api/create-external-connection Create External Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to create External connections in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#create-external-connection Stytch Docs} for a complete reference. * * @example * stytch.sso.external.createConnection({ * display_name: 'OneLogin External Connection', * }); * * @rbac action="create", resource="stytch.sso" * * @param data - {@link B2BSSOCreateExternalConnectionOptions} * * @returns A {@link B2BSSOCreateSAMLConnectionResponse} indicating that the SSO connection has been created. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ createConnection(data: B2BSSOCreateExternalConnectionOptions): Promise; /** * The Update External Connection method wraps the {@link https://stytch.com/docs/b2b/api/update-external-connection Update External Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to update External connections in other Organizations. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/sso#update-external-connection Stytch Docs} for a complete reference. * * @example * stytch.sso.external.updateConnection({ * connection_id: 'external-connection-test-51861cbc-d3b9-428b-9761-227f5fb12be9', * display_name: 'new display name', * }); * * @rbac action="update", resource="stytch.sso" * * @param data - {@link B2BSSOUpdateExternalConnectionOptions} * * @returns A {@link B2BSSOUpdateExternalConnectionResponse} indicating that the SSO connection has been updated. * * @throws A `StytchSDKAPIError` when the Stytch API returns an error. * @throws A `SDKAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ updateConnection(data: B2BSSOUpdateExternalConnectionOptions): Promise; }; } /** * The authentication methods we support through our UI. * Currently we support `emailMagicLinks`, `emailOtp`, `sso`, `passwords`, and `oauth`. */ declare enum B2BProducts { emailMagicLinks = "emailMagicLinks", emailOtp = "emailOtp", sso = "sso", passwords = "passwords", oauth = "oauth" } declare enum AuthFlowType { Discovery = "Discovery", Organization = "Organization", PasswordReset = "PasswordReset" } /** * The options for email magic links. This is used if you've enabled the `emailMagicLinks` product * in your configuration. */ type B2BEmailMagicLinksOptions = { loginRedirectURL?: string; signupRedirectURL?: string; discoveryRedirectURL?: string; loginTemplateId?: string; signupTemplateId?: string; /** * @param domainHint - An optional hint indicating what domain the email will be sent from. * This field is only required if your project uses more than one custom domain to send emails. */ domainHint?: string; locale?: string; }; /** * The options for SSO. This is used if you've enabled the `sso` product * in your configuration. */ type B2BSSOOptions = { loginRedirectURL?: string; signupRedirectURL?: string; }; /** * The options for OAuth. This is required if you've enabled the `oauth` product * in your configuration. */ type B2BOAuthOptions = { loginRedirectURL?: string; signupRedirectURL?: string; discoveryRedirectURL?: string; /** @deprecated Use customScopes in B2BOAuthProviderConfig instead */ customScopes?: string[]; providers: B2BOAuthProviderConfig[]; /** @deprecated Use providerParams in B2BOAuthProviderConfig instead */ providerParams?: Record; locale?: string; }; /** * Details about the OAuth provider you wish to use. Each B2BOAuthProviderConfig object can be either a plain * B2BOAuthProviders string (e.g. 'google'), or an object with a type key that determines the type of provider. For * Google OAuth, you can optionally specify the one_tap property to display Google One Tap. */ type B2BOAuthProviderConfig = EnumOrStringLiteral | { type: EnumOrStringLiteral; one_tap: boolean; /** * Whether to cancel the One Tap prompt when the user taps outside of it. * This is only applicable if one_tap is true. */ cancel_on_tap_outside?: boolean; customScopes?: string[]; providerParams?: Record; } | { type: EnumOrStringLiteral; customScopes?: string[]; providerParams?: Record; }; /** * The options for Passwords. This is used if you've enabled the `passwords` product * in your configuration. */ type B2BPasswordOptions = { loginRedirectURL?: string; resetPasswordRedirectURL?: string; resetPasswordExpirationMinutes?: number; resetPasswordTemplateId?: string; discoveryRedirectURL?: string; verifyEmailTemplateId?: string; locale?: string; }; type B2BEmailOTPOptions = { loginTemplateId?: string; signupTemplateId?: string; locale?: string; }; type B2BSMSOTPOptions = { locale?: string; }; type DirectLoginForSingleMembershipConfig = { /** * Whether or not direct login for single membership is enabled. */ status: boolean; /** * If enabled, logs user in directly even if they have pending invite to a different organization */ ignoreInvites: boolean; /** * If enabled, logs user in directly even if they have organizations they could join via JIT provisioning */ ignoreJitProvisioning: boolean; }; type StytchB2BUIConfig = { /** * The products array allows you to specify the authentication methods that you would like to * expose to your users. The order of the products that you include here will also be the order * in which they appear in the login form, */ products: EnumOrStringLiteral[]; authFlowType: EnumOrStringLiteral; sessionOptions: SessionOptions; emailMagicLinksOptions?: B2BEmailMagicLinksOptions; ssoOptions?: B2BSSOOptions; passwordOptions?: B2BPasswordOptions; oauthOptions?: B2BOAuthOptions; emailOtpOptions?: B2BEmailOTPOptions; smsOtpOptions?: B2BSMSOTPOptions; /** * An optional config that allows you to skip the discover flow and log a member * in directly only if they are a member of a single organization. */ directLoginForSingleMembership?: DirectLoginForSingleMembershipConfig; /** * Whether or not an organization should be created directly when a user has * no memberships, invitations, or organizations they could join via JIT * provisioning. This has no effect if the ability to create organizations * from the frontend SDK is disabled in the Stytch dashboard. Defaults to * `false`. */ directCreateOrganizationForNoMembership?: boolean; /** * Whether to prevent users who are not members of any organization from * creating a new organization during the discovery flow. This has no effect * if the ability to create organizations from the frontend SDK is disabled in * the Stytch dashboard. Defaults to `false`. */ disableCreateOrganization?: boolean; /** * The order to present MFA products to a member when multiple choices are * available, such as during enrollment. */ mfaProductOrder?: readonly EnumOrStringLiteral[]; /** * MFA products to include in the UI. If specified, the list of available * products will be limited to those included. Defaults to all available * products. * * Note that if an organization restricts the available MFA methods, the * organization's settings will take precedence. In addition, if a member is * enrolled in MFA compatible with their organization's policies, their * enrolled methods will always be made available. */ mfaProductInclude?: readonly EnumOrStringLiteral[]; /** * The slug of the organization to use in the organization-specific auth flow. * If not specified, the organization will be inferred from the URL based on * the project's configured slug pattern. * * This has no effect outside of the organization-specific auth flow. */ organizationSlug?: string | null; }; declare enum B2BMFAProducts { smsOtp = "smsOtp", totp = "totp" } /** * The OAuth providers we support in our B2B OAuth product. */ declare enum B2BOAuthProviders { Google = "google", Microsoft = "microsoft", HubSpot = "hubspot", Slack = "slack", GitHub = "github" } type B2BPasswordAuthenticateOptions = SessionDurationOptions & { /** * The id of the Organization under which the Member and password belong */ organization_id: string; /** * The email of the Member. */ email_address: string; /** * The password for the Member. */ password: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; type B2BPasswordDiscoveryAuthenticateResponse = B2BDiscoveryOrganizationsResponse & { intermediate_session_token: IfOpaqueTokens, "", string>; }; type B2BPasswordDiscoveryAuthenticateOptions = { /** * The email attempting to login. */ email_address: string; /** * The password for the email address. */ password: string; }; type B2BPasswordAuthenticateResponse = B2BAuthenticateResponseWithMFA & { /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; type B2BPasswordResetByEmailStartOptions = { /** * The id of the Organization under which the Member and password belong */ organization_id: string; /** * The email of the Member that requested the password reset. */ email_address: string; /** * The url that the Member clicks from the password reset email to skip resetting their password and directly login. * This should be a url that your app receives, parses, and subsequently sends an API request to the magic link authenticate endpoint to complete the login process without reseting their password. * If this value is not passed, the login redirect URL that you set in your Dashboard is used. * If you have not set a default login redirect URL, an error is returned. */ login_redirect_url?: string; /** * The url that the Member clicks from the password reset email to finish the reset password flow. * This should be a url that your app receives and parses before showing your app's reset password page. * After the Member submits a new password to your app, it should send an API request to complete the password reset process. * If this value is not passed, the default reset password redirect URL that you set in your Dashboard is used. * If you have not set a default reset password redirect URL, an error is returned. */ reset_password_redirect_url?: string; /** * Set the expiration for the password reset, in minutes. * By default, it expires in 30 minutes. * The minimum expiration is 5 minutes and the maximum is 7 days (10080 mins). */ reset_password_expiration_minutes?: number; /** * The email template ID to use for password reset. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Passwords reset custom HTML template. */ reset_password_template_id?: string; /** * The email template ID to use for first-time users verifying their email while resetting their password. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Passwords email verification custom HTML template. */ verify_email_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; }; type B2BPasswordResetByEmailStartResponse = ResponseCommon; type B2BPasswordDiscoveryResetByEmailStartOptions = { /** * The email that requested the password reset. */ email_address: string; /** * The url that the Member clicks from the password reset email to skip resetting their password and directly login. * This should be a url that your app receives, parses, and subsequently sends an API request to the magic link authenticate endpoint to complete the login process without reseting their password. * If this value is not passed, the login redirect URL that you set in your Dashboard is used. * If you have not set a default login redirect URL, an error is returned. */ discovery_redirect_url?: string; /** * The url that the Member clicks from the password reset email to finish the reset password flow. * This should be a url that your app receives and parses before showing your app's reset password page. * After the Member submits a new password to your app, it should send an API request to complete the password reset process. * If this value is not passed, the default reset password redirect URL that you set in your Dashboard is used. * If you have not set a default reset password redirect URL, an error is returned. */ reset_password_redirect_url?: string; /** * Set the expiration for the password reset, in minutes. * By default, it expires in 30 minutes. * The minimum expiration is 5 minutes and the maximum is 7 days (10080 mins). */ reset_password_expiration_minutes?: number; /** * The email template ID to use for password reset. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Passwords reset custom HTML template. */ reset_password_template_id?: string; /** * The email template ID to use for first-time users verifying their email while resetting their password. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or a Passwords email verification custom HTML template. */ verify_email_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; }; type B2BPasswordDiscoveryResetByEmailStartResponse = ResponseCommon; type B2BPasswordDiscoveryResetByEmailOptions = { /** * The token to authenticate. */ password_reset_token: string; /** * The new password for the Member. */ password: string; }; type B2BPasswordDiscoveryResetByEmailResponse = B2BDiscoveryOrganizationsResponse & { intermediate_session_token: IfOpaqueTokens, "", string>; }; type B2BPasswordResetByEmailOptions = SessionDurationOptions & { /** * The token to authenticate. */ password_reset_token: string; /** * The new password for the Member. */ password: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; // B2BPasswordEmailResetResponse type B2BPasswordResetByEmailResponse = B2BAuthenticateResponseWithMFA & { /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; type B2BPasswordResetByExistingPasswordOptions = SessionDurationOptions & { /** * The id of the Organization under which the Member and password belong */ organization_id: string; /** * The Member's email. */ email_address: string; /** * The Member's existing password. */ existing_password: string; /** * The new password for the Member. */ new_password: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; // B2BPasswordExistingPasswordResetResponse type B2BPasswordResetByExistingPasswordResponse = B2BAuthenticateResponseWithMFA & { /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; type B2BPasswordResetBySessionOptions = { /** * The new password for the Member. */ password: string; }; // B2BPasswordSessionResetResponse type B2BPasswordResetBySessionResponse = B2BAuthenticateResponse & { /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; type B2BPasswordStrengthCheckOptions = { /** * The email associated with the password. Provide this for a more accurate strength check. */ email_address?: string; /** * The password to strength check. */ password: string; }; type B2BPasswordStrengthCheckResponse = MemberResponseCommon & { /** * Whether the password is considered valid and secure. * Read more about password validity {@link https://stytch.com/docs/api/password-strength-check in our docs}. */ valid_password: boolean; /** * The score of the password as determined by {@link https://github.com/dropbox/zxcvbn zxcvbn}. */ score: number; /** * Determines if the password has been breached using {@link https://haveibeenpwned.com/ HaveIBeenPwned}. */ breached_password: boolean; /** * Will return true if breach detection will be evaluated. By default this option is enabled. * This option can be disabled by contacting support@stytch.com. If this value is false then * breached_password will always be false as well. */ breach_detection_on_create: boolean; /** * The strength policy type enforced, either `zxcvbn` or `luds`. */ strength_policy: "luds" | "zxcvbn"; /** * Feedback for how to improve the password's strength using {@link https://github.com/dropbox/zxcvbn zxcvbn}. */ zxcvbn_feedback: { suggestions: string[]; warning: string; }; /** * Feedback for how to improve the password's strength using Lowercase Uppercase Digits Special Characters */ luds_feedback: { has_lower_case: boolean; has_upper_case: boolean; has_digit: boolean; has_symbol: boolean; missing_complexity: number; missing_characters: number; }; }; interface IHeadlessB2BPasswordClient { /** * The Authenticate method wraps the {@link https://stytch.com/docs/b2b/api/passwords-authenticate Authenticate} Password API endpoint. * This endpoint verifies that the Member has a password currently set, and that the entered password is correct. * * There are cases where this endpoint will return a `reset_password` error even if the password entered is correct. * View our {@link https://stytch.com/docs/api/password-authenticate API Docs} for complete details. * * If this method succeeds, the Member will be logged in, granted an active session, and the * {@link https://stytch.com/docs/sdks/javascript-sdk/resources/cookies-and-session-management session cookies} will be minted and stored in the browser. * * @example * stytch.passwords.authenticate({ * email_address: 'sandbox@stytch.com', * password: 'aVerySecurePassword', * session_duration_minutes: 60 * }); * * @param options - {@link B2BPasswordAuthenticateOptions} * * @returns A {@link B2BPasswordAuthenticateResponse} indicating the password is valid and that the Member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(options: B2BPasswordAuthenticateOptions): Promise>; /** * The `resetByEmailStart` method wraps the {@link https://stytch.com/docs/b2b/api/email-reset-start Reset By Email Start} Password API endpoint. * This endpoint initiates a password reset for the email address provided. * This will trigger an email to be sent to the address, containing a magic link that will allow them to set a new password and authenticate. * * @example * stytch.passwords.resetByEmailStart({ * email_address: 'sandbox@stytch.com', * reset_password_redirect_url: 'https://example.com/login/reset', * reset_password_expiration_minutes: 10, * login_redirect_url: 'https://example.com/login/authenticate', * }); * * @param options - {@link B2BPasswordResetByEmailStartOptions} * * @returns A {@link B2BPasswordResetByEmailStartResponse} indicating the password is valid and that the Member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetByEmailStart(options: B2BPasswordResetByEmailStartOptions): Promise; /** * The `resetByEmail` method wraps the {@link https://stytch.com/docs/b2b/api/email-reset Password reset by email} API endpoint. * This endpoint resets the Member's password and authenticates them. * The provided password needs to meet your Stytch project's password strength requirements, which can be checked in advance using the {@link IHeadlessB2BPasswordClient#strengthCheck password strength check} method. * * If this method succeeds, the Member will be logged in, granted an active session, and the * {@link https://stytch.com/docs/sdks/javascript-sdk/resources/cookies-and-session-management session cookies} will be minted and stored in the browser. * * @example * const currentLocation = new URL(window.location.href); * const token = currentLocation.searchParams.get('token'); * stytch.passwords.resetByEmail({ * token, * email_address: 'sandbox@stytch.com', * password: 'aVerySecurePassword', * session_duration_minutes: 60 * }); * * @param options - {@link B2BPasswordResetByEmailOptions} * * @returns A {@link B2BPasswordResetByEmailResponse} indicating the password is valid and that the Member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetByEmail(options: B2BPasswordResetByEmailOptions): Promise>; /** * The strengthCheck method wraps the {@link https://stytch.com/docs/b2b/api/strength-check Strength Check} Password API endpoint. * * This endpoint allows you to check whether or not the Member’s provided password is valid, * and to provide feedback to the Member on how to increase the strength of their password. * * @example * const {valid_password, feedback} = await stytch.passwords.strengthCheck({ email, password }); * if (!valid_password) { * throw new Error('Password is not strong enough: ' + feedback.warning); * } * * @param options - {@link B2BPasswordStrengthCheckOptions} * * @returns A {@link B2BPasswordStrengthCheckResponse} containing password strength feedback. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ strengthCheck(options: B2BPasswordStrengthCheckOptions): Promise; /** * The resetByExistingPassword method wraps the {@link https://stytch.com/docs/b2b/api/existing-reset Reset By Existing Password} API endpoint. * If this method succeeds, the Member will be logged in, granted an active session, and the * {@link https://stytch.com/docs/sdks/javascript-sdk/resources/cookies-and-session-management session cookies} will be minted and stored in the browser. * * @example * stytch.passwords.resetByExistingPassword({ * email_address: 'sandbox@stytch.com', * existing_password: 'aVerySecurePassword', * new_password: 'aVerySecureNewPassword' * }); * * @param options - {@link B2BPasswordResetByExistingPasswordOptions} * * @returns A {@link B2BPasswordResetByExistingPasswordResponse} indicating the password is valid and that the Member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetByExistingPassword(options: B2BPasswordResetByExistingPasswordOptions): Promise>; /** * The resetBySession method wraps the {@link https://stytch.com/docs/b2b/api/session-reset Reset By Session} API endpoint. * If this method succeeds, the Member will be logged in, granted an active session, and the * {@link https://stytch.com/docs/sdks/javascript-sdk/resources/cookies-and-session-management session cookies} will be minted and stored in the browser. * * @example * stytch.passwords.resetBySession({ * password: 'aVerySecurePassword' * }); * * @param options - {@link B2BPasswordResetBySessionOptions} * * @returns A {@link B2BPasswordResetBySessionResponse} indicating the password is valid and that the Member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ resetBySession(options: B2BPasswordResetBySessionOptions): Promise>; discovery: { /** * The `resetByEmailStart` method wraps the {@link https://stytch.com/docs/b2b/api/discovery-email-reset-start Reset By Email Discovery Start} Password API endpoint. * If this method succeeds, an email will be sent to the provided email address with a link to reset the password. * @param options - {@link B2BPasswordDiscoveryResetByEmailStartOptions} * * @returns A {@link B2BPasswordDiscoveryResetByEmailStartResponse} indicating the password reset email has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ resetByEmailStart(options: B2BPasswordDiscoveryResetByEmailStartOptions): Promise; /** * The `resetByEmail` method wraps the {@link https://stytch.com/docs/b2b/api/discovery-email-reset Reset By Email Discovery} Password API endpoint. * This endpoint resets the password associated with an email and starts an intermediate session for the user. * @param options - {@link B2BPasswordDiscoveryResetByEmailOptions} * * @returns A {@link B2BPasswordDiscoveryResetByEmailResponse} indicating the password is valid and that the Member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ resetByEmail(options: B2BPasswordDiscoveryResetByEmailOptions): Promise>; /** * The `authenticate` method wraps the {@link https://stytch.com/docs/b2b/api/passwords-discovery-authenticate Discovery Authenticate} Password API endpoint. * This endpoint verifies that the email has a password currently set, and that the entered password is correct. * @param options - {@link B2BPasswordDiscoveryAuthenticateOptions} * * @returns A {@link B2BPasswordDiscoveryAuthenticateResponse} indicating the password is valid and that the Member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. */ authenticate(options: B2BPasswordDiscoveryAuthenticateOptions): Promise>; }; } // SMS OTP type B2BSMSSendOptions = { /** * The ID of the organization the member belongs to */ organization_id: string; /** * The ID of the member to send the OTP to */ member_id: string; /** * The phone number to send the OTP to. If the member already has a phone number, this argument is not needed. * If the member does not have a phone number and this argument is not provided, an error will be thrown. */ mfa_phone_number?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * Indicates whether the SMS message should include autofill metadata */ enable_autofill?: boolean; /** * Indicates how long the autofill session should be valid. Defaults to 5 minutes */ autofill_session_duration_minutes?: number; }; type B2BSMSSendResponse = ResponseCommon; type B2BSMSAuthenticateOptions = SessionDurationOptions & { /** * The ID of the organization the member belongs to */ organization_id: string; /** * The ID of the member to authenticate */ member_id: string; /** * The OTP to authenticate */ code: string; /** * If set to 'enroll', enrolls the member in MFA by setting the "mfa_enrolled" boolean to true. * If set to 'unenroll', unenrolls the member in MFA by setting the "mfa_enrolled" boolean to false. * If not set, does not affect the member's MFA enrollment. */ set_mfa_enrollment?: "enroll" | "unenroll"; }; // B2BOTPsSMSAuthenticateResponse type B2BSMSAuthenticateResponse = B2BAuthenticateResponse & { /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; // Tenanted Email OTP type B2BOTPsEmailLoginOrSignupOptions = { /** * The ID of the organization the member belongs to. */ organization_id: string; /** * The email of the member to send the OTP to. */ email_address: string; /** * The email template ID to use for login emails. If not provided, your default email template will be sent. * If providing a template ID, it must be either a template using Stytch's customizations, or an OTP Login custom HTML template. */ login_template_id?: string; /** * The email template ID to use for sign-up emails. * If not provided, your default email template will be sent. If providing a template ID, it must be either a template using Stytch's customizations, * or an OTP Sign-up custom HTML template. */ signup_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * The expiration time, in minutes, for a login OTP. If not authenticated within this time frame, the OTP email will need to be resent. * Defaults to 10 with a minimum of 2 and a maximum of 15. */ login_expiration_minutes?: number; /** * The expiration time, in minutes, for a signup OTP. If not authenticated within this time frame, the OTP will need to be resent. * Defaults to 10 with a minimum of 2 and a maximum of 15. */ signup_expiration_minutes?: number; }; type B2BOTPsEmailLoginOrSignupResponse = ResponseCommon; type B2BOTPsEmailAuthenticateOptions = SessionDurationOptions & { /** * The OTP to authenticate */ code: string; /** * The email of the member we're attempting to authenticate the otp for. */ email_address: string; /* * The organization ID of the member attempting to authenticate for. */ organization_id: string; /** * The locale will be used if an OTP code is sent to the member's phone number as part of a * secondary authentication requirement. */ locale?: locale; }; type B2BOTPsEmailAuthenticateResponse = B2BAuthenticateResponseWithMFA & { /** * The ID of the email used to send an OTP. */ method_id: string; /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; // Discovery Email OTP type B2BDiscoveryOTPEmailSendOptions = { /** * The email address to send the OTP to. */ email_address: string; /** * The email template ID to use for login emails. If not provided, your default email template will be sent. * If providing a template ID, it must be either a template using Stytch's customizations, or an OTP Login custom HTML template. */ login_template_id?: string; /** * The locale is used to determine which language to use in the email. Parameter is a {@link https://www.w3.org/International/articles/language-tags/ IETF BCP 47 language tag}, e.g. "en". * Currently supported languages are English ("en"), Spanish ("es"), and Brazilian Portuguese ("pt-br"); if no value is provided, the copy defaults to English. */ locale?: locale; /** * The expiration time, in minutes. If not accepted within this time frame, the OTP will need to be resent. * Defaults to 10 with a minimum of 2 and a maximum of 15. */ discovery_expiration_minutes?: number; }; type B2BDiscoveryOTPEmailSendResponse = ResponseCommon; type B2BDiscoveryOTPEmailAuthenticateOptions = { /** * The OTP to authenticate the user. */ code: string; /** * The email address of the member attempting to authenticate. */ email_address: string; }; type B2BDiscoveryOTPEmailAuthenticateResponse = B2BDiscoveryAuthenticateResponse; interface IHeadlessB2BOTPsClient { sms: { /** * The SMS Send method wraps the {@link https://stytch.com/docs/b2b/api/otp-sms-send send} via SMS API endpoint. Call this method to send an SMS passcode to an existing Member. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/otps#otps-sms-send Stytch Docs} for a complete reference. * * @example * stytch.otps.sms.send({ * organization_id: 'organization-test-123', * member_id: 'member-id-123', * phone_number: '+12025550162', * }); * * @param data - {@link B2BSMSSendOptions} * * @returns A {@link B2BSMSSendResponse} indicating that the SMS has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ send(data: B2BSMSSendOptions): Promise; /** * The SMS Authenticate method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-otp-sms authenticate SMS} API endpoint. * * If there is a current Member Session, the SDK will call the endpoint with the session token. * This will add the phone number factor to the existing Member Session. * Otherwise, the SDK will use the intermediate session token. * This will consume the intermediate session token and create a Member Session. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/otps#otps-sms-authenticate Stytch Docs} for a complete reference. * * @example * stytch.otps.sms.authenticate({ * organization_id: 'organization-test-123', * member_id: 'member-id-123', * code: '123456', * session_duration_minutes: 60, * }); * * @param data - {@link B2BSMSAuthenticateOptions} * * @returns A {@link B2BSMSAuthenticateResponse} indicating that the SMS OTP factor has been authenticated * and added to the member's session. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(data: B2BSMSAuthenticateOptions): Promise>; }; email: { /** * The loginOrSignup method wraps the {@link https://stytch.com/docs/b2b/api/send-login-signup-email-otp login_or_signup} Email OTP API endpoint. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-otps#login-or-signup Stytch Docs} for a complete reference. * * @example * stytch.otps.email.loginOrSignup({ * email_address: 'sandbox@stytch.com', * organization_id: 'organization-test-123', * }); * * @param data - {@link B2BOTPsEmailLoginOrSignupOptions} * * @returns A {@link B2BOTPsEmailLoginOrSignupResponse} indicating that the email has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ loginOrSignup(data: B2BOTPsEmailLoginOrSignupOptions): Promise; /** * The authenticate method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-email-otp authenticate} Email OTP API endpoint. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-otp#authenticate Stytch Docs} for a complete reference. * * @example * stytch.email.otps.authenticate({ * code: '123456', * member_id: 'member-id-123', * organization_id: 'organization-test-123', * session_duration_minutes: 60, * }); * * @param data - {@link B2BOTPsEmailAuthenticateOptions} * * @returns A {@link B2BOTPsEmailAuthenticateResponse} indicating that the OTP has been authenticated and the member is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(data: B2BOTPsEmailAuthenticateOptions): Promise>; discovery: { /** * The send method wraps the {@link https://stytch.com/docs/b2b/api/send-discovery-email-otp discovery} Email OTP discovery API endpoint. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-magic-links#send-discovery-email-otp Stytch Docs} for a complete reference. * * @example * stytch.otps.email.discovery.send({ * email_address: 'sandbox@stytch.com', * }); * * @param data - {@link B2BDiscoveryOTPEmailSendOptions} * * @returns A {@link B2BDiscoveryOTPEmailSendResponse} indicating that the email has been sent. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ send(data: B2BDiscoveryOTPEmailSendOptions): Promise; /** * The discovery authenticate method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-discovery-email-otp authenticate} discovery email OTP API endpoint. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/email-magic-links#authenticate-discovery-email-otp Stytch Docs} for a complete reference. * * @example * stytch.otps.email.discovery.authenticate({ * code: '123456', * email_address: 'sandbox@stytch.com', * }); * * @param data - {@link B2BDiscoveryOTPEmailAuthenticateOptions} * * @returns A {@link B2BDiscoveryOTPEmailAuthenticateResponse} indicating that the OTP has been authenticated. * The response will contain the intermediate_session_token, the email address that the OTP was sent to, * and a list of discovered organizations that are associated with the email address. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(data: B2BDiscoveryOTPEmailAuthenticateOptions): Promise>; }; }; } type B2BTOTPCreateOptions = { /** * The ID of the organization the member belongs to */ organization_id: string; /** * The ID of the member creating a TOTP */ member_id: string; /** * The expiration for the TOTP instance. If the newly created TOTP is not authenticated within this time frame the TOTP will be unusable. Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 1440. */ expiration_minutes?: number; }; type B2BTOTPCreateResponse = MemberResponseCommon & { /** * Globally unique UUID that identifies a specific TOTP registration in the Stytch API. */ totp_registration_id: string; /** * The TOTP secret key shared between the authenticator app and the server used to generate TOTP codes. */ secret: string; /** * The QR code image encoded in base64. */ qr_code: string; /** * The recovery codes used to authenticate the member without an authenticator app. */ recovery_codes: string[]; }; type B2BTOTPAuthenticateOptions = SessionDurationOptions & { /** * The ID of the organization the member belongs to */ organization_id: string; /** * The ID of the member to authenticate */ member_id: string; /** * The TOTP code to authenticate */ code: string; /** * If set to 'enroll', enrolls the member in MFA by setting the "mfa_enrolled" boolean to true. * If set to 'unenroll', unenrolls the member in MFA by setting the "mfa_enrolled" boolean to false. * If not set, does not affect the member's MFA enrollment. */ set_mfa_enrollment?: "enroll" | "unenroll"; /** * If set to true, sets TOTP as the member's default MFA method. */ set_default_mfa?: boolean; }; // B2BTOTPsAuthenticateResponse type B2BTOTPAuthenticateResponse = B2BAuthenticateResponse & { /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; interface IHeadlessB2BTOTPsClient { /** * The TOTP Authenticate method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-totp authenticate TOTP} API endpoint. * * If there is a current Member Session, the SDK will call the endpoint with the session token. * This will add the totp factor to the existing Member Session. * Otherwise, the SDK will use the intermediate session token. * This will consume the intermediate session token and create a Member Session. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/otps#totp-authenticate Stytch Docs} for a complete reference. * * @example * stytch.totp.authenticate({ * organization_id: 'organization-test-123', * member_id: 'member-id-123', * code: '123456', * }); * * @param data - {@link B2BTOTPAuthenticateOptions} * * @returns A {@link B2BTOTPAuthenticateResponse} indicating that the TOTP factor has been authenticated * and added to the member's session. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ authenticate(data: B2BTOTPAuthenticateOptions): Promise>; /** * The TOTP Create method wraps the {@link https://stytch.com/docs/b2b/api/totp-create create} endpoint. * Call this method to create a TOTP registration on an existing Member. * * @example * ``` * stytch.totp.create({ expiration_minutes: 60 }); * ``` * * @param options - {@link B2BTOTPCreateOptions} * * @returns A {@link B2BTOTPCreateResponse} indicating a new TOTP instance has been created. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ create(options: B2BTOTPCreateOptions): Promise; } type RecoveryCodeRecoverOptions = SessionDurationOptions & { /** * The ID of the organization the member belongs to */ organization_id: string; /** * The ID of the member creating a TOTP */ member_id: string; /** * The recovery code to authenticate. */ recovery_code: string; }; // B2BRecoveryCodesRecoverResponse type RecoveryCodeRecoverResponse = B2BAuthenticateResponse & { /** * Number of recovery codes remaining for the member. */ recovery_codes_remaining: number; /** * The device history of the member. */ member_device?: SDKDeviceHistory; }; type RecoveryCodeRotateResponse = ResponseCommon & { /** * The recovery codes used to authenticate the member without an authenticator app. */ recovery_codes: string[]; }; type RecoveryCodeGetResponse = ResponseCommon & { /** * The recovery codes used to authenticate the member in place of a secondary factor. */ recovery_codes: string[]; }; interface IHeadlessB2BRecoveryCodesClient { /** * The Recovery Codes Recover method wraps the {@link https://stytch.com/docs/b2b/api/recovery-codes-recover Recovery Codes Recover}API endpoint. * It takes a single `recovery_code` parameter, which is a recovery code that was previously generated for the Member. Calling * the recover endpoint will consume the recovery code and authenticate the Member, minting a new session for them. * * Currently, recovery codes are only generated when a Member enrolls in TOTP as their secondary MFA factor, and as such * authenticate members in place of a `stytch.totps.authenticate()`. * * If neither a Member Session nor an intermediate session token is present, this method will fail. * * @example * ``` * stytch.recoveryCodes.recover({ recovery_code: '12345678' }); * ``` * * @param options - {@link RecoveryCodeRecoverOptions} * * @returns A {@link RecoveryCodeRecoverResponse} indicating that the member has been authenticated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ recover(options: RecoveryCodeRecoverOptions): Promise>; /** * The Rotate Recovery Codes method wraps the {@link https://stytch.com/docs/b2b/api/recovery-codes-rotate Rotate Recovery Codes} API endpoint. * * Rotation requires a logged-in Member Session, as both `organization_id` and `member_id` will be inferred from the session. * All existing recovery codes will be invalidated and new ones will be generated. * * @example * ``` * stytch.recoveryCodes.rotate(); * ``` * * @returns A {@link RecoveryCodeRotateResponse} indicating that the member's recovery codes have been rotated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ rotate(): Promise; /** * The Get Recovery Codes method wraps the {@link https://stytch.com/docs/b2b/api/recovery-codes-get Get Recovery Codes} API endpoint. * Both the `organization_id` and `member_id` for this request will be inferred from the current Member's session. * @example * ``` * stytch.recoveryCodes.get(); * ``` * * @returns A {@link RecoveryCodeGetResponse} containing the member's recovery codes. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ get(): Promise; } type Actions = Record; type PermissionsMap> = { [ResourceID in keyof Permissions]: Actions; }; interface IHeadlessB2BRBACClient { /** * The `isAuthorizedSync` method determines whether the logged-in member is allowed to perform the specified action on the specified resource. * Returns `true` if the member can perform the action, `false` otherwise. * * If the member is not logged in, or the RBAC policy has not been loaded, this method will always return false. * If the resource or action provided are not valid for the configured RBAC policy, this method will return false. * @example * const isAuthorized = stytch.rbac.isAuthorizedSync('document', 'image'); */ isAuthorizedSync(resourceId: string, action: string): boolean; /** * The `isAuthorized` method determines whether the logged-in member is allowed to perform the specified action on the specified resource. * It will return a Promise that resolves after the RBAC policy has been loaded. Returns `true` if the member can perform the action, `false` otherwise. * * If the member is not logged in, this method will always return false. * If the resource or action provided are not valid for the configured RBAC policy, this method will return false. * * @example * const isAuthorized = await stytch.rbac.isAuthorizedSync('document', 'image'); */ isAuthorized(resourceId: string, action: string): Promise; /** * The `allPermissions` method returns the complete list of permissions assigned to the currently logged-in Member. If the Member is not logged in, all values will be `false`. * * As a best practice, authorization checks for sensitive actions should also occur on the backend. * * @example * type Permissions = { * document: 'create' | 'read' | 'write * image: 'create' | 'read' * } * const permissions = await stytch.rbac.allPermissions(); * console.log(permissions.document.create) // true * console.log(permissions.image.create) // false * @returns A {@link PermissionsMap} for the active member */ allPermissions>(): Promise>; } interface BaseSCIMConnection { /** * Globally unique UUID that identifies a specific Organization. */ organization_id: string; /** * Globally unique UUID that identifies a specific SCIM Connection. */ connection_id: string; /** * The status of the connection. The possible values are deleted or active. */ status: string; /** * A human-readable display name for the connection. */ display_name: string; /** * The identity provider of this connection. */ identity_provider: string; /** * The base URL of the SCIM connection. */ base_url: string; /** * An array of implicit group role assignments granted to members in this organization who are provisioned this SCIM connection * and belong to the specified group. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ scim_group_implicit_role_assignments: { role_id: string; group_id: string; }[]; } interface SCIMConnection extends BaseSCIMConnection { /** * Last four characters of the issued bearer token. */ bearer_token_last_four: string; /** * The time at which the bearer token expires. */ bearer_token_expires_at: string; /** * Present during rotation, the next bearer token's last four digits. */ next_bearer_token_last_four?: string; /** * Present during rotation, the time at which the next bearer token expires. */ next_bearer_token_expires_at?: string; } interface SCIMConnectionWithBearerToken extends BaseSCIMConnection { /** * The bearer token used to authenticate with the SCIM API. */ bearer_token: string; /** * The time at which the bearer token expires. */ bearer_token_expires_at: string; } interface SCIMConnectionWithNextBearerToken extends BaseSCIMConnection { /** * The bearer token used to authenticate with the SCIM API. */ next_bearer_token: string; /** * The time at which the bearer token expires. */ next_bearer_token_expires_at: string; /** * Last four characters of the issued bearer token. */ bearer_token_last_four: string; /** * The time at which the bearer token expires. */ bearer_token_expires_at: string; } interface SCIMGroup { /** * Globally unique UUID that identifies a specific Organization. */ organization_id: string; /** * Globally unique UUID that identifies a specific SCIM Connection. */ connection_id: string; /** * Globally unique UUID that identifies a specific SCIM Group. */ group_id: string; /** * Name given to the group by the IDP. */ group_name: string; } type B2BSCIMCreateConnectionOptions = { /** * A human-readable display name for the connection. */ display_name?: string; /** * The identity provider of this connection. */ identity_provider?: string; }; type B2BSCIMCreateConnectionResponse = ResponseCommon & { connection: SCIMConnectionWithBearerToken; }; type B2BSCIMUpdateConnectionOptions = { /** * Globally unique UUID that identifies a specific SCIM Connection. */ connection_id: string; /** * A human-readable display name for the connection. */ display_name?: string; /** * The identity provider of this connection. */ identity_provider?: string; /** * An array of implicit role assignments granted to members in this organization who are created via this SCIM connection * and belong to the specified group. * Before adding any group implicit role assignments, you must first provision groups from your IdP into Stytch, * see our {@link https://stytch.com/docs/b2b/guides/scim/overview scim-guide}. * See our {@link https://stytch.com/docs/b2b/guides/rbac/role-assignment RBAC guide} for more information about * role assignment. */ scim_group_implicit_role_assignments?: { role_id: string; group_id: string; }[]; }; type B2BSCIMUpdateConnectionResponse = ResponseCommon & { connection: SCIMConnection; }; type B2BSCIMDeleteConnectionResponse = ResponseCommon & { /** * Globally unique UUID that identifies a specific SCIM Connection. */ connection_id: string; }; type B2BSCIMGetConnectionResponse = ResponseCommon & { connection: SCIMConnection; }; type B2BSCIMGetConnectionGroupsOptions = { /** * The maximum number of groups that should be returned by the API. */ limit?: number; /** * The cursor to use to indicate where to start group results. */ cursor?: string; }; type B2BSCIMGetConnectionGroupsResponse = ResponseCommon & { /** * List of SCIM Groups for the connection. */ scim_groups: SCIMGroup[]; /** * The cursor to use to get the next page of results. */ next_cursor: string | null; }; type B2BSCIMRotateStartResponse = ResponseCommon & { connection: SCIMConnectionWithNextBearerToken; }; type B2BSCIMRotateCompleteResponse = ResponseCommon & { connection: SCIMConnection; }; type B2BSCIMRotateCancelResponse = ResponseCommon & { connection: SCIMConnection; }; interface IHeadlessB2BSCIMClient { /** * The Create SCIM Connection method wraps the {@link https://stytch.com/docs/b2b/api/create-scim-connection Create SCIM Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to create SCIM connections in other Organizations. * * @example * stytch.scim.createConnection({ * display_name: 'My SCIM Connection', * identity_provider: 'okta' * }); * * @rbac action="create", resource="stytch.scim" * * @param data - {@link B2BSCIMCreateConnectionOptions} * * returns A {@link B2BSCIMCreateConnectionResponse} indicating that the SCIM connection has been created. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ createConnection(data: B2BSCIMCreateConnectionOptions): Promise; /** * Updates an existing SCIM connection. * This method wraps the {@link https://stytch.com/docs/b2b/api/update-scim-connection update-connection} endpoint. * If attempting to modify the `scim_group_implicit_role_assignments` the caller must have the `update.settings.implicit-roles` permission on the `stytch.organization` resource. * For all other fields, the caller must have the `update` permission on the `stytch.scim` resource. * SCIM via the project's RBAC policy & their role assignments. * * @example * stytch.scim.updateConnection({ * connection_id: 'connection-id-123', * display_name: 'My SCIM Connection', * identity_provider: 'okta', * scim_group_implicit_role_assignments: [ * { * group_id: 'group-id-123', * role_id: 'role-id-123' * } * ] * }); * * @rbac action="update", resource="stytch.scim" * * @param data - {@link B2BSCIMUpdateConnectionOptions} * * returns A {@link B2BSCIMUpdateConnectionResponse} indicating that the SCIM connection has been updated. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ updateConnection(data: B2BSCIMUpdateConnectionOptions): Promise; /** * The Delete SCIM Connection method wraps the {@link https://stytch.com/docs/b2b/api/delete-scim-connection Delete SCIM Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to delete SCIM connections in other Organizations. * * @example * stytch.scim.deleteConnection('connection-id-123'); * * @rbac action="delete", resource="stytch.scim" * * @param connectionId * * returns A {@link B2BSCIMDeleteConnectionResponse} indicating that the SCIM connection has been deleted. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ deleteConnection(connectionId: string): Promise; /** * The Get SCIM Connection method wraps the {@link https://stytch.com/docs/b2b/api/get-scim-connection Get SCIM Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to get SCIM connection from other Organizations. * * @example * stytch.scim.getConnection(); * * @rbac action="get", resource="stytch.scim" * * @param connectionId * * returns A {@link B2BSCIMGetConnectionResponse} indicating that the SCIM connection has been retrieved. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ getConnection(connectionId: string): Promise; /** * The Get SCIM Connection Groups method wraps the {@link https://stytch.com/docs/b2b/api/get-scim-connection-groups Get SCIM Connection} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * * @example * stytch.scim.getConnectionGroups({ * limit: 10 * }); * * @rbac action="get", resource="stytch.scim" * * @param data */ getConnectionGroups(data: B2BSCIMGetConnectionGroupsOptions): Promise; /** * The SCIM Rotate Token Start method wraps the {@link https://stytch.com/docs/b2b/api/scim-rotate-token-start SCIM Rotate Token Start} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to start token rotations for SCIM connections in other Organizations. * * @example * stytch.scim.rotateStart('connection-id-123'); * * @rbac action="update", resource="stytch.scim" * * @param connectionId * * returns A {@link B2BSCIMRotateStartResponse} containing a new bearer token * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ rotateStart(connectionId: string): Promise; /** * The SCIM Rotate Token Complete method wraps the {@link https://stytch.com/docs/b2b/api/scim-rotate-token-complete SCIM Rotate Token Complete} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to complete token rotations for SCIM connections in other Organizations. * * @example * stytch.scim.rotateComplete('connection-id-123'); * * @rbac action="update", resource="stytch.scim" * * @param connectionId * * returns A {@link B2BSCIMRotateCompleteResponse} containing a new bearer token * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ rotateComplete(connectionId: string): Promise; /** * The SCIM Rotate Token Cancel method wraps the {@link https://stytch.com/docs/b2b/api/scim-rotate-token-cancel SCIM Rotate Token Cancel} API endpoint. * The `organization_id` will be automatically inferred from the logged-in Member's session. * This method cannot be used to cancel token rotations for SCIM connections in other Organizations. * * @example * stytch.scim.rotateCancel('connection-id-123'); * * @rbac action="update", resource="stytch.scim" * * @param connectionId * * returns A {@link B2BSCIMRotateCancelResponse} containing a new bearer token * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input. */ rotateCancel(connectionId: string): Promise; } type B2BOAuthAuthorizeStartOptions = { client_id: string; redirect_uri: string; response_type: string; scopes: string[]; prompt?: string; }; type B2BOAuthAuthorizeStartResponse = ResponseCommon & { client: ConnectedAppPublic; consent_required: boolean; scope_results: ScopeResult[]; }; type B2BOAuthAuthorizeSubmitOptions = { client_id: string; redirect_uri: string; response_type: string; scopes: string[]; state?: string; nonce?: string; code_challenge?: string; consent_granted: boolean; prompt?: string; }; type B2BOAuthAuthorizeSubmitResponse = ResponseCommon & { redirect_uri: string; authorization_code?: string; }; type B2BOAuthLogoutStartOptions = { client_id: string; post_logout_redirect_uri: string; state: string; id_token_hint?: string; }; type B2BOAuthLogoutStartResponse = ResponseCommon & { redirect_uri: string; consent_required: boolean; }; interface IHeadlessB2BIDPClient { /** * Initiates a request for authorization of a Connected App to access a Member's account. * * Call this endpoint using the query parameters from an OAuth Authorization request. This endpoint validates various fields (scope, client_id, redirect_uri, prompt, etc...) are correct and returns relevant information for rendering an OAuth Consent Screen. * * @example * const response = await stytch.idp.oauthAuthorizeStart({ * client_id: 'client_123', * redirect_uri: 'https://example.com/callback', * scope: 'openid email profile', * }); */ oauthAuthorizeStart(data: B2BOAuthAuthorizeStartOptions): Promise; /** * Completes a request for authorization of a Connected App to access a Member's account. * * Call this endpoint using the query parameters from an OAuth Authorization request, after previously validating those parameters using the Preflight Check API. Note that this endpoint takes in a few additional parameters the preflight check does not- state, nonce, and code_challenge. * * If the authorization was successful, the redirect_uri will contain a valid authorization_code embedded as a query parameter. If the authorization was unsuccessful, the redirect_uri will contain an OAuth2.1 error_code. In both cases, redirect the Member to the location for the response to be consumed by the Connected App. * * Exactly one of the following must be provided to identify the Member granting authorization: * organization_id + member_id * session_token * session_jwt * * If a session_token or session_jwt is passed, the OAuth Authorization will be linked to the Member's session for tracking purposes. One of these fields must be used if the Connected App intends to complete the Exchange Access Token flow. * * @example * const response = await stytch.idp.oauthAuthorizeSubmit({ * client_id: 'client_123', * redirect_uri: 'https://example.com/callback', * scope: 'openid email profile', * }); */ oauthAuthorizeSubmit(data: B2BOAuthAuthorizeSubmitOptions): Promise; } type B2BImpersonationAuthenticateOptions = { /** * The impersonation token used to authenticate a member */ impersonation_token: string; }; type B2BImpersonationAuthenticateResponse = B2BAuthenticateResponseWithMFA; interface IHeadlessB2BImpersonationClient { /** * The authenticate method wraps the {@link https://stytch.com/docs/b2b/api/authenticate-impersonation-token authenticate} Impersonation API endpoint. * * See the {@link https://stytch.com/docs/b2b/sdks/javascript-sdk/impersonation#authenticate Stytch Docs} for a complete reference. * * @example * stytch.impersonation.authenticate({ * token: 'token', * }); * * @param data - {@link B2BImpersonationAuthenticateOptions} * * @returns A {@link B2BImpersonationAuthenticateResponse} indicating that the token has been authenticated and the impersonator is now logged in. * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid email, invalid options, etc.) */ authenticate(data: B2BImpersonationAuthenticateOptions): Promise>; } /** * An Error class representing an error within Stytch. */ declare class StytchError extends Error { constructor(name: string, message: string); } type StytchSDKErrorOptions = { url?: string; }; /** * An Error class used in the Stytch SDK. */ declare class StytchSDKError extends StytchError { options?: StytchSDKErrorOptions; constructor(name: string, description: string, options?: StytchSDKErrorOptions); } /** * The authentication methods we support through our UI. * Currently we support `emailMagicLinks`, `oauth`, `otp`, `crypto` and `passwords`. */ declare enum Products { emailMagicLinks = "emailMagicLinks", oauth = "oauth", otp = "otp", crypto = "crypto", passwords = "passwords", passkeys = "passkeys" } /** * The options for email magic links. This is used if you've enabled the `emailMagicLinks` product * in your configuration. */ type EmailMagicLinksOptions = { loginRedirectURL?: string; loginExpirationMinutes?: number; signupRedirectURL?: string; signupExpirationMinutes?: number; loginTemplateId?: string; signupTemplateId?: string; createUserAsPending?: boolean; /** * @param domainHint - An optional hint indicating what domain the email will be sent from. * This field is only required if your project uses more than one custom domain to send emails. */ domainHint?: string; locale?: string; }; /** * The OAuth providers we support in our OAuth product. * Currently we support `Amazon`, `Apple`, `Bitbucket`, `Discord`, `Facebook`, `Figma`, `Google`, `GitLab`, * `LinkedIn`, `Microsoft`, `Salesforce`, `Slack`, `Snapchat`, `TikTok`, `Twitch`, `Twitter`, and `Yahoo`. */ declare enum OAuthProviders { Google = "google", Microsoft = "microsoft", Apple = "apple", Github = "github", GitLab = "gitlab", Facebook = "facebook", Discord = "discord", Salesforce = "salesforce", Slack = "slack", Amazon = "amazon", Bitbucket = "bitbucket", LinkedIn = "linkedin", Coinbase = "coinbase", Twitch = "twitch", Twitter = "twitter", TikTok = "tiktok", Snapchat = "snapchat", Figma = "figma", Yahoo = "yahoo" } /** * Supported behaviors for positioning Google One Tap. The actual behavior * depends on browser support and Google's One Tap implementation. */ declare enum OneTapPositions { /** * Display Google One Tap using a native browser prompt if available, or * embedded in the existing SDK login form otherwise. * @deprecated This option has been renamed to `floatingOrEmbedded` */ embedded = "embedded", /** * Display the One Tap prompt using a native browser prompt if available, or * in the top right corner otherwise. This is the default option. */ floating = "floating", /** * Display the One Tap prompt embedded in the existing SDK login form if a * native browser prompt is not available, or not at all otherwise. This * option is not recommended for new applications. */ embeddedOnly = "embeddedOnly", /** * Display the One Tap prompt using a native browser prompt if available, or * embedded in the existing SDK login form otherwise. */ floatingOrEmbedded = "floatingOrEmbedded", /** * Attempt to display the One Tap prompt embedded in the existing SDK login * form, even if a native browser prompt is supported. This option is not * recommended. It disables native browser FedCM support even where it is * available, and will stop being honored by Google in the future. */ forceLegacyEmbedded = "forceLegacyEmbedded" } type ProviderOptions = { type: EnumOrStringLiteral; one_tap?: boolean; position?: EnumOrStringLiteral; /** * Whether to cancel the One Tap prompt when the user taps outside of it. * This is only applicable if one_tap is true. */ cancel_on_tap_outside?: boolean; custom_scopes?: string[]; provider_params?: Record; }; /** * An array of OAuth providers you wish to use. Each Provider is an object with a type key that * determines the type of provider. Each Provider accepts an optional custom_scopes array of * scopes that Stytch will request for your application in addition to the base set of scopes * required for login. The order of the providers in the array determines the order of the * rendered buttons. */ type ProvidersOptions = ProviderOptions[]; /** * The options for oAuth. This is required if you've enabled the `oauth` product * in your configuration. */ type OAuthOptions = { loginRedirectURL?: string; signupRedirectURL?: string; providers: ProvidersOptions; }; /** * The methods array allows you to specify the authentication methods that you would like to expose * to your users. The order of the products that you include here will also be the order in which * they appear in the login form, with the first product specified appearing at the top of the login * form. We currently support passcodes on `email`, `sms` and `whatsapp` */ declare enum OTPMethods { SMS = "sms", WhatsApp = "whatsapp", Email = "email" } /** * The options for One Time Passcodes. This is required if you've enabled the `otp` product * in your configuration. */ type OtpOptions = { methods: EnumOrStringLiteral[]; expirationMinutes: number; loginTemplateId?: string; signupTemplateId?: string; locale?: string; }; /** * The options for passwords. This is used if you've enabled the `passwords` product * in your configuration. */ type PasswordOptions = { loginRedirectURL?: string; loginExpirationMinutes?: number; resetPasswordRedirectURL?: string; resetPasswordExpirationMinutes?: number; resetPasswordTemplateId?: string; locale?: string; }; /** * The options for Session Management. If you are using the UI components, * we also create a session for users when they log in. */ type SessionOptions = { sessionDurationMinutes: number; }; type PasskeyOptions = { /** * Sets the domain option for both webauthn registration and authentication. * @default window.location.hostname */ domain?: string; }; /** * The configuration object for the Stytch SDK's UI */ type StytchLoginConfig = { /** * The products array allows you to specify the authentication methods that you would like to * expose to your users. The order of the products that you include here will also be the order * in which they appear in the login form, */ products: EnumOrStringLiteral[]; emailMagicLinksOptions?: EmailMagicLinksOptions; oauthOptions?: OAuthOptions; otpOptions?: OtpOptions; sessionOptions?: SessionOptions; passwordOptions?: PasswordOptions; passkeyOptions?: PasskeyOptions; /** * The `enableShadowDOM` configuration option allows developers to use the Stytch SDK in a shadow DOM. This defaults to `false`. */ enableShadowDOM?: boolean; }; declare enum RNUIProducts { emailMagicLinks = 0, oauth = 1, otp = 2, passwords = 3 } type RNUIEmailMagicLinksOptions = { loginExpirationMinutes?: number; signupExpirationMinutes?: number; loginTemplateId?: string; signupTemplateId?: string; locale?: string; }; type RNUIOAuthOptions = { providers: EnumOrStringLiteral[] | ProvidersOptions; /** @deprecated Use custom_scopes in ProvidersOptions instead */ customScopes?: string[]; /** @deprecated Use provider_params in ProvidersOptions instead */ providerParams?: Record; }; type RNUIOTPOptions = { methods: EnumOrStringLiteral[]; expirationMinutes: number; loginTemplateId?: string; signupTemplateId?: string; locale?: string; }; type RNUIPasswordOptions = { loginExpirationMinutes?: number; resetPasswordExpirationMinutes?: number; resetPasswordTemplateId?: string; locale?: string; }; type RNUIProductConfig = { products: RNUIProducts[]; emailMagicLinksOptions: RNUIEmailMagicLinksOptions; oAuthOptions: RNUIOAuthOptions; otpOptions: RNUIOTPOptions; sessionOptions: SessionOptions; passwordOptions: RNUIPasswordOptions; }; type ImpersonationAuthenticateOptions = { /** * The impersonation token used to authenticate a user */ impersonation_token: string; }; type ImpersonationAuthenticateResponse = AuthenticateResponse; interface IHeadlessImpersonationClient { /** * Wraps Stytch's {@link https://stytch.com/docs/api/authenticate-impersonation-token Authenticate Impersonation Token} endpoint. * The authenticate method wraps the consumer impersonation authenticate endpoint. * * @param data - {@link ImpersonationAuthenticateOptions} * @returns A {@link ImpersonationAuthenticateResponse} indicating that the token has been authenticated * * @throws A `StytchAPIError` when the Stytch API returns an error. * @throws A `StytchAPIUnreachableError` when the SDK cannot contact the Stytch API. * @throws A `StytchSDKUsageError` when called with invalid input (invalid token, invalid options, etc.) */ authenticate(data: ImpersonationAuthenticateOptions): Promise>; } type Actions$0 = Record; type ConsumerPermissionsMap> = { [ResourceID in keyof Permissions]: Actions$0; }; interface IHeadlessRBACClient { /** * The `isAuthorizedSync` method determines whether the logged-in user is allowed to perform the specified action on the specified resource. * Returns `true` if the user can perform the action, `false` otherwise. * * If the user is not logged in, or the RBAC policy has not been loaded, this method will always return false. * If the resource or action provided are not valid for the configured RBAC policy, this method will return false. * @example * const isAuthorized = stytch.rbac.isAuthorizedSync('document', 'image'); */ isAuthorizedSync(resourceId: string, action: string): boolean; /** * The `isAuthorized` method determines whether the logged-in user is allowed to perform the specified action on the specified resource. * It will return a Promise that resolves after the RBAC policy has been loaded. Returns `true` if the user can perform the action, `false` otherwise. * * If the user is not logged in, this method will always return false. * If the resource or action provided are not valid for the configured RBAC policy, this method will return false. * * @example * const isAuthorized = await stytch.rbac.isAuthorizedSync('document', 'image'); */ isAuthorized(resourceId: string, action: string): Promise; /** * The `allPermissions` method returns the complete list of permissions assigned to the currently logged-in user. If the user is not logged in, all values will be `false`. * * As a best practice, authorization checks for sensitive actions should also occur on the backend. * * @example * type Permissions = { * document: 'create' | 'read' | 'write * image: 'create' | 'read' * } * const permissions = await stytch.rbac.allPermissions(); * console.log(permissions.document.create) // true * console.log(permissions.image.create) // false * @returns A {@link ConsumerPermissionsMap} for the active member */ allPermissions>(): Promise>; } type OAuthAuthorizeStartOptions = { client_id: string; redirect_uri: string; response_type: string; scopes: string[]; prompt?: string; }; type OAuthAuthorizeStartResponse = ResponseCommon & { user_id: string; user: User; client: ConnectedAppPublic; consent_required: boolean; scope_results: ScopeResult[]; }; type OAuthAuthorizeSubmitOptions = { client_id: string; redirect_uri: string; response_type: string; scopes: string[]; state?: string; nonce?: string; code_challenge?: string; consent_granted: boolean; prompt?: string; resource?: string[]; }; type OAuthAuthorizeSubmitResponse = ResponseCommon & { redirect_uri: string; authorization_code?: string; }; type OAuthLogoutStartOptions = { client_id: string; post_logout_redirect_uri: string; state?: string; id_token_hint?: string; }; type OAuthLogoutStartResponse = ResponseCommon & { redirect_uri: string; consent_required: boolean; }; interface IHeadlessIDPClient { /** * Initiates a request for authorization of a Connected App to access a User's account. * * Call this endpoint using the query parameters from an OAuth Authorization request. This endpoint validates various fields (scope, client_id, redirect_uri, prompt, etc...) are correct and returns relevant information for rendering an OAuth Consent Screen. * * @param data - The options for the OAuth authorization flow. * @returns The response from the OAuth authorization flow. * @example * const response = await stytch.idp.oauthAuthorizeStart({ * client_id: 'client_123', */ oauthAuthorizeStart(data: OAuthAuthorizeStartOptions): Promise; /** * Completes a request for authorization of a Connected App to access a Member's account. * * Call this endpoint using the query parameters from an OAuth Authorization request, after previously validating those parameters using the Preflight Check API. Note that this endpoint takes in a few additional parameters the preflight check does not- state, nonce, and code_challenge. * * If the authorization was successful, the redirect_uri will contain a valid authorization_code embedded as a query parameter. If the authorization was unsuccessful, the redirect_uri will contain an OAuth2.1 error_code. In both cases, redirect the Member to the location for the response to be consumed by the Connected App. * * Exactly one of the following must be provided to identify the Member granting authorization: * organization_id + member_id * session_token * session_jwt * * If a session_token or session_jwt is passed, the OAuth Authorization will be linked to the Member's session for tracking purposes. One of these fields must be used if the Connected App intends to complete the Exchange Access Token flow. * * @param data - The options for the OAuth authorization flow. * @returns The response from the OAuth authorization flow. * @example * const response = await stytch.idp.oauthAuthorizeSubmit({ * client_id: 'client_123', * redirect_uri: 'https://example.com/callback', * scope: 'openid email profile', * }); */ oauthAuthorizeSubmit(data: OAuthAuthorizeSubmitOptions): Promise; } type TokenType = "magic_links" | "oauth" | "reset_password"; declare enum EmailSentType { LoginOrCreateEML = "login_or_create_eml", LoginOrCreateOTP = "login_or_create_otp", ResetPassword = "reset_password" } type AnalyticsEvent = { name: "sdk_instance_instantiated"; details: { event_callback_registered: boolean; error_callback_registered: boolean; success_callback_registered: boolean; }; } | { name: "b2b_sdk_instance_instantiated"; details: { event_callback_registered: boolean; error_callback_registered: boolean; success_callback_registered: boolean; }; } | { name: "render_login_screen"; details: { options: StytchLoginConfig | RNUIProductConfig; bootstrap: BootstrapData; }; } | { name: "render_b2b_login_screen"; details: { options: StytchB2BUIConfig; bootstrap: BootstrapData; }; } | { name: "render_idp_screen"; details: { bootstrap: BootstrapData; }; } | { name: "render_b2b_idp_screen"; details: { bootstrap: BootstrapData; }; } | { name: "email_sent"; details: { email: string; type: EmailSentType; }; } | { name: "email_try_again_clicked"; details: { email: string; type: EmailSentType; }; } | { name: "start_oauth_flow"; details: { provider_type: string; custom_scopes?: string[]; cname_domain: string | null; pkce: boolean; provider_params?: Record; }; } | { name: "deeplink_handled_success"; details: { token_type: TokenType; }; } | { name: "deeplink_handled_failure"; details: { error: StytchSDKError | undefined; }; } | { name: "oauth_success"; details: { provider_type: string; }; } | { name: "oauth_failure"; details: { error: StytchSDKError | string | undefined; }; } | { name: "ui_authentication_success"; details: { method: "oauth" | "otp" | "magicLinks" | "passwords"; }; } | { name: "render_b2b_admin_portal_sso"; details: Record; } | { name: "render_b2b_admin_portal_org_settings"; details: Record; } | { name: "render_b2b_admin_portal_member_management"; details: Record; } | { name: "render_b2b_admin_portal_scim"; details: Record; }; type SDKRequestMethodAndBody = { method: "GET" | "DELETE"; body?: null; } | { method: "POST" | "PUT"; body?: Record; }; type SDKRequestInfo = SDKRequestMethodAndBody & { url: string; additionalMetadata?: Record; }; interface SDKTelemetry { event_id: string; app_session_id: string; persistent_id: string; client_sent_at: string; timezone: string; // Logged in user data // Why don't we generate this from the session_token in the auth header? // - We don't want to tie analytics ingest to session validation. There's no need to put // that kind of pressure on API, and ingest could be moved to somewhere that doesn't // have the ability to validate tokens // - For bulk event batches, we want to keep track of whether or not a user was logged // in at each event. If we have 10 events, the user logs in at event 5, then they'll have // a token when they log the batch, but we want to know that they were not logged in for the // first 4 events // Versioning app: { identifier: string; version?: string; }; os?: { identifier?: string; version?: string; }; device?: { model?: string; screen_size?: string; }; sdk: { identifier: string; version: string; }; } type AdditionalTelemetryData = { stytch_user_id?: string; stytch_session_id?: string; } | { stytch_member_id?: string; stytch_member_session_id?: string; }; interface INetworkClient { createTelemetryBlob(additionalMetadata?: SDKRequestInfo["additionalMetadata"]): SDKTelemetry; fetchSDK: (info: SDKRequestInfo) => Promise; retriableFetchSDK: (info: RetriableSDKRequestInfo) => Promise; logEvent({ name, details, error }: { name: E["name"]; details: E["details"]; error?: { error_code?: string; error_description?: string; http_status_code?: string; }; }): void; // @deprecated Use the new sessions.updateSession() method instead updateSessionToken: (sessionToken: string | null) => void; } type RetriableSDKRequestInfo = SDKRequestInfo & { retryCallback: (e: RetriableError, info: SDKBaseRequestInfo) => Promise; }; type RetriableSDKBaseRequestInfo = SDKBaseRequestInfo & { retryCallback: (e: RetriableError, info: SDKBaseRequestInfo) => Promise; }; declare enum RetriableErrorType { RequiredCaptcha = "CAPTCHA required" } declare class RetriableError extends Error { type: RetriableErrorType; constructor(type: RetriableErrorType); } declare function retriableFetchSDK({ method, finalURL, basicAuthHeader, xSDKClientHeader, xSDKParentHostHeader, body, retryCallback }: RetriableSDKBaseRequestInfo): Promise; type SDKBaseRequestInfo = { basicAuthHeader: string; xSDKClientHeader: string; xSDKParentHostHeader?: string; body: SDKRequestInfo["body"]; method: SDKRequestInfo["method"]; finalURL: string; }; declare function baseFetchSDK({ method, finalURL, basicAuthHeader, xSDKClientHeader, xSDKParentHostHeader, body }: SDKBaseRequestInfo): Promise; declare function baseSubmitFormSDK({ method, finalURL, basicAuthHeader, xSDKClientHeader, xSDKParentHostHeader, body }: SDKBaseRequestInfo): Promise; declare global { // The telemetry.js script will set a global function called GetTelemetryID on the window // object. This interface is allows us to call that function while pleasing the TypeScript // compiler. interface Window { GetTelemetryID: (publicToken: string, submitURL: string) => Promise; } } type DFPProtectedAuthMode = "OBSERVATION" | "DECISIONING"; type DFPProtectedAuthState = { publicToken: string; dfpBackendURL: string; mode?: DFPProtectedAuthMode; enabled: boolean; loaded: boolean; executeRecaptcha: () => Promise; }; declare class DFPProtectedAuthProvider { private bootstrapPromise; private state; constructor(publicToken: string, dfpBackendURL: string, dfpCdnDomain: string, bootstrapPromise: Promise, executeRecaptcha?: () => Promise); isEnabled: () => Promise; getTelemetryID: () => Promise; getDFPTelemetryIDAndCaptcha: () => Promise<{ dfp_telemetry_id?: string | undefined; captcha_token?: string | undefined; }>; retryWithCaptchaAndDFP: (e: RetriableError, req: SDKBaseRequestInfo) => Promise; } declare const DisabledDFPProtectedAuthProvider: () => { isEnabled: () => Promise; getTelemetryID: () => Promise; getDFPTelemetryIDAndCaptcha: () => Promise<{ dfp_telemetry_id: undefined; captcha_token: undefined; }>; retryWithCaptchaAndDFP: () => Promise; }; interface IDFPProtectedAuthProvider { isEnabled(): Promise; getTelemetryID(): Promise; retryWithCaptchaAndDFP(e: RetriableError, req: SDKBaseRequestInfo): Promise; getDFPTelemetryIDAndCaptcha(): Promise<{ dfp_telemetry_id?: string; captcha_token?: string; }>; } /** * Some errors are thrown from inside an iframe, but we can't serialize them * to the parent in Webkit. This class handles restoring marshalled errors * to their original form. * It preserves the error instance/class constructor by inspecting err.name * and calling `new` on the matching constructor. */ declare class ErrorMarshaller { static inflate Error>(ErrorClass: T, ErrorData: Record): Error; static unmarshall(error: Record): Error; } declare const DEFAULT_MAX_BATCH_SIZE = 15; declare const DEFAULT_INTERVAL_DURATION_MS = 800; type EventLoggerArgs = { maxBatchSize: number; intervalDurationMs: number; logEventURL: string; }; declare class EventLogger { private maxBatchSize; private logEventURL; private batch; constructor(args: EventLoggerArgs); logEvent(telemetry: SDKTelemetry, event: Record): void; flush(): Promise; } declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace Stytch { /** * Configuration for a Stytch project. This represents aspects of project * configuration that are controlled via the Stytch dashboard, but affect * SDK behavior. You can extend from this type for improved type safety when * creating your own project configuration. * * To specify a default project configuration for your entire project, * augment {@link DefaultProjectConfiguration} via declaration merging. For * more advanced use cases, many types accept `StytchProjectConfiguration` * as a generic type parameter directly. * * This type is equivalent to the exported `ProjectConfiguration` type; it * is defined in the `Stytch` namespace for convenience. * * @example * interface MyProjectConfiguration extends Stytch.ProjectConfiguration { * OpaqueTokens: true; * } * * const client = new StytchClient(...); */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type interface ProjectConfiguration extends StytchProjectConfiguration { } /** * The default project configuration. This project configuration is used * unless another configuration is specified (to another type, function, * etc.) via a generic type parameter. You can use declaration merging to * augment this type for your application. * * @example * // stytch.d.ts * declare namespace Stytch { * interface DefaultProjectConfiguration extends ProjectConfiguration { * OpaqueTokens: true; * } * } */ // eslint-disable-next-line @typescript-eslint/no-empty-object-type interface DefaultProjectConfiguration extends ProjectConfiguration { } } } interface StorageResponse { success: boolean; message?: string; } interface IStorageClient { getData: (key: string) => Promise; setData: (key: string, data: string) => Promise; clearData: (key: string) => Promise; } type SubscriberFunction = (value: T | null) => void; type Subscribers = Record>; declare class SubscriptionDataLayer { private _publicToken; private _storageClient; state: T | null; session_token: string | null; session_jwt: string | null; intermediate_session_token: string | null; intermediate_session_token_expiration: number | null; subscriptions: Subscribers; constructor(_publicToken: string, _storageClient: IStorageClient); syncToLocalStorage(): void; syncFromLocalStorage: () => Promise | null>; } type StateWithReadableTokensLoggedIn = { state: TState | null; intermediate_session_token: null; session_token: string; session_jwt: string; }; type StateWithOpaqueTokensLoggedIn = { state: TState | null; intermediate_session_token: null; session_token: true; session_jwt: true; }; type StateWithTokensLoggedIn = IfOpaqueTokens, StateWithReadableTokensLoggedIn>; type StateWithTokensLoggedOut = { state: null; session_token: null; session_jwt: null; intermediate_session_token: null; }; type StateWithReadableIntermediateSessionToken = { state: null; session_token: null; session_jwt: null; intermediate_session_token: string; }; type StateWithOpaqueIntermediateSessionToken = { state: null; session_token: null; session_jwt: null; intermediate_session_token: true; }; type StateWithIntermediateSessionToken = IfOpaqueTokens; type StateWithTokensDiff = StateWithTokensLoggedIn | StateWithTokensLoggedOut | StateWithIntermediateSessionToken; // Ensures sessionDurationMinutes is only set if state is not coming from cache type InternalSessionUpdateOptions = { fromCache: true; } | ({ fromCache: false; } & SessionUpdateOptions); interface CommonAuthenticateOptions { session_duration_minutes?: number; // Needed so TS does not complain about "no properties in common" error [key: string]: unknown; } interface ISubscriptionService { updateStateAndTokens(diff: StateWithTokensDiff): void; updateState(state: TState): void; updateTokens(tokens: SessionTokensUpdate): void; destroyState(): void; destroySession(): void; getTokens(): IfOpaqueTokens; getIntermediateSessionToken(): string | null; subscribeToState(callback: SubscriberFunction<(TState & SessionUpdateOptions) | null>): UnsubscribeFunction; getState(): TState | null; syncFromDeviceStorage(onCompleteCallback: () => void): void; getFromCache(): boolean; setCacheRefreshed(): void; } interface IConsumerSubscriptionService extends ISubscriptionService { updateSession(args: AuthenticateResponse, options?: SessionUpdateOptions): void; /** * Decorator version of updateSession that wraps an existing authenticate() implementation to bind its response * to subscriptionService.updateSession(). */ withUpdateSession< // These are a bit messy to be able to type all authenticate() implementations Args extends [ ] | [ options?: CommonAuthenticateOptions ] | (string | CommonAuthenticateOptions)[], Ret extends AuthenticateResponse | null>(authenticate: (...args: Args) => Promise): (...args: Args) => Promise; updateUser(user: User): void; getUser(): User | null; getSession(): Session | null; } interface IB2BSubscriptionService extends ISubscriptionService { updateSession(args: B2BAuthenticateResponse | B2BAuthenticateResponseWithMFA | B2BDiscoveryAuthenticateResponse, options?: SessionUpdateOptions): void; /** * Decorator version of updateSession that wraps an existing authenticate() implementation to bind its response * to subscriptionService.updateSession() */ withUpdateSession | B2BAuthenticateResponseWithMFA | B2BDiscoveryAuthenticateResponse>(authenticate: (options: Options) => Promise): (options: Options) => Promise; updateMember(member: Member): void; getMember(): Member | null; updateOrganization(organization: Organization): void; getOrganization(): Organization | null; getSession(): MemberSession | null; } declare class SubscriptionService implements ISubscriptionService { private _datalayer; /** * Whether the state was retrieved from the cache and is awaiting a refresh */ private fromCache; constructor(publicToken: string, storageClient: IStorageClient); syncFromDeviceStorage(onCompleteCallback: () => void): void; getState(): T | null; getTokens(): SessionTokens | null; removeIST(): void; removeSessionTokens(): void; getIntermediateSessionToken(): string | null; destroyState(): void; destroySession(): void; _updateStateAndTokensInternal(stateDiff: StateWithTokensDiff, options: InternalSessionUpdateOptions): void; updateStateAndTokens(stateDiff: StateWithTokensDiff, options?: InternalSessionUpdateOptions): void; updateState(state: T | null): void; updateTokens(tokens: SessionTokensUpdate): void; subscribeToState(callback: SubscriberFunction): UnsubscribeFunction; getFromCache(): boolean; setCacheRefreshed(): void; } declare class ConsumerSubscriptionService extends SubscriptionService implements IConsumerSubscriptionService { updateSession: IConsumerSubscriptionService["updateSession"]; withUpdateSession: | null>(authenticate: (...args: Args) => Promise) => (...args: Args) => Promise; updateUser: (user: User) => void; getUser: () => User | null; getSession: () => Session | null; } declare class B2BSubscriptionService extends SubscriptionService implements IB2BSubscriptionService { updateSession: IB2BSubscriptionService["updateSession"]; withUpdateSession: | B2BAuthenticateResponseWithMFA | B2BDiscoveryAuthenticateResponse>(authenticate: (options: Options) => Promise) => (options: Options) => Promise; updateMember: (member: Member) => void; getMember: () => Member | null; updateOrganization: (organization: Organization) => void; getOrganization: () => Organization | null; getSession: () => MemberSession | null; } declare class HeadlessUserClient implements IHeadlessUserClient { private _networkClient; private _subscriptionService; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService); get: () => Promise>; getSync: () => User | null; getInfo: () => UserInfo; update: (options: UserUpdateOptions) => Promise; deleteEmail: (emailId: string) => Promise; deletePhoneNumber: (phoneId: string) => Promise; deleteTOTP: (totpId: string) => Promise; deleteCryptoWallet: (cryptoWalletId: string) => Promise; deleteOAuthRegistration: (oauthUserRegistrationId: string) => Promise; deleteWebauthnRegistration: (webAuthnId: string) => Promise; deleteBiometricRegistration: (biometricRegistrationId: string) => Promise; onChange: (callback: UserOnChangeCallback) => UnsubscribeFunction; getConnectedApps: () => Promise; revokedConnectedApp: (connectedAppId: string) => Promise; } declare class HeadlessSessionClient implements IHeadlessSessionClient { private _networkClient; private _subscriptionService; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService); getSync: () => Session | null; getInfo: () => SessionInfo; onChange: (callback: SessionOnChangeCallback) => UnsubscribeFunction; revoke: (options?: SessionRevokeOptions) => Promise; private _authenticate; authenticate: (options?: Partial | undefined) => Promise>; exchangeAccessToken: (data: SessionAccessTokenExchangeOptions) => Promise : T extends false ? { session_token: string; session_jwt: string; } : { session_token: string; session_jwt: string; } | Redacted<{ session_token: string; session_jwt: string; }, ""> : never : never) & { __user: User & ResponseCommon; }>; getTokens(): IfOpaqueTokens, never, SessionTokens$0 | null>; updateSession(tokens: SessionTokensUpdate): void; attest: (data: SessionAttestOptions) => Promise>; } type ProofkeyPair = { code_challenge: string; code_verifier: string; }; interface IPKCEManager { startPKCETransaction(): Promise; getPKPair(): AsyncGetPKPair | SyncGetPKPair; clearPKPair(): Promise | void; } type AsyncGetPKPair = Promise; type SyncGetPKPair = ProofkeyPair | undefined; interface IAsyncPKCEManager extends IPKCEManager { startPKCETransaction(): Promise; getPKPair(): AsyncGetPKPair; clearPKPair(): Promise; } interface ISyncPKCEManager extends IPKCEManager { startPKCETransaction(): Promise; getPKPair(): SyncGetPKPair; clearPKPair(): void; } type DynamicConfig = Promise<{ pkceRequiredForEmailMagicLinks: boolean; }>; declare class HeadlessMagicLinksClient implements IHeadlessMagicLinksClient { private _networkClient; private _subscriptionService; private _pkceManager; private _passwordResetPKCEManager; private _config; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, _pkceManager: IPKCEManager, _passwordResetPKCEManager: IPKCEManager, _config: DynamicConfig, dfpProtectedAuth: IDFPProtectedAuthProvider); private getCodeChallenge; private handlePKCEForAuthenticate; email: { loginOrCreate: (email: string, options?: MagicLinksLoginOrCreateOptions) => Promise; send: (email: string, options?: MagicLinksSendOptions) => Promise; }; authenticate: (token: string, options: SessionDurationOptions) => Promise : T extends false ? { session_token: string; session_jwt: string; } : { session_token: string; session_jwt: string; } | Redacted<{ session_token: string; session_jwt: string; }, ""> : never : never) & { method_id: string; } & { __user: User & ResponseCommon; }>; } declare class HeadlessOTPClient implements IHeadlessOTPsClient { private _networkClient; private _subscriptionService; private executeRecaptcha; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, executeRecaptcha: () => Promise, dfpProtectedAuth: IDFPProtectedAuthProvider); sms: { loginOrCreate: (phone_number: string, options: OTPCodeSMSOptions) => Promise; send: (phone_number: string, options: OTPCodeSMSOptions) => Promise; }; whatsapp: { loginOrCreate: (phone_number: string, options: OTPCodeOptions) => Promise; send: (phone_number: string, options: OTPCodeOptions) => Promise; }; email: { loginOrCreate: (email: string, options: OTPCodeEmailOptions) => Promise; send: (email: string, options: OTPCodeEmailOptions) => Promise; }; authenticate: (code: string, method_id: string, options: OTPAuthenticateOptions) => Promise : T extends false ? { session_token: string; session_jwt: string; } : { session_token: string; session_jwt: string; } | Redacted<{ session_token: string; session_jwt: string; }, ""> : never : never) & { method_id: string; user_device?: SDKDeviceHistory | undefined; } & { __user: User & ResponseCommon; }>; } type DynamicConfig$0 = Promise<{ cnameDomain: null | string; pkceRequiredForOAuth: boolean; }>; type Config = { publicToken: string; testAPIURL: string; liveAPIURL: string; }; declare class HeadlessOAuthClient implements IHeadlessOAuthClient { private _networkClient; private _subscriptionService; private _pkceManager; private _dynamicConfig; private _config; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, _pkceManager: IPKCEManager, _dynamicConfig: DynamicConfig$0, _config: Config); google: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; apple: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; microsoft: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; github: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; gitlab: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; facebook: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; discord: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; salesforce: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; slack: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; amazon: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; bitbucket: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; linkedin: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; coinbase: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; twitch: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; twitter: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; tiktok: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; snapchat: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; figma: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; yahoo: { start: ({ login_redirect_url, signup_redirect_url, custom_scopes, provider_params, oauth_attach_token }?: OAuthGetURLOptions) => Promise; }; authenticate: (token: string, options: SessionDurationOptions) => Promise : T extends false ? { session_token: string; session_jwt: string; } : { session_token: string; session_jwt: string; } | Redacted<{ session_token: string; session_jwt: string; }, ""> : never : never) & { provider_subject: string; provider_type: string; profile_picture_url: string; locale: string; provider_values: { access_token: string; id_token: string; refresh_token: string; scopes: string[]; expires_at: string; }; } & { __user: User & ResponseCommon; }>; attach(provider: string): Promise; private getBaseApiUrl; private startOAuthFlow; } type DynamicConfig$1 = Promise<{ siweRequiredForCryptoWallets: boolean; }>; declare class HeadlessCryptoWalletClient implements IHeadlessCryptoWalletClient { private _networkClient; private _apiNetworkClient; private _subscriptionService; private executeRecaptcha; private dfpProtectedAuth; private _config; constructor(_networkClient: INetworkClient, _apiNetworkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, executeRecaptcha: () => Promise, dfpProtectedAuth: IDFPProtectedAuthProvider, _config?: DynamicConfig$1); authenticateStart(options: CryptoWalletAuthenticateStartOptions): Promise; authenticate: (options: CryptoWalletAuthenticateOptions) => Promise>; } declare class HeadlessTOTPClient implements IHeadlessTOTPClient { private _networkClient; private _subscriptionService; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, dfpProtectedAuth: IDFPProtectedAuthProvider); create(options: TOTPCreateOptions): Promise; authenticate: (options: TOTPAuthenticateOptions) => Promise>; recoveryCodes(): Promise; recover: (options: TOTPRecoverOptions) => Promise>; } declare class HeadlessWebAuthnClient implements IHeadlessWebAuthnClient { _networkClient: INetworkClient; private _subscriptionService; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, dfpProtectedAuth: IDFPProtectedAuthProvider); register: (options?: WebAuthnRegisterStartOptions | undefined) => Promise>; authenticate: (options: WebAuthnAuthenticateStartOptions) => Promise | null>; update(options: WebAuthnUpdateOptions): Promise; browserSupportsAutofill(): Promise; private checkEligibleInputs; } type DynamicConfig$2 = Promise<{ pkceRequiredForPasswordResets: boolean; }>; declare class HeadlessPasswordClient implements IHeadlessPasswordClient { private _networkClient; private _subscriptionService; private _pkceManager; private _config; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, _pkceManager: IPKCEManager, _config: DynamicConfig$2, dfpProtectedAuth: IDFPProtectedAuthProvider); private getCodeChallenge; create: (options: PasswordCreateOptions) => Promise>; authenticate: (options: PasswordAuthenticateOptions) => Promise>; resetByEmailStart(options: PasswordResetByEmailStartOptions): Promise; resetByEmail: (options: PasswordResetByEmailOptions) => Promise>; resetByExistingPassword: (options: PasswordResetByExistingPasswordOptions) => Promise>; resetBySession: (options: PasswordResetBySessionOptions) => Promise>; strengthCheck(options: PasswordStrengthCheckOptions): Promise; } declare class HeadlessImpersonationClient implements IHeadlessImpersonationClient { private _networkClient; private _subscriptionService; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IConsumerSubscriptionService, dfpProtectedAuth: IDFPProtectedAuthProvider); authenticate: (data: ImpersonationAuthenticateOptions) => Promise>; } type CachedConfig = { rbacPolicy: RBACPolicyRaw | null; }; type DynamicConfig$3 = Promise; declare class HeadlessRBACClient implements IHeadlessRBACClient { private _subscriptionService; private cachedPolicy; private policyPromise; constructor(cachedConfig: CachedConfig, dynamicConfig: DynamicConfig$3, _subscriptionService: IConsumerSubscriptionService); allPermissions>(): Promise>; isAuthorizedSync: IHeadlessRBACClient["isAuthorizedSync"]; isAuthorized: IHeadlessRBACClient["isAuthorized"]; private roleIds; } declare class HeadlessIDPClient implements IHeadlessIDPClient { private _networkClient; constructor(_networkClient: INetworkClient); oauthAuthorizeStart: (data: OAuthAuthorizeStartOptions) => Promise; oauthAuthorizeSubmit: (data: OAuthAuthorizeSubmitOptions) => Promise; oauthLogoutStart: (data: OAuthLogoutStartOptions) => Promise; } type DynamicConfig$4 = Promise<{ pkceRequiredForEmailMagicLinks: boolean; }>; declare class HeadlessB2BMagicLinksClient implements IHeadlessB2BMagicLinksClient { private _networkClient; private _subscriptionService; private _pkceManager; private _passwordResetPKCEManager; private _config; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, _pkceManager: IPKCEManager, _passwordResetPKCEManager: IPKCEManager, _config?: DynamicConfig$4, dfpProtectedAuth?: IDFPProtectedAuthProvider); private getCodeChallenge; private handlePKCEForAuthenticate; email: { invite: (data: B2BMagicLinksInviteOptions) => Promise; loginOrSignup: (data: B2BMagicLinkLoginOrSignupOptions) => Promise; discovery: { send: (data: B2BMagicLinksEmailDiscoverySendOptions) => Promise; }; }; authenticate: (options: B2BMagicLinksAuthenticateOptions) => Promise>; discovery: { authenticate: (options: B2BMagicLinksDiscoveryAuthenticateOptions) => Promise>; }; } declare class HeadlessB2BSelfClient implements IHeadlessB2BSelfClient { private _networkClient; private _apiNetworkClient; private _subscriptionService; constructor(_networkClient: INetworkClient, _apiNetworkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService); get: () => Promise; getSync: () => Member | null; getInfo: () => MemberInfo; onChange: (callback: B2BMemberOnChangeCallback) => UnsubscribeFunction; update: (data: B2BMemberUpdateOptions) => Promise; deleteMFAPhoneNumber: () => Promise; deleteMFATOTP: () => Promise; deletePassword: (passwordId: string) => Promise; unlinkRetiredEmail: (data: B2BMemberUnlinkRetiredEmailRequest) => Promise; startEmailUpdate: (data: B2BMemberStartEmailUpdateRequest) => Promise; getConnectedApps: () => Promise; revokeConnectedApp: (data: B2BMemberRevokeConnectedAppOptions) => Promise; } type DynamicConfig$5 = Promise<{ pkceRequiredForSso: boolean; }>; type Config$0 = { publicToken: string; testAPIURL: string; liveAPIURL: string; }; declare class HeadlessB2BSSOClient implements IHeadlessB2BSSOClient { protected _networkClient: INetworkClient; protected _subscriptionService: IB2BSubscriptionService; protected _pkceManager: IPKCEManager; protected _dynamicConfig: DynamicConfig$5; protected _config: Config$0; protected dfpProtectedAuth: IDFPProtectedAuthProvider; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, _pkceManager: IPKCEManager, _dynamicConfig: DynamicConfig$5, _config: Config$0, dfpProtectedAuth: IDFPProtectedAuthProvider); authenticate: (options: SSOAuthenticateOptions) => Promise>; protected getBaseApiUrl(): Promise; start({ connection_id, login_redirect_url, signup_redirect_url }: SSOStartOptions): Promise; getConnections(): Promise; discoverConnections(emailAddress: string): Promise; deleteConnection(connectionId: string): Promise; saml: { createConnection: (data: B2BSSOSAMLCreateConnectionOptions) => Promise; updateConnection: (data: B2BSSOSAMLUpdateConnectionOptions) => Promise; updateConnectionByURL: (data: B2BSSOSAMLUpdateConnectionByURLOptions) => Promise; deleteVerificationCertificate: (data: B2BSSOSAMLDeleteVerificationCertificateOptions) => Promise; deleteEncryptionPrivateKey: (data: B2BSSOSAMLDeleteEncryptionPrivateKeyOptions) => Promise; }; oidc: { createConnection: (data: B2BSSOOIDCCreateConnectionOptions) => Promise; updateConnection: (data: B2BSSOOIDCUpdateConnectionOptions) => Promise; }; external: { createConnection: (data: B2BSSOCreateExternalConnectionOptions) => Promise; updateConnection: (data: B2BSSOUpdateExternalConnectionOptions) => Promise; }; } declare class HeadlessB2BSCIMClient implements IHeadlessB2BSCIMClient { protected _networkClient: INetworkClient; protected _subscriptionService: IB2BSubscriptionService; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService); createConnection(data: B2BSCIMCreateConnectionOptions): Promise; updateConnection(data: B2BSCIMUpdateConnectionOptions): Promise; deleteConnection(connectionId: string): Promise; getConnection(): Promise; getConnectionGroups(data: B2BSCIMGetConnectionGroupsOptions): Promise; rotateStart(connectionId: string): Promise; rotateComplete(connectionId: string): Promise; rotateCancel(connectionId: string): Promise; } declare class HeadlessB2BOrganizationClient implements IHeadlessB2BOrganizationClient { private _networkClient; private _apiNetworkClient; private _subscriptionService; constructor(_networkClient: INetworkClient, _apiNetworkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService); get: () => Promise; getSync: () => Organization | null; getInfo: () => OrganizationInfo; onChange: (callback: (organization: Organization | null) => void) => UnsubscribeFunction; update: (data: B2BOrganizationsUpdateOptions) => Promise; delete: () => Promise; getBySlug: (data: B2BOrganizationsGetBySlugOptions) => Promise; getConnectedApps: () => Promise; getConnectedApp: (data: B2BOrganizationsGetConnectedAppOptions) => Promise; members: { create: (data: B2BOrganizationsMembersCreateOptions) => Promise; search: (data: B2BOrganizationsMembersSearchOptions) => Promise; update: (data: B2BOrganizationsMembersUpdateOptions) => Promise; deletePassword: (passwordId: string) => Promise; deleteMFAPhoneNumber: (memberId: string) => Promise; deleteMFATOTP: (memberId: string) => Promise; delete: (memberId: string) => Promise; reactivate: (memberId: string) => Promise; unlinkRetiredEmail: (data: B2BOrganizationsMemberUnlinkRetiredEmailOptions) => Promise; startEmailUpdate: (data: B2BOrganizationsMemberStartEmailUpdateOptions) => Promise; getConnectedApps: (data: B2BOrganizationsMemberGetConnectedAppsOptions) => Promise; revokeConnectedApp: (data: B2BOrganizationsMemberRevokeConnectedAppOptions) => Promise; }; private updateMemberIfSelf; } type DynamicConfig$6 = Promise<{ cnameDomain: null | string; pkceRequiredForOAuth: boolean; }>; type Config$1 = { publicToken: string; testAPIURL: string; liveAPIURL: string; }; declare class HeadlessB2BOAuthClient implements IHeadlessB2BOAuthClient { protected _networkClient: INetworkClient; protected _subscriptionService: IB2BSubscriptionService; protected _pkceManager: IPKCEManager; protected _dynamicConfig: DynamicConfig$6; protected _config: Config$1; protected dfpProtectedAuth: IDFPProtectedAuthProvider; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, _pkceManager: IPKCEManager, _dynamicConfig: DynamicConfig$6, _config: Config$1, dfpProtectedAuth: IDFPProtectedAuthProvider); authenticate: (options: B2BOAuthAuthenticateOptions) => Promise>; protected getBaseApiUrl(): Promise; protected startOAuthFlow(providerType: B2BOAuthProviders): ({ organization_id, organization_slug, login_redirect_url, signup_redirect_url, custom_scopes, provider_params }: OAuthStartOptions) => Promise; protected startDiscoveryOAuthFlow(providerType: B2BOAuthProviders): ({ discovery_redirect_url, custom_scopes, provider_params }: B2BOAuthDiscoveryStartOptions) => Promise; discovery: { authenticate: (options: OAuthDiscoveryAuthenticateOptions) => Promise>; }; google: { start: ({ organization_id, organization_slug, login_redirect_url, signup_redirect_url, custom_scopes, provider_params }: OAuthStartOptions) => Promise; discovery: { start: ({ discovery_redirect_url, custom_scopes, provider_params }: B2BOAuthDiscoveryStartOptions) => Promise; }; }; microsoft: { start: ({ organization_id, organization_slug, login_redirect_url, signup_redirect_url, custom_scopes, provider_params }: OAuthStartOptions) => Promise; discovery: { start: ({ discovery_redirect_url, custom_scopes, provider_params }: B2BOAuthDiscoveryStartOptions) => Promise; }; }; hubspot: { start: ({ organization_id, organization_slug, login_redirect_url, signup_redirect_url, custom_scopes, provider_params }: OAuthStartOptions) => Promise; discovery: { start: ({ discovery_redirect_url, custom_scopes, provider_params }: B2BOAuthDiscoveryStartOptions) => Promise; }; }; slack: { start: ({ organization_id, organization_slug, login_redirect_url, signup_redirect_url, custom_scopes, provider_params }: OAuthStartOptions) => Promise; discovery: { start: ({ discovery_redirect_url, custom_scopes, provider_params }: B2BOAuthDiscoveryStartOptions) => Promise; }; }; github: { start: ({ organization_id, organization_slug, login_redirect_url, signup_redirect_url, custom_scopes, provider_params }: OAuthStartOptions) => Promise; discovery: { start: ({ discovery_redirect_url, custom_scopes, provider_params }: B2BOAuthDiscoveryStartOptions) => Promise; }; }; } declare class HeadlessB2BSessionClient implements IHeadlessB2BSessionClient { private _networkClient; private _subscriptionService; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService); getSync: () => MemberSession | null; getInfo: () => MemberSessionInfo; onChange: (callback: B2BSessionOnChangeCallback) => UnsubscribeFunction; revoke: (options?: B2BSessionRevokeOptions) => Promise; revokeForMember: (options: { member_id: string; }) => Promise; private _authenticate; authenticate: (options: Partial | undefined) => Promise>; getTokens(): IfOpaqueTokens, never, SessionTokens$0 | null>; updateSession(tokens: SessionTokensUpdate): void; exchange: (options: B2BSessionExchangeOptions) => Promise>; exchangeAccessToken: (options: B2BSessionAccessTokenExchangeOptions) => Promise>; attest: (options: B2BSessionAttestOptions) => Promise>; } declare class HeadlessB2BDiscoveryClient implements IHeadlessB2BDiscoveryClient { private _networkClient; private _subscriptionService; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService); organizations: { list: () => Promise; create: (options: B2BDiscoveryOrganizationsCreateOptions) => Promise>; }; intermediateSessions: { exchange: (options: B2BDiscoveryIntermediateSessionsExchangeOptions) => Promise>; }; } type DynamicConfig$7 = Promise<{ pkceRequiredForPasswordResets: boolean; }>; declare class HeadlessB2BPasswordsClient implements IHeadlessB2BPasswordClient { private _networkClient; private _subscriptionService; private _pkceManager; private _config; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, _pkceManager: IPKCEManager, _config: DynamicConfig$7, dfpProtectedAuth: IDFPProtectedAuthProvider); private getCodeChallenge; authenticate: (options: B2BPasswordAuthenticateOptions) => Promise>; resetByEmailStart(options: B2BPasswordResetByEmailStartOptions): Promise; discovery: { resetByEmailStart: (options: B2BPasswordDiscoveryResetByEmailStartOptions) => Promise; resetByEmail: (options: B2BPasswordDiscoveryResetByEmailOptions) => Promise>; authenticate: (options: B2BPasswordDiscoveryAuthenticateOptions) => Promise>; }; resetByEmail: (options: B2BPasswordResetByEmailOptions) => Promise>; resetByExistingPassword: (options: B2BPasswordResetByExistingPasswordOptions) => Promise>; resetBySession: (options: B2BPasswordResetBySessionOptions) => Promise>; strengthCheck(options: B2BPasswordStrengthCheckOptions): Promise; } declare class HeadlessB2BOTPsClient implements IHeadlessB2BOTPsClient { private _networkClient; private _subscriptionService; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, dfpProtectedAuth: IDFPProtectedAuthProvider); sms: { send: (data: B2BSMSSendOptions) => Promise; authenticate: (options: B2BSMSAuthenticateOptions) => Promise>; }; email: { loginOrSignup: (data: B2BOTPsEmailLoginOrSignupOptions) => Promise; authenticate: (options: B2BOTPsEmailAuthenticateOptions) => Promise>; discovery: { send: (data: B2BDiscoveryOTPEmailSendOptions) => Promise; authenticate: (options: B2BDiscoveryOTPEmailAuthenticateOptions) => Promise>; }; }; } declare class HeadlessB2BTOTPsClient implements IHeadlessB2BTOTPsClient { private _networkClient; private _subscriptionService; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, dfpProtectedAuth: IDFPProtectedAuthProvider); create(data: B2BTOTPCreateOptions): Promise; authenticate: (options: B2BTOTPAuthenticateOptions) => Promise>; } declare class HeadlessB2BRecoveryCodesClient implements IHeadlessB2BRecoveryCodesClient { private _networkClient; private _subscriptionService; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, dfpProtectedAuth: IDFPProtectedAuthProvider); recover: (options: RecoveryCodeRecoverOptions) => Promise>; rotate(): Promise; get(): Promise; } type CachedConfig$0 = { rbacPolicy: RBACPolicyRaw | null; }; type DynamicConfig$8 = Promise; declare class HeadlessB2BRBACClient implements IHeadlessB2BRBACClient { private _subscriptionService; private cachedPolicy; private policyPromise; constructor(cachedConfig: CachedConfig$0, dynamicConfig: DynamicConfig$8, _subscriptionService: IB2BSubscriptionService); /** * Gets the effective policy for the current session by merging project policy with org custom roles */ private getEffectivePolicy; /** * Gets the effective policy synchronously for the current session * Uses cached policies only */ private getEffectivePolicySync; allPermissions>(): Promise>; isAuthorizedSync: IHeadlessB2BRBACClient["isAuthorizedSync"]; isAuthorized: IHeadlessB2BRBACClient["isAuthorized"]; private roleIds; } declare class HeadlessB2BImpersonationClient implements IHeadlessB2BImpersonationClient { private _networkClient; private _subscriptionService; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, _subscriptionService: IB2BSubscriptionService, dfpProtectedAuth: IDFPProtectedAuthProvider); authenticate: (options: B2BImpersonationAuthenticateOptions) => Promise>; } declare class HeadlessB2BIDPClient implements IHeadlessB2BIDPClient { private _networkClient; constructor(_networkClient: INetworkClient); /** * Initiates a request for authorization of a Connected App to access a Member's account. * * Call this endpoint using the query parameters from an OAuth Authorization request. This endpoint validates various fields (scope, client_id, redirect_uri, prompt, etc...) are correct and returns relevant information for rendering an OAuth Consent Screen. * * @example * const response = await stytch.idp.oauthAuthorizeStart({ * client_id: 'client_123', * redirect_uri: 'https://example.com/callback', * scope: 'openid email profile', * }); */ oauthAuthorizeStart: (data: B2BOAuthAuthorizeStartOptions) => Promise; /** * Completes a request for authorization of a Connected App to access a Member's account. * * Call this endpoint using the query parameters from an OAuth Authorization request, after previously validating those parameters using the Preflight Check API. Note that this endpoint takes in a few additional parameters the preflight check does not- state, nonce, and code_challenge. * * If the authorization was successful, the redirect_uri will contain a valid authorization_code embedded as a query parameter. If the authorization was unsuccessful, the redirect_uri will contain an OAuth2.1 error_code. In both cases, redirect the Member to the location for the response to be consumed by the Connected App. * * Exactly one of the following must be provided to identify the Member granting authorization: * organization_id + member_id * session_token * session_jwt * * If a session_token or session_jwt is passed, the OAuth Authorization will be linked to the Member's session for tracking purposes. One of these fields must be used if the Connected App intends to complete the Exchange Access Token flow. * * @example * const response = await stytch.idp.oauthAuthorizeSubmit({ * client_id: 'client_123', * redirect_uri: 'https://example.com/callback', * scope: 'openid email profile', * }); */ oauthAuthorizeSubmit: (data: B2BOAuthAuthorizeSubmitOptions) => Promise; oauthLogoutStart: (data: B2BOAuthLogoutStartOptions) => Promise; } declare class IframeHostClient { private iframeURL; frame: Promise; constructor(iframeURL: string); private createIframe; call(method: string, args: unknown[]): Promise; } /** * RPC methods supported by clientside-services */ interface RPCManifest { oneTapStart: (req: OneTapStartRequest) => Promise; oneTapSubmit: (req: OneTapSubmitRequest) => Promise; parsedPhoneNumber: (req: ParsedPhoneNumberRequest) => Promise; } type ParsedPhoneNumberRequest = { phoneNumber: string; regionCode?: string; }; type ParsedPhoneNumberResponse = { isValid: boolean; number: string; national: string; }; type OneTapStartRequest = { publicToken: string; }; type OneTapStartResponse = { requestId: string; googleClientId: string; stytchCsrfToken: string; oauthCallbackId: string; }; type OneTapSubmitRequest = { publicToken: string; idToken: string; oauthCallbackID: string; loginRedirectURL?: string; signupRedirectURL?: string; }; type OneTapSubmitResponse = { redirect_url: string; }; type UserSearchData = ResponseCommon & { userType: "new" | "passwordless" | "password"; }; type InternalMember = Pick; type MemberSearchData = ResponseCommon & { member: InternalMember | null; }; interface ISearchData { searchUser: (email: string) => Promise; searchMember: (email: string, organization_id: string) => Promise; } declare class SearchDataManager implements ISearchData { private _networkClient; private dfpProtectedAuth; constructor(_networkClient: INetworkClient, dfpProtectedAuth: IDFPProtectedAuthProvider); searchUser(email: string): Promise; searchMember(email: string, organization_id: string): Promise; } interface ISessionManager { performBackgroundRefresh: () => void; cancelBackgroundRefresh: () => void; } declare class SessionManager implements ISessionManager { private _subscriptionService; private _headlessSessionClient; private _publicToken; private _options; // Three minutes private static REFRESH_INTERVAL_MS; // When testing - it's often more useful to set to a shorter duration // private static REFRESH_INTERVAL_MS = 1000 * 3; private timeout; /** In minutes */ private lastAuthenticationSessionDuration; private static registry; private register; private unregister; constructor(_subscriptionService: IConsumerSubscriptionService | IB2BSubscriptionService, _headlessSessionClient: IHeadlessSessionClient | IHeadlessB2BSessionClient, _publicToken: string, _options: { keepSessionAlive?: boolean; }); /** * The core logic of the session refresh recursive trampoline * - Refreshes the currently issued session * - Schedules a future refresh if successful */ performBackgroundRefresh(): void; private scheduleBackgroundRefresh; cancelBackgroundRefresh(): void; /** * We need to listen to a few types of events: * - If the user logs in via invoking a .authenticate() call, we should start the background worker * - If the user steps up their authentication via another .authenticate call(), we should restart the background worker * - If the user logs out, we should terminate the worker * - We should ignore session changes that we ourselves caused - so if we already have a timeout, leave it be! */ private _onDataChange; // In cases where we cannot get a satisfactory request: // - Stytch is hard-down // - The user's network is disconnected for an extended period of time // we will continue to retry every 4 minutes ad infinum private _reauthenticateWithBackoff; // We start with a backoff of 2000ms and increase exponentially to ~4 minutes (+/- 175 ms for jitter) // A short backoff initially helps increase the chance that we refresh the session before the JWT expires static timeoutForAttempt(count: number): number; // eslint-disable-next-line @typescript-eslint/no-explicit-any static isUnrecoverableError(error: any): boolean; } type DeepReadonly = { readonly [P in keyof T]: DeepReadonly; }; type StateChangeHandler = (state: DeepReadonly) => void; type StateChangeRegisterFunction = (callback: StateChangeHandler) => UnsubscribeFunction; declare class StateChangeClient { private readonly _subscriptionService; private readonly emptyState; constructor(_subscriptionService: ISubscriptionService, emptyState: T); onStateChange: StateChangeRegisterFunction; } type DeepEqualOpts = { KEYS_TO_EXCLUDE?: string[]; }; declare const createDeepEqual: ({ KEYS_TO_EXCLUDE }?: DeepEqualOpts) => (a: any, b: any) => boolean; export { TEST_API_URL, LIVE_API_URL, CLIENTSIDE_SERVICES_IFRAME_URL, STYTCH_DFP_BACKEND_URL, STYTCH_DFP_CDN_URL, STYTCH_SESSION_COOKIE, STYTCH_SESSION_JWT_COOKIE, POWERED_BY_STYTCH_IMG_URL, GOOGLE_ONE_TAP_HOST, GOOGLE_ONE_TAP_SCRIPT_URL, DEFAULT_SESSION_DURATION_MINUTES, DEFAULT_OTP_EXPIRATION_MINUTES, MULTIPLE_STYTCH_CLIENTS_DETECTED_WARNING, DFPProtectedAuthMode, DFPProtectedAuthState, DFPProtectedAuthProvider, DisabledDFPProtectedAuthProvider, IDFPProtectedAuthProvider, ErrorMarshaller, DEFAULT_MAX_BATCH_SIZE, DEFAULT_INTERVAL_DURATION_MS, EventLogger, EmailSentType, AnalyticsEvent, HeadlessUserClient, HeadlessSessionClient, HeadlessMagicLinksClient, HeadlessOTPClient, HeadlessOAuthClient, HeadlessCryptoWalletClient, HeadlessTOTPClient, HeadlessWebAuthnClient, HeadlessPasswordClient, HeadlessImpersonationClient, HeadlessRBACClient, HeadlessIDPClient, HeadlessB2BMagicLinksClient, HeadlessB2BSelfClient, HeadlessB2BSSOClient, HeadlessB2BSCIMClient, HeadlessB2BOrganizationClient, HeadlessB2BOAuthClient, HeadlessB2BSessionClient, HeadlessB2BDiscoveryClient, HeadlessB2BPasswordsClient, HeadlessB2BOTPsClient, HeadlessB2BTOTPsClient, HeadlessB2BRecoveryCodesClient, HeadlessB2BRBACClient, HeadlessB2BImpersonationClient, HeadlessB2BIDPClient, SDKRequestInfo, SDKTelemetry, AdditionalTelemetryData, INetworkClient, RetriableSDKRequestInfo, RetriableSDKBaseRequestInfo, RetriableErrorType, RetriableError, retriableFetchSDK, SDKBaseRequestInfo, baseFetchSDK, baseSubmitFormSDK, ProofkeyPair, IPKCEManager, IAsyncPKCEManager, ISyncPKCEManager, IframeHostClient, RPCManifest, ParsedPhoneNumberRequest, ParsedPhoneNumberResponse, OneTapStartRequest, OneTapStartResponse, OneTapSubmitRequest, OneTapSubmitResponse, InternalMember, MemberSearchData, ISearchData, SearchDataManager, ISessionManager, SessionManager, StateChangeHandler, StateChangeRegisterFunction, StateChangeClient, StorageResponse, IStorageClient, SubscriptionDataLayer, InternalSessionUpdateOptions, CommonAuthenticateOptions, ISubscriptionService, IConsumerSubscriptionService, IB2BSubscriptionService, SubscriptionService, ConsumerSubscriptionService, B2BSubscriptionService, ExtractOpaqueTokens, AllowedOpaqueTokens, OpaqueTokensNeverConfig, OpaqueTokensNever, IfOpaqueTokens, RedactedToken, BootstrapData, EnvironmentOptions, InternalStytchClientOptions, SessionUpdateOptions, loadESModule, getLiveApiURL, getTestApiURL, checkPublicToken, checkNotSSR, checkB2BNotSSR, COUNTRIES_LIST, CountryCode, getDFPBackendURL, getDFPCdnURL, logger, arrayUtils, isTestPublicToken, normalizePromiseLike, createEventId, createAppSessionId, createPersistentId, validate, isPhoneMethod, isEmailMethod, removeResponseCommon, WithUser, omitUser, WILDCARD_ACTION, RBACPolicyRole, RBACPolicyScope, RBACPolicyResource, RBACPolicyRaw, RBACPolicy, OAuthAuthorizeStartOptions, OAuthAuthorizeStartResponse, OAuthAuthorizeSubmitOptions, OAuthAuthorizeSubmitResponse, OAuthLogoutStartOptions, OAuthLogoutStartResponse, IHeadlessIDPClient, VERTICAL_B2B, VERTICAL_CONSUMER, Vertical, createDeepEqual }; export type { Cacheable, EnumOrStringLiteral, StringLiteralFromEnum };