diff --git a/dist/b2b/client.js b/dist/b2b/client.js index f119cec0..abf3d61e 100644 --- a/dist/b2b/client.js +++ b/dist/b2b/client.js @@ -5,25 +5,25 @@ Object.defineProperty(exports, "__esModule", { }); exports.B2BClient = void 0; -var _magic_links = require("./magic_links"); +var jose = _interopRequireWildcard(require("jose")); -var _sessions = require("./sessions"); +var _client = require("../shared/client"); -var _organizations = require("./organizations"); +var _discovery = require("./discovery"); -var _sso = require("./sso"); +var _magic_links = require("./magic_links"); -var _client = require("../shared/client"); +var _oauth = require("./oauth"); -var jose = _interopRequireWildcard(require("jose")); +var _organizations = require("./organizations"); -var _discovery = require("./discovery"); +var _otp = require("./otp"); var _passwords = require("./passwords"); -var _oauth = require("./oauth"); +var _sessions = require("./sessions"); -var _otps = require("./otps"); +var _sso = require("./sso"); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } @@ -32,26 +32,20 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && class B2BClient extends _client.BaseClient { constructor(config) { super(config); - - if (!this.fetchConfig.baseURL.endsWith("b2b/")) { - this.fetchConfig.baseURL += "b2b/"; - } - this.jwtConfig = { // Only allow JWTs that were meant for this project. projectID: config.project_id, // Fetch the signature verification keys for this project as needed. - jwks: jose.createRemoteJWKSet(new URL(`sessions/jwks/${config.project_id}`, this.fetchConfig.baseURL)) + jwks: jose.createRemoteJWKSet(new URL(`/v1/sessions/jwks/${config.project_id}`, this.fetchConfig.baseURL)) }; + this.discovery = new _discovery.Discovery(this.fetchConfig); this.magicLinks = new _magic_links.MagicLinks(this.fetchConfig); - this.sessions = new _sessions.Sessions(this.fetchConfig, this.jwtConfig); this.oauth = new _oauth.OAuth(this.fetchConfig); + this.otps = new _otp.OTPs(this.fetchConfig); this.organizations = new _organizations.Organizations(this.fetchConfig); - this.sso = new _sso.SSO(this.fetchConfig); - this.discovery = new _discovery.Discovery(this.fetchConfig); this.passwords = new _passwords.Passwords(this.fetchConfig); - this.oauth = new _oauth.OAuth(this.fetchConfig); - this.otps = new _otps.OTPs(this.fetchConfig); + this.sso = new _sso.SSO(this.fetchConfig); + this.sessions = new _sessions.Sessions(this.fetchConfig, this.jwtConfig); } } diff --git a/dist/b2b/discovery.js b/dist/b2b/discovery.js index 2ed7aecc..9d755eac 100644 --- a/dist/b2b/discovery.js +++ b/dist/b2b/discovery.js @@ -5,51 +5,20 @@ Object.defineProperty(exports, "__esModule", { }); exports.Discovery = void 0; -var _shared = require("../shared"); +var _discovery_intermediate_sessions = require("./discovery_intermediate_sessions"); -class Organizations { - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - } - - list(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: "discovery/organizations", - data - }); - } - - create(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: "discovery/organizations/create", - data - }); - } - -} - -class IntermediateSessions { - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - } - - exchange(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: "discovery/intermediate_sessions/exchange", - data - }); - } - -} +var _discovery_organizations = require("./discovery_organizations"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class Discovery { constructor(fetchConfig) { this.fetchConfig = fetchConfig; - this.organizations = new Organizations(this.fetchConfig); - this.intermediateSessions = new IntermediateSessions(this.fetchConfig); + this.intermediateSessions = new _discovery_intermediate_sessions.IntermediateSessions(this.fetchConfig); + this.organizations = new _discovery_organizations.Organizations(this.fetchConfig); } } diff --git a/dist/b2b/discovery_intermediate_sessions.js b/dist/b2b/discovery_intermediate_sessions.js new file mode 100644 index 00000000..0592b59c --- /dev/null +++ b/dist/b2b/discovery_intermediate_sessions.js @@ -0,0 +1,56 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.IntermediateSessions = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class IntermediateSessions { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Exchange an Intermediate Session for a fully realized + * [Member Session](https://stytch.com/docs/b2b/api/session-object) in a desired + * [Organization](https://stytch.com/docs/b2b/api/organization-object). + * This operation consumes the Intermediate Session. + * + * This endpoint can be used to accept invites and create new members via domain matching. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`. + * The `intermediate_session_token` will not be consumed and instead will be returned in the response. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BDiscoveryIntermediateSessionsExchangeRequest} + * @returns {@link B2BDiscoveryIntermediateSessionsExchangeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + exchange(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/discovery/intermediate_sessions/exchange`, + data + }); + } + +} + +exports.IntermediateSessions = IntermediateSessions; \ No newline at end of file diff --git a/dist/b2b/discovery_organizations.js b/dist/b2b/discovery_organizations.js new file mode 100644 index 00000000..8ab31bcd --- /dev/null +++ b/dist/b2b/discovery_organizations.js @@ -0,0 +1,93 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Organizations = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Organizations { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * If an end user does not want to join any already-existing organization, or has no possible organizations + * to join, this endpoint can be used to create a new + * [Organization](https://stytch.com/docs/b2b/api/organization-object) and + * [Member](https://stytch.com/docs/b2b/api/member-object). + * + * This operation consumes the Intermediate Session. + * + * This endpoint can also be used to start an initial session for the newly created member and organization. + * + * (Coming Soon) If the new Organization is created with a `mfa_policy` of `REQUIRED_FOR_ALL`, the newly + * created Member will need to complete an MFA step to log in to the Organization. + * The `intermediate_session_token` will not be consumed and instead will be returned in the response. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BDiscoveryOrganizationsCreateRequest} + * @returns {@link B2BDiscoveryOrganizationsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + create(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/discovery/organizations/create`, + data + }); + } + /** + * List all possible organization relationships connected to a + * [Member Session](https://stytch.com/docs/b2b/api/session-object) or Intermediate Session. + * + * When a Member Session is passed in, relationships with a type of `active_member`, `pending_member`, or + * `invited_member` + * will be returned, and any membership can be assumed by calling the + * [Exchange Session](https://stytch.com/docs/b2b/api/exchange-session) endpoint. + * + * When an Intermediate Session is passed in, all relationship types - `active_member`, `pending_member`, + * `invited_member`, + * and `eligible_to_join_by_email_domain` - will be returned, + * and any membership can be assumed by calling the + * [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) endpoint. + * + * This endpoint requires either an `intermediate_session_token`, `session_jwt` or `session_token` be + * included in the request. + * It will return an error if multiple are present. + * + * This operation does not consume the Intermediate Session or Session Token passed in. + * @param data {@link B2BDiscoveryOrganizationsListRequest} + * @returns {@link B2BDiscoveryOrganizationsListResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + list(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/discovery/organizations`, + data + }); + } + +} + +exports.Organizations = Organizations; \ No newline at end of file diff --git a/dist/b2b/magic_links.js b/dist/b2b/magic_links.js index 653f339f..611a0f84 100644 --- a/dist/b2b/magic_links.js +++ b/dist/b2b/magic_links.js @@ -5,86 +5,55 @@ Object.defineProperty(exports, "__esModule", { }); exports.MagicLinks = void 0; -var _shared = require("../shared"); - -class EmailDiscovery { - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - } - - send(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: "magic_links/email/discovery/send", - data - }); - } - -} - -class Discovery { - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - } - - authenticate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: "magic_links/discovery/authenticate", - data - }); - } +var _magic_links_discovery = require("./magic_links_discovery"); -} - -class Email { - delivery = "email"; - - constructor(fetchConfig, parent_path) { - this.fetchConfig = fetchConfig; - this.base_path = `${parent_path}`; - this.discovery = new EmailDiscovery(fetchConfig); - } - - endpoint(path) { - return `${this.base_path}/${this.delivery}/${path}`; - } - - loginOrSignup(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_signup"), - data - }); - } - - invite(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("invite"), - data - }); - } +var _magic_links_email = require("./magic_links_email"); -} +var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class MagicLinks { - base_path = "magic_links"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; - this.email = new Email(fetchConfig, this.base_path); - this.discovery = new Discovery(fetchConfig); - } + this.email = new _magic_links_email.Email(this.fetchConfig); + this.discovery = new _magic_links_discovery.Discovery(this.fetchConfig); + } + /** + * Authenticate a Member with a Magic Link. This endpoint requires a Magic Link token that is not expired + * or previously used. If the Member’s status is `pending` or `invited`, they will be updated to `active`. + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. If the + * `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 minute + * duration. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BMagicLinksAuthenticateRequest} + * @returns {@link B2BMagicLinksAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/b2b/magic_links/authenticate`, data }); } diff --git a/dist/b2b/magic_links_discovery.js b/dist/b2b/magic_links_discovery.js new file mode 100644 index 00000000..6e219f07 --- /dev/null +++ b/dist/b2b/magic_links_discovery.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Discovery = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Discovery { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Authenticates the Discovery Magic Link token and exchanges it for an Intermediate Session Token. + * Intermediate Session Tokens can be used for various Discovery login flows and are valid for 10 minutes. + * @param data {@link B2BMagicLinksDiscoveryAuthenticateRequest} + * @returns {@link B2BMagicLinksDiscoveryAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + authenticate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/magic_links/discovery/authenticate`, + data + }); + } + +} + +exports.Discovery = Discovery; \ No newline at end of file diff --git a/dist/b2b/magic_links_email.js b/dist/b2b/magic_links_email.js new file mode 100644 index 00000000..acc25e24 --- /dev/null +++ b/dist/b2b/magic_links_email.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Email = void 0; + +var _magic_links_email_discovery = require("./magic_links_email_discovery"); + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Email { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + this.discovery = new _magic_links_email_discovery.Discovery(this.fetchConfig); + } + /** + * Send either a login or signup magic link to a Member. A new, pending, or invited Member will receive a + * signup Email Magic Link. Members will have a `pending` status until they successfully authenticate. An + * active Member will receive a login Email Magic Link. + * @param data {@link B2BMagicLinksEmailLoginOrSignupRequest} + * @returns {@link B2BMagicLinksEmailLoginOrSignupResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + loginOrSignup(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/magic_links/email/login_or_signup`, + data + }); + } + /** + * Send an invite email to a new Member to join an Organization. The Member will be created with an + * `invited` status until they successfully authenticate. Sending invites to `pending` Members will update + * their status to `invited`. Sending invites to already `active` Members will return an error. + * @param data {@link B2BMagicLinksEmailInviteRequest} + * @returns {@link B2BMagicLinksEmailInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + invite(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/magic_links/email/invite`, + data + }); + } + +} + +exports.Email = Email; \ No newline at end of file diff --git a/dist/b2b/magic_links_email_discovery.js b/dist/b2b/magic_links_email_discovery.js new file mode 100644 index 00000000..037a4beb --- /dev/null +++ b/dist/b2b/magic_links_email_discovery.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Discovery = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Discovery { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Send a discovery magic link to an email address. + * @param data {@link B2BMagicLinksEmailDiscoverySendRequest} + * @returns {@link B2BMagicLinksEmailDiscoverySendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + send(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/magic_links/email/discovery/send`, + data + }); + } + +} + +exports.Discovery = Discovery; \ No newline at end of file diff --git a/dist/b2b/members.js b/dist/b2b/members.js deleted file mode 100644 index 0c3258fb..00000000 --- a/dist/b2b/members.js +++ /dev/null @@ -1,65 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Members = void 0; - -var _shared = require("../shared"); - -class Members { - constructor(fetchConfig, parent_path) { - this.fetchConfig = fetchConfig; - this.base_path = `${parent_path}`; - } - - create(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: `${this.base_path}/${data.organization_id}/members`, - data - }); - } - - get(params) { - return (0, _shared.request)(this.fetchConfig, { - method: "GET", - url: `${this.base_path}/${params.organization_id}/member`, - params: { ...params - } - }); - } - - update(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "PUT", - url: `${this.base_path}/${data.organization_id}/members/${data.member_id}`, - data - }); - } - - delete(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "DELETE", - url: `${this.base_path}/${data.organization_id}/members/${data.member_id}` - }); - } - - search(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: `${this.base_path}/members/search`, - data - }); - } - - deletePhoneNumber(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "DELETE", - url: `${this.base_path}/${data.organization_id}/members/mfa_phone_numbers/${data.member_id}` - }); - } - -} - -exports.Members = Members; \ No newline at end of file diff --git a/dist/b2b/oauth.js b/dist/b2b/oauth.js index 65e7246a..620525c0 100644 --- a/dist/b2b/oauth.js +++ b/dist/b2b/oauth.js @@ -5,45 +5,51 @@ Object.defineProperty(exports, "__esModule", { }); exports.OAuth = void 0; -var _shared = require("../shared"); - -class Discovery { - base_path = "oauth/discovery"; - - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - } - - endpoint(path) { - return `${this.base_path}/${path}`; - } +var _oauth_discovery = require("./oauth_discovery"); - authenticate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data - }); - } - -} +var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class OAuth { - base_path = "oauth"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; - this.discovery = new Discovery(fetchConfig); + this.discovery = new _oauth_discovery.Discovery(this.fetchConfig); } + /** + * Authenticate a Member given a `token`. This endpoint verifies that the member completed the OAuth flow + * by verifying that the token is valid and hasn't expired. Provide the `session_duration_minutes` + * parameter to set the lifetime of the session. If the `session_duration_minutes` parameter is not + * specified, a Stytch session will be created with a 60 minute duration. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BOAuthAuthenticateRequest} + * @returns {@link B2BOAuthAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/b2b/oauth/authenticate`, data }); } diff --git a/dist/b2b/oauth_discovery.js b/dist/b2b/oauth_discovery.js new file mode 100644 index 00000000..19f62c27 --- /dev/null +++ b/dist/b2b/oauth_discovery.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Discovery = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Discovery { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Authenticates the Discovery OAuth token and exchanges it for an Intermediate Session Token. Intermediate + * Session Tokens can be used for various Discovery login flows and are valid for 10 minutes. + * @param data {@link B2BOAuthDiscoveryAuthenticateRequest} + * @returns {@link B2BOAuthDiscoveryAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + authenticate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/oauth/discovery/authenticate`, + data + }); + } + +} + +exports.Discovery = Discovery; \ No newline at end of file diff --git a/dist/b2b/oidc.js b/dist/b2b/oidc.js deleted file mode 100644 index 9e116575..00000000 --- a/dist/b2b/oidc.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.OIDC = void 0; - -var _shared = require("../shared"); - -class OIDC { - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - } - - create({ - organization_id, - ...data - }) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: `sso/oidc/${organization_id}`, - data - }); - } - - update({ - organization_id, - connection_id, - ...data - }) { - return (0, _shared.request)(this.fetchConfig, { - method: "PUT", - url: `sso/oidc/${organization_id}/connections/${connection_id}`, - data - }); - } - -} - -exports.OIDC = OIDC; \ No newline at end of file diff --git a/dist/b2b/organizations.js b/dist/b2b/organizations.js index 128fce5a..74f95311 100644 --- a/dist/b2b/organizations.js +++ b/dist/b2b/organizations.js @@ -5,61 +5,134 @@ Object.defineProperty(exports, "__esModule", { }); exports.Organizations = void 0; -var _shared = require("../shared"); +var _organizations_members = require("./organizations_members"); -var _members = require("./members"); +var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +// ENDMANUAL(SearchQueryOperand) class Organizations { - base_path = "organizations"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; - this.members = new _members.Members(fetchConfig, this.base_path); + this.members = new _organizations_members.Members(this.fetchConfig); } + /** + * Creates an Organization. An `organization_name` and a unique `organization_slug` are required. + * + * By default, `email_invites` and `sso_jit_provisioning` will be set to `ALL_ALLOWED`, and `mfa_policy` + * will be set to `OPTIONAL` if no Organization authentication settings are explicitly defined in the + * request. + * + * *See the [Organization authentication settings](https://stytch.com/docs/b2b/api/org-auth-settings) + * resource to learn more about fields like `email_jit_provisioning`, `email_invites`, + * `sso_jit_provisioning`, etc., and their behaviors. + * @param data {@link B2BOrganizationsCreateRequest} + * @returns {@link B2BOrganizationsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } create(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.base_path, + url: `/v1/b2b/organizations`, data }); } + /** + * Returns an Organization specified by `organization_id`. + * @param data {@link B2BOrganizationsGetRequest} + * @returns {@link B2BOrganizationsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - get({ - organization_id - }) { + get(params) { return (0, _shared.request)(this.fetchConfig, { method: "GET", - url: this.endpoint(organization_id) + url: `/v1/b2b/organizations/${params.organization_id}`, + params: {} }); } + /** + * Updates an Organization specified by `organization_id`. An Organization must always have at least one + * auth setting set to either `RESTRICTED` or `ALL_ALLOWED` in order to provision new Members. test + * + * *See the [Organization authentication settings](https://stytch.com/docs/b2b/api/org-auth-settings) + * resource to learn more about fields like `email_jit_provisioning`, `email_invites`, + * `sso_jit_provisioning`, etc., and their behaviors. + * @param data {@link B2BOrganizationsUpdateRequest} + * @returns {@link B2BOrganizationsUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - search(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("search"), - data - }); - } update(data) { return (0, _shared.request)(this.fetchConfig, { method: "PUT", - url: this.endpoint(data.organization_id), - data + url: `/v1/b2b/organizations/${data.organization_id}`, + data: { + organization_name: data.organization_name, + organization_slug: data.organization_slug, + organization_logo_url: data.organization_logo_url, + trusted_metadata: data.trusted_metadata, + sso_default_connection_id: data.sso_default_connection_id, + sso_jit_provisioning: data.sso_jit_provisioning, + sso_jit_provisioning_allowed_connections: data.sso_jit_provisioning_allowed_connections, + email_allowed_domains: data.email_allowed_domains, + email_jit_provisioning: data.email_jit_provisioning, + email_invites: data.email_invites, + auth_methods: data.auth_methods, + allowed_auth_methods: data.allowed_auth_methods, + mfa_policy: data.mfa_policy + } }); } + /** + * Deletes an Organization specified by `organization_id`. All Members of the Organization will also be + * deleted. + * @param data {@link B2BOrganizationsDeleteRequest} + * @returns {@link B2BOrganizationsDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - delete({ - organization_id - }) { + delete(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(organization_id) + url: `/v1/b2b/organizations/${data.organization_id}`, + data: {} + }); + } + /** + * Search for Organizations. If you send a request with no body params, no filtering will be applied and + * the endpoint will return all Organizations. All fuzzy search filters require a minimum of three + * characters. + * @param data {@link B2BOrganizationsSearchRequest} + * @returns {@link B2BOrganizationsSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + search(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/organizations/search`, + data }); } diff --git a/dist/b2b/organizations_members.js b/dist/b2b/organizations_members.js new file mode 100644 index 00000000..20ab3688 --- /dev/null +++ b/dist/b2b/organizations_members.js @@ -0,0 +1,160 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Members = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Members { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Updates a Member specified by `organization_id` and `member_id`. + * @param data {@link B2BOrganizationsMembersUpdateRequest} + * @returns {@link B2BOrganizationsMembersUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + update(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "PUT", + url: `/v1/b2b/organizations/${data.organization_id}/members/${data.member_id}`, + data: { + name: data.name, + trusted_metadata: data.trusted_metadata, + untrusted_metadata: data.untrusted_metadata, + is_breakglass: data.is_breakglass, + mfa_phone_number: data.mfa_phone_number, + mfa_enrolled: data.mfa_enrolled + } + }); + } + /** + * Deletes a Member specified by `organization_id` and `member_id`. + * @param data {@link B2BOrganizationsMembersDeleteRequest} + * @returns {@link B2BOrganizationsMembersDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + delete(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "DELETE", + url: `/v1/b2b/organizations/${data.organization_id}/members/${data.member_id}`, + data: {} + }); + } + /** + * @param data {@link B2BOrganizationsMembersDeleteMFAPhoneNumberRequest} + * @returns {@link B2BOrganizationsMembersDeleteMFAPhoneNumberResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + deleteMFAPhoneNumber(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "DELETE", + url: `/v1/b2b/organizations/${data.organization_id}/members/mfa_phone_numbers/${data.member_id}`, + data: {} + }); + } + /** + * Search for Members within specified Organizations. An array with at least one `organization_id` is + * required. Submitting an empty `query` returns all Members within the specified Organizations. + * + * *All fuzzy search filters require a minimum of three characters. + * @param data {@link B2BOrganizationsMembersSearchRequest} + * @returns {@link B2BOrganizationsMembersSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + search(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/organizations/members/search`, + data + }); + } + /** + * Delete a Member's password. + * @param data {@link B2BOrganizationsMembersDeletePasswordRequest} + * @returns {@link B2BOrganizationsMembersDeletePasswordResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + deletePassword(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "DELETE", + url: `/v1/b2b/organizations/${data.organization_id}/members/passwords/${data.member_password_id}`, + data: {} + }); + } + /** + * Creates a Member. An `organization_id` and `email_address` are required. + * @param data {@link B2BOrganizationsMembersCreateRequest} + * @returns {@link B2BOrganizationsMembersCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + create(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/organizations/${data.organization_id}/members`, + data: { + email_address: data.email_address, + name: data.name, + trusted_metadata: data.trusted_metadata, + untrusted_metadata: data.untrusted_metadata, + create_member_as_pending: data.create_member_as_pending, + is_breakglass: data.is_breakglass, + mfa_phone_number: data.mfa_phone_number, + mfa_enrolled: data.mfa_enrolled + } + }); + } + /** + * Get a Member by `member_id` or `email_address`. + * @param data {@link B2BOrganizationsMembersGetRequest} + * @returns {@link B2BOrganizationsMembersGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + get(params) { + return (0, _shared.request)(this.fetchConfig, { + method: "GET", + url: `/v1/b2b/organizations/${params.organization_id}/member`, + params: { ...params + } + }); + } + +} + +exports.Members = Members; \ No newline at end of file diff --git a/dist/b2b/otp.js b/dist/b2b/otp.js new file mode 100644 index 00000000..f5ab4460 --- /dev/null +++ b/dist/b2b/otp.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OTPs = void 0; + +var _otp_sms = require("./otp_sms"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class OTPs { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + this.sms = new _otp_sms.Sms(this.fetchConfig); + } + +} + +exports.OTPs = OTPs; \ No newline at end of file diff --git a/dist/b2b/otp_sms.js b/dist/b2b/otp_sms.js new file mode 100644 index 00000000..b1d10da9 --- /dev/null +++ b/dist/b2b/otp_sms.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Sms = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Sms { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Send a one-time passcode (OTP) to a Member's phone number. If the Member already has a phone number, + * this will send an OTP to the number associated with their `member_id`. If not, then this will send an + * OTP to the `phone_number` provided and link the `phone_number` with the Member. + * An error will be thrown if the Member already has a phone number and the provided `phone_number` does + * not match the existing one. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * If a Member has a phone number and is enrolled in MFA, then after a successful primary authentication + * event (e.g. [email magic link](https://stytch.com/docs/b2b/api/authenticate-magic-link) or + * [SSO](https://stytch.com/docs/b2b/api/sso-authenticate) login is complete), an SMS OTP will + * automatically be sent to their phone number. In that case, this endpoint should only be used for + * subsequent authentication events, such as prompting a Member for an OTP again after a period of + * inactivity. + * @param data {@link B2BOTPSmsSendRequest} + * @returns {@link B2BOTPSmsSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + send(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/otps/sms/send`, + data + }); + } + /** + * Authenticates a Member's OTP code. This endpoint verifies that the code is valid and hasn't expired or + * been previously used. A given Member may only have a single active OTP code at any given time. If a + * Member requests another OTP code before the first one has expired, the first one will be invalidated. + * + * Exactly one of `intermediate_session_token`, `session_token`, or `session_jwt` must be provided in the + * request. + * If an intermediate session token is provided, this operation will consume it. + * + * If the Organization's MFA policy is `REQUIRED_FOR_ALL`, a successful OTP authentication will change the + * Member's `mfa_enrolled` status to `true` if it is not already `true`. + * If the Organization's MFA policy is `OPTIONAL`, the Member's MFA enrollment can be toggled by passing in + * a value for the `set_mfa_enrollment` field. + * + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. If the + * `session_duration_minutes` parameter is not specified, a Stytch session will be created with a duration + * of 60 minutes. + * @param data {@link B2BOTPSmsAuthenticateRequest} + * @returns {@link B2BOTPSmsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + authenticate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/otps/sms/authenticate`, + data + }); + } + +} + +exports.Sms = Sms; \ No newline at end of file diff --git a/dist/b2b/otps.js b/dist/b2b/otps.js deleted file mode 100644 index e5164ba3..00000000 --- a/dist/b2b/otps.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.OTPs = void 0; - -var _shared = require("../shared"); - -class SMS { - delivery = "sms"; - - constructor(fetchConfig, base_path) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - endpoint(path) { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data - }); - } - - authenticate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data - }); - } - -} - -class OTPs { - base_path = "otps"; - - constructor(fetchConfig) { - this.sms = new SMS(fetchConfig, this.base_path); - } - -} - -exports.OTPs = OTPs; \ No newline at end of file diff --git a/dist/b2b/passwords.js b/dist/b2b/passwords.js index 846ae5c5..2e4a0e73 100644 --- a/dist/b2b/passwords.js +++ b/dist/b2b/passwords.js @@ -5,72 +5,123 @@ Object.defineProperty(exports, "__esModule", { }); exports.Passwords = void 0; +var _passwords_email = require("./passwords_email"); + +var _passwords_existing_password = require("./passwords_existing_password"); + var _shared = require("../shared"); -class Passwords { - base_path = "passwords"; +var _passwords_session = require("./passwords_session"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Passwords { constructor(fetchConfig) { this.fetchConfig = fetchConfig; + this.email = new _passwords_email.Email(this.fetchConfig); + this.sessions = new _passwords_session.Sessions(this.fetchConfig); + this.existingPassword = new _passwords_existing_password.ExistingPassword(this.fetchConfig); } + /** + * This API allows you to check whether the user’s provided password is valid, and to provide feedback to + * the user on how to increase the strength of their password. + * + * This endpoint adapts to your Project's password strength configuration. If you're using + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your passwords are + * considered valid if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are considered valid if + * they meet the requirements that you've set with Stytch. You may update your password strength + * configuration in the [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * ## Password feedback + * The zxcvbn_feedback and luds_feedback objects contains relevant fields for you to relay feedback to + * users that failed to create a strong enough password. + * + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the feedback object + * will contain warning and suggestions for any password that does not meet the + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy) strength requirements. You can return + * these strings directly to the user to help them craft a strong password. + * + * If you're using [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), the feedback object + * will contain a collection of fields that the user failed or passed. You'll want to prompt the user to + * create a password that meets all requirements that they failed. + * @param data {@link B2BPasswordsStrengthCheckRequest} + * @returns {@link B2BPasswordsStrengthCheckResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } - authenticate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data: data - }); - } - - resetByEmailStart(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("email/reset/start"), - data: data - }); - } - - resetByEmail(data) { + strengthCheck(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("email/reset"), - data: data + url: `/v1/b2b/passwords/strength_check`, + data }); } + /** + * Adds an existing password to a member's email that doesn't have a password yet. We support migrating + * members from passwords stored with bcrypt, scrypt, argon2, MD-5, SHA-1, and PBKDF2. This endpoint has a + * rate limit of 100 requests per second. + * @param data {@link B2BPasswordsMigrateRequest} + * @returns {@link B2BPasswordsMigrateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - resetByExistingPassword(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("existing_password/reset"), - data: data - }); - } - resetBySession(data) { + migrate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("session/reset"), - data: data + url: `/v1/b2b/passwords/migrate`, + data }); } + /** + * Authenticate a member with their email address and password. This endpoint verifies that the member has + * a password currently set, and that the entered password is correct. There are two instances where the + * endpoint will return a reset_password error even if they enter their previous password: + * * The member’s credentials appeared in the HaveIBeenPwned dataset. + * * We force a password reset to ensure that the member is the legitimate owner of the email address, + * and not a malicious actor abusing the compromised credentials. + * * A member that has previously authenticated with email/password uses a passwordless authentication + * method tied to the same email address (e.g. Magic Links) for the first time. Any subsequent + * email/password authentication attempt will result in this error. + * * We force a password reset in this instance in order to safely deduplicate the account by email + * address, without introducing the risk of a pre-hijack account takeover attack. + * * Imagine a bad actor creates many accounts using passwords and the known email addresses of their + * victims. If a victim comes to the site and logs in for the first time with an email-based passwordless + * authentication method then both the victim and the bad actor have credentials to access to the same + * account. To prevent this, any further email/password login attempts first require a password reset which + * can only be accomplished by someone with access to the underlying email address. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsAuthenticateRequest} + * @returns {@link B2BPasswordsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - strengthCheck(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("strength_check"), - data: data - }); - } - migrate(data) { + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("migrate"), - data: data + url: `/v1/b2b/passwords/authenticate`, + data }); } diff --git a/dist/b2b/passwords_email.js b/dist/b2b/passwords_email.js new file mode 100644 index 00000000..0e8d3897 --- /dev/null +++ b/dist/b2b/passwords_email.js @@ -0,0 +1,81 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Email = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Email { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * 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. + * + * This endpoint adapts to your Project's password strength configuration. + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your + * passwords are considered valid + * if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are + * considered valid if they meet the requirements that you've set with Stytch. + * You may update your password strength configuration in the + * [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * @param data {@link B2BPasswordsEmailResetStartRequest} + * @returns {@link B2BPasswordsEmailResetStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + resetStart(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/email/reset/start`, + data + }); + } + /** + * Reset the member's password and authenticate them. This endpoint checks that the password reset 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 password strength endpoint. If the token and password are accepted, the password is securely + * stored for future authentication and the user is authenticated. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsEmailResetRequest} + * @returns {@link B2BPasswordsEmailResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + reset(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/email/reset`, + data + }); + } + +} + +exports.Email = Email; \ No newline at end of file diff --git a/dist/b2b/passwords_existing_password.js b/dist/b2b/passwords_existing_password.js new file mode 100644 index 00000000..23db1a93 --- /dev/null +++ b/dist/b2b/passwords_existing_password.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExistingPassword = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class ExistingPassword { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Reset the member’s password using their existing password. + * + * This endpoint adapts to your Project's password strength configuration. + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your + * passwords are considered valid + * if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are + * considered valid if they meet the requirements that you've set with Stytch. + * You may update your password strength configuration in the + * [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsExistingPasswordResetRequest} + * @returns {@link B2BPasswordsExistingPasswordResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + reset(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/existing_password/reset`, + data + }); + } + +} + +exports.ExistingPassword = ExistingPassword; \ No newline at end of file diff --git a/dist/b2b/passwords_session.js b/dist/b2b/passwords_session.js new file mode 100644 index 00000000..b3c86f95 --- /dev/null +++ b/dist/b2b/passwords_session.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Sessions = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Sessions { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Reset the Member's password using their existing session. The endpoint will error if the session does + * not contain an authentication factor that has been issued within the last 5 minutes. Either + * `session_token` or `session_jwt` should be provided. + * @param data {@link B2BPasswordsSessionResetRequest} + * @returns {@link B2BPasswordsSessionResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + reset(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/session/reset`, + data + }); + } + +} + +exports.Sessions = Sessions; \ No newline at end of file diff --git a/dist/b2b/saml.js b/dist/b2b/saml.js deleted file mode 100644 index 2fdbefe9..00000000 --- a/dist/b2b/saml.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.SAML = void 0; - -var _shared = require("../shared"); - -class SAML { - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - } - - create({ - organization_id, - ...data - }) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: `sso/saml/${organization_id}`, - data - }); - } - - update({ - organization_id, - connection_id, - ...data - }) { - return (0, _shared.request)(this.fetchConfig, { - method: "PUT", - url: `sso/saml/${organization_id}/connections/${connection_id}`, - data - }); - } - - deleteVerificationCertificate({ - organization_id, - connection_id, - certificate_id - }) { - return (0, _shared.request)(this.fetchConfig, { - method: "DELETE", - url: `sso/saml/${organization_id}/connections/${connection_id}/verification_certificates/${certificate_id}` - }); - } - -} - -exports.SAML = SAML; \ No newline at end of file diff --git a/dist/b2b/sessions.js b/dist/b2b/sessions.js index 4d8b474b..ce5e9976 100644 --- a/dist/b2b/sessions.js +++ b/dist/b2b/sessions.js @@ -5,15 +5,16 @@ Object.defineProperty(exports, "__esModule", { }); exports.Sessions = void 0; -var _shared = require("../shared"); - var _sessions = require("../shared/sessions"); -const organizationClaim = "https://stytch.com/organization"; +var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class Sessions { - base_path = "sessions"; - constructor(fetchConfig, jwtConfig) { this.fetchConfig = fetchConfig; this.jwksClient = jwtConfig.jwks; @@ -23,39 +24,122 @@ class Sessions { typ: "JWT" }; } + /** + * Retrieves all active Sessions for a Member. + * @param data {@link B2BSessionsGetRequest} + * @returns {@link B2BSessionsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } - get({ - organization_id, - member_id - }) { + get(params) { return (0, _shared.request)(this.fetchConfig, { method: "GET", - url: this.base_path, - params: { - organization_id, - member_id + url: `/v1/b2b/sessions`, + params: { ...params } }); } + /** + * Authenticates a Session and updates its lifetime by the specified `session_duration_minutes`. If the + * `session_duration_minutes` is not specified, a Session will not be extended. This endpoint requires + * either a `session_jwt` or `session_token` be included in the request. It will return an error if both + * are present. + * + * You may provide a JWT that needs to be refreshed and is expired according to its `exp` claim. A new JWT + * will be returned if both the signature and the underlying Session are still valid. + * @param data {@link B2BSessionsAuthenticateRequest} + * @returns {@link B2BSessionsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - jwks(project_id) { + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { - method: "GET", - url: this.endpoint(`jwks/${project_id}`) + method: "POST", + url: `/v1/b2b/sessions/authenticate`, + data }); } + /** + * Revoke a Session and immediately invalidate all its tokens. To revoke a specific Session, pass either + * the `member_session_id`, `session_token`, or `session_jwt`. To revoke all Sessions for a Member, pass + * the `member_id`. + * @param data {@link B2BSessionsRevokeRequest} + * @returns {@link B2BSessionsRevokeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - authenticate(data) { + + revoke(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/sessions/revoke`, + data + }); + } + /** + * Use this endpoint to exchange a Member's existing session for another session in a different + * Organization. This can be used to accept an invite, but not to create a new member via domain matching. + * + * To create a new member via domain matching, use the + * [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) flow + * instead. + * + * Only Email Magic Link, OAuth, and SMS OTP factors can be transferred between sessions. Other + * authentication factors, such as password factors, will not be transferred to the new session. + * SMS OTP factors can be used to fulfill MFA requirements for the target Organization if both the original + * and target Member have the same phone number and the phone number is verified for both Members. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BSessionsExchangeRequest} + * @returns {@link B2BSessionsExchangeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + exchange(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/b2b/sessions/exchange`, data }); } + /** + * Get the JSON Web Key Set (JWKS) for a project. + * @param data {@link B2BSessionsGetJWKSRequest} + * @returns {@link B2BSessionsGetJWKSResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + getJWKS(params) { + return (0, _shared.request)(this.fetchConfig, { + method: "GET", + url: `/v1/b2b/sessions/jwks/${params.project_id}`, + params: {} + }); + } // MANUAL(authenticateJwt)(SERVICE_METHOD) + /** Parse a JWT and verify the signature, preferring local verification over remote. * * If max_token_age_seconds is set, remote verification will be forced if the JWT was issued at @@ -98,6 +182,7 @@ class Sessions { async authenticateJwtLocal(jwt, options) { const sess = await (0, _sessions.authenticateJwtLocal)(this.jwksClient, this.jwtOptions, jwt, options); + const organizationClaim = "https://stytch.com/organization"; const { [organizationClaim]: orgClaimUntyped, ...claims @@ -113,23 +198,8 @@ class Sessions { expires_at: sess.expires_at, custom_claims: claims }; - } + } // ENDMANUAL(authenticateJwt) - exchange(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("exchange"), - data - }); - } - - revoke(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("revoke"), - data - }); - } } diff --git a/dist/b2b/shared_b2b.js b/dist/b2b/shared_b2b.js deleted file mode 100644 index c5187cad..00000000 --- a/dist/b2b/shared_b2b.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.SearchOperator = void 0; -let SearchOperator; -exports.SearchOperator = SearchOperator; - -(function (SearchOperator) { - SearchOperator["OR"] = "OR"; - SearchOperator["AND"] = "AND"; -})(SearchOperator || (exports.SearchOperator = SearchOperator = {})); \ No newline at end of file diff --git a/dist/b2b/sso.js b/dist/b2b/sso.js index 97f20993..2c69200a 100644 --- a/dist/b2b/sso.js +++ b/dist/b2b/sso.js @@ -5,42 +5,88 @@ Object.defineProperty(exports, "__esModule", { }); exports.SSO = void 0; -var _shared = require("../shared"); +var _sso_oidc = require("./sso_oidc"); -var _saml = require("./saml"); +var _shared = require("../shared"); -var _oidc = require("./oidc"); +var _sso_saml = require("./sso_saml"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class SSO { constructor(fetchConfig) { this.fetchConfig = fetchConfig; - this.saml = new _saml.SAML(fetchConfig); - this.oidc = new _oidc.OIDC(fetchConfig); + this.oidc = new _sso_oidc.OIDC(this.fetchConfig); + this.saml = new _sso_saml.SAML(this.fetchConfig); } + /** + * Get all SSO Connections owned by the organization. + * @param data {@link B2BSSOGetConnectionsRequest} + * @returns {@link B2BSSOGetConnectionsResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - get({ - organization_id - }) { + getConnections(params) { return (0, _shared.request)(this.fetchConfig, { method: "GET", - url: `sso/${organization_id}` + url: `/v1/b2b/sso/${params.organization_id}`, + params: {} }); } + /** + * Delete an existing SSO connection. + * @param data {@link B2BSSODeleteConnectionRequest} + * @returns {@link B2BSSODeleteConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - delete({ - organization_id, - connection_id - }) { + + deleteConnection(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: `sso/${organization_id}/connections/${connection_id}` + url: `/v1/b2b/sso/${data.organization_id}/connections/${data.connection_id}`, + data: {} }); } + /** + * Authenticate a user given a token. + * This endpoint verifies that the user completed the SSO Authentication flow by verifying that the token + * is valid and hasn't expired. + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 + * minute duration. + * To link this authentication event to an existing Stytch session, include either the `session_token` or + * `session_jwt` param. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BSSOAuthenticateRequest} + * @returns {@link B2BSSOAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: `sso/authenticate`, + url: `/v1/b2b/sso/authenticate`, data }); } diff --git a/dist/b2b/sso_oidc.js b/dist/b2b/sso_oidc.js new file mode 100644 index 00000000..44fe87ac --- /dev/null +++ b/dist/b2b/sso_oidc.js @@ -0,0 +1,92 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.OIDC = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class OIDC { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Create a new OIDC Connection. + * @param data {@link B2BSSOOIDCCreateConnectionRequest} + * @returns {@link B2BSSOOIDCCreateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + createConnection(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/sso/oidc/${data.organization_id}`, + data: { + display_name: data.display_name + } + }); + } + /** + * Updates an existing OIDC connection. + * + * 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 `$/.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. + * + * Note that a newly created connection will not become active until all of the following fields are + * provided: + * * `issuer` + * * `client_id` + * * `client_secret` + * * `authorization_url` + * * `token_url` + * * `userinfo_url` + * * `jwks_url` + * @param data {@link B2BSSOOIDCUpdateConnectionRequest} + * @returns {@link B2BSSOOIDCUpdateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + updateConnection(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "PUT", + url: `/v1/b2b/sso/oidc/${data.organization_id}/connections/${data.connection_id}`, + data: { + display_name: data.display_name, + client_id: data.client_id, + client_secret: data.client_secret, + issuer: data.issuer, + authorization_url: data.authorization_url, + token_url: data.token_url, + userinfo_url: data.userinfo_url, + jwks_url: data.jwks_url + } + }); + } + +} + +exports.OIDC = OIDC; \ No newline at end of file diff --git a/dist/b2b/sso_saml.js b/dist/b2b/sso_saml.js new file mode 100644 index 00000000..b5efec6b --- /dev/null +++ b/dist/b2b/sso_saml.js @@ -0,0 +1,90 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SAML = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class SAML { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Create a new SAML Connection. + * @param data {@link B2BSSOSAMLCreateConnectionRequest} + * @returns {@link B2BSSOSAMLCreateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + createConnection(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/sso/saml/${data.organization_id}`, + data: { + display_name: data.display_name + } + }); + } + /** + * Updates an existing SAML connection. + * + * Note that a newly created connection will not become active until all of the following are provided: + * * `idp_sso_url` + * * `attribute_mapping` + * * `idp_entity_id` + * * `x509_certificate` + * @param data {@link B2BSSOSAMLUpdateConnectionRequest} + * @returns {@link B2BSSOSAMLUpdateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + updateConnection(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "PUT", + url: `/v1/b2b/sso/saml/${data.organization_id}/connections/${data.connection_id}`, + data: { + idp_entity_id: data.idp_entity_id, + display_name: data.display_name, + attribute_mapping: data.attribute_mapping, + x509_certificate: data.x509_certificate, + idp_sso_url: data.idp_sso_url + } + }); + } + /** + * Delete a SAML verification certificate. + * + * 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. + * @param data {@link B2BSSOSAMLDeleteVerificationCertificateRequest} + * @returns {@link B2BSSOSAMLDeleteVerificationCertificateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + deleteVerificationCertificate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "DELETE", + url: `/v1/b2b/sso/saml/${data.organization_id}/connections/${data.connection_id}/verification_certificates/${data.certificate_id}`, + data: {} + }); + } + +} + +exports.SAML = SAML; \ No newline at end of file diff --git a/dist/b2c/shared_b2c.js b/dist/b2c/attribute.js similarity index 100% rename from dist/b2c/shared_b2c.js rename to dist/b2c/attribute.js diff --git a/dist/b2c/client.js b/dist/b2c/client.js index 9391a2af..d202f966 100644 --- a/dist/b2c/client.js +++ b/dist/b2c/client.js @@ -5,6 +5,10 @@ Object.defineProperty(exports, "__esModule", { }); exports.Client = void 0; +var jose = _interopRequireWildcard(require("jose")); + +var _client = require("../shared/client"); + var _crypto_wallets = require("./crypto_wallets"); var _magic_links = require("./magic_links"); @@ -23,10 +27,6 @@ var _users = require("./users"); var _webauthn = require("./webauthn"); -var _client = require("../shared/client"); - -var jose = _interopRequireWildcard(require("jose")); - function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } @@ -38,17 +38,17 @@ class Client extends _client.BaseClient { // Only allow JWTs that were meant for this project. projectID: config.project_id, // Fetch the signature verification keys for this project as needed. - jwks: jose.createRemoteJWKSet(new URL(`sessions/jwks/${config.project_id}`, this.fetchConfig.baseURL)) + jwks: jose.createRemoteJWKSet(new URL(`/v1/sessions/jwks/${config.project_id}`, this.fetchConfig.baseURL)) }; - this.users = new _users.Users(this.fetchConfig); + this.cryptoWallets = new _crypto_wallets.CryptoWallets(this.fetchConfig); this.magicLinks = new _magic_links.MagicLinks(this.fetchConfig); this.oauth = new _oauth.OAuth(this.fetchConfig); this.otps = new _otps.OTPs(this.fetchConfig); this.passwords = new _passwords.Passwords(this.fetchConfig); this.sessions = new _sessions.Sessions(this.fetchConfig, this.jwtConfig); this.totps = new _totps.TOTPs(this.fetchConfig); + this.users = new _users.Users(this.fetchConfig); this.webauthn = new _webauthn.WebAuthn(this.fetchConfig); - this.cryptoWallets = new _crypto_wallets.CryptoWallets(this.fetchConfig); } } diff --git a/dist/b2c/crypto_wallets.js b/dist/b2c/crypto_wallets.js index c9c1893b..3abfdf84 100644 --- a/dist/b2c/crypto_wallets.js +++ b/dist/b2c/crypto_wallets.js @@ -7,29 +7,47 @@ exports.CryptoWallets = void 0; var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class CryptoWallets { - base_path = "crypto_wallets"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; } + /** + * Initiate the authentication of a crypto wallet. After calling this endpoint, the user will need to sign + * a message containing only the returned `challenge` field. + * @param data {@link CryptoWalletsAuthenticateStartRequest} + * @returns {@link CryptoWalletsAuthenticateStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } authenticateStart(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate/start"), + url: `/v1/crypto_wallets/authenticate/start`, data }); } + /** + * Complete the authentication of a crypto wallet by passing the signature. + * @param data {@link CryptoWalletsAuthenticateRequest} + * @returns {@link CryptoWalletsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/crypto_wallets/authenticate`, data }); } diff --git a/dist/b2c/magic_links.js b/dist/b2c/magic_links.js index 031e8200..51e8d229 100644 --- a/dist/b2c/magic_links.js +++ b/dist/b2c/magic_links.js @@ -5,82 +5,61 @@ Object.defineProperty(exports, "__esModule", { }); exports.MagicLinks = void 0; -var _shared = require("../shared"); +var _magic_links_email = require("./magic_links_email"); -class Email { - delivery = "email"; +var _shared = require("../shared"); - constructor(fetchConfig, parent_path) { +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class MagicLinks { + constructor(fetchConfig) { this.fetchConfig = fetchConfig; - this.base_path = `${parent_path}`; - } - - endpoint(path) { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data - }); - } - - loginOrCreate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data - }); - } - - invite(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("invite"), - data - }); + this.email = new _magic_links_email.Email(this.fetchConfig); } - - revokeInvite(data) { + /** + * Authenticate a User given a Magic Link. This endpoint verifies that the Magic Link token is valid, + * hasn't expired or been previously used, and any optional security settings such as IP match or user + * agent match are satisfied. + * @param data {@link MagicLinksAuthenticateRequest} + * @returns {@link MagicLinksAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("revoke_invite"), + url: `/v1/magic_links/authenticate`, data }); } + /** + * Create an embeddable Magic Link token for a User. Access to this endpoint is restricted. To enable it, + * please send us a note at support@stytch.com. + * + * ### Next steps + * Send the returned `token` value to the end user in a link which directs to your application. When the + * end user follows your link, collect the token, and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksCreateRequest} + * @returns {@link MagicLinksCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ -} - -class MagicLinks { - base_path = "magic_links"; - - constructor(fetchConfig) { - this.fetchConfig = fetchConfig; - this.email = new Email(fetchConfig, this.base_path); - } - - endpoint(path) { - return `${this.base_path}/${path}`; - } create(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.base_path, - data: data - }); - } - - authenticate(token, data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data: { - token, - ...data - } + url: `/v1/magic_links`, + data }); } diff --git a/dist/b2c/magic_links_email.js b/dist/b2c/magic_links_email.js new file mode 100644 index 00000000..3c6b5fd2 --- /dev/null +++ b/dist/b2c/magic_links_email.js @@ -0,0 +1,125 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Email = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Email { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Send a magic link to an existing Stytch user using their email address. If you'd like to create a user + * and send them a magic link by email with one request, use our + * [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email). + * + * ### Add an email to an existing user + * This endpoint also allows you to add a new email to an existing Stytch User. Including a `user_id`, + * `session_token`, or `session_jwt` in the request will add the email to the pre-existing Stytch User upon + * successful authentication. + * + * Adding a new email to an existing Stytch User requires the user to be present and validate the email via + * magic link. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * The user is emailed a magic link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/guides/magic-links/email-magic-links/redirect-routing). Collect + * the `token` from the URL query parameters, and call + * [Authenticate magic link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailSendRequest} + * @returns {@link MagicLinksEmailSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + send(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/send`, + data + }); + } + /** + * Send either a login or signup Magic Link to the User based on if the email is associated with a User + * already. A new or pending User will receive a signup Magic Link. An active User will receive a login + * Magic Link. For more information on how to control the status your Users are created in see the + * `create_user_as_pending` flag. + * + * ### Next steps + * The User is emailed a Magic Link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/magic-links#email-magic-links_redirect-routing). Collect the + * `token` from the URL query parameters and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailLoginOrCreateRequest} + * @returns {@link MagicLinksEmailLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + loginOrCreate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/login_or_create`, + data + }); + } + /** + * Create a User and send an invite Magic Link to the provided `email`. The User will be created with a + * `pending` status until they click the Magic Link in the invite email. + * + * ### Next steps + * The User is emailed a Magic Link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/magic-links#email-magic-links_redirect-routing). Collect the + * `token` from the URL query parameters and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailInviteRequest} + * @returns {@link MagicLinksEmailInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + invite(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/invite`, + data + }); + } + /** + * Revoke a pending invite based on the `email` provided. + * @param data {@link MagicLinksEmailRevokeInviteRequest} + * @returns {@link MagicLinksEmailRevokeInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + revokeInvite(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/revoke_invite`, + data + }); + } + +} + +exports.Email = Email; \ No newline at end of file diff --git a/dist/b2c/oauth.js b/dist/b2c/oauth.js index 829c9ac8..6fac1d52 100644 --- a/dist/b2c/oauth.js +++ b/dist/b2c/oauth.js @@ -7,32 +7,58 @@ exports.OAuth = void 0; var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class OAuth { - base_path = "oauth"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; } + /** + * Generate an OAuth Attach Token to pre-associate an OAuth flow with an existing Stytch User. 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 for a new user. + * + * Exactly one of `user_id`, `session_token`, or `session_jwt` must be provided to identify the target + * Stytch User. + * + * This is an optional step in the OAuth flow. Stytch can often determine whether to create a new user or + * log in an existing one based on verified identity provider information. This endpoint is useful for + * cases where we can't, such as missing or unverified provider information. + * @param data {@link OAuthAttachRequest} + * @returns {@link OAuthAttachResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } - authenticate(token, data) { + attach(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), - data: { - token, - ...data - } + url: `/v1/oauth/attach`, + data }); } + /** + * Authenticate a User given a `token`. This endpoint verifies that the user completed the OAuth flow by + * verifying that the token is valid and hasn't expired. To initiate a Stytch session for the user while + * authenticating their OAuth token, include `session_duration_minutes`; a session with the identity + * provider, e.g. Google or Facebook, will always be initiated upon successful authentication. + * @param data {@link OAuthAuthenticateRequest} + * @returns {@link OAuthAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - attach(data) { + + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("attach"), + url: `/v1/oauth/authenticate`, data }); } diff --git a/dist/b2c/otps.js b/dist/b2c/otps.js index b6e08ad5..b3e077bb 100644 --- a/dist/b2c/otps.js +++ b/dist/b2c/otps.js @@ -5,116 +5,44 @@ Object.defineProperty(exports, "__esModule", { }); exports.OTPs = void 0; -var _shared = require("../shared"); - -class Email { - delivery = "email"; - - constructor(fetchConfig, base_path) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - endpoint(path) { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data - }); - } - - loginOrCreate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data - }); - } - -} - -class SMS { - delivery = "sms"; - - constructor(fetchConfig, base_path) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - endpoint(path) { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data - }); - } - - loginOrCreate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data - }); - } - -} - -class WhatsApp { - delivery = "whatsapp"; - - constructor(fetchConfig, base_path) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - endpoint(path) { - return `${this.base_path}/${this.delivery}/${path}`; - } +var _otps_email = require("./otps_email"); - send(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data - }); - } +var _shared = require("../shared"); - loginOrCreate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data - }); - } +var _otps_sms = require("./otps_sms"); -} +var _otps_whatsapp = require("./otps_whatsapp"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class OTPs { - base_path = "otps"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; - this.email = new Email(fetchConfig, this.base_path); - this.sms = new SMS(fetchConfig, this.base_path); - this.whatsapp = new WhatsApp(fetchConfig, this.base_path); - } + this.sms = new _otps_sms.Sms(this.fetchConfig); + this.whatsapp = new _otps_whatsapp.Whatsapp(this.fetchConfig); + this.email = new _otps_email.Email(this.fetchConfig); + } + /** + * Authenticate a User given a `method_id` (the associated `email_id` or `phone_id`) and a `code`. This + * endpoint verifies that the code is valid, hasn't expired or been previously used, and any optional + * security settings such as IP match or user agent match are satisfied. A given `method_id` may only have + * a single active OTP code at any given time, if a User requests another OTP code before the first one has + * expired, the first one will be invalidated. + * @param data {@link OTPsAuthenticateRequest} + * @returns {@link OTPsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/otps/authenticate`, data }); } diff --git a/dist/b2c/otps_email.js b/dist/b2c/otps_email.js new file mode 100644 index 00000000..73dda2b3 --- /dev/null +++ b/dist/b2c/otps_email.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Email = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Email { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Send a one-time passcode (OTP) to a User using their email. If you'd like to create a user and send them + * a passcode with one request, use our + * [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email-otp). + * + * ### Add an email to an existing user + * This endpoint also allows you to add a new email to an existing Stytch User. Including a `user_id`, + * `session_token`, or `session_jwt` in the request will add the email to the pre-existing Stytch User upon + * successful authentication. + * + * Adding a new email to an existing Stytch User requires the User to be present and validate the email via + * OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsEmailSendRequest} + * @returns {@link OTPsEmailSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + send(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/otps/email/send`, + data + }); + } + /** + * Send a one-time passcode (OTP) to a User using their email. If the email is not associated with a User + * already, a User will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsEmailLoginOrCreateRequest} + * @returns {@link OTPsEmailLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + loginOrCreate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/otps/email/login_or_create`, + data + }); + } + +} + +exports.Email = Email; \ No newline at end of file diff --git a/dist/b2c/otps_sms.js b/dist/b2c/otps_sms.js new file mode 100644 index 00000000..76ff6524 --- /dev/null +++ b/dist/b2c/otps_sms.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Sms = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Sms { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Send a one-time passcode (OTP) to a user's phone number. If you'd like to create a user and send them a + * passcode with one request, use our + * [log in or create](https://stytch.com/docs/api/log-in-or-create-user-by-sms) endpoint. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * ### Add a phone number to an existing user + * + * This endpoint also allows you to add a new phone number to an existing Stytch User. Including a + * `user_id`, `session_token`, or `session_jwt` in the request will add the phone number to the + * pre-existing Stytch User upon successful authentication. + * + * Adding a new phone number to an existing Stytch User requires the user to be present and validate the + * phone number via OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsSmsSendRequest} + * @returns {@link OTPsSmsSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + send(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/otps/sms/send`, + data + }); + } + /** + * Send a one-time passcode (OTP) to a User using their phone number. If the phone number is not associated + * with a user already, a user will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsSmsLoginOrCreateRequest} + * @returns {@link OTPsSmsLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + loginOrCreate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/otps/sms/login_or_create`, + data + }); + } + +} + +exports.Sms = Sms; \ No newline at end of file diff --git a/dist/b2c/otps_whatsapp.js b/dist/b2c/otps_whatsapp.js new file mode 100644 index 00000000..74bef551 --- /dev/null +++ b/dist/b2c/otps_whatsapp.js @@ -0,0 +1,82 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Whatsapp = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Whatsapp { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Send a one-time passcode (OTP) to a User's WhatsApp. If you'd like to create a user and send them a + * passcode with one request, use our + * [log in or create](https://stytch.com/docs/api/whatsapp-login-or-create) endpoint. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * ### Add a phone number to an existing user + * + * This endpoint also allows you to add a new phone number to an existing Stytch User. Including a + * `user_id`, `session_token`, or `session_jwt` in the request will add the phone number to the + * pre-existing Stytch User upon successful authentication. + * + * Adding a new phone number to an existing Stytch User requires the user to be present and validate the + * phone number via OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsWhatsappSendRequest} + * @returns {@link OTPsWhatsappSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + send(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/otps/whatsapp/send`, + data + }); + } + /** + * Send a one-time passcode (OTP) to a User's WhatsApp using their phone number. If the phone number is not + * associated with a User already, a User will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsWhatsappLoginOrCreateRequest} + * @returns {@link OTPsWhatsappLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + loginOrCreate(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/otps/whatsapp/login_or_create`, + data + }); + } + +} + +exports.Whatsapp = Whatsapp; \ No newline at end of file diff --git a/dist/b2c/passwords.js b/dist/b2c/passwords.js index 43fa6e5e..8935b2e9 100644 --- a/dist/b2c/passwords.js +++ b/dist/b2c/passwords.js @@ -5,84 +5,140 @@ Object.defineProperty(exports, "__esModule", { }); exports.Passwords = void 0; +var _passwords_email = require("./passwords_email"); + +var _passwords_existing_password = require("./passwords_existing_password"); + var _shared = require("../shared"); -class Passwords { - base_path = "passwords"; +var _passwords_session = require("./passwords_session"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Passwords { constructor(fetchConfig) { this.fetchConfig = fetchConfig; + this.email = new _passwords_email.Email(this.fetchConfig); + this.existingPassword = new _passwords_existing_password.ExistingPassword(this.fetchConfig); + this.sessions = new _passwords_session.Sessions(this.fetchConfig); } + /** + * Create a new user with a password and an authenticated session for the user if requested. 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 password strength endpoint. + * @param data {@link PasswordsCreateRequest} + * @returns {@link PasswordsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } create(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.base_path, - data: data - }); - } - - authenticate(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data: data - }); - } - - resetByEmailStart(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("email/reset/start"), - data: data + url: `/v1/passwords`, + data }); } + /** + * Authenticate a user with their email address and password. This endpoint verifies that the user has a + * password currently set, and that the entered password is correct. There are two instances where the + * endpoint will return a `reset_password` error even if they enter their previous password: + * + * **One:** The user’s credentials appeared in the HaveIBeenPwned dataset. We force a password reset to + * ensure that the user is the legitimate owner of the email address, and not a malicious actor abusing the + * compromised credentials. + * + * **Two:** A user that has previously authenticated with email/password uses a passwordless authentication + * method tied to the same email address (e.g. Magic Links, Google OAuth) for the first time. Any + * subsequent email/password authentication attempt will result in this error. We force a password reset in + * this instance in order to safely deduplicate the account by email address, without introducing the risk + * of a pre-hijack account takeover attack. + * + * Imagine a bad actor creates many accounts using passwords and the known email addresses of their + * victims. If a victim comes to the site and logs in for the first time with an email-based passwordless + * authentication method then both the victim and the bad actor have credentials to access to the same + * account. To prevent this, any further email/password login attempts first require a password reset which + * can only be accomplished by someone with access to the underlying email address. + * @param data {@link PasswordsAuthenticateRequest} + * @returns {@link PasswordsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - resetByEmail(token, password, data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("email/reset"), - data: { - token, - password, - ...data - } - }); - } - resetByExistingPassword(data) { + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("existing_password/reset"), - data: data + url: `/v1/passwords/authenticate`, + data }); } + /** + * This API 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. + * + * This endpoint adapts to your Project's password strength configuration. If you're using + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your passwords are + * considered valid if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are considered valid if + * they meet the requirements that you've set with Stytch. You may update your password strength + * configuration in the [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * + * ### Password feedback + * + * The `feedback` object contains relevant fields for you to relay feedback to users that failed to create + * a strong enough password. + * + * If you're using zxcvbn, the `feedback` object will contain `warning` and `suggestions` for any password + * that does not meet the zxcvbn strength requirements. You can return these strings directly to the user + * to help them craft a strong password. + * + * If you're using LUDS, the `feedback` object will contain an object named `luds_requirements` which + * contain a collection of fields that the user failed or passed. You'll want to prompt the user to create + * a password that meets all of the requirements that they failed. + * @param data {@link PasswordsStrengthCheckRequest} + * @returns {@link PasswordsStrengthCheckResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - resetBySession(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("session/reset"), - data: data - }); - } strengthCheck(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("strength_check"), - data: data + url: `/v1/passwords/strength_check`, + data }); } + /** + * Adds an existing password to a User's email that doesn't have a password yet. We support migrating users + * from passwords stored with `bcrypt`, `scrypt`, `argon2`, `MD-5`, `SHA-1`, or `PBKDF2`. This endpoint has + * a rate limit of 100 requests per second. + * @param data {@link PasswordsMigrateRequest} + * @returns {@link PasswordsMigrateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + migrate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("migrate"), - data: data + url: `/v1/passwords/migrate`, + data }); } diff --git a/dist/b2c/passwords_email.js b/dist/b2c/passwords_email.js new file mode 100644 index 00000000..2af138ae --- /dev/null +++ b/dist/b2c/passwords_email.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Email = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Email { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * 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. + * @param data {@link PasswordsEmailResetStartRequest} + * @returns {@link PasswordsEmailResetStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + resetStart(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/email/reset/start`, + data + }); + } + /** + * Reset the user’s password and authenticate them. This endpoint checks that the magic link `token` is + * valid, hasn’t expired, or already been used – and can optionally require additional security settings, + * such as the IP address and user agent matching the initial reset request. + * + * The provided password needs to meet our password strength requirements, which can be checked in advance + * with the password strength endpoint. If the token and password are accepted, the password is securely + * stored for future authentication and the user is authenticated. + * @param data {@link PasswordsEmailResetRequest} + * @returns {@link PasswordsEmailResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + reset(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/email/reset`, + data + }); + } + +} + +exports.Email = Email; \ No newline at end of file diff --git a/dist/b2c/passwords_existing_password.js b/dist/b2c/passwords_existing_password.js new file mode 100644 index 00000000..5854494b --- /dev/null +++ b/dist/b2c/passwords_existing_password.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExistingPassword = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class ExistingPassword { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Reset the User’s password using their existing password. + * @param data {@link PasswordsExistingPasswordResetRequest} + * @returns {@link PasswordsExistingPasswordResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + reset(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/existing_password/reset`, + data + }); + } + +} + +exports.ExistingPassword = ExistingPassword; \ No newline at end of file diff --git a/dist/b2c/passwords_session.js b/dist/b2c/passwords_session.js new file mode 100644 index 00000000..9d5cc524 --- /dev/null +++ b/dist/b2c/passwords_session.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Sessions = void 0; + +var _shared = require("../shared"); + +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Sessions { + constructor(fetchConfig) { + this.fetchConfig = fetchConfig; + } + /** + * Reset the user’s password using their existing session. The endpoint will error if the session does not + * have a password, email magic link, or email OTP authentication factor that has been issued within the + * last 5 minutes. This endpoint requires either a `session_jwt` or `session_token` be included in the + * request. + * @param data {@link PasswordsSessionResetRequest} + * @returns {@link PasswordsSessionResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + reset(data) { + return (0, _shared.request)(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/session/reset`, + data + }); + } + +} + +exports.Sessions = Sessions; \ No newline at end of file diff --git a/dist/b2c/sessions.js b/dist/b2c/sessions.js index 5babfd7c..94f31fa4 100644 --- a/dist/b2c/sessions.js +++ b/dist/b2c/sessions.js @@ -5,13 +5,16 @@ Object.defineProperty(exports, "__esModule", { }); exports.Sessions = void 0; -var _shared = require("../shared"); - var _sessions = require("../shared/sessions"); -class Sessions { - base_path = "sessions"; +var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +class Sessions { constructor(fetchConfig, jwtConfig) { this.fetchConfig = fetchConfig; this.jwksClient = jwtConfig.jwks; @@ -21,34 +24,83 @@ class Sessions { typ: "JWT" }; } + /** + * List all active Sessions for a given `user_id`. All timestamps are formatted according to the RFC 3339 + * standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. + * @param data {@link SessionsGetRequest} + * @returns {@link SessionsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } get(params) { return (0, _shared.request)(this.fetchConfig, { method: "GET", - url: this.base_path, + url: `/v1/sessions`, params: { ...params } }); } + /** + * Authenticate a session token and retrieve associated session data. If `session_duration_minutes` is + * included, update the lifetime of the session to be that many minutes from now. All timestamps are + * formatted according to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. This + * endpoint requires exactly one `session_jwt` or `session_token` as part of the request. If both are + * included you will receive a `too_many_session_arguments` error. + * @param data {@link SessionsAuthenticateRequest} + * @returns {@link SessionsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - jwks(project_id) { + + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { - method: "GET", - url: this.endpoint(`jwks/${project_id}`) + method: "POST", + url: `/v1/sessions/authenticate`, + data }); } + /** + * Revoke a Session, immediately invalidating all of its session tokens. You can revoke a session in three + * ways: using its ID, or using one of its session tokens, or one of its JWTs. This endpoint requires + * exactly one of those to be included in the request. It will return an error if multiple are present. + * @param data {@link SessionsRevokeRequest} + * @returns {@link SessionsRevokeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - authenticate(data) { + + revoke(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/sessions/revoke`, data }); } + /** + * Get the JSON Web Key Set (JWKS) for a Stytch Project. + * @param data {@link SessionsGetJWKSRequest} + * @returns {@link SessionsGetJWKSResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + getJWKS(params) { + return (0, _shared.request)(this.fetchConfig, { + method: "GET", + url: `/v1/sessions/jwks/${params.project_id}`, + params: {} + }); + } // MANUAL(authenticateJwt)(SERVICE_METHOD) + /** Parse a JWT and verify the signature, preferring local verification over remote. * * If max_token_age_seconds is set, remote verification will be forced if the JWT was issued at @@ -101,15 +153,8 @@ class Sessions { expires_at: sess.expires_at, custom_claims: sess.custom_claims }; - } + } // ENDMANUAL(authenticateJwt) - revoke(data) { - return (0, _shared.request)(this.fetchConfig, { - method: "POST", - url: this.endpoint("revoke"), - data - }); - } } diff --git a/dist/b2c/totps.js b/dist/b2c/totps.js index b4579806..01335863 100644 --- a/dist/b2c/totps.js +++ b/dist/b2c/totps.js @@ -7,45 +7,81 @@ exports.TOTPs = void 0; var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class TOTPs { - base_path = "totps"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; } + /** + * 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. + * @param data {@link TOTPsCreateRequest} + * @returns {@link TOTPsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } create(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.base_path, + url: `/v1/totps`, data }); } + /** + * Authenticate a TOTP code entered by a user. + * @param data {@link TOTPsAuthenticateRequest} + * @returns {@link TOTPsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/totps/authenticate`, data }); } + /** + * Retrieve the recovery codes for a TOTP instance tied to a User. + * @param data {@link TOTPsRecoveryCodesRequest} + * @returns {@link TOTPsRecoveryCodesResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + recoveryCodes(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("recovery_codes"), + url: `/v1/totps/recovery_codes`, data }); } + /** + * Authenticate a recovery code for a TOTP instance. + * @param data {@link TOTPsRecoverRequest} + * @returns {@link TOTPsRecoverResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + recover(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("recover"), + url: `/v1/totps/recover`, data }); } diff --git a/dist/b2c/users.js b/dist/b2c/users.js index 8545195a..ab82e7d5 100644 --- a/dist/b2c/users.js +++ b/dist/b2c/users.js @@ -3,18 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true }); -exports.Users = exports.UserSearchIterator = exports.UserSearchOperator = void 0; +exports.Users = exports.UserSearchIterator = void 0; var _shared = require("../shared"); -let UserSearchOperator; -exports.UserSearchOperator = UserSearchOperator; - -(function (UserSearchOperator) { - UserSearchOperator["OR"] = "OR"; - UserSearchOperator["AND"] = "AND"; -})(UserSearchOperator || (exports.UserSearchOperator = UserSearchOperator = {})); - +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! +// ENDMANUAL(SearchUsersQueryOperand) +// MANUAL(UserSearchIterator)(FREE_FUNCTION) var mode; (function (mode) { @@ -55,118 +54,255 @@ class UserSearchIterator { } } -} +} // ENDMANUAL(UserSearchIterator) + exports.UserSearchIterator = UserSearchIterator; class Users { - base_path = "users"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; } + /** + * Add a User to Stytch. A `user_id` is returned in the response that can then be used to perform other + * operations within Stytch. An `email` or a `phone_number` is required. + * @param data {@link UsersCreateRequest} + * @returns {@link UsersCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } create(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.base_path, + url: `/v1/users`, data }); } + /** + * Get information about a specific User. + * @param data {@link UsersGetRequest} + * @returns {@link UsersGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - get(userID) { + + get(params) { return (0, _shared.request)(this.fetchConfig, { method: "GET", - url: this.endpoint(userID) + url: `/v1/users/${params.user_id}`, + params: {} }); } + /** + * Search for Users within your Stytch Project. Submit an empty `query` in the request to return all Users. + * @param data {@link UsersSearchRequest} + * @returns {@link UsersSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + search(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("search"), + url: `/v1/users/search`, data }); } - - searchAll(data) { - return new UserSearchIterator(this, data); - } - - update(userID, data) { + /** + * Update a User's attributes. + * + * **Note:** In order to add a new email address or phone number to an existing User object, pass the new + * email address or phone number into the respective `/send` endpoint for the authentication method of your + * choice. If you specify the existing User's `user_id` while calling the `/send` endpoint, the new email + * address or phone number will be added to the existing User object upon successful authentication. We + * require this process to guard against an account takeover vulnerability. + * @param data {@link UsersUpdateRequest} + * @returns {@link UsersUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + + + update(data) { return (0, _shared.request)(this.fetchConfig, { method: "PUT", - url: this.endpoint(userID), - data + url: `/v1/users/${data.user_id}`, + data: { + name: data.name, + attributes: data.attributes, + trusted_metadata: data.trusted_metadata, + untrusted_metadata: data.untrusted_metadata + } }); } + /** + * Delete a User from Stytch. + * @param data {@link UsersDeleteRequest} + * @returns {@link UsersDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - delete(userID) { + delete(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(userID) + url: `/v1/users/${data.user_id}`, + data: {} }); } + /** + * Delete an email from a User. + * @param data {@link UsersDeleteEmailRequest} + * @returns {@link UsersDeleteEmailResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - deleteEmail(emailID) { + + deleteEmail(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`emails/${emailID}`) + url: `/v1/users/emails/${data.email_id}`, + data: {} }); } + /** + * Delete a phone number from a User. + * @param data {@link UsersDeletePhoneNumberRequest} + * @returns {@link UsersDeletePhoneNumberResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - deletePhoneNumber(phoneID) { + deletePhoneNumber(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`phone_numbers/${phoneID}`) + url: `/v1/users/phone_numbers/${data.phone_id}`, + data: {} }); } + /** + * Delete a WebAuthn registration from a User. + * @param data {@link UsersDeleteWebAuthnRegistrationRequest} + * @returns {@link UsersDeleteWebAuthnRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - deleteWebAuthnRegistration(webAuthnRegistrationID) { + + deleteWebAuthnRegistration(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`webauthn_registrations/${webAuthnRegistrationID}`) + url: `/v1/users/webauthn_registrations/${data.webauthn_registration_id}`, + data: {} }); } + /** + * Delete a biometric registration from a User. + * @param data {@link UsersDeleteBiometricRegistrationRequest} + * @returns {@link UsersDeleteBiometricRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - deleteBiometricRegistration(biometricRegistrationID) { + deleteBiometricRegistration(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`biometric_registrations/${biometricRegistrationID}`) + url: `/v1/users/biometric_registrations/${data.biometric_registration_id}`, + data: {} }); } + /** + * Delete a TOTP from a User. + * @param data {@link UsersDeleteTOTPRequest} + * @returns {@link UsersDeleteTOTPResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - deleteTOTP(totpID) { + + deleteTOTP(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`totps/${totpID}`) + url: `/v1/users/totps/${data.totp_id}`, + data: {} }); } + /** + * Delete a crypto wallet from a User. + * @param data {@link UsersDeleteCryptoWalletRequest} + * @returns {@link UsersDeleteCryptoWalletResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - deleteCryptoWallet(cryptoWalletID) { + deleteCryptoWallet(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`crypto_wallets/${cryptoWalletID}`) + url: `/v1/users/crypto_wallets/${data.crypto_wallet_id}`, + data: {} }); } + /** + * Delete a password from a User. + * @param data {@link UsersDeletePasswordRequest} + * @returns {@link UsersDeletePasswordResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + - deletePassword(passwordID) { + deletePassword(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`passwords/${passwordID}`) + url: `/v1/users/passwords/${data.password_id}`, + data: {} }); } + /** + * Delete an OAuth registration from a User. + * @param data {@link UsersDeleteOAuthRegistrationRequest} + * @returns {@link UsersDeleteOAuthRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - deleteOAuthUserRegistration(oauthUserRegistrationID) { + + deleteOAuthRegistration(data) { return (0, _shared.request)(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`oauth/${oauthUserRegistrationID}`) + url: `/v1/users/oauth/${data.oauth_user_registration_id}`, + data: {} }); - } + } // MANUAL(searchAll)(SERVICE_METHOD) + // Return an iterator over all search results. Submit an empty `query` in the request to return all Users. + + + searchAll(data) { + return new UserSearchIterator(this, data); + } // ENDMANUAL(searchAll) + } diff --git a/dist/b2c/webauthn.js b/dist/b2c/webauthn.js index 94a4a7c5..4330aaa0 100644 --- a/dist/b2c/webauthn.js +++ b/dist/b2c/webauthn.js @@ -7,45 +7,117 @@ exports.WebAuthn = void 0; var _shared = require("../shared"); +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! class WebAuthn { - base_path = "webauthn"; - constructor(fetchConfig) { this.fetchConfig = fetchConfig; } + /** + * Initiate the process of creating a new WebAuthn registration. After calling this endpoint, the browser + * will need to call + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) with the data + * from + * [public_key_credential_creation_options](https://w3c.github.io/webauthn/#dictionary-makecredentialoptions) + * passed to the [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) + * request via the public key argument. We recommend using the `create()` wrapper provided by the + * webauthn-json library. + * + * If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, the + * `public_key_credential_creation_options` will need to be converted to a suitable public key by + * unmarshalling the JSON, base64 decoding the user ID field, and converting user ID and the challenge + * fields into an array buffer. + * @param data {@link WebAuthnRegisterStartRequest} + * @returns {@link WebAuthnRegisterStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ - endpoint(path) { - return `${this.base_path}/${path}`; - } registerStart(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("register/start"), + url: `/v1/webauthn/register/start`, data }); } + /** + * Complete the creation of a WebAuthn registration by passing the response from the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) request to + * this endpoint as the `public_key_credential` parameter. + * + * If the [webauthn-json](https://github.com/github/webauthn-json) library's `create()` method was used, + * the response can be passed directly to the + * [register endpoint](https://stytch.com/docs/api/webauthn-register). If not, some fields (the client data + * and the attestation object) from the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) response will + * need to be converted from array buffers to strings and marshalled into JSON. + * @param data {@link WebAuthnRegisterRequest} + * @returns {@link WebAuthnRegisterResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + register(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("register"), + url: `/v1/webauthn/register`, data }); } + /** + * Initiate the authentication of a WebAuthn registration. After calling this endpoint, the browser will + * need to call [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) with the + * data from `public_key_credential_request_options` passed to the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request via the + * public key argument. We recommend using the `get()` wrapper provided by the webauthn-json library. + * + * If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, `the + * public_key_credential_request_options` will need to be converted to a suitable public key by + * unmarshalling the JSON and converting some the fields to array buffers. + * @param data {@link WebAuthnAuthenticateStartRequest} + * @returns {@link WebAuthnAuthenticateStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticateStart(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate/start"), + url: `/v1/webauthn/authenticate/start`, data }); } + /** + * Complete the authentication of a WebAuthn registration by passing the response from the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request to the + * authenticate endpoint. + * + * If the [webauthn-json](https://github.com/github/webauthn-json) library's `get()` method was used, the + * response can be passed directly to the + * [authenticate endpoint](https://stytch.com/docs/api/webauthn-authenticate). If not some fields from the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) response will need to + * be converted from array buffers to strings and marshalled into JSON. + * @param data {@link WebAuthnAuthenticateRequest} + * @returns {@link WebAuthnAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data) { return (0, _shared.request)(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/webauthn/authenticate`, data }); } diff --git a/dist/index.js b/dist/index.js index 9e266bff..b7decb48 100644 --- a/dist/index.js +++ b/dist/index.js @@ -6,9 +6,7 @@ Object.defineProperty(exports, "__esModule", { var _exportNames = { Client: true, B2BClient: true, - envs: true, - UserSearchOperator: true, - SearchOperator: true + envs: true }; Object.defineProperty(exports, "Client", { enumerable: true, @@ -22,18 +20,6 @@ Object.defineProperty(exports, "B2BClient", { return _client2.B2BClient; } }); -Object.defineProperty(exports, "UserSearchOperator", { - enumerable: true, - get: function () { - return _users.UserSearchOperator; - } -}); -Object.defineProperty(exports, "SearchOperator", { - enumerable: true, - get: function () { - return _shared_b2b.SearchOperator; - } -}); exports.envs = void 0; var _client = require("./b2c/client"); @@ -72,10 +58,6 @@ var _envs = _interopRequireWildcard(require("./shared/envs")); exports.envs = _envs; -var _users = require("./b2c/users"); - -var _shared_b2b = require("./b2b/shared_b2b"); - var _errors = require("./shared/errors"); Object.keys(_errors).forEach(function (key) { diff --git a/dist/shared/envs.js b/dist/shared/envs.js index ce57f9ec..2cfb8295 100644 --- a/dist/shared/envs.js +++ b/dist/shared/envs.js @@ -4,7 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.live = exports.test = void 0; -const test = "https://test.stytch.com/v1/"; +const test = "https://test.stytch.com/"; exports.test = test; -const live = "https://api.stytch.com/v1/"; +const live = "https://api.stytch.com/"; exports.live = live; \ No newline at end of file diff --git a/lib/b2b/client.ts b/lib/b2b/client.ts index 6a5f1a32..f176e4bf 100644 --- a/lib/b2b/client.ts +++ b/lib/b2b/client.ts @@ -1,50 +1,48 @@ -import { MagicLinks } from "./magic_links"; -import { Sessions } from "./sessions"; -import { Organizations } from "./organizations"; -import { SSO } from "./sso"; -import { BaseClient, ClientConfig } from "../shared/client"; import * as jose from "jose"; -import { JwtConfig } from "../shared/sessions"; +import { BaseClient, ClientConfig } from "../shared/client"; import { Discovery } from "./discovery"; -import { Passwords } from "./passwords"; +import { JwtConfig } from "../shared/sessions"; +import { MagicLinks } from "./magic_links"; import { OAuth } from "./oauth"; -import { OTPs } from "./otps"; +import { Organizations } from "./organizations"; +import { OTPs } from "./otp"; +import { Passwords } from "./passwords"; +import { Sessions } from "./sessions"; +import { SSO } from "./sso"; export class B2BClient extends BaseClient { protected jwtConfig: JwtConfig; + discovery: Discovery; magicLinks: MagicLinks; - sessions: Sessions; oauth: OAuth; + otps: OTPs; organizations: Organizations; - sso: SSO; - discovery: Discovery; passwords: Passwords; - otps: OTPs; + sso: SSO; + sessions: Sessions; constructor(config: ClientConfig) { super(config); - if (!this.fetchConfig.baseURL.endsWith("b2b/")) { - this.fetchConfig.baseURL += "b2b/"; - } - this.jwtConfig = { // Only allow JWTs that were meant for this project. projectID: config.project_id, // Fetch the signature verification keys for this project as needed. jwks: jose.createRemoteJWKSet( - new URL(`sessions/jwks/${config.project_id}`, this.fetchConfig.baseURL) + new URL( + `/v1/sessions/jwks/${config.project_id}`, + this.fetchConfig.baseURL + ) ), }; + this.discovery = new Discovery(this.fetchConfig); this.magicLinks = new MagicLinks(this.fetchConfig); - this.sessions = new Sessions(this.fetchConfig, this.jwtConfig); this.oauth = new OAuth(this.fetchConfig); + this.otps = new OTPs(this.fetchConfig); this.organizations = new Organizations(this.fetchConfig); - this.sso = new SSO(this.fetchConfig); - this.discovery = new Discovery(this.fetchConfig); this.passwords = new Passwords(this.fetchConfig); - this.oauth = new OAuth(this.fetchConfig); - this.otps = new OTPs(this.fetchConfig); + this.sso = new SSO(this.fetchConfig); + this.sessions = new Sessions(this.fetchConfig, this.jwtConfig); } } diff --git a/lib/b2b/discovery.ts b/lib/b2b/discovery.ts index 2115b1ae..4c61ab2d 100644 --- a/lib/b2b/discovery.ts +++ b/lib/b2b/discovery.ts @@ -1,122 +1,66 @@ -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import { BaseResponse, request, fetchConfig } from "../shared"; -import { DiscoveredOrganization } from "./organizations"; -import { MfaRequired } from "./mfa"; - -export interface B2BDiscoveryOrganizationsRequest { - intermediate_session_token?: string; - session_token?: string; - session_jwt?: string; -} - -export interface B2BDiscoveryOrganizationsResponse extends BaseResponse { - email_address: string; - discovered_organizations: DiscoveredOrganization[]; - organization_id_hint: string | null; -} - -export interface B2BDiscoveryOrganizationCreateRequest { - intermediate_session_token: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - organization_name?: string; - organization_slug?: string; - organization_logo_url?: string; - trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - sso_jit_provisioning?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - email_allowed_domains?: string[]; - email_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; - email_invites?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - auth_methods?: "ALL_ALLOWED" | "RESTRICTED"; - allowed_auth_methods?: string[]; - mfa_policy?: "OPTIONAL" | "REQUIRED_FOR_ALL"; -} - -export interface B2BDiscoveryOrganizationCreateResponse - extends ResponseWithMember { - member_session: MemberSession | null; - session_token: string; - session_jwt: string; - member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; -} +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export interface B2BDiscoveryIntermediateSessionExchangeRequest { - intermediate_session_token: string; - organization_id: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - locale?: "en" | "es" | "pt-br" | string; -} +import { fetchConfig } from "../shared"; +import { IntermediateSessions } from "./discovery_intermediate_sessions"; +import { Member, Organization } from "./organizations"; +import { MfaRequired } from "./mfa"; +import { Organizations } from "./discovery_organizations"; -export interface B2BDiscoveryIntermediateSessionExchangeResponse - extends ResponseWithMember { - member_session: MemberSession | null; - session_token: string; - session_jwt: string; +export interface DiscoveredOrganization { + /** + * Indicates whether the Member has all of the factors needed to fully authenticate to this Organization. + * If false, the Member may need to complete an MFA step or complete a different primary authentication + * flow. See the `primary_required` and `mfa_required` fields for more details on each. + */ member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization?: Organization; + // Information about the membership. + membership?: Membership; + // (Coming Soon) Information about the primary authentication requirements of the Organization. + primary_required?: PrimaryRequired; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } -class Organizations { - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig) { - this.fetchConfig = fetchConfig; - } - - list( - data: B2BDiscoveryOrganizationsRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: "discovery/organizations", - data, - }); - } - - create( - data: B2BDiscoveryOrganizationCreateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: "discovery/organizations/create", - data, - }); - } +export interface Membership { + // Either `active_member`, `pending_member`, `invited_member`, or `eligible_to_join_by_email_domain` + type: string; + // An object containing additional metadata about the membership, if available. + details?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The [Member object](https://stytch.com/docs/b2b/api/member-object) if one already exists, or null if one + * does not. + */ + member?: Member; } -class IntermediateSessions { - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig) { - this.fetchConfig = fetchConfig; - } - - exchange( - data: B2BDiscoveryIntermediateSessionExchangeRequest - ): Promise { - return request( - this.fetchConfig, - { - method: "POST", - url: "discovery/intermediate_sessions/exchange", - data, - } - ); - } +export interface PrimaryRequired { + /** + * If non-empty, indicates that the Organization restricts the authentication methods it allows for login + * (such as `sso` or `password`), and the end user must complete one of those authentication methods to log + * in. If empty, indicates that the Organization does not restrict the authentication method it allows for + * login, but the end user does not have any transferrable primary factors. Only email magic link and OAuth + * factors can be transferred between Organizations. + */ + allowed_auth_methods: string[]; } export class Discovery { private fetchConfig: fetchConfig; - organizations: Organizations; intermediateSessions: IntermediateSessions; + organizations: Organizations; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; - this.organizations = new Organizations(this.fetchConfig); this.intermediateSessions = new IntermediateSessions(this.fetchConfig); + this.organizations = new Organizations(this.fetchConfig); } } diff --git a/lib/b2b/discovery_intermediate_sessions.ts b/lib/b2b/discovery_intermediate_sessions.ts new file mode 100644 index 00000000..82a431d8 --- /dev/null +++ b/lib/b2b/discovery_intermediate_sessions.ts @@ -0,0 +1,171 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +import { request } from "../shared"; + +// Request type for `discovery.intermediateSessions.exchange`. +export interface B2BDiscoveryIntermediateSessionsExchangeRequest { + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `discovery.intermediateSessions.exchange`. +export interface B2BDiscoveryIntermediateSessionsExchangeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * The returned Intermediate Session Token is identical to the one that was originally passed in to the + * request. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ + intermediate_session_token: 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} + +export class IntermediateSessions { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Exchange an Intermediate Session for a fully realized + * [Member Session](https://stytch.com/docs/b2b/api/session-object) in a desired + * [Organization](https://stytch.com/docs/b2b/api/organization-object). + * This operation consumes the Intermediate Session. + * + * This endpoint can be used to accept invites and create new members via domain matching. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`. + * The `intermediate_session_token` will not be consumed and instead will be returned in the response. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BDiscoveryIntermediateSessionsExchangeRequest} + * @returns {@link B2BDiscoveryIntermediateSessionsExchangeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + exchange( + data: B2BDiscoveryIntermediateSessionsExchangeRequest + ): Promise { + return request( + this.fetchConfig, + { + method: "POST", + url: `/v1/b2b/discovery/intermediate_sessions/exchange`, + data, + } + ); + } +} diff --git a/lib/b2b/discovery_organizations.ts b/lib/b2b/discovery_organizations.ts new file mode 100644 index 00000000..7ef8b5c6 --- /dev/null +++ b/lib/b2b/discovery_organizations.ts @@ -0,0 +1,347 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { DiscoveredOrganization } from "./discovery"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +import { request } from "../shared"; + +// Request type for `discovery.organizations.create`. +export interface B2BDiscoveryOrganizationsCreateRequest { + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + /** + * The name of the Organization. If the name is not specified, a default name will be created based on the + * email used to initiate the discovery flow. If the email domain is a common email provider such as + * gmail.com, or if the email is a .edu email, the organization name will be generated based on the name + * portion of the email. Otherwise, the organization name will be generated based on the email domain. + */ + 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: `-` `.` `_` `~`. If the slug is not + * specified, a default slug will be created based on the email used to initiate the discovery flow. If the + * email domain is a common email provider such as gmail.com, or if the email is a .edu email, the + * organization slug will be generated based on the name portion of the email. Otherwise, the organization + * slug will be generated based on the email domain. + */ + organization_slug: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // The image URL of the Organization logo. + organization_logo_url?: string; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ + 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: + * + * `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?: string; + /** + * 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?: string; + /** + * 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`, and `microsoft_oauth`. + * + */ + allowed_auth_methods?: string[]; + /** + * (Coming Soon) 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; +} + +// Response type for `discovery.organizations.create`. +export interface B2BDiscoveryOrganizationsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * The returned Intermediate Session Token is identical to the one that was originally passed in to the + * request. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ + intermediate_session_token: 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization?: Organization; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} + +// Request type for `discovery.organizations.list`. +export interface B2BDiscoveryOrganizationsListRequest { + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token?: string; + // A secret token for a given Stytch Session. + session_token?: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt?: string; +} + +// Response type for `discovery.organizations.list`. +export interface B2BDiscoveryOrganizationsListResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The email address. + email_address: string; + /** + * An array of `discovered_organization` objects tied to the `intermediate_session_token`, `session_token`, + * or `session_jwt`. See the + * [Discovered Organization Object](https://stytch.com/docs/b2b/api/discovered-organization-object) for + * complete details. + * + * Note that Organizations will only appear here under any of the following conditions: + * 1. The end user is already a Member of the Organization. + * 2. The end user is invited to the Organization. + * 3. The end user can join the Organization because: + * + * a) The Organization allows JIT provisioning. + * + * b) The Organizations' allowed domains list contains the Member's email domain. + * + * c) The Organization has at least one other Member with a verified email address with the same + * domain as the end user (to prevent phishing attacks). + */ + discovered_organizations: DiscoveredOrganization[]; + /** + * 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; + /** + * If the intermediate session token is associated with a specific Organization, that Organization ID will + * be returned here. The Organization ID will be null if the intermediate session token was generated by a + * email magic link discovery or OAuth discovery flow. If a session token or session JWT is provided, the + * Organization ID hint will be null. + */ + organization_id_hint?: string; +} + +export class Organizations { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * If an end user does not want to join any already-existing organization, or has no possible organizations + * to join, this endpoint can be used to create a new + * [Organization](https://stytch.com/docs/b2b/api/organization-object) and + * [Member](https://stytch.com/docs/b2b/api/member-object). + * + * This operation consumes the Intermediate Session. + * + * This endpoint can also be used to start an initial session for the newly created member and organization. + * + * (Coming Soon) If the new Organization is created with a `mfa_policy` of `REQUIRED_FOR_ALL`, the newly + * created Member will need to complete an MFA step to log in to the Organization. + * The `intermediate_session_token` will not be consumed and instead will be returned in the response. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BDiscoveryOrganizationsCreateRequest} + * @returns {@link B2BDiscoveryOrganizationsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create( + data: B2BDiscoveryOrganizationsCreateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/discovery/organizations/create`, + data, + }); + } + + /** + * List all possible organization relationships connected to a + * [Member Session](https://stytch.com/docs/b2b/api/session-object) or Intermediate Session. + * + * When a Member Session is passed in, relationships with a type of `active_member`, `pending_member`, or + * `invited_member` + * will be returned, and any membership can be assumed by calling the + * [Exchange Session](https://stytch.com/docs/b2b/api/exchange-session) endpoint. + * + * When an Intermediate Session is passed in, all relationship types - `active_member`, `pending_member`, + * `invited_member`, + * and `eligible_to_join_by_email_domain` - will be returned, + * and any membership can be assumed by calling the + * [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) endpoint. + * + * This endpoint requires either an `intermediate_session_token`, `session_jwt` or `session_token` be + * included in the request. + * It will return an error if multiple are present. + * + * This operation does not consume the Intermediate Session or Session Token passed in. + * @param data {@link B2BDiscoveryOrganizationsListRequest} + * @returns {@link B2BDiscoveryOrganizationsListResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + list( + data: B2BDiscoveryOrganizationsListRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/discovery/organizations`, + data, + }); + } +} diff --git a/lib/b2b/index.ts b/lib/b2b/index.ts index db1fb6ae..973f85a2 100644 --- a/lib/b2b/index.ts +++ b/lib/b2b/index.ts @@ -1,128 +1,176 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +// MANUAL(exports)(TYPES) +export type { SearchQueryOperand } from "./organizations"; +// ENDMANUAL(exports) + +export type { MemberOptions, MfaRequired } from "./mfa"; + export type { - B2BAuthenticationFactor, - MemberSession, + ActiveSSOConnection, Member, - SSORegistration, OAuthRegistration, -} from "./shared_b2b"; + Organization, + B2BOrganizationsResultsMetadata, + SSORegistration, + SearchQuery, + B2BOrganizationsCreateRequest, + B2BOrganizationsCreateResponse, + B2BOrganizationsDeleteRequest, + B2BOrganizationsDeleteResponse, + B2BOrganizationsGetRequest, + B2BOrganizationsGetResponse, + B2BOrganizationsSearchRequest, + B2BOrganizationsSearchResponse, + B2BOrganizationsUpdateRequest, + B2BOrganizationsUpdateResponse, +} from "./organizations"; + +export type { + B2BOrganizationsMembersCreateRequest, + B2BOrganizationsMembersCreateResponse, + B2BOrganizationsMembersDeleteMFAPhoneNumberRequest, + B2BOrganizationsMembersDeleteMFAPhoneNumberResponse, + B2BOrganizationsMembersDeletePasswordRequest, + B2BOrganizationsMembersDeletePasswordResponse, + B2BOrganizationsMembersDeleteRequest, + B2BOrganizationsMembersDeleteResponse, + B2BOrganizationsMembersGetRequest, + B2BOrganizationsMembersGetResponse, + B2BOrganizationsMembersSearchRequest, + B2BOrganizationsMembersSearchResponse, + B2BOrganizationsMembersUpdateRequest, + B2BOrganizationsMembersUpdateResponse, +} from "./organizations_members"; + +export type { + MemberSession, + B2BSessionsAuthenticateRequest, + B2BSessionsAuthenticateResponse, + B2BSessionsExchangeRequest, + B2BSessionsExchangeResponse, + B2BSessionsGetJWKSRequest, + B2BSessionsGetJWKSResponse, + B2BSessionsGetRequest, + B2BSessionsGetResponse, + B2BSessionsRevokeRequest, + B2BSessionsRevokeResponse, +} from "./sessions"; export type { - B2BDiscoveryIntermediateSessionExchangeRequest, - B2BDiscoveryIntermediateSessionExchangeResponse, - B2BDiscoveryOrganizationCreateRequest, - B2BDiscoveryOrganizationCreateResponse, - B2BDiscoveryOrganizationsRequest, - B2BDiscoveryOrganizationsResponse, + DiscoveredOrganization, + Membership, + PrimaryRequired, } from "./discovery"; +export type { + B2BDiscoveryIntermediateSessionsExchangeRequest, + B2BDiscoveryIntermediateSessionsExchangeResponse, +} from "./discovery_intermediate_sessions"; + +export type { + B2BDiscoveryOrganizationsCreateRequest, + B2BDiscoveryOrganizationsCreateResponse, + B2BDiscoveryOrganizationsListRequest, + B2BDiscoveryOrganizationsListResponse, +} from "./discovery_organizations"; + export type { B2BMagicLinksAuthenticateRequest, B2BMagicLinksAuthenticateResponse, - B2BMagicLinksInviteByEmailRequest, - B2BMagicLinksInviteByEmailResponse, - B2BMagicLinksDiscoveryAuthenticateRequest, - B2BMagicLinksDiscoveryAuthenticateResponse, - B2BMagicLinksDiscoveryByEmailRequest, - B2BMagicLinksDiscoveryByEmailResponse, - B2BMagicLinksLoginOrSignupByEmailRequest, - B2BMagicLinksLoginOrSignupByEmailResponse, } from "./magic_links"; export type { - B2BMemberCreateRequest, - B2BMemberCreateResponse, - B2BMemberGetRequest, - B2BMemberGetResponse, - B2BMemberUpdateRequest, - B2BMemberUpdateResponse, - B2BMemberDeleteRequest, - B2BMemberDeleteResponse, - B2BMemberSearchRequest, - B2BMemberSearchResponse, -} from "./members"; + B2BMagicLinksEmailInviteRequest, + B2BMagicLinksEmailInviteResponse, + B2BMagicLinksEmailLoginOrSignupRequest, + B2BMagicLinksEmailLoginOrSignupResponse, +} from "./magic_links_email"; export type { - B2BOIDCCreateConnectionRequest, - B2BOIDCCreateConnectionResponse, - B2BOIDCUpdateConnectionRequest, - B2BOIDCUpdateConnectionResponse, -} from "./oidc"; + B2BMagicLinksEmailDiscoverySendRequest, + B2BMagicLinksEmailDiscoverySendResponse, +} from "./magic_links_email_discovery"; export type { + B2BMagicLinksDiscoveryAuthenticateRequest, + B2BMagicLinksDiscoveryAuthenticateResponse, +} from "./magic_links_discovery"; + +export type { + B2BOAuthProviderValues, B2BOAuthAuthenticateRequest, B2BOAuthAuthenticateResponse, - B2BDiscoveryOAuthAuthenticateRequest, - B2BDiscoveryOAuthAuthenticateResponse, } from "./oauth"; export type { - B2BOrganizationCreateRequest, - B2BOrganizationCreateResponse, - B2BOrganizationGetRequest, - B2BOrganizationGetResponse, - B2BOrganizationUpdateRequest, - B2BOrganizationUpdateResponse, - B2BOrganizationSearchRequest, - B2BOrganizationSearchResponse, - B2BOrganizationDeleteRequest, - B2BOrganizationDeleteResponse, - Organization, - DiscoveredOrganization, -} from "./organizations"; + B2BOAuthDiscoveryAuthenticateRequest, + B2BOAuthDiscoveryAuthenticateResponse, +} from "./oauth_discovery"; + +export type { + B2BOTPSmsAuthenticateRequest, + B2BOTPSmsAuthenticateResponse, + B2BOTPSmsSendRequest, + B2BOTPSmsSendResponse, +} from "./otp_sms"; export type { + LudsFeedback, + ZxcvbnFeedback, B2BPasswordsAuthenticateRequest, B2BPasswordsAuthenticateResponse, B2BPasswordsMigrateRequest, B2BPasswordsMigrateResponse, B2BPasswordsStrengthCheckRequest, B2BPasswordsStrengthCheckResponse, - B2BPasswordsEmailResetStartRequest, - B2BPasswordsEmailResetStartResponse, +} from "./passwords"; + +export type { B2BPasswordsEmailResetRequest, B2BPasswordsEmailResetResponse, - B2BPasswordsExistingPasswordResetRequest, - B2BPasswordsExistingPasswordResetResponse, - B2BPasswordsSessionResetRequest, - B2BPasswordsSessionResetResponse, -} from "./passwords"; + B2BPasswordsEmailResetStartRequest, + B2BPasswordsEmailResetStartResponse, +} from "./passwords_email"; export type { - B2BSAMLCreateConnectionRequest, - B2BSAMLCreateConnectionResponse, - B2BSAMLUpdateConnectionRequest, - B2BSAMLUpdateConnectionResponse, - B2BSAMLDeleteVerificationCertificateRequest, - B2BSAMLDeleteVerificationCertificateResponse, -} from "./saml"; + B2BPasswordsSessionResetRequest, + B2BPasswordsSessionResetResponse, +} from "./passwords_session"; export type { - B2BSessionsAuthenticateRequest, - B2BSessionsAuthenticateResponse, - B2BSessionsGetRequest, - B2BSessionsGetResponse, - B2BSessionsExchangeRequest, - B2BSessionsExchangeResponse, - B2BSessionsRevokeRequest, - B2BSessionsRevokeResponse, - B2BSessionsJwksResponse, -} from "./sessions"; + B2BPasswordsExistingPasswordResetRequest, + B2BPasswordsExistingPasswordResetResponse, +} from "./passwords_existing_password"; export type { + OIDCConnection, + SAMLConnection, + X509Certificate, B2BSSOAuthenticateRequest, B2BSSOAuthenticateResponse, - B2BSSOGetConnectionsRequest, - B2BSSOGetConnectionsResponse, B2BSSODeleteConnectionRequest, B2BSSODeleteConnectionResponse, - X509Certificate, - SAMLConnection, - OIDCConnection, + B2BSSOGetConnectionsRequest, + B2BSSOGetConnectionsResponse, } from "./sso"; export type { - B2BOTPsSMSSendRequest, - B2BOTPsSMSSendResponse, - B2BOTPsSMSAuthenticateRequest, - B2BOTPsSMSAuthenticateResponse, -} from "./otps"; + B2BSSOOIDCCreateConnectionRequest, + B2BSSOOIDCCreateConnectionResponse, + B2BSSOOIDCUpdateConnectionRequest, + B2BSSOOIDCUpdateConnectionResponse, +} from "./sso_oidc"; + +export type { + B2BSSOSAMLCreateConnectionRequest, + B2BSSOSAMLCreateConnectionResponse, + B2BSSOSAMLDeleteVerificationCertificateRequest, + B2BSSOSAMLDeleteVerificationCertificateResponse, + B2BSSOSAMLUpdateConnectionRequest, + B2BSSOSAMLUpdateConnectionResponse, +} from "./sso_saml"; diff --git a/lib/b2b/magic_links.ts b/lib/b2b/magic_links.ts index e7d4e502..69879f2d 100644 --- a/lib/b2b/magic_links.ts +++ b/lib/b2b/magic_links.ts @@ -1,179 +1,190 @@ -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import { BaseResponse, fetchConfig, request } from "../shared"; -import { DiscoveredOrganization } from "./organizations"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Discovery } from "./magic_links_discovery"; +import { Email } from "./magic_links_email"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; import { MfaRequired } from "./mfa"; +import { request } from "../shared"; -export interface B2BMagicLinksLoginOrSignupByEmailRequest { - organization_id: string; - email_address: string; - login_redirect_url?: string; - signup_redirect_url?: string; - pkce_code_challenge?: string; - login_template_id?: string; - signup_template_id?: string; - locale?: "en" | "es" | "pt-br" | string; -} - -export interface B2BMagicLinksLoginOrSignupByEmailResponse - extends ResponseWithMember { - member_created: boolean; -} - -export interface B2BMagicLinksInviteByEmailRequest { - organization_id: string; - email_address: string; - name?: string; - invite_redirect_url?: string; - invited_by_member_id?: string; - invite_template_id?: string; - trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - locale?: "en" | "es" | "pt-br" | string; -} - -export type B2BMagicLinksInviteByEmailResponse = ResponseWithMember; - +// Request type for `magicLinks.authenticate`. export interface B2BMagicLinksAuthenticateRequest { + // The Email Magic Link token to authenticate. magic_links_token: string; + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. + pkce_code_verifier?: string; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_token`, Stytch will + * update the session. + * If the `session_token` and `magic_links_token` belong to different Members, the `session_token` + * will be ignored. This endpoint will error if + * both `session_token` and `session_jwt` are provided. + */ session_token?: string; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_jwt`, Stytch will + * update the session. If the `session_jwt` + * and `magic_links_token` belong to different Members, the `session_jwt` will be ignored. This + * endpoint will error if both `session_token` and `session_jwt` + * are provided. + */ session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - pkce_code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BMagicLinksAuthenticateResponse extends ResponseWithMember { - organization_id: string; +// Response type for `magicLinks.authenticate`. +export interface B2BMagicLinksAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The email or device involved in the authentication. method_id: string; - member_session: MemberSession | null; - session_token?: string; - session_jwt?: string; + /** + * Indicates if all Sessions linked to the Member need to be reset. You should check this field if you + * aren't using + * Stytch's Session product. If you are using Stytch's Session product, we revoke the Member’s other + * Sessions for you. + */ reset_sessions: boolean; - member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; -} - -export interface B2BMagicLinksDiscoveryByEmailRequest { - email_address: string; - discovery_redirect_url?: string; - pkce_code_challenge?: string; - login_template_id?: string; - locale?: "en" | "es" | "pt-br" | string; -} - -export type B2BMagicLinksDiscoveryByEmailResponse = BaseResponse; - -export interface B2BMagicLinksDiscoveryAuthenticateRequest { - discovery_magic_links_token: string; - pkce_code_verifier?: string; -} - -export interface B2BMagicLinksDiscoveryAuthenticateResponse - extends BaseResponse { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session: MemberSession; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * The returned Intermediate Session Token contains an Email Magic Link factor associated with the Member's + * email address. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization that allows login with Email Magic Links, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ intermediate_session_token: string; - email_address: string; - discovered_organizations: DiscoveredOrganization[]; -} - -class EmailDiscovery { - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig) { - this.fetchConfig = fetchConfig; - } - - send( - data: B2BMagicLinksDiscoveryByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: "magic_links/email/discovery/send", - data, - }); - } -} - -class Discovery { - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig) { - this.fetchConfig = fetchConfig; - } - - authenticate( - data: B2BMagicLinksDiscoveryAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: "magic_links/discovery/authenticate", - data, - }); - } -} - -class Email { - private base_path: string; - private delivery = "email"; - - private fetchConfig: fetchConfig; - discovery: EmailDiscovery; - - constructor(fetchConfig: fetchConfig, parent_path: string) { - this.fetchConfig = fetchConfig; - this.base_path = `${parent_path}`; - this.discovery = new EmailDiscovery(fetchConfig); - } - - private endpoint(path: string): string { - return `${this.base_path}/${this.delivery}/${path}`; - } - - loginOrSignup( - data: B2BMagicLinksLoginOrSignupByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_signup"), - data, - }); - } - - invite( - data: B2BMagicLinksInviteByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("invite"), - data, - }); - } + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } export class MagicLinks { - private base_path = "magic_links"; + private fetchConfig: fetchConfig; email: Email; discovery: Discovery; - private fetchConfig: fetchConfig; - constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; - this.email = new Email(fetchConfig, this.base_path); - this.discovery = new Discovery(fetchConfig); - } - - private endpoint(path: string): string { - return `${this.base_path}/${path}`; + this.email = new Email(this.fetchConfig); + this.discovery = new Discovery(this.fetchConfig); } + /** + * Authenticate a Member with a Magic Link. This endpoint requires a Magic Link token that is not expired + * or previously used. If the Member’s status is `pending` or `invited`, they will be updated to `active`. + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. If the + * `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 minute + * duration. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BMagicLinksAuthenticateRequest} + * @returns {@link B2BMagicLinksAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( data: B2BMagicLinksAuthenticateRequest ): Promise { return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/b2b/magic_links/authenticate`, data, }); } diff --git a/lib/b2b/magic_links_discovery.ts b/lib/b2b/magic_links_discovery.ts new file mode 100644 index 00000000..7d3bd030 --- /dev/null +++ b/lib/b2b/magic_links_discovery.ts @@ -0,0 +1,95 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { DiscoveredOrganization } from "./discovery"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; + +// Request type for `magicLinks.discovery.authenticate`. +export interface B2BMagicLinksDiscoveryAuthenticateRequest { + // The Discovery Email Magic Link token to authenticate. + discovery_magic_links_token: string; + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. + pkce_code_verifier?: string; +} + +// Response type for `magicLinks.discovery.authenticate`. +export interface B2BMagicLinksDiscoveryAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + // The email address. + email_address: string; + /** + * An array of `discovered_organization` objects tied to the `intermediate_session_token`, `session_token`, + * or `session_jwt`. See the + * [Discovered Organization Object](https://stytch.com/docs/b2b/api/discovered-organization-object) for + * complete details. + * + * Note that Organizations will only appear here under any of the following conditions: + * 1. The end user is already a Member of the Organization. + * 2. The end user is invited to the Organization. + * 3. The end user can join the Organization because: + * + * a) The Organization allows JIT provisioning. + * + * b) The Organizations' allowed domains list contains the Member's email domain. + * + * c) The Organization has at least one other Member with a verified email address with the same + * domain as the end user (to prevent phishing attacks). + */ + discovered_organizations: DiscoveredOrganization[]; + /** + * 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; +} + +export class Discovery { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Authenticates the Discovery Magic Link token and exchanges it for an Intermediate Session Token. + * Intermediate Session Tokens can be used for various Discovery login flows and are valid for 10 minutes. + * @param data {@link B2BMagicLinksDiscoveryAuthenticateRequest} + * @returns {@link B2BMagicLinksDiscoveryAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate( + data: B2BMagicLinksDiscoveryAuthenticateRequest + ): Promise { + return request( + this.fetchConfig, + { + method: "POST", + url: `/v1/b2b/magic_links/discovery/authenticate`, + data, + } + ); + } +} diff --git a/lib/b2b/magic_links_email.ts b/lib/b2b/magic_links_email.ts new file mode 100644 index 00000000..492cae2f --- /dev/null +++ b/lib/b2b/magic_links_email.ts @@ -0,0 +1,214 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Discovery } from "./magic_links_email_discovery"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { request } from "../shared"; + +// Request type for `magicLinks.email.invite`. +export interface B2BMagicLinksEmailInviteRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // The email address of the Member. + 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; + // The `member_id` of the Member who sends the invite. + invited_by_member_id?: string; + // The name of the Member. + name?: string; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `magicLinks.email.invite`. +export interface B2BMagicLinksEmailInviteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; +} + +// Request type for `magicLinks.email.loginOrSignup`. +export interface B2BMagicLinksEmailLoginOrSignupRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // The email address of the Member. + email_address: string; + /** + * The URL that the Member clicks from the login 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 login. 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 Member clicks from the signup 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 login. 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; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + pkce_code_challenge?: string; + /** + * Use a custom template for login emails. By default, it will use your default email template. The + * template must be from Stytch's + * built-in customizations or a custom HTML email for Magic Links - Login. + */ + login_template_id?: string; + /** + * Use a custom template for signup emails. By default, it will use your default email template. The + * template must be from Stytch's + * built-in customizations or a custom HTML email for Magic Links - Signup. + */ + 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `magicLinks.email.loginOrSignup`. +export interface B2BMagicLinksEmailLoginOrSignupResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + /** + * A flag indicating `true` if a new Member object was created and `false` if the Member object already + * existed. + */ + member_created: boolean; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; +} + +export class Email { + private fetchConfig: fetchConfig; + discovery: Discovery; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + this.discovery = new Discovery(this.fetchConfig); + } + + /** + * Send either a login or signup magic link to a Member. A new, pending, or invited Member will receive a + * signup Email Magic Link. Members will have a `pending` status until they successfully authenticate. An + * active Member will receive a login Email Magic Link. + * @param data {@link B2BMagicLinksEmailLoginOrSignupRequest} + * @returns {@link B2BMagicLinksEmailLoginOrSignupResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrSignup( + data: B2BMagicLinksEmailLoginOrSignupRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/magic_links/email/login_or_signup`, + data, + }); + } + + /** + * Send an invite email to a new Member to join an Organization. The Member will be created with an + * `invited` status until they successfully authenticate. Sending invites to `pending` Members will update + * their status to `invited`. Sending invites to already `active` Members will return an error. + * @param data {@link B2BMagicLinksEmailInviteRequest} + * @returns {@link B2BMagicLinksEmailInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + invite( + data: B2BMagicLinksEmailInviteRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/magic_links/email/invite`, + data, + }); + } +} diff --git a/lib/b2b/magic_links_email_discovery.ts b/lib/b2b/magic_links_email_discovery.ts new file mode 100644 index 00000000..222a6628 --- /dev/null +++ b/lib/b2b/magic_links_email_discovery.ts @@ -0,0 +1,86 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { request } from "../shared"; + +// Request type for `magicLinks.email.discovery.send`. +export interface B2BMagicLinksEmailDiscoverySendRequest { + // The email address of the Member. + email_address: string; + /** + * The URL that the end user clicks from the discovery Magic Link. This URL should be an endpoint in the + * backend server that + * verifies the request by querying Stytch's discovery authenticate endpoint and continues the flow. 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; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + pkce_code_challenge?: string; + /** + * Use a custom template for discovery emails. By default, it will use your default email template. The + * template must be from Stytch's + * built-in customizations or a custom HTML email for Magic Links - Login. + */ + login_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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `magicLinks.email.discovery.send`. +export interface B2BMagicLinksEmailDiscoverySendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} + +export class Discovery { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Send a discovery magic link to an email address. + * @param data {@link B2BMagicLinksEmailDiscoverySendRequest} + * @returns {@link B2BMagicLinksEmailDiscoverySendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send( + data: B2BMagicLinksEmailDiscoverySendRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/magic_links/email/discovery/send`, + data, + }); + } +} diff --git a/lib/b2b/members.ts b/lib/b2b/members.ts deleted file mode 100644 index 0c9ca2fc..00000000 --- a/lib/b2b/members.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { - Member, - SearchOperator, - ResultsMetadata, - ResponseWithMember, -} from "./shared_b2b"; -import { BaseResponse, request, fetchConfig } from "../shared"; -import { Organization } from "./organizations"; - -export interface B2BMemberCreateRequest { - organization_id: string; - email_address: string; - name?: string; - trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - create_member_as_pending?: boolean; - is_breakglass?: boolean; - mfa_phone_number?: string; - mfa_enrolled?: boolean; -} - -export type B2BMemberCreateResponse = ResponseWithMember; - -export interface B2BMemberGetRequest { - organization_id: string; - member_id?: string; - email_address?: string; -} - -export type B2BMemberGetResponse = ResponseWithMember; - -export interface B2BMemberUpdateRequest { - organization_id: string; - member_id: string; - name?: string; - trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - is_breakglass?: boolean; - mfa_phone_number?: string; - mfa_enrolled?: boolean; -} - -export type B2BMemberUpdateResponse = ResponseWithMember; - -export type MemberSearchOperand = - | { - 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; - }; - -export interface B2BMemberSearchRequest { - organization_ids: string[]; - limit?: number; - query?: { - operator: SearchOperator; - operands: MemberSearchOperand[]; - }; - cursor?: string | null; -} - -export interface B2BMemberSearchResponse extends BaseResponse { - members: Member[]; - results_metadata: ResultsMetadata; - organizations: Record; -} - -export interface B2BMemberDeleteRequest { - member_id: string; - organization_id: string; -} - -export interface B2BMemberDeleteResponse extends BaseResponse { - member_id: string; -} - -export interface B2BMemberDeletePhoneNumberRequest { - organization_id: string; - member_id: string; -} - -export type B2BMemberDeletePhoneNumberResponse = ResponseWithMember; - -export class Members { - private base_path: string; - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig, parent_path: string) { - this.fetchConfig = fetchConfig; - this.base_path = `${parent_path}`; - } - - create(data: B2BMemberCreateRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: `${this.base_path}/${data.organization_id}/members`, - data, - }); - } - - get(params: B2BMemberGetRequest): Promise { - return request(this.fetchConfig, { - method: "GET", - url: `${this.base_path}/${params.organization_id}/member`, - params: { ...params }, - }); - } - - update(data: B2BMemberUpdateRequest): Promise { - return request(this.fetchConfig, { - method: "PUT", - url: `${this.base_path}/${data.organization_id}/members/${data.member_id}`, - data, - }); - } - - delete(data: B2BMemberDeleteRequest): Promise { - return request(this.fetchConfig, { - method: "DELETE", - url: `${this.base_path}/${data.organization_id}/members/${data.member_id}`, - }); - } - - search(data: B2BMemberSearchRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: `${this.base_path}/members/search`, - data, - }); - } - - deletePhoneNumber( - data: B2BMemberDeletePhoneNumberRequest - ): Promise { - return request(this.fetchConfig, { - method: "DELETE", - url: `${this.base_path}/${data.organization_id}/members/mfa_phone_numbers/${data.member_id}`, - }); - } -} diff --git a/lib/b2b/mfa.ts b/lib/b2b/mfa.ts index 3e5293ca..b7d9d0d9 100644 --- a/lib/b2b/mfa.ts +++ b/lib/b2b/mfa.ts @@ -1,8 +1,21 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + export interface MemberOptions { mfa_phone_number: string; } export interface MfaRequired { - member_options: MemberOptions; - secondary_auth_initiated: "sms_otp" | null; + // Information about the Member's options for completing MFA. + member_options?: MemberOptions; + /** + * If null, indicates that no secondary authentication has been initiated. If equal to "sms_otp", indicates + * that the Member has a phone number, and a one time passcode has been sent to the Member's phone number. + * No secondary authentication will be initiated during calls to the discovery authenticate or list + * organizations endpoints, even if the Member has a phone number. + */ + secondary_auth_initiated?: string; } diff --git a/lib/b2b/oauth.ts b/lib/b2b/oauth.ts index 6f5f4c0f..7bbd0107 100644 --- a/lib/b2b/oauth.ts +++ b/lib/b2b/oauth.ts @@ -1,95 +1,205 @@ -import { MemberSession, Member } from "./shared_b2b"; -import { request, BaseResponse, fetchConfig } from "../shared"; -import { DiscoveredOrganization, Organization } from "./organizations"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Discovery } from "./oauth_discovery"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; import { MfaRequired } from "./mfa"; +import { request } from "../shared"; + +export interface B2BOAuthProviderValues { + // The `access_token` that you may use to access the User's data in the provider's API. + access_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 `refresh_token` that you may use to refresh a User's session within the provider's API. + refresh_token?: string; + expires_at?: 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 [OpenID Connect](https://openid.net/foundation/) + * specification, which is based on OAuth. + */ + id_token?: string; +} +// Request type for `oauth.authenticate`. export interface B2BOAuthAuthenticateRequest { + // The token to authenticate. oauth_token: string; + // A secret token for a given Stytch Session. session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. pkce_code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BDiscoveryOAuthAuthenticateRequest { - discovery_oauth_token: string; - pkce_code_verifier?: string; -} - -export interface B2BDiscoveryOAuthAuthenticateResponse extends BaseResponse { - intermediate_session_token: string; - email_address: string; - discovered_organizations: DiscoveredOrganization[]; -} - -export interface B2BOAuthAuthenticateResponse extends BaseResponse { +// Response type for `oauth.authenticate`. +export interface B2BOAuthAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. member_id: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the `sub` or + * "Subject field" in OAuth protocols. + */ + provider_subject: string; + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Microsoft, GitHub + * etc. + */ + provider_type: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). member: Member; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). organization: Organization; - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; - provider_values: ProvidersValues; + reset_sessions: boolean; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ member_authenticated: boolean; + /** + * The returned Intermediate Session Token contains an OAuth factor associated with the Member's email + * address. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization that allows login with OAuth, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; -} - -export interface ProvidersValues { - access_token?: string; - refresh_token?: string; - id_token?: string; - expires_at?: number; - scopes: string[]; -} - -class Discovery { - private base_path = "oauth/discovery"; - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig) { - this.fetchConfig = fetchConfig; - } - - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - authenticate( - data: B2BDiscoveryOAuthAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data, - }); - } + /** + * 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; + /** + * 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` is only + * returned by Microsoft. + */ + provider_values?: B2BOAuthProviderValues; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } export class OAuth { - private base_path = "oauth"; - discovery: Discovery; - private fetchConfig: fetchConfig; + discovery: Discovery; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; - this.discovery = new Discovery(fetchConfig); - } - - private endpoint(path: string): string { - return `${this.base_path}/${path}`; + this.discovery = new Discovery(this.fetchConfig); } + /** + * Authenticate a Member given a `token`. This endpoint verifies that the member completed the OAuth flow + * by verifying that the token is valid and hasn't expired. Provide the `session_duration_minutes` + * parameter to set the lifetime of the session. If the `session_duration_minutes` parameter is not + * specified, a Stytch session will be created with a 60 minute duration. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BOAuthAuthenticateRequest} + * @returns {@link B2BOAuthAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( data: B2BOAuthAuthenticateRequest ): Promise { - return request(this.fetchConfig, { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/b2b/oauth/authenticate`, data, }); } diff --git a/lib/b2b/oauth_discovery.ts b/lib/b2b/oauth_discovery.ts new file mode 100644 index 00000000..91f6ec07 --- /dev/null +++ b/lib/b2b/oauth_discovery.ts @@ -0,0 +1,96 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { DiscoveredOrganization } from "./discovery"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; + +// Request type for `oauth.discovery.authenticate`. +export interface B2BOAuthDiscoveryAuthenticateRequest { + // The Discovery OAuth token to authenticate. + discovery_oauth_token: string; + session_token?: string; + session_duration_minutes?: number; + session_jwt?: string; + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. + pkce_code_verifier?: string; +} + +// Response type for `oauth.discovery.authenticate`. +export interface B2BOAuthDiscoveryAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + // The email address. + email_address: string; + /** + * An array of `discovered_organization` objects tied to the `intermediate_session_token`, `session_token`, + * or `session_jwt`. See the + * [Discovered Organization Object](https://stytch.com/docs/b2b/api/discovered-organization-object) for + * complete details. + * + * Note that Organizations will only appear here under any of the following conditions: + * 1. The end user is already a Member of the Organization. + * 2. The end user is invited to the Organization. + * 3. The end user can join the Organization because: + * + * a) The Organization allows JIT provisioning. + * + * b) The Organizations' allowed domains list contains the Member's email domain. + * + * c) The Organization has at least one other Member with a verified email address with the same + * domain as the end user (to prevent phishing attacks). + */ + discovered_organizations: DiscoveredOrganization[]; + /** + * 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; +} + +export class Discovery { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Authenticates the Discovery OAuth token and exchanges it for an Intermediate Session Token. Intermediate + * Session Tokens can be used for various Discovery login flows and are valid for 10 minutes. + * @param data {@link B2BOAuthDiscoveryAuthenticateRequest} + * @returns {@link B2BOAuthDiscoveryAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate( + data: B2BOAuthDiscoveryAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/oauth/discovery/authenticate`, + data, + }); + } +} diff --git a/lib/b2b/oidc.ts b/lib/b2b/oidc.ts deleted file mode 100644 index f3e305c6..00000000 --- a/lib/b2b/oidc.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { BaseResponse, request, fetchConfig } from "../shared"; -import { OIDCConnection } from "./sso"; - -export interface B2BOIDCCreateConnectionRequest { - organization_id: string; - display_name?: string; -} - -export interface B2BOIDCCreateConnectionResponse extends BaseResponse { - connection: OIDCConnection; -} - -export interface B2BOIDCUpdateConnectionRequest { - organization_id: string; - connection_id: string; - display_name?: string; - client_id?: string; - client_secret?: string; - issuer?: string; - authorization_url?: string; - token_url?: string; - userinfo_url?: string; - jwks_url?: string; -} - -export interface B2BOIDCUpdateConnectionResponse extends BaseResponse { - connection: OIDCConnection; -} - -export class OIDC { - constructor(private readonly fetchConfig: fetchConfig) {} - - create({ - organization_id, - ...data - }: B2BOIDCCreateConnectionRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: `sso/oidc/${organization_id}`, - data, - }); - } - - update({ - organization_id, - connection_id, - ...data - }: B2BOIDCUpdateConnectionRequest): Promise { - return request(this.fetchConfig, { - method: "PUT", - url: `sso/oidc/${organization_id}/connections/${connection_id}`, - data, - }); - } -} diff --git a/lib/b2b/organizations.ts b/lib/b2b/organizations.ts index 3b85388f..046a1731 100644 --- a/lib/b2b/organizations.ts +++ b/lib/b2b/organizations.ts @@ -1,220 +1,757 @@ -import { SearchOperator, ResultsMetadata, Member } from "./shared_b2b"; -import { BaseResponse, request, fetchConfig } from "../shared"; -import { Members } from "./members"; -import { MfaRequired } from "./mfa"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export type OrganizationSearchOperand = - | { - filter_name: "organization_ids"; - filter_value: string[]; - } - | { - filter_name: "organization_slugs"; - filter_value: string[]; - } - | { - filter_name: "organization_name_fuzzy"; - filter_value: string; - } - | { - filter_name: "organization_slug_fuzzy"; - filter_value: string; - } - | { - filter_name: "member_emails"; - filter_value: string[]; - } - | { - filter_name: "member_email_fuzzy"; - filter_value: string; - } - | { - filter_name: "allowed_domains"; - filter_value: string[]; - } - | { - filter_name: "allowed_domain_fuzzy"; - filter_value: string; - }; +import { fetchConfig } from "../shared"; +import { Members } from "./organizations_members"; +import { request } from "../shared"; + +export interface ActiveSSOConnection { + // Globally unique UUID that identifies a specific SSO `connection_id` for a Member. + connection_id: string; + // A human-readable display name for the connection. + display_name: string; +} + +export interface B2BOrganizationsResultsMetadata { + // The total number of results returned by your search query. + 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; +} + +export interface Member { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The email address. + email_address: string; + // The status of the Member. The possible values are: `pending`, `invited`, `active`, or `deleted`. + status: string; + // The name of the Member. + name: string; + /** + * An array of registered [SAML Connection](saml-connection-object) objects the Member has authenticated + * with. + */ + 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. Refer to the + * [Organization object](organization-object) and its `auth_methods` and `allowed_auth_methods` fields for + * more details. + */ + is_breakglass: boolean; + // Globally unique UUID that identifies a Member's password. + member_password_id: string; + // A list of OAuth registrations for this member. + oauth_registrations: OAuthRegistration[]; + /** + * (Coming Soon) 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; + // (Coming Soon) The Member's phone number. A Member may only have one phone number. + mfa_phone_number: string; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +export interface OAuthRegistration { + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Microsoft, GitHub + * etc. + */ + provider_type: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the `sub` or + * "Subject field" in OAuth protocols. + */ + provider_subject: string; + // The unique ID of an OAuth registration. + member_oauth_registration_id: 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. Google profile picture. + */ + profile_picture_url?: string; + /** + * If available, the `locale` is the Member's locale set in the OAuth identity provider that the user has + * authenticated with. + */ + locale?: string; +} export interface Organization { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; + // The name of the Organization. organization_name: string; - organization_slug: string; + // The image URL of the Organization logo. organization_logo_url: string; - trusted_metadata: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - - sso_default_connection_id: string | null; - sso_jit_provisioning: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; + /** + * 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 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_id`s that reference + * [SAML Connection objects](https://stytch.com/docs/b2b/api/saml-connection-object). + * 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[]; - sso_active_connections: Array<{ - connection_id: string; - display_name: string; - }>; - + // An array of active [SAML Connection references](https://stytch.com/docs/b2b/api/saml-connection-object). + sso_active_connections: ActiveSSOConnection[]; + /** + * 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ email_allowed_domains: string[]; - email_jit_provisioning: "RESTRICTED" | "NOT_ALLOWED"; - email_invites: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - - auth_methods: "ALL_ALLOWED" | "RESTRICTED"; + /** + * The authentication setting that controls how a new Member can be provisioned by authenticating via Email + * Magic Link. The accepted values are: + * + * `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: string; + /** + * 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: string; + /** + * 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`, and `microsoft_oauth`. + * + */ allowed_auth_methods: string[]; + mfa_policy: string; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // The default connection used for SSO when there are multiple active connections. + sso_default_connection_id?: string; +} - mfa_policy: "OPTIONAL" | "REQUIRED_FOR_ALL"; +export interface SSORegistration { + // Globally unique UUID that identifies a specific SSO `connection_id` for a Member. + connection_id: string; + // The ID of the member given by the identity provider. + external_id: string; + // The unique ID of an SSO Registration. + registration_id: string; + // An object for storing SSO attributes brought over from the identity provider. + sso_attributes?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export 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; - }; - member_authenticated: boolean; - primary_required: { - allowed_auth_methods: string[]; - } | null; - mfa_required: MfaRequired | null; -} - -export interface B2BOrganizationCreateRequest { +export interface SearchQuery { + /** + * 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[]; +} + +// Request type for `organizations.create`. +export interface B2BOrganizationsCreateRequest { + // The name of the Organization. organization_name: string; - organization_slug: 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; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - sso_jit_provisioning?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; + /** + * 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 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ email_allowed_domains?: string[]; - email_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; - email_invites?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - auth_methods?: "ALL_ALLOWED" | "RESTRICTED"; + /** + * The authentication setting that controls how a new Member can be provisioned by authenticating via Email + * Magic Link. The accepted values are: + * + * `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?: string; + /** + * 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?: string; + /** + * 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`, and `microsoft_oauth`. + * + */ allowed_auth_methods?: string[]; - mfa_policy?: "OPTIONAL" | "REQUIRED_FOR_ALL"; + /** + * (Coming Soon) 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; } -export interface B2BOrganizationCreateResponse extends BaseResponse { +// Response type for `organizations.create`. +export interface B2BOrganizationsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). organization: Organization; + /** + * 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; } -export interface B2BOrganizationGetRequest { +// Request type for `organizations.delete`. +export interface B2BOrganizationsDeleteRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; } -export interface B2BOrganizationGetResponse extends BaseResponse { - organization: Organization; +// Response type for `organizations.delete`. +export interface B2BOrganizationsDeleteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_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; } -export interface B2BOrganizationSearchRequest { - limit?: number; - query?: { - operator: SearchOperator; - operands: OrganizationSearchOperand[]; - }; - cursor?: string | null; +// Request type for `organizations.get`. +export interface B2BOrganizationsGetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; } -export interface B2BOrganizationSearchResponse extends BaseResponse { - organizations: Organization[]; - results_metadata: ResultsMetadata; +// Response type for `organizations.get`. +export interface B2BOrganizationsGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; } -export interface B2BOrganizationDeleteRequest { - organization_id: string; +// Request type for `organizations.search`. +export interface B2BOrganizationsSearchRequest { + /** + * 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 Organizations with no filtering applied. + */ + query?: SearchQuery; } -export interface B2BOrganizationDeleteResponse extends BaseResponse { - organization_id: string; +// Response type for `organizations.search`. +export interface B2BOrganizationsSearchResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // An array of [Organization objects](https://stytch.com/docs/b2b/api/organization-object). + organizations: Organization[]; + /** + * The search `results_metadata` object contains metadata relevant to your specific query like `total` and + * `next_cursor`. + */ + results_metadata: B2BOrganizationsResultsMetadata; + /** + * 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; } -export interface B2BOrganizationUpdateRequest { +// Request type for `organizations.update`. +export interface B2BOrganizationsUpdateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; + // 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; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - + // The default connection used for SSO when there are multiple active connections. sso_default_connection_id?: string; - sso_jit_provisioning?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; + /** + * 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_id`s that reference + * [SAML Connection objects](https://stytch.com/docs/b2b/api/saml-connection-object). + * 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ email_allowed_domains?: string[]; - email_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; - email_invites?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - - auth_methods?: "ALL_ALLOWED" | "RESTRICTED"; + /** + * The authentication setting that controls how a new Member can be provisioned by authenticating via Email + * Magic Link. The accepted values are: + * + * `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?: string; + /** + * 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?: string; + /** + * 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`, and `microsoft_oauth`. + * + */ allowed_auth_methods?: string[]; - - mfa_policy?: "OPTIONAL" | "REQUIRED_FOR_ALL"; + /** + * (Coming Soon) 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; } -export interface B2BOrganizationUpdateResponse extends BaseResponse { +// Response type for `organizations.update`. +export interface B2BOrganizationsUpdateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). organization: Organization; + /** + * 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; } -export class Organizations { - private base_path = "organizations"; - members: Members; +// MANUAL(SearchQueryOperand)(TYPES) +export type OrganizationSearchOperand = + | { + filter_name: "organization_ids"; + filter_value: string[]; + } + | { + filter_name: "organization_slugs"; + filter_value: string[]; + } + | { + filter_name: "organization_name_fuzzy"; + filter_value: string; + } + | { + filter_name: "organization_slug_fuzzy"; + filter_value: string; + } + | { + filter_name: "member_emails"; + filter_value: string[]; + } + | { + filter_name: "member_email_fuzzy"; + filter_value: string; + } + | { + filter_name: "allowed_domains"; + filter_value: string[]; + } + | { + filter_name: "allowed_domain_fuzzy"; + filter_value: string; + }; + +export type MemberSearchOperand = + | { + 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_phone_numbers"; + filter_value: string[]; + } + | { + filter_name: "member_phone_number_fuzzy"; + filter_value: string; + }; +export type SearchQueryOperand = + | OrganizationSearchOperand + | MemberSearchOperand + | { + filter_name: string; + [key: string]: unknown; + }; +// ENDMANUAL(SearchQueryOperand) + +export class Organizations { private fetchConfig: fetchConfig; + members: Members; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; - this.members = new Members(fetchConfig, this.base_path); - } - - private endpoint(path: string): string { - return `${this.base_path}/${path}`; + this.members = new Members(this.fetchConfig); } + /** + * Creates an Organization. An `organization_name` and a unique `organization_slug` are required. + * + * By default, `email_invites` and `sso_jit_provisioning` will be set to `ALL_ALLOWED`, and `mfa_policy` + * will be set to `OPTIONAL` if no Organization authentication settings are explicitly defined in the + * request. + * + * *See the [Organization authentication settings](https://stytch.com/docs/b2b/api/org-auth-settings) + * resource to learn more about fields like `email_jit_provisioning`, `email_invites`, + * `sso_jit_provisioning`, etc., and their behaviors. + * @param data {@link B2BOrganizationsCreateRequest} + * @returns {@link B2BOrganizationsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ create( - data: B2BOrganizationCreateRequest - ): Promise { - return request(this.fetchConfig, { + data: B2BOrganizationsCreateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.base_path, + url: `/v1/b2b/organizations`, data, }); } - get({ - organization_id, - }: B2BOrganizationGetRequest): Promise { - return request(this.fetchConfig, { + /** + * Returns an Organization specified by `organization_id`. + * @param data {@link B2BOrganizationsGetRequest} + * @returns {@link B2BOrganizationsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get( + params: B2BOrganizationsGetRequest + ): Promise { + return request(this.fetchConfig, { method: "GET", - url: this.endpoint(organization_id), - }); - } - - search( - data: B2BOrganizationSearchRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("search"), - data, + url: `/v1/b2b/organizations/${params.organization_id}`, + params: {}, }); } + /** + * Updates an Organization specified by `organization_id`. An Organization must always have at least one + * auth setting set to either `RESTRICTED` or `ALL_ALLOWED` in order to provision new Members. test + * + * *See the [Organization authentication settings](https://stytch.com/docs/b2b/api/org-auth-settings) + * resource to learn more about fields like `email_jit_provisioning`, `email_invites`, + * `sso_jit_provisioning`, etc., and their behaviors. + * @param data {@link B2BOrganizationsUpdateRequest} + * @returns {@link B2BOrganizationsUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ update( - data: B2BOrganizationUpdateRequest - ): Promise { - return request(this.fetchConfig, { + data: B2BOrganizationsUpdateRequest + ): Promise { + return request(this.fetchConfig, { method: "PUT", - url: this.endpoint(data.organization_id), - data, + url: `/v1/b2b/organizations/${data.organization_id}`, + data: { + organization_name: data.organization_name, + organization_slug: data.organization_slug, + organization_logo_url: data.organization_logo_url, + trusted_metadata: data.trusted_metadata, + sso_default_connection_id: data.sso_default_connection_id, + sso_jit_provisioning: data.sso_jit_provisioning, + sso_jit_provisioning_allowed_connections: + data.sso_jit_provisioning_allowed_connections, + email_allowed_domains: data.email_allowed_domains, + email_jit_provisioning: data.email_jit_provisioning, + email_invites: data.email_invites, + auth_methods: data.auth_methods, + allowed_auth_methods: data.allowed_auth_methods, + mfa_policy: data.mfa_policy, + }, }); } - delete({ - organization_id, - }: B2BOrganizationDeleteRequest): Promise { - return request(this.fetchConfig, { + /** + * Deletes an Organization specified by `organization_id`. All Members of the Organization will also be + * deleted. + * @param data {@link B2BOrganizationsDeleteRequest} + * @returns {@link B2BOrganizationsDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + delete( + data: B2BOrganizationsDeleteRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(organization_id), + url: `/v1/b2b/organizations/${data.organization_id}`, + data: {}, + }); + } + + /** + * Search for Organizations. If you send a request with no body params, no filtering will be applied and + * the endpoint will return all Organizations. All fuzzy search filters require a minimum of three + * characters. + * @param data {@link B2BOrganizationsSearchRequest} + * @returns {@link B2BOrganizationsSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + search( + data: B2BOrganizationsSearchRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/organizations/search`, + data, }); } } diff --git a/lib/b2b/organizations_members.ts b/lib/b2b/organizations_members.ts new file mode 100644 index 00000000..5177fa0f --- /dev/null +++ b/lib/b2b/organizations_members.ts @@ -0,0 +1,459 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { + B2BOrganizationsResultsMetadata, + Member, + Organization, + SearchQuery, +} from "./organizations"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; + +// Request type for `organizations.members.create`. +export interface B2BOrganizationsMembersCreateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // The email address of the Member. + email_address: string; + // The name of the Member. + name?: string; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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. Refer to the + * [Organization object](organization-object) and its `auth_methods` and `allowed_auth_methods` fields for + * more details. + */ + is_breakglass?: boolean; + mfa_phone_number?: string; + /** + * (Coming Soon) 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; +} + +// Response type for `organizations.members.create`. +export interface B2BOrganizationsMembersCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; +} + +export interface B2BOrganizationsMembersDeleteMFAPhoneNumberRequest { + organization_id: string; + member_id: string; +} + +export interface B2BOrganizationsMembersDeleteMFAPhoneNumberResponse { + request_id: string; + member_id: string; + member: Member; + organization: Organization; + status_code: number; +} + +// Request type for `organizations.members.deletePassword`. +export interface B2BOrganizationsMembersDeletePasswordRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // Globally unique UUID that identifies a Member's password. + member_password_id: string; +} + +// Response type for `organizations.members.deletePassword`. +export interface B2BOrganizationsMembersDeletePasswordResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; +} + +// Request type for `organizations.members.delete`. +export interface B2BOrganizationsMembersDeleteRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; +} + +// Response type for `organizations.members.delete`. +export interface B2BOrganizationsMembersDeleteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_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; +} + +// Request type for `organizations.members.get`. +export interface B2BOrganizationsMembersGetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id?: string; + // The email address of the Member. + email_address?: string; +} + +// Response type for `organizations.members.get`. +export interface B2BOrganizationsMembersGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; +} + +// Request type for `organizations.members.search`. +export interface B2BOrganizationsMembersSearchRequest { + // An array of organization_ids. At least one value is required. + organization_ids: string[]; + /** + * 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?: SearchQuery; +} + +// Response type for `organizations.members.search`. +export interface B2BOrganizationsMembersSearchResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // An array of [Member objects](member-object). + members: Member[]; + /** + * The search `results_metadata` object contains metadata relevant to your specific query like `total` and + * `next_cursor`. + */ + results_metadata: B2BOrganizationsResultsMetadata; + /** + * 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; + /** + * 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; +} + +// Request type for `organizations.members.update`. +export interface B2BOrganizationsMembersUpdateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; + // The name of the Member. + name?: string; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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. Refer to the + * [Organization object](organization-object) and its `auth_methods` and `allowed_auth_methods` fields for + * more details. + */ + is_breakglass?: boolean; + mfa_phone_number?: string; + /** + * (Coming Soon) 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; +} + +// Response type for `organizations.members.update`. +export interface B2BOrganizationsMembersUpdateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; +} + +export class Members { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Updates a Member specified by `organization_id` and `member_id`. + * @param data {@link B2BOrganizationsMembersUpdateRequest} + * @returns {@link B2BOrganizationsMembersUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + update( + data: B2BOrganizationsMembersUpdateRequest + ): Promise { + return request(this.fetchConfig, { + method: "PUT", + url: `/v1/b2b/organizations/${data.organization_id}/members/${data.member_id}`, + data: { + name: data.name, + trusted_metadata: data.trusted_metadata, + untrusted_metadata: data.untrusted_metadata, + is_breakglass: data.is_breakglass, + mfa_phone_number: data.mfa_phone_number, + mfa_enrolled: data.mfa_enrolled, + }, + }); + } + + /** + * Deletes a Member specified by `organization_id` and `member_id`. + * @param data {@link B2BOrganizationsMembersDeleteRequest} + * @returns {@link B2BOrganizationsMembersDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + delete( + data: B2BOrganizationsMembersDeleteRequest + ): Promise { + return request(this.fetchConfig, { + method: "DELETE", + url: `/v1/b2b/organizations/${data.organization_id}/members/${data.member_id}`, + data: {}, + }); + } + + /** + * @param data {@link B2BOrganizationsMembersDeleteMFAPhoneNumberRequest} + * @returns {@link B2BOrganizationsMembersDeleteMFAPhoneNumberResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteMFAPhoneNumber( + data: B2BOrganizationsMembersDeleteMFAPhoneNumberRequest + ): Promise { + return request( + this.fetchConfig, + { + method: "DELETE", + url: `/v1/b2b/organizations/${data.organization_id}/members/mfa_phone_numbers/${data.member_id}`, + data: {}, + } + ); + } + + /** + * Search for Members within specified Organizations. An array with at least one `organization_id` is + * required. Submitting an empty `query` returns all Members within the specified Organizations. + * + * *All fuzzy search filters require a minimum of three characters. + * @param data {@link B2BOrganizationsMembersSearchRequest} + * @returns {@link B2BOrganizationsMembersSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + search( + data: B2BOrganizationsMembersSearchRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/organizations/members/search`, + data, + }); + } + + /** + * Delete a Member's password. + * @param data {@link B2BOrganizationsMembersDeletePasswordRequest} + * @returns {@link B2BOrganizationsMembersDeletePasswordResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deletePassword( + data: B2BOrganizationsMembersDeletePasswordRequest + ): Promise { + return request( + this.fetchConfig, + { + method: "DELETE", + url: `/v1/b2b/organizations/${data.organization_id}/members/passwords/${data.member_password_id}`, + data: {}, + } + ); + } + + /** + * Creates a Member. An `organization_id` and `email_address` are required. + * @param data {@link B2BOrganizationsMembersCreateRequest} + * @returns {@link B2BOrganizationsMembersCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create( + data: B2BOrganizationsMembersCreateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/organizations/${data.organization_id}/members`, + data: { + email_address: data.email_address, + name: data.name, + trusted_metadata: data.trusted_metadata, + untrusted_metadata: data.untrusted_metadata, + create_member_as_pending: data.create_member_as_pending, + is_breakglass: data.is_breakglass, + mfa_phone_number: data.mfa_phone_number, + mfa_enrolled: data.mfa_enrolled, + }, + }); + } + + /** + * Get a Member by `member_id` or `email_address`. + * @param data {@link B2BOrganizationsMembersGetRequest} + * @returns {@link B2BOrganizationsMembersGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get( + params: B2BOrganizationsMembersGetRequest + ): Promise { + return request(this.fetchConfig, { + method: "GET", + url: `/v1/b2b/organizations/${params.organization_id}/member`, + params: { ...params }, + }); + } +} diff --git a/lib/b2b/otp.ts b/lib/b2b/otp.ts new file mode 100644 index 00000000..ebfede62 --- /dev/null +++ b/lib/b2b/otp.ts @@ -0,0 +1,18 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { Sms } from "./otp_sms"; + +export class OTPs { + private fetchConfig: fetchConfig; + sms: Sms; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + this.sms = new Sms(this.fetchConfig); + } +} diff --git a/lib/b2b/otp_sms.ts b/lib/b2b/otp_sms.ts new file mode 100644 index 00000000..207c355e --- /dev/null +++ b/lib/b2b/otp_sms.ts @@ -0,0 +1,226 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { request } from "../shared"; + +// Request type for `otps.sms.authenticate`. +export interface B2BOTPSmsAuthenticateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; + // The code to authenticate. + code: string; + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token?: string; + // A secret token for a given Stytch Session. + session_token?: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * Optionally sets the Member’s MFA enrollment status upon a successful authentication. If the + * Organization’s MFA policy is `REQUIRED_FOR_ALL`, this field will be ignored. If this field is not passed + * in, the Member’s `mfa_enrolled` boolean will not be affected. The options are: + * + * `enroll` – sets the Member's `mfa_enrolled` boolean to `true`. The Member will be required to complete + * an MFA step upon subsequent logins to the Organization. + * + * `unenroll` – sets the Member's `mfa_enrolled` boolean to `false`. The Member will no longer be + * required to complete MFA steps when logging in to the Organization. + * + */ + set_mfa_enrollment?: string; +} + +// Response type for `otps.sms.authenticate`. +export interface B2BOTPSmsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; +} + +// Request type for `otps.sms.send`. +export interface B2BOTPSmsSendRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; + mfa_phone_number?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `otps.sms.send`. +export interface B2BOTPSmsSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; +} + +export class Sms { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Send a one-time passcode (OTP) to a Member's phone number. If the Member already has a phone number, + * this will send an OTP to the number associated with their `member_id`. If not, then this will send an + * OTP to the `phone_number` provided and link the `phone_number` with the Member. + * An error will be thrown if the Member already has a phone number and the provided `phone_number` does + * not match the existing one. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * If a Member has a phone number and is enrolled in MFA, then after a successful primary authentication + * event (e.g. [email magic link](https://stytch.com/docs/b2b/api/authenticate-magic-link) or + * [SSO](https://stytch.com/docs/b2b/api/sso-authenticate) login is complete), an SMS OTP will + * automatically be sent to their phone number. In that case, this endpoint should only be used for + * subsequent authentication events, such as prompting a Member for an OTP again after a period of + * inactivity. + * @param data {@link B2BOTPSmsSendRequest} + * @returns {@link B2BOTPSmsSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: B2BOTPSmsSendRequest): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/otps/sms/send`, + data, + }); + } + + /** + * Authenticates a Member's OTP code. This endpoint verifies that the code is valid and hasn't expired or + * been previously used. A given Member may only have a single active OTP code at any given time. If a + * Member requests another OTP code before the first one has expired, the first one will be invalidated. + * + * Exactly one of `intermediate_session_token`, `session_token`, or `session_jwt` must be provided in the + * request. + * If an intermediate session token is provided, this operation will consume it. + * + * If the Organization's MFA policy is `REQUIRED_FOR_ALL`, a successful OTP authentication will change the + * Member's `mfa_enrolled` status to `true` if it is not already `true`. + * If the Organization's MFA policy is `OPTIONAL`, the Member's MFA enrollment can be toggled by passing in + * a value for the `set_mfa_enrollment` field. + * + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. If the + * `session_duration_minutes` parameter is not specified, a Stytch session will be created with a duration + * of 60 minutes. + * @param data {@link B2BOTPSmsAuthenticateRequest} + * @returns {@link B2BOTPSmsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate( + data: B2BOTPSmsAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/otps/sms/authenticate`, + data, + }); + } +} diff --git a/lib/b2b/otps.ts b/lib/b2b/otps.ts deleted file mode 100644 index 1cb9d58b..00000000 --- a/lib/b2b/otps.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import { fetchConfig, request } from "../shared"; - -export interface B2BOTPsSMSSendRequest { - organization_id: string; - member_id: string; - mfa_phone_number?: string; - locale?: "en" | "es" | "pt-br" | string; -} - -export type B2BOTPsSMSSendResponse = ResponseWithMember; - -export interface B2BOTPsSMSAuthenticateRequest { - organization_id: string; - member_id: string; - code: string; - intermediate_session_token?: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - set_mfa_enrollment?: "enroll" | "unenroll"; -} - -export interface B2BOTPsSMSAuthenticateResponse extends ResponseWithMember { - session_token: string; - session_jwt: string; - member_session: MemberSession; -} - -class SMS { - base_path: string; - delivery = "sms"; - - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig, base_path: string) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - private endpoint(path: string): string { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data: B2BOTPsSMSSendRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data, - }); - } - - authenticate( - data: B2BOTPsSMSAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data, - }); - } -} - -export class OTPs { - base_path = "otps"; - sms: SMS; - - constructor(fetchConfig: fetchConfig) { - this.sms = new SMS(fetchConfig, this.base_path); - } -} diff --git a/lib/b2b/passwords.ts b/lib/b2b/passwords.ts index fb157ddc..1942d0ff 100644 --- a/lib/b2b/passwords.ts +++ b/lib/b2b/passwords.ts @@ -1,229 +1,422 @@ -import { request, BaseResponse, fetchConfig } from "../shared"; -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import * as shared from "../shared/passwords"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { + Argon2Config, + MD5Config, + PBKDF2Config, + SHA1Config, + ScryptConfig, +} from "../b2c/passwords"; +import { Email } from "./passwords_email"; +import { ExistingPassword } from "./passwords_existing_password"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; import { MfaRequired } from "./mfa"; +import { request } from "../shared"; +import { Sessions } from "./passwords_session"; -export interface B2BPasswordsAuthenticateRequest { - organization_id: string; - email_address: string; - password: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - locale?: "en" | "es" | "pt-br" | string; +export interface LudsFeedback { + // For LUDS validation, whether the password contains at least one lowercase letter. + has_lower_case: boolean; + // For LUDS validation, whether the password contains at least one uppercase letter. + has_upper_case: boolean; + // For LUDS validation, whether the password contains at least one digit. + has_digit: boolean; + /** + * For LUDS validation, whether the password contains at least one symbol. Any UTF8 character outside of + * a-z or A-Z may count as a valid symbol. + */ + has_symbol: boolean; + /** + * For LUDS validation, the number of complexity requirements that are missing from the password. + * Check the complexity fields to see which requirements are missing. + */ + missing_complexity: number; + /** + * For LUDS validation, this is the required length of the password that you've set minus the length of the + * password being checked. + * The user will need to add this many characters to the password to make it valid. + */ + missing_characters: number; } -export interface B2BPasswordsAuthenticateResponse extends ResponseWithMember { - organization_id: string; - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; - member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; +export interface ZxcvbnFeedback { + /** + * For zxcvbn validation, contains an end user consumable warning if the password is valid but not strong + * enough. + */ + warning: string; + /** + * For zxcvbn validation, contains end user consumable suggestions on how to improve the strength of the + * password. + */ + suggestions: string[]; } -export interface B2BPasswordsEmailResetStartRequest { +// Request type for `passwords.authenticate`. +export interface B2BPasswordsAuthenticateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; + // The email address of the Member. email_address: string; - login_redirect_url?: string; - reset_password_redirect_url?: string; - reset_password_expiration_minutes?: number; - reset_password_template_id?: string; - code_challenge?: string; - locale?: string; -} - -export interface B2BPasswordsEmailResetStartResponse extends BaseResponse { - member_id: string; - member_email_id: string; -} - -export interface B2BPasswordsEmailResetRequest { - password_reset_token: string; + // The password to authenticate. password: string; + // A secret token for a given Stytch Session. session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BPasswordsEmailResetResponse extends ResponseWithMember { - member_email_id: string; +// Response type for `passwords.authenticate`. +export interface B2BPasswordsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; - member_authenticated: boolean; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * The returned Intermediate Session Token contains a password factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * Password factors are not transferable between Organizations, so the intermediate session token is + * not valid for use with discovery endpoints. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; -} - -export interface B2BPasswordsExistingPasswordResetRequest { - email_address: string; - existing_password: string; - new_password: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - organization_id: string; - locale?: "en" | "es" | "pt-br" | string; -} - -export interface B2BPasswordsExistingPasswordResetResponse - extends ResponseWithMember { - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; + /** + * 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } -export interface B2BPasswordsSessionResetRequest { - password: string; +// Request type for `passwords.migrate`. +export interface B2BPasswordsMigrateRequest { + // The email address of the Member. + email_address: string; + // The password hash. For a Scrypt or PBKDF2 hash, the hash needs to be a base64 encoded string. + hash: string; + /** + * The password hash used. Currently `bcrypt`, `scrypt`, `argon2i`, `argon2id`, `md_5`, `sha_1`, and + * `pbkdf_2` are supported. + */ + hash_type: + | "bcrypt" + | "md_5" + | "argon_2i" + | "argon_2id" + | "sha_1" + | "scrypt" + | "phpass" + | "pbkdf_2" + | string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; - session_token?: string; - session_jwt?: string; + // Optional parameters for MD-5 hash types. + md_5_config?: MD5Config; + // Required parameters if the argon2 hex form, as opposed to the encoded form, is supplied. + argon_2_config?: Argon2Config; + // Optional parameters for SHA-1 hash types. + sha_1_config?: SHA1Config; + // Required parameters if the scrypt is not provided in a **PHC encoded form**. + scrypt_config?: ScryptConfig; + /** + * Required additional parameters for PBKDF2 hash keys. Note that we use the SHA-256 by default, please + * contact [support@stytch.com](mailto:support@stytch.com) if you use another hashing function. + */ + pbkdf_2_config?: PBKDF2Config; + // The name of the Member. Each field in the name object is optional. + name?: string; + // An arbitrary JSON object for storing application-specific data or identity-provider-specific data. + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2BPasswordsSessionResetResponse extends ResponseWithMember { - member_session?: MemberSession; +// Response type for `passwords.migrate`. +export interface B2BPasswordsMigrateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + /** + * A flag indicating `true` if a new Member object was created and `false` if the Member object already + * existed. + */ + member_created: boolean; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; } +// Request type for `passwords.strengthCheck`. export interface B2BPasswordsStrengthCheckRequest { - email_address?: string; + // The password to authenticate. password: string; + // The email address of the Member. + email_address?: string; } -export interface B2BPasswordsStrengthCheckResponse extends BaseResponse { +// Response type for `passwords.strengthCheck`. +export interface B2BPasswordsStrengthCheckResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * Returns `true` if the password passes our password validation. We offer two validation options, + * [zxcvbn](https://stytch.com/docs/passwords#strength-requirements) is the default option which offers a + * high level of sophistication. + * We also offer [LUDS](https://stytch.com/docs/passwords#strength-requirements). If an email address is + * included in the call we also + * require that the password hasn't been compromised using built-in breach detection powered by + * [HaveIBeenPwned](https://haveibeenpwned.com/) + */ valid_password: boolean; + /** + * The score of the password determined by [zxcvbn](https://github.com/dropbox/zxcvbn). Values will be + * between 1 and 4, a 3 or greater is required to pass validation. + */ score: number; + /** + * Returns `true` if the password has been breached. Powered by + * [HaveIBeenPwned](https://haveibeenpwned.com/). + */ breached_password: boolean; + // The strength policy type enforced, either `zxcvbn` or `luds`. strength_policy: string; + /** + * 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](mailto:support@stytch.com?subject=Password%20strength%20configuration). + * If this value is false then `breached_password` will always be `false` as well. + */ breach_detection_on_create: boolean; - zxcvbn_feedback: { - suggestions: string[]; - warning: string; - }; - luds_feedback: { - has_lower_case: boolean; - has_upper_case: boolean; - has_digit: boolean; - has_symbol: boolean; - missing_complexity: number; - missing_characters: number; - }; -} - -interface MigrateRequestBase { - organization_id: string; - email_address: string; - hash: string; - name?: string; - trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any -} - -export type B2BPasswordsMigrateRequest = - | (shared.MD5MigrateRequest & MigrateRequestBase) - | (shared.BcryptMigrateRequest & MigrateRequestBase) - | (shared.Argon2IMigrateRequest & MigrateRequestBase) - | (shared.Argon2IDMigrateRequest & MigrateRequestBase) - | (shared.SHA1MigrateRequest & MigrateRequestBase) - | (shared.ScryptMigrateRequest & MigrateRequestBase) - | (shared.PHPassMigrateRequest & MigrateRequestBase) - | (shared.PBKDF2MigrateRequest & MigrateRequestBase); - -export interface B2BPasswordsMigrateResponse extends ResponseWithMember { - organization_id: string; - member_created: boolean; + /** + * 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; + /** + * Feedback for how to improve the password's strength using + * [luds](https://stytch.com/docs/passwords#strength-requirements). + */ + luds_feedback?: LudsFeedback; + /** + * Feedback for how to improve the password's strength using + * [zxcvbn](https://stytch.com/docs/passwords#strength-requirements). + */ + zxcvbn_feedback?: ZxcvbnFeedback; } export class Passwords { - base_path = "passwords"; - private fetchConfig: fetchConfig; + email: Email; + sessions: Sessions; + existingPassword: ExistingPassword; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; + this.email = new Email(this.fetchConfig); + this.sessions = new Sessions(this.fetchConfig); + this.existingPassword = new ExistingPassword(this.fetchConfig); } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - authenticate( - data?: B2BPasswordsAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data: data, - }); - } - - resetByEmailStart( - data: B2BPasswordsEmailResetStartRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("email/reset/start"), - data: data, - }); - } - - resetByEmail( - data?: B2BPasswordsEmailResetRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("email/reset"), - data: data, - }); - } - - resetByExistingPassword( - data: B2BPasswordsExistingPasswordResetRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("existing_password/reset"), - data: data, - }); - } - - resetBySession( - data: B2BPasswordsSessionResetRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("session/reset"), - data: data, - }); - } - + /** + * This API allows you to check whether the user’s provided password is valid, and to provide feedback to + * the user on how to increase the strength of their password. + * + * This endpoint adapts to your Project's password strength configuration. If you're using + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your passwords are + * considered valid if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are considered valid if + * they meet the requirements that you've set with Stytch. You may update your password strength + * configuration in the [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * ## Password feedback + * The zxcvbn_feedback and luds_feedback objects contains relevant fields for you to relay feedback to + * users that failed to create a strong enough password. + * + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the feedback object + * will contain warning and suggestions for any password that does not meet the + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy) strength requirements. You can return + * these strings directly to the user to help them craft a strong password. + * + * If you're using [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), the feedback object + * will contain a collection of fields that the user failed or passed. You'll want to prompt the user to + * create a password that meets all requirements that they failed. + * @param data {@link B2BPasswordsStrengthCheckRequest} + * @returns {@link B2BPasswordsStrengthCheckResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ strengthCheck( data: B2BPasswordsStrengthCheckRequest ): Promise { - return request(this.fetchConfig, { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("strength_check"), - data: data, + url: `/v1/b2b/passwords/strength_check`, + data, }); } + /** + * Adds an existing password to a member's email that doesn't have a password yet. We support migrating + * members from passwords stored with bcrypt, scrypt, argon2, MD-5, SHA-1, and PBKDF2. This endpoint has a + * rate limit of 100 requests per second. + * @param data {@link B2BPasswordsMigrateRequest} + * @returns {@link B2BPasswordsMigrateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ migrate( data: B2BPasswordsMigrateRequest ): Promise { - return request(this.fetchConfig, { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/migrate`, + data, + }); + } + + /** + * Authenticate a member with their email address and password. This endpoint verifies that the member has + * a password currently set, and that the entered password is correct. There are two instances where the + * endpoint will return a reset_password error even if they enter their previous password: + * * The member’s credentials appeared in the HaveIBeenPwned dataset. + * * We force a password reset to ensure that the member is the legitimate owner of the email address, + * and not a malicious actor abusing the compromised credentials. + * * A member that has previously authenticated with email/password uses a passwordless authentication + * method tied to the same email address (e.g. Magic Links) for the first time. Any subsequent + * email/password authentication attempt will result in this error. + * * We force a password reset in this instance in order to safely deduplicate the account by email + * address, without introducing the risk of a pre-hijack account takeover attack. + * * Imagine a bad actor creates many accounts using passwords and the known email addresses of their + * victims. If a victim comes to the site and logs in for the first time with an email-based passwordless + * authentication method then both the victim and the bad actor have credentials to access to the same + * account. To prevent this, any further email/password login attempts first require a password reset which + * can only be accomplished by someone with access to the underlying email address. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsAuthenticateRequest} + * @returns {@link B2BPasswordsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate( + data: B2BPasswordsAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("migrate"), - data: data, + url: `/v1/b2b/passwords/authenticate`, + data, }); } } diff --git a/lib/b2b/passwords_email.ts b/lib/b2b/passwords_email.ts new file mode 100644 index 00000000..c66085ed --- /dev/null +++ b/lib/b2b/passwords_email.ts @@ -0,0 +1,274 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +import { request } from "../shared"; + +// Request type for `passwords.email.reset`. +export interface B2BPasswordsEmailResetRequest { + // The password reset token to authenticate. + password_reset_token: string; + // The password to reset. + password: string; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_token`, Stytch will + * update the session. + * If the `session_token` and `magic_links_token` belong to different Members, the `session_token` + * will be ignored. This endpoint will error if + * both `session_token` and `session_jwt` are provided. + */ + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_jwt`, Stytch will + * update the session. If the `session_jwt` + * and `magic_links_token` belong to different Members, the `session_jwt` will be ignored. This + * endpoint will error if both `session_token` and `session_jwt` + * are provided. + */ + session_jwt?: string; + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. + code_verifier?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `passwords.email.reset`. +export interface B2BPasswordsEmailResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // Globally unique UUID that identifies a member's email + member_email_id: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * The returned Intermediate Session Token contains a password factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * Password factors are not transferable between Organizations, so the intermediate session token is + * not valid for use with discovery endpoints. + */ + intermediate_session_token: string; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} + +// Request type for `passwords.email.resetStart`. +export interface B2BPasswordsEmailResetStartRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // The email address of the Member to start the email reset process for. + email_address: string; + /** + * The URL that the Member clicks from the reset password link. This URL should be an endpoint in the + * backend server that verifies the request by querying + * Stytch's authenticate endpoint and finishes the reset password flow. 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; + // Sets a time limit after which the email link to reset the member's password will no longer be valid. + reset_password_expiration_minutes?: number; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: string; + /** + * The URL that the member clicks from the reset without password link. This URL should be an endpoint in + * the backend server + * that verifies the request by querying Stytch's authenticate endpoint and finishes the magic link + * flow. If this value is not passed, the + * default `login_redirect_url` that you set in your Dashboard is used. This value is only used if + * magic links are enabled for the member. If + * you have not set a default `login_redirect_url` and magic links are not enabled for the member, an + * error is returned. + */ + login_redirect_url?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for reset password 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 + * - Reset Password. + */ + reset_password_template_id?: string; +} + +// Response type for `passwords.email.resetStart`. +export interface B2BPasswordsEmailResetStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // Globally unique UUID that identifies a member's email + member_email_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; +} + +export class Email { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * 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. + * + * This endpoint adapts to your Project's password strength configuration. + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your + * passwords are considered valid + * if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are + * considered valid if they meet the requirements that you've set with Stytch. + * You may update your password strength configuration in the + * [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * @param data {@link B2BPasswordsEmailResetStartRequest} + * @returns {@link B2BPasswordsEmailResetStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + resetStart( + data: B2BPasswordsEmailResetStartRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/email/reset/start`, + data, + }); + } + + /** + * Reset the member's password and authenticate them. This endpoint checks that the password reset 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 password strength endpoint. If the token and password are accepted, the password is securely + * stored for future authentication and the user is authenticated. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsEmailResetRequest} + * @returns {@link B2BPasswordsEmailResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset( + data: B2BPasswordsEmailResetRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/email/reset`, + data, + }); + } +} diff --git a/lib/b2b/passwords_existing_password.ts b/lib/b2b/passwords_existing_password.ts new file mode 100644 index 00000000..886bf6fb --- /dev/null +++ b/lib/b2b/passwords_existing_password.ts @@ -0,0 +1,166 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +import { request } from "../shared"; + +// Request type for `passwords.existingPassword.reset`. +export interface B2BPasswordsExistingPasswordResetRequest { + // The email address of the Member. + email_address: string; + // The member's current password that they supplied. + existing_password: string; + // The member's elected new password. + new_password: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // A secret token for a given Stytch Session. + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `passwords.existingPassword.reset`. +export interface B2BPasswordsExistingPasswordResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * The returned Intermediate Session Token contains a password factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * Password factors are not transferable between Organizations, so the intermediate session token is + * not valid for use with discovery endpoints. + */ + intermediate_session_token: string; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} + +export class ExistingPassword { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Reset the member’s password using their existing password. + * + * This endpoint adapts to your Project's password strength configuration. + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your + * passwords are considered valid + * if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are + * considered valid if they meet the requirements that you've set with Stytch. + * You may update your password strength configuration in the + * [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsExistingPasswordResetRequest} + * @returns {@link B2BPasswordsExistingPasswordResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset( + data: B2BPasswordsExistingPasswordResetRequest + ): Promise { + return request( + this.fetchConfig, + { + method: "POST", + url: `/v1/b2b/passwords/existing_password/reset`, + data, + } + ); + } +} diff --git a/lib/b2b/passwords_session.ts b/lib/b2b/passwords_session.ts new file mode 100644 index 00000000..7683fa53 --- /dev/null +++ b/lib/b2b/passwords_session.ts @@ -0,0 +1,75 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { request } from "../shared"; + +// Request type for `passwords.sessions.reset`. +export interface B2BPasswordsSessionResetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // The password to authenticate. + password: string; + // A secret token for a given Stytch Session. + session_token?: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt?: string; +} + +// Response type for `passwords.sessions.reset`. +export interface B2BPasswordsSessionResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. + member_id: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). + organization: Organization; + /** + * 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; +} + +export class Sessions { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Reset the Member's password using their existing session. The endpoint will error if the session does + * not contain an authentication factor that has been issued within the last 5 minutes. Either + * `session_token` or `session_jwt` should be provided. + * @param data {@link B2BPasswordsSessionResetRequest} + * @returns {@link B2BPasswordsSessionResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset( + data: B2BPasswordsSessionResetRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/passwords/session/reset`, + data, + }); + } +} diff --git a/lib/b2b/saml.ts b/lib/b2b/saml.ts deleted file mode 100644 index c448e71a..00000000 --- a/lib/b2b/saml.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { BaseResponse, request, fetchConfig } from "../shared"; -import { SAMLConnection } from "./sso"; - -export interface B2BSAMLCreateConnectionRequest { - organization_id: string; - display_name?: string; -} - -export interface B2BSAMLCreateConnectionResponse extends BaseResponse { - connection: SAMLConnection; -} - -export interface B2BSAMLUpdateConnectionRequest { - organization_id: string; - connection_id: string; - idp_entity_id?: string; - display_name?: string; - attribute_mapping?: Record; - x509_certificate?: string; - idp_sso_url?: string; -} - -export interface B2BSAMLUpdateConnectionResponse extends BaseResponse { - connection: SAMLConnection; -} - -export interface B2BSAMLDeleteVerificationCertificateRequest { - organization_id: string; - connection_id: string; - certificate_id: string; -} - -export interface B2BSAMLDeleteVerificationCertificateResponse - extends BaseResponse { - certificate_id: string; -} - -export class SAML { - constructor(private readonly fetchConfig: fetchConfig) {} - - create({ - organization_id, - ...data - }: B2BSAMLCreateConnectionRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: `sso/saml/${organization_id}`, - data, - }); - } - - update({ - organization_id, - connection_id, - ...data - }: B2BSAMLUpdateConnectionRequest): Promise { - return request(this.fetchConfig, { - method: "PUT", - url: `sso/saml/${organization_id}/connections/${connection_id}`, - data, - }); - } - - deleteVerificationCertificate({ - organization_id, - connection_id, - certificate_id, - }: B2BSAMLDeleteVerificationCertificateRequest): Promise { - return request(this.fetchConfig, { - method: "DELETE", - url: `sso/saml/${organization_id}/connections/${connection_id}/verification_certificates/${certificate_id}`, - }); - } -} diff --git a/lib/b2b/sessions.ts b/lib/b2b/sessions.ts index e79bbfad..d29608f8 100644 --- a/lib/b2b/sessions.ts +++ b/lib/b2b/sessions.ts @@ -1,91 +1,306 @@ -import { BaseResponse, request, fetchConfig } from "../shared"; -import { B2BAuthenticationFactor, Member, MemberSession } from "./shared_b2b"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + import * as jose from "jose"; import { authenticateJwtLocal, JwtConfig } from "../shared/sessions"; -import { Organization } from "./organizations"; +import { AuthenticationFactor, JWK } from "../b2c/sessions"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; import { MfaRequired } from "./mfa"; +import { request } from "../shared"; -export interface B2BSessionsGetRequest { - organization_id: string; +export interface MemberSession { + // Globally unique UUID that identifies a specific Session. + member_session_id: string; + // Globally unique UUID that identifies a specific Member. member_id: string; + /** + * The timestamp when the Session was created. Values conform to the RFC 3339 standard and are expressed in + * UTC, e.g. `2021-12-29T12:33:09Z`. + */ + started_at: string; + /** + * The timestamp when the Session was last 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 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; + // An array of different authentication factors that have initiated a Session. + authentication_factors: AuthenticationFactor[]; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * The custom claims map for a Session. Claims can be added to a session during a Sessions authenticate + * call. + */ + custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2BSessionsGetResponse extends BaseResponse { - member_sessions: MemberSession[]; -} - -export interface B2BSessionsJwksResponse extends BaseResponse { - keys: JWK[]; -} - -export interface JWK { - alg: string; - key_ops: string[]; - kid: string; - kty: string; - use: string; - x5c: string[]; - "x5t#S256": string; - - n: string; - e: string; -} - +// Request type for `sessions.authenticate`. export interface B2BSessionsAuthenticateRequest { - session_duration_minutes?: number; + // A secret token for a given Stytch Session. session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + // The JSON Web Token (JWT) for a given Stytch Session. session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2BSessionsAuthenticateResponse extends BaseResponse { +// Response type for `sessions.authenticate`. +export interface B2BSessionsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). member_session: MemberSession; - member: Member; + // A secret token for a given Stytch Session. session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. session_jwt: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). organization: Organization; + /** + * 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; } -export type B2BSessionsRevokeRequest = - | { member_session_id: string } - | { session_token: string } - | { session_jwt: string } - | { member_id: string }; - -export type B2BSessionsRevokeResponse = BaseResponse; - +// Request type for `sessions.exchange`. export interface B2BSessionsExchangeRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; + // The `session_token` belonging to the member that you wish to associate the email with. session_token?: string; + // The `session_jwt` belonging to the member that you wish to associate the email with. session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BSessionsExchangeResponse extends BaseResponse { +// Response type for `sessions.exchange`. +export interface B2BSessionsExchangeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. member_id: string; - member_session: MemberSession | null; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session: MemberSession; + // A secret token for a given Stytch Session. session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. session_jwt: string; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). member: Member; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). organization: Organization; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ member_authenticated: boolean; + /** + * The returned Intermediate Session Token contains any Email Magic Link or OAuth factors from the original + * member session that are valid for the target Organization. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the target Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; + /** + * 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; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } -const organizationClaim = "https://stytch.com/organization"; +// Request type for `sessions.getJWKS`. +export interface B2BSessionsGetJWKSRequest { + // The `project_id` to get the JWKS for. + project_id: string; +} + +// Response type for `sessions.getJWKS`. +export interface B2BSessionsGetJWKSResponse { + // The JWK + keys: JWK[]; + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} + +// Request type for `sessions.get`. +export interface B2BSessionsGetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; +} + +// Response type for `sessions.get`. +export interface B2BSessionsGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // An array of [Session objects](https://stytch.com/docs/b2b/api/session-object). + member_sessions: MemberSession[]; + /** + * 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; +} + +// Request type for `sessions.revoke`. +export interface B2BSessionsRevokeRequest { + /** + * Globally unique UUID that identifies a specific Session in the Stytch API. The `member_session_id` is + * critical to perform operations on an Session, so be sure to preserve this value. + */ + member_session_id?: string; + // A secret token for a given Stytch Session. + session_token?: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt?: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id?: string; +} + +// Response type for `sessions.revoke`. +export interface B2BSessionsRevokeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} export class Sessions { - private base_path = "sessions"; private fetchConfig: fetchConfig; private jwksClient: jose.JWTVerifyGetKey; private jwtOptions: jose.JWTVerifyOptions; constructor(fetchConfig: fetchConfig, jwtConfig: JwtConfig) { this.fetchConfig = fetchConfig; - this.jwksClient = jwtConfig.jwks; this.jwtOptions = { audience: jwtConfig.projectID, @@ -94,38 +309,122 @@ export class Sessions { }; } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - get({ - organization_id, - member_id, - }: B2BSessionsGetRequest): Promise { + /** + * Retrieves all active Sessions for a Member. + * @param data {@link B2BSessionsGetRequest} + * @returns {@link B2BSessionsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: B2BSessionsGetRequest): Promise { return request(this.fetchConfig, { method: "GET", - url: this.base_path, - params: { organization_id, member_id }, - }); - } - - jwks(project_id: string): Promise { - return request(this.fetchConfig, { - method: "GET", - url: this.endpoint(`jwks/${project_id}`), + url: `/v1/b2b/sessions`, + params: { ...params }, }); } + /** + * Authenticates a Session and updates its lifetime by the specified `session_duration_minutes`. If the + * `session_duration_minutes` is not specified, a Session will not be extended. This endpoint requires + * either a `session_jwt` or `session_token` be included in the request. It will return an error if both + * are present. + * + * You may provide a JWT that needs to be refreshed and is expired according to its `exp` claim. A new JWT + * will be returned if both the signature and the underlying Session are still valid. + * @param data {@link B2BSessionsAuthenticateRequest} + * @returns {@link B2BSessionsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( data: B2BSessionsAuthenticateRequest ): Promise { return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/b2b/sessions/authenticate`, data, }); } + /** + * Revoke a Session and immediately invalidate all its tokens. To revoke a specific Session, pass either + * the `member_session_id`, `session_token`, or `session_jwt`. To revoke all Sessions for a Member, pass + * the `member_id`. + * @param data {@link B2BSessionsRevokeRequest} + * @returns {@link B2BSessionsRevokeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + revoke(data: B2BSessionsRevokeRequest): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/sessions/revoke`, + data, + }); + } + + /** + * Use this endpoint to exchange a Member's existing session for another session in a different + * Organization. This can be used to accept an invite, but not to create a new member via domain matching. + * + * To create a new member via domain matching, use the + * [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) flow + * instead. + * + * Only Email Magic Link, OAuth, and SMS OTP factors can be transferred between sessions. Other + * authentication factors, such as password factors, will not be transferred to the new session. + * SMS OTP factors can be used to fulfill MFA requirements for the target Organization if both the original + * and target Member have the same phone number and the phone number is verified for both Members. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BSessionsExchangeRequest} + * @returns {@link B2BSessionsExchangeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + exchange( + data: B2BSessionsExchangeRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/sessions/exchange`, + data, + }); + } + + /** + * Get the JSON Web Key Set (JWKS) for a project. + * @param data {@link B2BSessionsGetJWKSRequest} + * @returns {@link B2BSessionsGetJWKSResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + getJWKS( + params: B2BSessionsGetJWKSRequest + ): Promise { + return request(this.fetchConfig, { + method: "GET", + url: `/v1/b2b/sessions/jwks/${params.project_id}`, + params: {}, + }); + } + + // MANUAL(authenticateJwt)(SERVICE_METHOD) /** Parse a JWT and verify the signature, preferring local verification over remote. * * If max_token_age_seconds is set, remote verification will be forced if the JWT was issued at @@ -181,6 +480,7 @@ export class Sessions { options ); + const organizationClaim = "https://stytch.com/organization"; const { [organizationClaim]: orgClaimUntyped, ...claims } = sess.custom_claims; @@ -191,29 +491,12 @@ export class Sessions { member_id: sess.sub, organization_id: orgClaim.organization_id, authentication_factors: - sess.authentication_factors as B2BAuthenticationFactor[], + sess.authentication_factors as AuthenticationFactor[], started_at: sess.started_at, last_accessed_at: sess.last_accessed_at, expires_at: sess.expires_at, custom_claims: claims, }; } - - exchange( - data: B2BSessionsExchangeRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("exchange"), - data, - }); - } - - revoke(data: B2BSessionsRevokeRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("revoke"), - data, - }); - } + // ENDMANUAL(authenticateJwt) } diff --git a/lib/b2b/shared_b2b.ts b/lib/b2b/shared_b2b.ts deleted file mode 100644 index ddc03bc0..00000000 --- a/lib/b2b/shared_b2b.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { BaseResponse } from "../shared"; -import { Organization } from "./organizations"; - -export interface EmailFactor { - delivery_method: "email"; - type: string; - last_authenticated_at: string; - email_factor: { - email_id: string; - email_address: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} - -export interface PhoneNumberFactor { - delivery_method: "sms" | "whatsapp"; - type: string; - last_authenticated_at: string; - phone_number_factor: { - phone_id: string; - phone_number: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} - -export interface GoogleOAuthFactor { - delivery_method: "oauth_google"; - type: string; - last_authenticated_at: string; - google_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} - -export interface MicrosoftOAuthFactor { - delivery_method: "oauth_microsoft"; - type: string; - last_authenticated_at: string; - microsoft_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} - -export type B2BAuthenticationFactor = - | EmailFactor - | GoogleOAuthFactor - | MicrosoftOAuthFactor - | PhoneNumberFactor; -export interface MemberSession { - member_session_id: string; - member_id: string; - organization_id: string; - started_at: string; - last_accessed_at: string; - expires_at: string; - authentication_factors: B2BAuthenticationFactor[]; - custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any -} - -export interface Member { - organization_id: string; - member_id: string; - email_address: string; - status: string; - name: string; - oauth_registrations: OAuthRegistration[]; - sso_registrations: SSORegistration[]; - trusted_metadata: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - untrusted_metadata: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - is_breakglass: boolean; - member_password_id: string; - mfa_enrolled: boolean; - mfa_phone_number: string; -} - -export interface SSORegistration { - connection_id: string; - external_id: string; - registration_id: string; - sso_attributes: Record; // eslint-disable-line @typescript-eslint/no-explicit-any -} - -export interface OAuthRegistration { - provider_subject: string; - provider_type: string; - member_oauth_registration_id: string; - locale?: string | null; - profile_picture_url?: string | null; -} - -export interface ResultsMetadata { - total: number; - next_cursor: string; -} - -export enum SearchOperator { - OR = "OR", - AND = "AND", -} - -export interface ResponseWithMember extends BaseResponse { - member_id: string; - member: Member; - organization: Organization; -} diff --git a/lib/b2b/sso.ts b/lib/b2b/sso.ts index e49d1569..0e292c36 100644 --- a/lib/b2b/sso.ts +++ b/lib/b2b/sso.ts @@ -1,17 +1,16 @@ -import { BaseResponse, request, fetchConfig } from "../shared"; -import { Member, MemberSession } from "./shared_b2b"; -import { SAML } from "./saml"; -import { Organization } from "./organizations"; -import { OIDC } from "./oidc"; -import { MfaRequired } from "./mfa"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export interface X509Certificate { - certificate_id: string; - certificate: string; - issuer: string; - created_at: string; - expires_at: string; -} +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +import { OIDC } from "./sso_oidc"; +import { request } from "../shared"; +import { SAML } from "./sso_saml"; export interface OIDCConnection { organization_id: string; @@ -32,7 +31,6 @@ export interface SAMLConnection { organization_id: string; connection_id: string; status: string; - attribute_mapping: Record; idp_entity_id: string; display_name: string; idp_sso_url: string; @@ -40,85 +38,264 @@ export interface SAMLConnection { audience_uri: string; signing_certificates: X509Certificate[]; verification_certificates: X509Certificate[]; + attribute_mapping?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2BSSOGetConnectionsRequest { - organization_id: string; -} - -export interface B2BSSOGetConnectionsResponse extends BaseResponse { - saml_connections: SAMLConnection[]; - oidc_connections: OIDCConnection[]; -} - -export interface B2BSSODeleteConnectionRequest { - organization_id: string; - connection_id: string; -} - -export interface B2BSSODeleteConnectionResponse extends BaseResponse { - connection_id: string; +export interface X509Certificate { + certificate_id: string; + certificate: string; + issuer: string; + created_at?: string; + expires_at?: string; } +// Request type for `sso.authenticate`. export interface B2BSSOAuthenticateRequest { + // The token to authenticate. sso_token: string; + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. + pkce_code_verifier?: string; + // The `session_token` belonging to the member that you wish to associate the email with. session_token?: string; + // The `session_jwt` belonging to the member that you wish to associate the email with. session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - pkce_code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BSSOAuthenticateResponse extends BaseResponse { +// Response type for `sso.authenticate`. +export interface B2BSSOAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // Globally unique UUID that identifies a specific Member. member_id: string; - member: Member; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; - method_id: string; - session_token?: string; - session_jwt?: string; - session: MemberSession | null; + // The [Member object](https://stytch.com/docs/b2b/api/member-object). + member: Member; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * Indicates if all Sessions linked to the Member need to be reset. You should check this field if you + * aren't using + * Stytch's Session product. If you are using Stytch's Session product, we revoke the Member’s other + * Sessions for you. + */ reset_session: boolean; + // The [Organization object](https://stytch.com/docs/b2b/api/organization-object). organization: Organization; - member_authenticated: boolean; + /** + * The returned Intermediate Session Token contains an SSO factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * SSO factors are not transferable between Organizations, so the intermediate session token is not + * valid for use with discovery endpoints. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + // The [Session object](https://stytch.com/docs/b2b/api/session-object). + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} + +// Request type for `sso.deleteConnection`. +export interface B2BSSODeleteConnectionRequest { + // The organization ID that the SSO connection belongs to. + organization_id: string; + // The ID of the SSO connection. Both SAML and OIDC connection IDs can be provided. + connection_id: string; +} + +// Response type for `sso.deleteConnection`. +export interface B2BSSODeleteConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The `connection_id` that was deleted as part of the delete request. + connection_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; +} + +// Request type for `sso.getConnections`. +export interface B2BSSOGetConnectionsRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; +} + +// Response type for `sso.getConnections`. +export interface B2BSSOGetConnectionsResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * The list of [SAML Connections](https://stytch.com/docs/b2b/api/saml-connection-object) owned by this + * organization. + */ + saml_connections: SAMLConnection[]; + /** + * The list of [OIDC Connections](https://stytch.com/docs/b2b/api/oidc-connection-object) owned by this + * organization. + */ + oidc_connections: OIDCConnection[]; + /** + * 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; } export class SSO { - saml: SAML; + private fetchConfig: fetchConfig; oidc: OIDC; + saml: SAML; - constructor(private readonly fetchConfig: fetchConfig) { - this.saml = new SAML(fetchConfig); - this.oidc = new OIDC(fetchConfig); + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + this.oidc = new OIDC(this.fetchConfig); + this.saml = new SAML(this.fetchConfig); } - get({ - organization_id, - }: B2BSSOGetConnectionsRequest): Promise { - return request(this.fetchConfig, { + /** + * Get all SSO Connections owned by the organization. + * @param data {@link B2BSSOGetConnectionsRequest} + * @returns {@link B2BSSOGetConnectionsResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + getConnections( + params: B2BSSOGetConnectionsRequest + ): Promise { + return request(this.fetchConfig, { method: "GET", - url: `sso/${organization_id}`, + url: `/v1/b2b/sso/${params.organization_id}`, + params: {}, }); } - delete({ - organization_id, - connection_id, - }: B2BSSODeleteConnectionRequest): Promise { - return request(this.fetchConfig, { + /** + * Delete an existing SSO connection. + * @param data {@link B2BSSODeleteConnectionRequest} + * @returns {@link B2BSSODeleteConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteConnection( + data: B2BSSODeleteConnectionRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: `sso/${organization_id}/connections/${connection_id}`, + url: `/v1/b2b/sso/${data.organization_id}/connections/${data.connection_id}`, + data: {}, }); } + /** + * Authenticate a user given a token. + * This endpoint verifies that the user completed the SSO Authentication flow by verifying that the token + * is valid and hasn't expired. + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 + * minute duration. + * To link this authentication event to an existing Stytch session, include either the `session_token` or + * `session_jwt` param. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BSSOAuthenticateRequest} + * @returns {@link B2BSSOAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( data: B2BSSOAuthenticateRequest ): Promise { - return request(this.fetchConfig, { + return request(this.fetchConfig, { method: "POST", - url: `sso/authenticate`, + url: `/v1/b2b/sso/authenticate`, data, }); } diff --git a/lib/b2b/sso_oidc.ts b/lib/b2b/sso_oidc.ts new file mode 100644 index 00000000..869d6449 --- /dev/null +++ b/lib/b2b/sso_oidc.ts @@ -0,0 +1,186 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { OIDCConnection } from "./sso"; +import { request } from "../shared"; + +// Request type for `sso.oidc.createConnection`. +export interface B2BSSOOIDCCreateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // A human-readable display name for the connection. + display_name?: string; +} + +// Response type for `sso.oidc.createConnection`. +export interface B2BSSOOIDCCreateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `OIDC Connection` object affected by this API call. See the + * [OIDC Connection Object](https://stytch.com/docs/b2b/api/oidc-connection-object) for complete response + * field details. + */ + connection?: OIDCConnection; +} + +// Request type for `sso.oidc.updateConnection`. +export interface B2BSSOOIDCUpdateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // Globally unique UUID that identifies a specific SSO `connection_id` for a Member. + connection_id: string; + // A human-readable display name for the connection. + display_name?: 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; + // A case-sensitive `https://` URL that uniquely identifies the IdP. This will be provided by the IdP. + issuer?: 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](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). 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; +} + +// Response type for `sso.oidc.updateConnection`. +export interface B2BSSOOIDCUpdateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `OIDC Connection` object affected by this API call. See the + * [OIDC Connection Object](https://stytch.com/docs/b2b/api/oidc-connection-object) for complete response + * field details. + */ + 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; +} + +export class OIDC { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Create a new OIDC Connection. + * @param data {@link B2BSSOOIDCCreateConnectionRequest} + * @returns {@link B2BSSOOIDCCreateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + createConnection( + data: B2BSSOOIDCCreateConnectionRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/sso/oidc/${data.organization_id}`, + data: { + display_name: data.display_name, + }, + }); + } + + /** + * Updates an existing OIDC connection. + * + * 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 `$/.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. + * + * Note that a newly created connection will not become active until all of the following fields are + * provided: + * * `issuer` + * * `client_id` + * * `client_secret` + * * `authorization_url` + * * `token_url` + * * `userinfo_url` + * * `jwks_url` + * @param data {@link B2BSSOOIDCUpdateConnectionRequest} + * @returns {@link B2BSSOOIDCUpdateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + updateConnection( + data: B2BSSOOIDCUpdateConnectionRequest + ): Promise { + return request(this.fetchConfig, { + method: "PUT", + url: `/v1/b2b/sso/oidc/${data.organization_id}/connections/${data.connection_id}`, + data: { + display_name: data.display_name, + client_id: data.client_id, + client_secret: data.client_secret, + issuer: data.issuer, + authorization_url: data.authorization_url, + token_url: data.token_url, + userinfo_url: data.userinfo_url, + jwks_url: data.jwks_url, + }, + }); + } +} diff --git a/lib/b2b/sso_saml.ts b/lib/b2b/sso_saml.ts new file mode 100644 index 00000000..9f6f658f --- /dev/null +++ b/lib/b2b/sso_saml.ts @@ -0,0 +1,197 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { SAMLConnection } from "./sso"; + +// Request type for `sso.saml.createConnection`. +export interface B2BSSOSAMLCreateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // A human-readable display name for the connection. + display_name?: string; +} + +// Response type for `sso.saml.createConnection`. +export interface B2BSSOSAMLCreateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `SAML Connection` object affected by this API call. See the + * [SAML Connection Object](https://stytch.com/docs/b2b/api/saml-connection-object) for complete response + * field details. + */ + connection?: SAMLConnection; +} + +// Request type for `sso.saml.deleteVerificationCertificate`. +export interface B2BSSOSAMLDeleteVerificationCertificateRequest { + // The organization ID that the SAML connection belongs to. + organization_id: string; + // The ID of the SAML connection. + connection_id: string; + // The ID of the certificate to be deleted. + certificate_id: string; +} + +// Response type for `sso.saml.deleteVerificationCertificate`. +export interface B2BSSOSAMLDeleteVerificationCertificateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The ID of the certificate that was deleted. + certificate_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; +} + +// Request type for `sso.saml.updateConnection`. +export interface B2BSSOSAMLUpdateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + // Globally unique UUID that identifies a specific SSO `connection_id` for a Member. + 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; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * A certificate that Stytch will use to verify the sign-in assertion sent by the IdP, in + * [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format. See our + * [X509 guide](https://stytch.com/docs/b2b/api/saml-certificates) for more info. + */ + x509_certificate?: string; + // The URL for which assertions for login requests will be sent. This will be provided by the IdP. + idp_sso_url?: string; +} + +// Response type for `sso.saml.updateConnection`. +export interface B2BSSOSAMLUpdateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `SAML Connection` object affected by this API call. See the + * [SAML Connection Object](https://stytch.com/docs/b2b/api/saml-connection-object) for complete response + * field details. + */ + connection?: SAMLConnection; +} + +export class SAML { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Create a new SAML Connection. + * @param data {@link B2BSSOSAMLCreateConnectionRequest} + * @returns {@link B2BSSOSAMLCreateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + createConnection( + data: B2BSSOSAMLCreateConnectionRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/b2b/sso/saml/${data.organization_id}`, + data: { + display_name: data.display_name, + }, + }); + } + + /** + * Updates an existing SAML connection. + * + * Note that a newly created connection will not become active until all of the following are provided: + * * `idp_sso_url` + * * `attribute_mapping` + * * `idp_entity_id` + * * `x509_certificate` + * @param data {@link B2BSSOSAMLUpdateConnectionRequest} + * @returns {@link B2BSSOSAMLUpdateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + updateConnection( + data: B2BSSOSAMLUpdateConnectionRequest + ): Promise { + return request(this.fetchConfig, { + method: "PUT", + url: `/v1/b2b/sso/saml/${data.organization_id}/connections/${data.connection_id}`, + data: { + idp_entity_id: data.idp_entity_id, + display_name: data.display_name, + attribute_mapping: data.attribute_mapping, + x509_certificate: data.x509_certificate, + idp_sso_url: data.idp_sso_url, + }, + }); + } + + /** + * Delete a SAML verification certificate. + * + * 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. + * @param data {@link B2BSSOSAMLDeleteVerificationCertificateRequest} + * @returns {@link B2BSSOSAMLDeleteVerificationCertificateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteVerificationCertificate( + data: B2BSSOSAMLDeleteVerificationCertificateRequest + ): Promise { + return request( + this.fetchConfig, + { + method: "DELETE", + url: `/v1/b2b/sso/saml/${data.organization_id}/connections/${data.connection_id}/verification_certificates/${data.certificate_id}`, + data: {}, + } + ); + } +} diff --git a/lib/b2c/attribute.ts b/lib/b2c/attribute.ts new file mode 100644 index 00000000..bfb57d2d --- /dev/null +++ b/lib/b2c/attribute.ts @@ -0,0 +1,12 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +export interface Attributes { + // The IP address of the user. + ip_address?: string; + // The user agent of the User. + user_agent?: string; +} diff --git a/lib/b2c/client.ts b/lib/b2c/client.ts index 1b857461..33da7428 100644 --- a/lib/b2c/client.ts +++ b/lib/b2c/client.ts @@ -1,4 +1,7 @@ +import * as jose from "jose"; +import { BaseClient, ClientConfig } from "../shared/client"; import { CryptoWallets } from "./crypto_wallets"; +import { JwtConfig } from "../shared/sessions"; import { MagicLinks } from "./magic_links"; import { OAuth } from "./oauth"; import { OTPs } from "./otps"; @@ -7,21 +10,18 @@ import { Sessions } from "./sessions"; import { TOTPs } from "./totps"; import { Users } from "./users"; import { WebAuthn } from "./webauthn"; -import { BaseClient, ClientConfig } from "../shared/client"; -import * as jose from "jose"; -import { JwtConfig } from "../shared/sessions"; export class Client extends BaseClient { protected jwtConfig: JwtConfig; - users: Users; + cryptoWallets: CryptoWallets; magicLinks: MagicLinks; - otps: OTPs; oauth: OAuth; + otps: OTPs; passwords: Passwords; sessions: Sessions; totps: TOTPs; + users: Users; webauthn: WebAuthn; - cryptoWallets: CryptoWallets; constructor(config: ClientConfig) { super(config); @@ -31,18 +31,21 @@ export class Client extends BaseClient { projectID: config.project_id, // Fetch the signature verification keys for this project as needed. jwks: jose.createRemoteJWKSet( - new URL(`sessions/jwks/${config.project_id}`, this.fetchConfig.baseURL) + new URL( + `/v1/sessions/jwks/${config.project_id}`, + this.fetchConfig.baseURL + ) ), }; - this.users = new Users(this.fetchConfig); + this.cryptoWallets = new CryptoWallets(this.fetchConfig); this.magicLinks = new MagicLinks(this.fetchConfig); this.oauth = new OAuth(this.fetchConfig); this.otps = new OTPs(this.fetchConfig); this.passwords = new Passwords(this.fetchConfig); this.sessions = new Sessions(this.fetchConfig, this.jwtConfig); this.totps = new TOTPs(this.fetchConfig); + this.users = new Users(this.fetchConfig); this.webauthn = new WebAuthn(this.fetchConfig); - this.cryptoWallets = new CryptoWallets(this.fetchConfig); } } diff --git a/lib/b2c/crypto_wallets.ts b/lib/b2c/crypto_wallets.ts index 10861259..a6f73e0f 100644 --- a/lib/b2c/crypto_wallets.ts +++ b/lib/b2c/crypto_wallets.ts @@ -1,68 +1,168 @@ -import { Session, User } from "./shared_b2c"; -import { request, fetchConfig, BaseResponse } from "../shared"; -import { UserID } from "./users"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export interface B2CCryptoWalletsAuthenticateStartRequest { - crypto_wallet_address: string; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; + +// Request type for `cryptoWallets.authenticate`. +export interface CryptoWalletsAuthenticateRequest { + /** + * The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. Wallets for any + * EVM-compatible chains (such as Polygon or BSC) are also supported and are grouped under the `ethereum` + * type. + */ crypto_wallet_type: string; - user_id?: UserID; + // The crypto wallet address to authenticate. + crypto_wallet_address: string; + // The signature from the message challenge. + signature: string; + // The `session_token` associated with a User's existing Session. session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2CCryptoWalletsAuthenticateStartResponse - extends BaseResponse { - user_id: UserID; - challenge: string; - user_created: boolean; +// Response type for `cryptoWallets.authenticate`. +export interface CryptoWalletsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; } -export interface B2CCryptoWalletsAuthenticateRequest { - crypto_wallet_address: string; +// Request type for `cryptoWallets.authenticateStart`. +export interface CryptoWalletsAuthenticateStartRequest { + /** + * The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. Wallets for any + * EVM-compatible chains (such as Polygon or BSC) are also supported and are grouped under the `ethereum` + * type. + */ crypto_wallet_type: string; - signature: string; + // The crypto wallet address to authenticate. + crypto_wallet_address: string; + // The unique ID of a specific User. + user_id?: string; + // The `session_token` associated with a User's existing Session. session_token?: string; + // The `session_jwt` associated with a User's existing Session. session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2CCryptoWalletsAuthenticateResponse extends BaseResponse { - user_id: UserID; - user: User; - session_token?: string; - session_jwt?: string; - session?: Session; +// Response type for `cryptoWallets.authenticateStart`. +export interface CryptoWalletsAuthenticateStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // A challenge string to be signed by the wallet in order to prove ownership. + challenge: string; + // In `login_or_create` endpoints, this field indicates whether or not a User was just created. + user_created: boolean; + /** + * 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; } export class CryptoWallets { - base_path = "crypto_wallets"; private fetchConfig: fetchConfig; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - + /** + * Initiate the authentication of a crypto wallet. After calling this endpoint, the user will need to sign + * a message containing only the returned `challenge` field. + * @param data {@link CryptoWalletsAuthenticateStartRequest} + * @returns {@link CryptoWalletsAuthenticateStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticateStart( - data: B2CCryptoWalletsAuthenticateStartRequest - ): Promise { - return request(this.fetchConfig, { + data: CryptoWalletsAuthenticateStartRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate/start"), + url: `/v1/crypto_wallets/authenticate/start`, data, }); } + /** + * Complete the authentication of a crypto wallet by passing the signature. + * @param data {@link CryptoWalletsAuthenticateRequest} + * @returns {@link CryptoWalletsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( - data: B2CCryptoWalletsAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { + data: CryptoWalletsAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/crypto_wallets/authenticate`, data, }); } diff --git a/lib/b2c/index.ts b/lib/b2c/index.ts index 8e15e46f..c915d2c1 100644 --- a/lib/b2c/index.ts +++ b/lib/b2c/index.ts @@ -1,131 +1,214 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +// MANUAL(exports)(TYPES) +export type { SearchUsersQueryOperand } from "./users"; +// ENDMANUAL(exports) + +export type { Attributes } from "./attribute"; + export type { - User, - Name, + BiometricRegistration, + CryptoWallet, Email, + Name, + OAuthProvider, Password, PhoneNumber, - OAuthProvider, - WebAuthnRegistration, - BiometricRegistration, + UsersResultsMetadata, + SearchUsersQuery, TOTP, - CryptoWallet, + User, + WebAuthnRegistration, + UsersCreateRequest, + UsersCreateResponse, + UsersDeleteBiometricRegistrationRequest, + UsersDeleteBiometricRegistrationResponse, + UsersDeleteCryptoWalletRequest, + UsersDeleteCryptoWalletResponse, + UsersDeleteEmailRequest, + UsersDeleteEmailResponse, + UsersDeleteOAuthRegistrationRequest, + UsersDeleteOAuthRegistrationResponse, + UsersDeletePasswordRequest, + UsersDeletePasswordResponse, + UsersDeletePhoneNumberRequest, + UsersDeletePhoneNumberResponse, + UsersDeleteRequest, + UsersDeleteResponse, + UsersDeleteTOTPRequest, + UsersDeleteTOTPResponse, + UsersDeleteWebAuthnRegistrationRequest, + UsersDeleteWebAuthnRegistrationResponse, + UsersGetRequest, + UsersGetResponse, + UsersSearchRequest, + UsersSearchResponse, + UsersUpdateRequest, + UsersUpdateResponse, +} from "./users"; + +export type { + AmazonOAuthFactor, + AppleOAuthFactor, + AuthenticationFactor, + AuthenticatorAppFactor, + BiometricFactor, + BitbucketOAuthFactor, + CoinbaseOAuthFactor, + CryptoWalletFactor, + DiscordOAuthFactor, + EmailFactor, + EmbeddableMagicLinkFactor, + FacebookOAuthFactor, + FigmaOAuthFactor, + GitLabOAuthFactor, + GithubOAuthFactor, + GoogleOAuthFactor, + InstagramOAuthFactor, + JWK, + LinkedInOAuthFactor, + MicrosoftOAuthFactor, + OIDCSSOFactor, + PhoneNumberFactor, + RecoveryCodeFactor, + SAMLSSOFactor, + SalesforceOAuthFactor, Session, - B2CAuthenticationFactor, - Attributes, -} from "./shared_b2c"; + ShopifyOAuthFactor, + SlackOAuthFactor, + SnapchatOAuthFactor, + SpotifyOAuthFactor, + SteamOAuthFactor, + TikTokOAuthFactor, + TwitchOAuthFactor, + TwitterOAuthFactor, + WebAuthnFactor, + YahooOAuthFactor, + SessionsAuthenticateRequest, + SessionsAuthenticateResponse, + SessionsGetJWKSRequest, + SessionsGetJWKSResponse, + SessionsGetRequest, + SessionsGetResponse, + SessionsRevokeRequest, + SessionsRevokeResponse, +} from "./sessions"; export type { - B2CCryptoWalletsAuthenticateStartRequest, - B2CCryptoWalletsAuthenticateStartResponse, - B2CCryptoWalletsAuthenticateRequest, - B2CCryptoWalletsAuthenticateResponse, + CryptoWalletsAuthenticateRequest, + CryptoWalletsAuthenticateResponse, + CryptoWalletsAuthenticateStartRequest, + CryptoWalletsAuthenticateStartResponse, } from "./crypto_wallets"; export type { - B2CMagicLinksRevokePendingInviteByEmailRequest, - B2CMagicLinksRevokePendingInviteByEmailResponse, - B2CMagicLinksAuthenticateRequest, - B2CMagicLinksAuthenticateResponse, - B2CMagicLinksInviteByEmailResponse, - B2CMagicLinksInviteByEmailRequest, - B2CMagicLinksSendByEmailRequest, - B2CMagicLinksSendByEmailResponse, - B2CMagicLinksLoginOrCreateByEmailRequest, - B2CMagicLinksLoginOrCreateByEmailResponse, - B2CMagicLinksCreateRequest, - B2CMagicLinksCreateResponse, + Options, + MagicLinksAuthenticateRequest, + MagicLinksAuthenticateResponse, + MagicLinksCreateRequest, + MagicLinksCreateResponse, } from "./magic_links"; export type { - B2COAuthAuthenticateRequest, - B2COAuthAuthenticateResponse, - B2COAuthAttachRequest, - B2COAuthAttachResponse, -} from "./oauth"; + MagicLinksEmailInviteRequest, + MagicLinksEmailInviteResponse, + MagicLinksEmailLoginOrCreateRequest, + MagicLinksEmailLoginOrCreateResponse, + MagicLinksEmailRevokeInviteRequest, + MagicLinksEmailRevokeInviteResponse, + MagicLinksEmailSendRequest, + MagicLinksEmailSendResponse, +} from "./magic_links_email"; export type { - B2COTPsAuthenticateRequest, - B2COTPsAuthenticateResponse, - B2COTPsSMSSendRequest, - B2COTPsSMSSendResponse, - B2COTPsSMSLoginOrCreateRequest, - B2COTPsSMSLoginOrCreateResponse, - B2COTPsEmailSendRequest, - B2COTPsEmailSendResponse, - B2COTPsEmailLoginOrCreateRequest, - B2COTPsEmailLoginOrCreateResponse, - B2COTPsWhatsAppSendRequest, - B2COTPsWhatsAppSendResponse, - B2COTPsWhatsAppLoginOrCreateRequest, - B2COTPsWhatsAppLoginOrCreateResponse, -} from "./otps"; + Argon2Config, + Feedback, + LUDSRequirements, + MD5Config, + PBKDF2Config, + SHA1Config, + ScryptConfig, + PasswordsAuthenticateRequest, + PasswordsAuthenticateResponse, + PasswordsCreateRequest, + PasswordsCreateResponse, + PasswordsMigrateRequest, + PasswordsMigrateResponse, + PasswordsStrengthCheckRequest, + PasswordsStrengthCheckResponse, +} from "./passwords"; export type { - B2CPasswordsAuthenticateRequest, - B2CPasswordsAuthenticateResponse, - B2CPasswordsCreateRequest, - B2CPasswordsCreateResponse, - B2CPasswordsResetByEmailRequest, - B2CPasswordsResetByEmailResponse, - B2CPasswordsResetByEmailStartRequest, - B2CPasswordsResetByEmailStartResponse, - B2CPasswordsResetByExistingPasswordRequest, - B2CPasswordsResetByExistingPasswordResponse, - B2CPasswordsMigrateRequest, - B2CPasswordsMigrateResponse, - B2CPasswordsResetBySessionRequest, - B2CPasswordsResetBySessionResponse, - B2CPasswordsStrengthCheckRequest, - B2CPasswordsStrengthCheckResponse, -} from "./passwords"; + PasswordsEmailResetRequest, + PasswordsEmailResetResponse, + PasswordsEmailResetStartRequest, + PasswordsEmailResetStartResponse, +} from "./passwords_email"; export type { - B2CSessionsAuthenticateRequest, - B2CSessionsAuthenticateResponse, - B2CSessionsRevokeRequest, - B2CSessionsRevokeResponse, - B2CSessionsGetRequest, - B2CSessionsGetResponse, - B2CSessionsJwksResponse, -} from "./sessions"; + PasswordsExistingPasswordResetRequest, + PasswordsExistingPasswordResetResponse, +} from "./passwords_existing_password"; export type { - B2CTOTPsAuthenticateRequest, - B2CTOTPsAuthenticateResponse, - B2CTOTPsCreateRequest, - B2CTOTPsCreateResponse, - B2CTOTPsRecoverRequest, - B2CTOTPsRecoverResponse, - B2CTOTPsRecoveryCodesRequest, - B2CTOTPsRecoveryCodesResponse, -} from "./totps"; + PasswordsSessionResetRequest, + PasswordsSessionResetResponse, +} from "./passwords_session"; export type { - B2CUsersCreateRequest, - B2CUsersCreateResponse, - B2CUsersSearchRequest, - B2CUsersSearchResponse, - B2CUsersGetResponse, - B2CUsersUpdateRequest, - B2CUsersUpdateResponse, - B2CUsersDeleteCryptoWalletResponse, - B2CUsersDeleteTOTPResponse, - B2CUsersDeleteWebAuthnRegistrationResponse, - B2CUsersDeletePhoneNumberResponse, - B2CUsersDeleteEmailResponse, - B2CUsersDeleteBiometricRegistrationResponse, - B2CUsersDeleteOAuthUserRegistrationResponse, - B2CUsersDeletePasswordResponse, - B2CUsersDeleteResponse, -} from "./users"; + OAuthProviderValues, + OAuthAttachRequest, + OAuthAttachResponse, + OAuthAuthenticateRequest, + OAuthAuthenticateResponse, +} from "./oauth"; + +export type { OTPsAuthenticateRequest, OTPsAuthenticateResponse } from "./otps"; + +export type { + OTPsSmsLoginOrCreateRequest, + OTPsSmsLoginOrCreateResponse, + OTPsSmsSendRequest, + OTPsSmsSendResponse, +} from "./otps_sms"; + +export type { + OTPsWhatsappLoginOrCreateRequest, + OTPsWhatsappLoginOrCreateResponse, + OTPsWhatsappSendRequest, + OTPsWhatsappSendResponse, +} from "./otps_whatsapp"; + +export type { + OTPsEmailLoginOrCreateRequest, + OTPsEmailLoginOrCreateResponse, + OTPsEmailSendRequest, + OTPsEmailSendResponse, +} from "./otps_email"; + +export type { + TOTPWithRecoveryCodes, + TOTPsAuthenticateRequest, + TOTPsAuthenticateResponse, + TOTPsCreateRequest, + TOTPsCreateResponse, + TOTPsRecoverRequest, + TOTPsRecoverResponse, + TOTPsRecoveryCodesRequest, + TOTPsRecoveryCodesResponse, +} from "./totps"; export type { - B2CWebAuthnRegisterStartRequest, - B2CWebAuthnRegisterStartResponse, - B2CWebAuthnRegisterRequest, - B2CWebAuthnRegisterResponse, - B2CWebAuthnAuthenticateStartRequest, - B2CWebAuthnAuthenticateStartResponse, - B2CWebAuthnAuthenticateRequest, - B2CWebAuthnAuthenticateResponse, + WebAuthnAuthenticateRequest, + WebAuthnAuthenticateResponse, + WebAuthnAuthenticateStartRequest, + WebAuthnAuthenticateStartResponse, + WebAuthnRegisterRequest, + WebAuthnRegisterResponse, + WebAuthnRegisterStartRequest, + WebAuthnRegisterStartResponse, } from "./webauthn"; diff --git a/lib/b2c/magic_links.ts b/lib/b2c/magic_links.ts index d993ea22..7bf4b59c 100644 --- a/lib/b2c/magic_links.ts +++ b/lib/b2c/magic_links.ts @@ -1,194 +1,185 @@ -import { request, BaseResponse, fetchConfig } from "../shared"; -import { Attributes, Name, Session, User } from "./shared_b2c"; - -export interface B2CMagicLinksSendByEmailRequest { - email: string; - login_magic_link_url?: string; - signup_magic_link_url?: string; - login_expiration_minutes?: number; - signup_expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - attributes?: Attributes; - code_challenge?: string; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} - -export interface B2CMagicLinksSendByEmailResponse extends BaseResponse { - user_id: string; - email_id: string; -} - -export interface B2CMagicLinksLoginOrCreateByEmailRequest { - email: string; - login_magic_link_url?: string; - signup_magic_link_url?: string; - login_expiration_minutes?: number; - signup_expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - create_user_as_pending?: boolean; - attributes?: Attributes; - code_challenge?: string; - locale?: string; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Attributes } from "./attribute"; +import { Email } from "./magic_links_email"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; + +export interface Options { + // Require that the IP address the Magic Link was requested from matches the IP address it's clicked from. + ip_match_required: boolean; + // Require that the user agent the Magic Link was requested from matches the user agent it's clicked from. + user_agent_match_required: boolean; } -export interface B2CMagicLinksLoginOrCreateByEmailResponse - extends BaseResponse { - user_id: string; - email_id: string; - user_created: boolean; -} - -export interface B2CMagicLinksInviteByEmailRequest { - email: string; - invite_magic_link_url?: string; - invite_expiration_minutes?: number; - invite_template_id?: string; - name?: Name; - attributes?: Attributes; - locale?: string; -} - -export interface B2CMagicLinksInviteByEmailResponse extends BaseResponse { - user_id: string; - email_id: string; -} - -export interface B2CMagicLinksCreateRequest { - user_id: string; - expiration_minutes?: number; - attributes?: Attributes; -} - -export interface B2CMagicLinksCreateResponse extends BaseResponse { +// Request type for `magicLinks.authenticate`. +export interface MagicLinksAuthenticateRequest { + // The token to authenticate. token: string; - user_id: string; -} - -export interface B2CMagicLinksAuthenticateRequest { - options?: { - ip_match_required?: boolean; - user_agent_match_required?: boolean; - }; + // Provided attributes help with fraud detection. attributes?: Attributes; + // Specify optional security settings. + options?: Options; + // The `session_token` associated with a User's existing Session. session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. code_verifier?: string; } -export interface B2CMagicLinksAuthenticateResponse extends BaseResponse { +// Response type for `magicLinks.authenticate`. +export interface MagicLinksAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. user_id: string; - user: User; + // The `email_id` or `phone_id` involved in the given authentication. method_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * Indicates if all other of the User's Sessions need to be reset. You should check this field if you + * aren't using Stytch's Session product. If you are using Stytch's Session product, we revoke the User's + * other sessions for you. + */ reset_sessions: boolean; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; } -export interface B2CMagicLinksRevokePendingInviteByEmailRequest { - email: string; +// Request type for `magicLinks.create`. +export interface MagicLinksCreateRequest { + // The unique ID of a specific User. + user_id: string; + /** + * Set the expiration for the Magic Link `token` in minutes. By default, it expires in 1 hour. The minimum + * expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + expiration_minutes?: number; + // Provided attributes help with fraud detection. + attributes?: Attributes; } -// eslint-disable-next-line @typescript-eslint/no-empty-interface -export interface B2CMagicLinksRevokePendingInviteByEmailResponse - extends BaseResponse {} - -class Email { - base_path: string; - delivery = "email"; - - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig, parent_path: string) { - this.fetchConfig = fetchConfig; - this.base_path = `${parent_path}`; - } - - private endpoint(path: string): string { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send( - data: B2CMagicLinksSendByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data, - }); - } - - loginOrCreate( - data: B2CMagicLinksLoginOrCreateByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data, - }); - } - - invite( - data: B2CMagicLinksInviteByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("invite"), - data, - }); - } - - revokeInvite( - data: B2CMagicLinksRevokePendingInviteByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("revoke_invite"), - data, - }); - } +// Response type for `magicLinks.create`. +export interface MagicLinksCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The Magic Link `token` that you'll include in your contact method of choice, e.g. email or SMS. + token: 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; } export class MagicLinks { - base_path = "magic_links"; - email: Email; - private fetchConfig: fetchConfig; + email: Email; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; - this.email = new Email(fetchConfig, this.base_path); - } - - private endpoint(path: string): string { - return `${this.base_path}/${path}`; + this.email = new Email(this.fetchConfig); } - create( - data: B2CMagicLinksCreateRequest - ): Promise { - return request(this.fetchConfig, { + /** + * Authenticate a User given a Magic Link. This endpoint verifies that the Magic Link token is valid, + * hasn't expired or been previously used, and any optional security settings such as IP match or user + * agent match are satisfied. + * @param data {@link MagicLinksAuthenticateRequest} + * @returns {@link MagicLinksAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate( + data: MagicLinksAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.base_path, - data: data, + url: `/v1/magic_links/authenticate`, + data, }); } - authenticate( - token: string, - data?: B2CMagicLinksAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { + /** + * Create an embeddable Magic Link token for a User. Access to this endpoint is restricted. To enable it, + * please send us a note at support@stytch.com. + * + * ### Next steps + * Send the returned `token` value to the end user in a link which directs to your application. When the + * end user follows your link, collect the token, and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksCreateRequest} + * @returns {@link MagicLinksCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: MagicLinksCreateRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), - data: { token, ...data }, + url: `/v1/magic_links`, + data, }); } } diff --git a/lib/b2c/magic_links_email.ts b/lib/b2c/magic_links_email.ts new file mode 100644 index 00000000..3a2b66c5 --- /dev/null +++ b/lib/b2c/magic_links_email.ts @@ -0,0 +1,376 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { Name } from "./users"; +import { request } from "../shared"; + +// Request type for `magicLinks.email.invite`. +export interface MagicLinksEmailInviteRequest { + // The email address of the User to send the invite Magic Link to. + email: 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + // The name of the user. Each field in the name object is optional. + name?: Name; + /** + * The URL the end user clicks from the Email Magic Link. This should be a URL that your app receives and + * parses and subsequently sends an API request to authenticate the Magic Link and log in the User. 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 sign-up redirect URL, an error is returned. + */ + invite_magic_link_url?: string; + /** + * Set the expiration for the email magic link, in minutes. By default, it expires in 1 hour. The minimum + * expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + invite_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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `magicLinks.email.invite`. +export interface MagicLinksEmailInviteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID of a specific email address. + email_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; +} + +// Request type for `magicLinks.email.loginOrCreate`. +export interface MagicLinksEmailLoginOrCreateRequest { + // The email address of the end user. + email: string; + /** + * The URL the end 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; + /** + * The URL the end 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 login email magic link, in minutes. By default, it expires in 1 hour. The + * minimum expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + login_expiration_minutes?: number; + /** + * 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 7 days (10080 mins). + */ + signup_expiration_minutes?: number; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `magicLinks.email.loginOrCreate`. +export interface MagicLinksEmailLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID of a specific email address. + email_id: string; + // In `login_or_create` endpoints, this field indicates whether or not a User was just created. + user_created: boolean; + /** + * 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; +} + +// Request type for `magicLinks.email.revokeInvite`. +export interface MagicLinksEmailRevokeInviteRequest { + // The email of the user. + email: string; +} + +// Response type for `magicLinks.email.revokeInvite`. +export interface MagicLinksEmailRevokeInviteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} + +// Request type for `magicLinks.email.send`. +export interface MagicLinksEmailSendRequest { + // The email address of the User to send the Magic Link to. + email: string; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * The URL the end 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; + /** + * The URL the end 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 login email magic link, in minutes. By default, it expires in 1 hour. The + * minimum expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + login_expiration_minutes?: number; + /** + * 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 7 days (10080 mins). + */ + signup_expiration_minutes?: number; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: string; + // The unique ID of a specific User. + user_id?: string; + // The `session_token` of the user to associate the email with. + session_token?: string; + // The `session_jwt` of the user to associate the email with. + session_jwt?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; +} + +// Response type for `magicLinks.email.send`. +export interface MagicLinksEmailSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID of a specific email address. + email_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; +} + +export class Email { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Send a magic link to an existing Stytch user using their email address. If you'd like to create a user + * and send them a magic link by email with one request, use our + * [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email). + * + * ### Add an email to an existing user + * This endpoint also allows you to add a new email to an existing Stytch User. Including a `user_id`, + * `session_token`, or `session_jwt` in the request will add the email to the pre-existing Stytch User upon + * successful authentication. + * + * Adding a new email to an existing Stytch User requires the user to be present and validate the email via + * magic link. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * The user is emailed a magic link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/guides/magic-links/email-magic-links/redirect-routing). Collect + * the `token` from the URL query parameters, and call + * [Authenticate magic link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailSendRequest} + * @returns {@link MagicLinksEmailSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: MagicLinksEmailSendRequest): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/send`, + data, + }); + } + + /** + * Send either a login or signup Magic Link to the User based on if the email is associated with a User + * already. A new or pending User will receive a signup Magic Link. An active User will receive a login + * Magic Link. For more information on how to control the status your Users are created in see the + * `create_user_as_pending` flag. + * + * ### Next steps + * The User is emailed a Magic Link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/magic-links#email-magic-links_redirect-routing). Collect the + * `token` from the URL query parameters and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailLoginOrCreateRequest} + * @returns {@link MagicLinksEmailLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate( + data: MagicLinksEmailLoginOrCreateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/login_or_create`, + data, + }); + } + + /** + * Create a User and send an invite Magic Link to the provided `email`. The User will be created with a + * `pending` status until they click the Magic Link in the invite email. + * + * ### Next steps + * The User is emailed a Magic Link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/magic-links#email-magic-links_redirect-routing). Collect the + * `token` from the URL query parameters and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailInviteRequest} + * @returns {@link MagicLinksEmailInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + invite( + data: MagicLinksEmailInviteRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/invite`, + data, + }); + } + + /** + * Revoke a pending invite based on the `email` provided. + * @param data {@link MagicLinksEmailRevokeInviteRequest} + * @returns {@link MagicLinksEmailRevokeInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + revokeInvite( + data: MagicLinksEmailRevokeInviteRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/magic_links/email/revoke_invite`, + data, + }); + } +} diff --git a/lib/b2c/oauth.ts b/lib/b2c/oauth.ts index 77d13b8f..fa6db80b 100644 --- a/lib/b2c/oauth.ts +++ b/lib/b2c/oauth.ts @@ -1,76 +1,225 @@ -import { Session, User } from "./shared_b2c"; -import { request, BaseResponse, fetchConfig } from "../shared"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export interface B2COAuthAuthenticateRequest { - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - code_verifier?: string; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; + +export interface OAuthProviderValues { + // The `access_token` that you may use to access the User's data in the provider's API. + access_token: string; + // The `refresh_token` that you may use to refresh a User's session within the provider's API. + refresh_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 [OpenID Connect](https://openid.net/foundation/) + * specification, which is based on OAuth. + */ + id_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; } -export interface B2COAuthAuthenticateResponse extends BaseResponse { - user_id: string; - user: User; - oauth_user_registration_id: string; - provider_subject: string; - provider_type: string; +// Request type for `oauth.attach`. +export interface OAuthAttachRequest { + // The OAuth provider's name. + provider: string; + // The unique ID of a specific User. + user_id?: string; + // The `session_token` associated with a User's existing Session. session_token?: string; + // The `session_jwt` associated with a User's existing Session. session_jwt?: string; - session?: Session; - provider_values: ProvidersValues; - reset_sessions: boolean; } -export interface ProvidersValues { - access_token?: string; - refresh_token?: string; - id_token?: string; - expires_at?: number; - scopes: string[]; +// Response type for `oauth.attach`. +export interface OAuthAttachResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * A single-use token for connecting the Stytch User selection from an OAuth Attach request to the + * corresponding OAuth Start request. + */ + oauth_attach_token: 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; } -export interface B2COAuthAttachRequest { - provider: string; - - /** Exactly one of these user-selection fields must be provided. */ - user_id?: string; +// Request type for `oauth.authenticate`. +export interface OAuthAuthenticateRequest { + // The token to authenticate. + token: string; + /** + * Reuse an existing session instead of creating a new one. If you provide us with a `session_token`, then + * we'll update the session represented by this session token with this OAuth factor. If this + * `session_token` belongs to a different user than the OAuth token, the session_jwt will be ignored. This + * endpoint will error if both `session_token` and `session_jwt` are provided. + */ session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + /** + * Reuse an existing session instead of creating a new one. If you provide us with a `session_jwt`, then + * we'll update the session represented by this JWT with this OAuth factor. If this `session_jwt` belongs + * to a different user than the OAuth token, the session_jwt will be ignored. This endpoint will error if + * both `session_token` and `session_jwt` are provided. + */ session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. + code_verifier?: string; } -export interface B2COAuthAttachResponse extends BaseResponse { - oauth_attach_token: string; +// Response type for `oauth.authenticate`. +export interface OAuthAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the "sub" or + * "Subject field" in OAuth protocols. + */ + provider_subject: string; + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Facebook, GitHub + * etc. + */ + provider_type: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: 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` is only + * returned by OIDC complaint identity providers. + */ + provider_values: OAuthProviderValues; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * Indicates if all other of the User's Sessions need to be reset. You should check this field if you + * aren't using Stytch's Session product. If you are using Stytch's Session product, we revoke the User's + * other sessions for you. + */ + reset_sessions: boolean; + // The unique ID for an OAuth registration. + oauth_user_registration_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; + /** + * A `Session` object. For backwards compatibility reasons, the session from an OAuth authenticate call is + * labeled as `user_session`, but is otherwise just a standard stytch `Session` object. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + user_session?: Session; } export class OAuth { - base_path = "oauth"; - private fetchConfig: fetchConfig; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - authenticate( - token: string, - data?: B2COAuthAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { + /** + * Generate an OAuth Attach Token to pre-associate an OAuth flow with an existing Stytch User. 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 for a new user. + * + * Exactly one of `user_id`, `session_token`, or `session_jwt` must be provided to identify the target + * Stytch User. + * + * This is an optional step in the OAuth flow. Stytch can often determine whether to create a new user or + * log in an existing one based on verified identity provider information. This endpoint is useful for + * cases where we can't, such as missing or unverified provider information. + * @param data {@link OAuthAttachRequest} + * @returns {@link OAuthAttachResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + attach(data: OAuthAttachRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), - data: { token, ...data }, + url: `/v1/oauth/attach`, + data, }); } - attach(data?: B2COAuthAttachRequest): Promise { - return request(this.fetchConfig, { + /** + * Authenticate a User given a `token`. This endpoint verifies that the user completed the OAuth flow by + * verifying that the token is valid and hasn't expired. To initiate a Stytch session for the user while + * authenticating their OAuth token, include `session_duration_minutes`; a session with the identity + * provider, e.g. Google or Facebook, will always be initiated upon successful authentication. + * @param data {@link OAuthAuthenticateRequest} + * @returns {@link OAuthAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate( + data: OAuthAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("attach"), + url: `/v1/oauth/authenticate`, data, }); } diff --git a/lib/b2c/otps.ts b/lib/b2c/otps.ts index fd45a6ac..56c40221 100644 --- a/lib/b2c/otps.ts +++ b/lib/b2c/otps.ts @@ -1,248 +1,132 @@ -import { Attributes, Session, User } from "./shared_b2c"; -import { request, BaseResponse, fetchConfig } from "../shared"; - -export interface B2COTPsEmailSendRequest { - email: string; - expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - attributes?: Attributes; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} - -export interface B2COTPsEmailSendResponse extends BaseResponse { - user_id: string; - email_id: string; -} - -export interface B2COTPsEmailLoginOrCreateRequest { - email: string; - expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - attributes?: Attributes; - create_user_as_pending?: boolean; - locale?: string; -} - -export interface B2COTPsEmailLoginOrCreateResponse extends BaseResponse { - user_id: string; - email_id: string; - user_created: boolean; -} - -export interface B2COTPsSMSSendRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} - -export interface B2COTPsSMSSendResponse extends BaseResponse { - user_id: string; - phone_id: string; -} - -export interface B2COTPsSMSLoginOrCreateRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - create_user_as_pending?: boolean; - locale?: string; -} - -export interface B2COTPsSMSLoginOrCreateResponse extends BaseResponse { - user_id: string; - phone_id: string; - user_created: boolean; -} - -export interface B2COTPsWhatsAppSendRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} - -export interface B2COTPsWhatsAppSendResponse extends BaseResponse { - user_id: string; - phone_id: string; -} - -export interface B2COTPsWhatsAppLoginOrCreateRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - create_user_as_pending?: boolean; - locale?: string; -} - -export interface B2COTPsWhatsAppLoginOrCreateResponse extends BaseResponse { - user_id: string; - phone_id: string; - user_created: boolean; -} - -export interface B2COTPsAuthenticateRequest { +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Attributes } from "./attribute"; +import { Email } from "./otps_email"; +import { fetchConfig } from "../shared"; +import { Options } from "./magic_links"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { Sms } from "./otps_sms"; +import { User } from "./users"; +import { Whatsapp } from "./otps_whatsapp"; + +// Request type for `otps.authenticate`. +export interface OTPsAuthenticateRequest { + // The `email_id` or `phone_id` involved in the given authentication. method_id: string; + // The code to authenticate. code: string; + // Provided attributes help with fraud detection. attributes?: Attributes; - options?: { - ip_match_required?: boolean; - user_agent_match_required?: boolean; - }; + // Specify optional security settings. + options?: Options; + // The `session_token` associated with a User's existing Session. session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2COTPsAuthenticateResponse extends BaseResponse { +// Response type for `otps.authenticate`. +export interface OTPsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. user_id: string; - user: User; + // The `email_id` or `phone_id` involved in the given authentication. method_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * Indicates if all other of the User's Sessions need to be reset. You should check this field if you + * aren't using Stytch's Session product. If you are using Stytch's Session product, we revoke the User's + * other sessions for you. + */ reset_sessions: boolean; -} - -class Email { - base_path: string; - delivery = "email"; - - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig, base_path: string) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - private endpoint(path: string): string { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data: B2COTPsEmailSendRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data, - }); - } - - loginOrCreate( - data: B2COTPsEmailLoginOrCreateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data, - }); - } -} - -class SMS { - base_path: string; - delivery = "sms"; - - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig, base_path: string) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - private endpoint(path: string): string { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data: B2COTPsSMSSendRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data, - }); - } - - loginOrCreate( - data: B2COTPsSMSLoginOrCreateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data, - }); - } -} - -class WhatsApp { - base_path: string; - delivery = "whatsapp"; - - private fetchConfig: fetchConfig; - - constructor(fetchConfig: fetchConfig, base_path: string) { - this.fetchConfig = fetchConfig; - this.base_path = base_path; - } - - private endpoint(path: string): string { - return `${this.base_path}/${this.delivery}/${path}`; - } - - send(data: B2COTPsWhatsAppSendRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("send"), - data, - }); - } - - loginOrCreate( - data: B2COTPsWhatsAppLoginOrCreateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("login_or_create"), - data, - }); - } + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; } export class OTPs { - base_path = "otps"; - email: Email; - sms: SMS; - whatsapp: WhatsApp; - private fetchConfig: fetchConfig; + sms: Sms; + whatsapp: Whatsapp; + email: Email; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; - this.email = new Email(fetchConfig, this.base_path); - this.sms = new SMS(fetchConfig, this.base_path); - this.whatsapp = new WhatsApp(fetchConfig, this.base_path); - } - - private endpoint(path: string): string { - return `${this.base_path}/${path}`; + this.sms = new Sms(this.fetchConfig); + this.whatsapp = new Whatsapp(this.fetchConfig); + this.email = new Email(this.fetchConfig); } + /** + * Authenticate a User given a `method_id` (the associated `email_id` or `phone_id`) and a `code`. This + * endpoint verifies that the code is valid, hasn't expired or been previously used, and any optional + * security settings such as IP match or user agent match are satisfied. A given `method_id` may only have + * a single active OTP code at any given time, if a User requests another OTP code before the first one has + * expired, the first one will be invalidated. + * @param data {@link OTPsAuthenticateRequest} + * @returns {@link OTPsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( - data: B2COTPsAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { + data: OTPsAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/otps/authenticate`, data, }); } diff --git a/lib/b2c/otps_email.ts b/lib/b2c/otps_email.ts new file mode 100644 index 00000000..dfd21af8 --- /dev/null +++ b/lib/b2c/otps_email.ts @@ -0,0 +1,206 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; + +// Request type for `otps.email.loginOrCreate`. +export interface OTPsEmailLoginOrCreateRequest { + /** + * The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test + * this endpoint, see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + email: string; + /** + * 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; +} + +// Response type for `otps.email.loginOrCreate`. +export interface OTPsEmailLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID of a specific email address. + email_id: string; + // In `login_or_create` endpoints, this field indicates whether or not a User was just created. + user_created: boolean; + /** + * 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; +} + +// Request type for `otps.email.send`. +export interface OTPsEmailSendRequest { + /** + * The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test + * this endpoint, see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + email: string; + /** + * 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + // The unique ID of a specific User. + user_id?: string; + // The `session_token` associated with a User's existing Session. + session_token?: string; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; +} + +// Response type for `otps.email.send`. +export interface OTPsEmailSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID of a specific email address. + email_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; +} + +export class Email { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Send a one-time passcode (OTP) to a User using their email. If you'd like to create a user and send them + * a passcode with one request, use our + * [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email-otp). + * + * ### Add an email to an existing user + * This endpoint also allows you to add a new email to an existing Stytch User. Including a `user_id`, + * `session_token`, or `session_jwt` in the request will add the email to the pre-existing Stytch User upon + * successful authentication. + * + * Adding a new email to an existing Stytch User requires the User to be present and validate the email via + * OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsEmailSendRequest} + * @returns {@link OTPsEmailSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: OTPsEmailSendRequest): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/otps/email/send`, + data, + }); + } + + /** + * Send a one-time passcode (OTP) to a User using their email. If the email is not associated with a User + * already, a User will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsEmailLoginOrCreateRequest} + * @returns {@link OTPsEmailLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate( + data: OTPsEmailLoginOrCreateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/otps/email/login_or_create`, + data, + }); + } +} diff --git a/lib/b2c/otps_sms.ts b/lib/b2c/otps_sms.ts new file mode 100644 index 00000000..e18dcc45 --- /dev/null +++ b/lib/b2c/otps_sms.ts @@ -0,0 +1,188 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; + +// Request type for `otps.sms.loginOrCreate`. +export interface OTPsSmsLoginOrCreateRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `otps.sms.loginOrCreate`. +export interface OTPsSmsLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID for the phone number. + phone_id: string; + // In `login_or_create` endpoints, this field indicates whether or not a User was just created. + user_created: boolean; + /** + * 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; +} + +// Request type for `otps.sms.send`. +export interface OTPsSmsSendRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + // The unique ID of a specific User. + user_id?: string; + // The `session_token` associated with a User's existing Session. + session_token?: string; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; +} + +// Response type for `otps.sms.send`. +export interface OTPsSmsSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID for the phone number. + phone_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; +} + +export class Sms { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Send a one-time passcode (OTP) to a user's phone number. If you'd like to create a user and send them a + * passcode with one request, use our + * [log in or create](https://stytch.com/docs/api/log-in-or-create-user-by-sms) endpoint. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * ### Add a phone number to an existing user + * + * This endpoint also allows you to add a new phone number to an existing Stytch User. Including a + * `user_id`, `session_token`, or `session_jwt` in the request will add the phone number to the + * pre-existing Stytch User upon successful authentication. + * + * Adding a new phone number to an existing Stytch User requires the user to be present and validate the + * phone number via OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsSmsSendRequest} + * @returns {@link OTPsSmsSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: OTPsSmsSendRequest): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/otps/sms/send`, + data, + }); + } + + /** + * Send a one-time passcode (OTP) to a User using their phone number. If the phone number is not associated + * with a user already, a user will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsSmsLoginOrCreateRequest} + * @returns {@link OTPsSmsLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate( + data: OTPsSmsLoginOrCreateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/otps/sms/login_or_create`, + data, + }); + } +} diff --git a/lib/b2c/otps_whatsapp.ts b/lib/b2c/otps_whatsapp.ts new file mode 100644 index 00000000..5c270131 --- /dev/null +++ b/lib/b2c/otps_whatsapp.ts @@ -0,0 +1,188 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; + +// Request type for `otps.whatsapp.loginOrCreate`. +export interface OTPsWhatsappLoginOrCreateRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} + +// Response type for `otps.whatsapp.loginOrCreate`. +export interface OTPsWhatsappLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID for the phone number. + phone_id: string; + // In `login_or_create` endpoints, this field indicates whether or not a User was just created. + user_created: boolean; + /** + * 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; +} + +// Request type for `otps.whatsapp.send`. +export interface OTPsWhatsappSendRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + // The unique ID of a specific User. + user_id?: string; + // The `session_token` associated with a User's existing Session. + session_token?: string; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; +} + +// Response type for `otps.whatsapp.send`. +export interface OTPsWhatsappSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID for the phone number. + phone_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; +} + +export class Whatsapp { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Send a one-time passcode (OTP) to a User's WhatsApp. If you'd like to create a user and send them a + * passcode with one request, use our + * [log in or create](https://stytch.com/docs/api/whatsapp-login-or-create) endpoint. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * ### Add a phone number to an existing user + * + * This endpoint also allows you to add a new phone number to an existing Stytch User. Including a + * `user_id`, `session_token`, or `session_jwt` in the request will add the phone number to the + * pre-existing Stytch User upon successful authentication. + * + * Adding a new phone number to an existing Stytch User requires the user to be present and validate the + * phone number via OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsWhatsappSendRequest} + * @returns {@link OTPsWhatsappSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: OTPsWhatsappSendRequest): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/otps/whatsapp/send`, + data, + }); + } + + /** + * Send a one-time passcode (OTP) to a User's WhatsApp using their phone number. If the phone number is not + * associated with a User already, a User will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsWhatsappLoginOrCreateRequest} + * @returns {@link OTPsWhatsappLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate( + data: OTPsWhatsappLoginOrCreateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/otps/whatsapp/login_or_create`, + data, + }); + } +} diff --git a/lib/b2c/passwords.ts b/lib/b2c/passwords.ts index 26be0d5d..c2f591fa 100644 --- a/lib/b2c/passwords.ts +++ b/lib/b2c/passwords.ts @@ -1,251 +1,518 @@ -import { Attributes, Name, Session, User } from "./shared_b2c"; -import { request, BaseResponse, fetchConfig } from "../shared"; -import { UserMetadata } from "./users"; -import * as shared from "../shared/passwords"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export interface B2CPasswordsCreateRequest { - email: string; - password: string; - name?: Name; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; +import { Email } from "./passwords_email"; +import { ExistingPassword } from "./passwords_existing_password"; +import { fetchConfig } from "../shared"; +import { Name, User } from "./users"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { Sessions } from "./passwords_session"; + +export interface Argon2Config { + // The salt value. + salt: string; + // The iteration amount. + iteration_amount: number; + // The memory in kibibytes. + memory: number; + // The thread value, also known as the parallelism factor. + threads: number; + // The key length, also known as the hash length. + key_length: number; } -export interface B2CPasswordsCreateResponse extends BaseResponse { - user_id: string; - user: User; - email_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; +export interface Feedback { + /** + * For `zxcvbn` validation, contains an end user consumable warning if the password is valid but not strong + * enough. + */ + warning: string; + /** + * For `zxcvbn` validation, contains end user consumable suggestions on how to improve the strength of the + * password. + */ + suggestions: 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?: LUDSRequirements; } -export interface B2CPasswordsAuthenticateRequest { - email: string; - password: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any +export interface LUDSRequirements { + // For LUDS validation, whether the password contains at least one lowercase letter. + has_lower_case: boolean; + // For LUDS validation, whether the password contains at least one uppercase letter. + has_upper_case: boolean; + // For LUDS validation, whether the password contains at least one digit. + has_digit: boolean; + /** + * For LUDS validation, whether the password contains at least one symbol. Any UTF8 character outside of + * a-z or A-Z may count as a valid symbol. + */ + has_symbol: boolean; + /** + * For LUDS validation, the number of complexity requirements that are missing from the password. Check the + * complexity fields to see which requirements are missing. + */ + missing_complexity: number; + /** + * For LUDS validation, this is the required length of the password that you've set minus the length of the + * password being checked. The user will need to add this many characters to the password to make it valid. + */ + missing_characters: number; } -export interface B2CPasswordsAuthenticateResponse extends BaseResponse { - user_id: string; - user: User; - session_token?: string; - session_jwt?: string; - session?: Session; +export interface MD5Config { + // The salt that should be prepended to the migrated password. + prepend_salt: string; + // The salt that should be appended to the migrated password. + append_salt: string; } -export interface B2CPasswordsResetByEmailStartRequest { - email: string; - login_redirect_url?: string; - reset_password_redirect_url?: string; - reset_password_expiration_minutes?: number; - reset_password_template_id?: string; - attributes?: Attributes; - code_challenge?: string; - locale?: string; +export interface PBKDF2Config { + // The salt value, which should be in a base64 encoded string form. + salt: string; + // The iteration amount. + iteration_amount: number; + // The key length, also known as the hash length. + key_length: number; } -export interface B2CPasswordsResetByEmailStartResponse extends BaseResponse { - user_id: string; - email_id: string; +export interface SHA1Config { + // The salt that should be prepended to the migrated password. + prepend_salt: string; + // The salt that should be appended to the migrated password. + append_salt: string; +} + +export interface ScryptConfig { + // The salt value, which should be in a base64 encoded string form. + salt: string; + /** + * The N value, also known as the iterations count. It must be a power of two greater than 1 and less than + * 262,145. + * If your applicaiton's N parameter is larger than 262,144, please reach out to + * [support@stytch.com](mailto:support@stytch.com) + */ + n_parameter: number; + // The r parameter, also known as the block size. + r_parameter: number; + // The p parameter, also known as the parallelism factor. + p_parameter: number; + // The key length, also known as the hash length. + key_length: number; } -export interface B2CPasswordsResetByEmailRequest { - options?: { - ip_match_required?: boolean; - user_agent_match_required?: boolean; - }; - attributes?: Attributes; +// Request type for `passwords.authenticate`. +export interface PasswordsAuthenticateRequest { + // The email address of the end user. + email: string; + // The password of the user + password: string; + // The `session_token` associated with a User's existing Session. session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any - code_verifier?: string; } -export interface B2CPasswordsResetByEmailResponse extends BaseResponse { +// Response type for `passwords.authenticate`. +export interface PasswordsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. user_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - session_token?: string; - session_jwt?: 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } -export interface B2CPasswordsResetByExistingPasswordRequest { +// Request type for `passwords.create`. +export interface PasswordsCreateRequest { + // The email address of the end user. email: string; - existing_password: string; - new_password: string; - session_token?: string; - session_jwt?: string; + // The password of the user + password: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // The name of the user. Each field in the name object is optional. + name?: Name; } -export interface B2CPasswordsResetByExistingPasswordResponse - extends BaseResponse { +// Response type for `passwords.create`. +export interface PasswordsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. user_id: string; + // The unique ID of a specific email address. + email_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - session_token?: string; - session_jwt?: 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } -export interface B2CPasswordsResetBySessionRequest { - password: string; - session_token?: string; - session_jwt?: string; +// Request type for `passwords.migrate`. +export interface PasswordsMigrateRequest { + // The email address of the end user. + email: string; + // The password hash. For a Scrypt or PBKDF2 hash, the hash needs to be a base64 encoded string. + hash: string; + /** + * The password hash used. Currently `bcrypt`, `scrypt`, `argon_2i`, `argon_2id`, `md_5`, `sha_1`, and + * `pbkdf_2` are supported. + */ + hash_type: + | "bcrypt" + | "md_5" + | "argon_2i" + | "argon_2id" + | "sha_1" + | "scrypt" + | "phpass" + | "pbkdf_2" + | string; + // Optional parameters for MD-5 hash types. + md_5_config?: MD5Config; + // Required parameters if the argon2 hex form, as opposed to the encoded form, is supplied. + argon_2_config?: Argon2Config; + // Optional parameters for SHA-1 hash types. + sha_1_config?: SHA1Config; + /** + * Required parameters if the scrypt is not provided in a + * [PHC encoded form](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#phc-string-format). + */ + scrypt_config?: ScryptConfig; + // Required additional parameters for PBKDF2 hash keys. + pbkdf_2_config?: PBKDF2Config; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // The name of the user. Each field in the name object is optional. + name?: Name; } -export interface B2CPasswordsResetBySessionResponse extends BaseResponse { +// Response type for `passwords.migrate`. +export interface PasswordsMigrateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. user_id: string; + // The unique ID of a specific email address. + email_id: string; + // In `login_or_create` endpoints, this field indicates whether or not a User was just created. + user_created: boolean; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - session: Session; + /** + * 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; } -export interface B2CPasswordsStrengthCheckRequest { - email?: string; +// Request type for `passwords.strengthCheck`. +export interface PasswordsStrengthCheckRequest { + // The password of the user password: string; + // The email address of the end user. + email?: string; } -export interface B2CPasswordsStrengthCheckResponse extends BaseResponse { +// Response type for `passwords.strengthCheck`. +export interface PasswordsStrengthCheckResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * Returns `true` if the password passes our password validation. We offer two validation options, + * [zxcvbn](https://stytch.com/docs/passwords#strength-requirements) is the default option which offers a + * high level of sophistication. We also offer + * [LUDS](https://stytch.com/docs/passwords#strength-requirements). If an email address is included in the + * call we also require that the password hasn't been compromised using built-in breach detection powered + * by [HaveIBeenPwned](https://haveibeenpwned.com/). + */ valid_password: boolean; + /** + * The score of the password determined by [zxcvbn](https://github.com/dropbox/zxcvbn). Values will be + * between 1 and 4, a 3 or greater is required to pass validation. + */ score: number; + /** + * Returns `true` if the password has been breached. Powered by + * [HaveIBeenPwned](https://haveibeenpwned.com/). + */ breached_password: boolean; + // The strength policy type enforced, either `zxcvbn` or `luds`. strength_policy: string; + /** + * 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](mailto:support@stytch.com?subject=Password%20strength%20configuration). If this + * value is `false` then `breached_password` will always be `false` as well. + */ breach_detection_on_create: boolean; - feedback: { - suggestions: string[]; - warning: string; - luds_requirements: { - has_lower_case: boolean; - has_upper_case: boolean; - has_digit: boolean; - has_symbol: boolean; - missing_complexity: number; - missing_characters: number; - }; - }; -} - -interface MigrateRequestBase { - email: string; - hash: string; - name?: Name; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; -} - -export type B2CPasswordsMigrateRequest = - | (shared.MD5MigrateRequest & MigrateRequestBase) - | (shared.BcryptMigrateRequest & MigrateRequestBase) - | (shared.Argon2IMigrateRequest & MigrateRequestBase) - | (shared.Argon2IDMigrateRequest & MigrateRequestBase) - | (shared.SHA1MigrateRequest & MigrateRequestBase) - | (shared.ScryptMigrateRequest & MigrateRequestBase) - | (shared.PHPassMigrateRequest & MigrateRequestBase) - | (shared.PBKDF2MigrateRequest & MigrateRequestBase); - -export interface B2CPasswordsMigrateResponse extends BaseResponse { - user_id: string; - email_id: string; - user_created: boolean; + /** + * 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; + // Feedback for how to improve the password's strength [HaveIBeenPwned](https://haveibeenpwned.com/). + feedback?: Feedback; } export class Passwords { - base_path = "passwords"; - private fetchConfig: fetchConfig; + email: Email; + existingPassword: ExistingPassword; + sessions: Sessions; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; + this.email = new Email(this.fetchConfig); + this.existingPassword = new ExistingPassword(this.fetchConfig); + this.sessions = new Sessions(this.fetchConfig); } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - create(data: B2CPasswordsCreateRequest): Promise { - return request(this.fetchConfig, { + /** + * Create a new user with a password and an authenticated session for the user if requested. 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 password strength endpoint. + * @param data {@link PasswordsCreateRequest} + * @returns {@link PasswordsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: PasswordsCreateRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.base_path, - data: data, + url: `/v1/passwords`, + data, }); } + /** + * Authenticate a user with their email address and password. This endpoint verifies that the user has a + * password currently set, and that the entered password is correct. There are two instances where the + * endpoint will return a `reset_password` error even if they enter their previous password: + * + * **One:** The user’s credentials appeared in the HaveIBeenPwned dataset. We force a password reset to + * ensure that the user is the legitimate owner of the email address, and not a malicious actor abusing the + * compromised credentials. + * + * **Two:** A user that has previously authenticated with email/password uses a passwordless authentication + * method tied to the same email address (e.g. Magic Links, Google OAuth) for the first time. Any + * subsequent email/password authentication attempt will result in this error. We force a password reset in + * this instance in order to safely deduplicate the account by email address, without introducing the risk + * of a pre-hijack account takeover attack. + * + * Imagine a bad actor creates many accounts using passwords and the known email addresses of their + * victims. If a victim comes to the site and logs in for the first time with an email-based passwordless + * authentication method then both the victim and the bad actor have credentials to access to the same + * account. To prevent this, any further email/password login attempts first require a password reset which + * can only be accomplished by someone with access to the underlying email address. + * @param data {@link PasswordsAuthenticateRequest} + * @returns {@link PasswordsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( - data?: B2CPasswordsAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("authenticate"), - data: data, - }); - } - - resetByEmailStart( - data: B2CPasswordsResetByEmailStartRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("email/reset/start"), - data: data, - }); - } - - resetByEmail( - token: string, - password: string, - data?: B2CPasswordsResetByEmailRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("email/reset"), - data: { token, password, ...data }, - }); - } - - resetByExistingPassword( - data: B2CPasswordsResetByExistingPasswordRequest - ): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("existing_password/reset"), - data: data, - }); - } - - resetBySession( - data: B2CPasswordsResetBySessionRequest - ): Promise { - return request(this.fetchConfig, { + data: PasswordsAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("session/reset"), - data: data, + url: `/v1/passwords/authenticate`, + data, }); } + /** + * This API 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. + * + * This endpoint adapts to your Project's password strength configuration. If you're using + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your passwords are + * considered valid if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are considered valid if + * they meet the requirements that you've set with Stytch. You may update your password strength + * configuration in the [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * + * ### Password feedback + * + * The `feedback` object contains relevant fields for you to relay feedback to users that failed to create + * a strong enough password. + * + * If you're using zxcvbn, the `feedback` object will contain `warning` and `suggestions` for any password + * that does not meet the zxcvbn strength requirements. You can return these strings directly to the user + * to help them craft a strong password. + * + * If you're using LUDS, the `feedback` object will contain an object named `luds_requirements` which + * contain a collection of fields that the user failed or passed. You'll want to prompt the user to create + * a password that meets all of the requirements that they failed. + * @param data {@link PasswordsStrengthCheckRequest} + * @returns {@link PasswordsStrengthCheckResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ strengthCheck( - data: B2CPasswordsStrengthCheckRequest - ): Promise { - return request(this.fetchConfig, { + data: PasswordsStrengthCheckRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("strength_check"), - data: data, + url: `/v1/passwords/strength_check`, + data, }); } - migrate( - data: B2CPasswordsMigrateRequest - ): Promise { - return request(this.fetchConfig, { + /** + * Adds an existing password to a User's email that doesn't have a password yet. We support migrating users + * from passwords stored with `bcrypt`, `scrypt`, `argon2`, `MD-5`, `SHA-1`, or `PBKDF2`. This endpoint has + * a rate limit of 100 requests per second. + * @param data {@link PasswordsMigrateRequest} + * @returns {@link PasswordsMigrateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + migrate(data: PasswordsMigrateRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("migrate"), - data: data, + url: `/v1/passwords/migrate`, + data, }); } } diff --git a/lib/b2c/passwords_email.ts b/lib/b2c/passwords_email.ts new file mode 100644 index 00000000..ad5bbf62 --- /dev/null +++ b/lib/b2c/passwords_email.ts @@ -0,0 +1,212 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { Options } from "./magic_links"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; + +// Request type for `passwords.email.reset`. +export interface PasswordsEmailResetRequest { + // The token to authenticate. + token: string; + // The password of the user + password: string; + // The `session_token` associated with a User's existing Session. + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + // A base64url encoded one time secret used to validate that the request starts and ends on the same device. + code_verifier?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + // Provided attributes help with fraud detection. + attributes?: Attributes; + // Specify optional security settings. + options?: Options; +} + +// Response type for `passwords.email.reset`. +export interface PasswordsEmailResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; +} + +// Request type for `passwords.email.resetStart`. +export interface PasswordsEmailResetStartRequest { + // The email of the User that requested the password reset. + email: string; + /** + * 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; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: string; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * The URL Stytch redirects to after the OAuth flow is completed for a user that already exists. This URL + * should be a route in your application which will run `oauth.authenticate` (see below) and finish the + * login. + * + * The URL must be configured as a Login URL in the [Redirect URL page](/dashboard/redirect-urls). If the + * field is not specified, the default Login URL will be used. + */ + login_redirect_url?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for password reset 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 Passwords + * - Password reset. + */ + reset_password_template_id?: string; +} + +// Response type for `passwords.email.resetStart`. +export interface PasswordsEmailResetStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID of a specific email address. + email_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; +} + +export class Email { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * 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. + * @param data {@link PasswordsEmailResetStartRequest} + * @returns {@link PasswordsEmailResetStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + resetStart( + data: PasswordsEmailResetStartRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/email/reset/start`, + data, + }); + } + + /** + * Reset the user’s password and authenticate them. This endpoint checks that the magic link `token` is + * valid, hasn’t expired, or already been used – and can optionally require additional security settings, + * such as the IP address and user agent matching the initial reset request. + * + * The provided password needs to meet our password strength requirements, which can be checked in advance + * with the password strength endpoint. If the token and password are accepted, the password is securely + * stored for future authentication and the user is authenticated. + * @param data {@link PasswordsEmailResetRequest} + * @returns {@link PasswordsEmailResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset( + data: PasswordsEmailResetRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/email/reset`, + data, + }); + } +} diff --git a/lib/b2c/passwords_existing_password.ts b/lib/b2c/passwords_existing_password.ts new file mode 100644 index 00000000..9b3efbc4 --- /dev/null +++ b/lib/b2c/passwords_existing_password.ts @@ -0,0 +1,108 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; + +// Request type for `passwords.existingPassword.reset`. +export interface PasswordsExistingPasswordResetRequest { + // The email address of the end user. + email: string; + // The user's existing password. + existing_password: string; + // The new password for the user. + new_password: string; + // The `session_token` associated with a User's existing Session. + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +// Response type for `passwords.existingPassword.reset`. +export interface PasswordsExistingPasswordResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; +} + +export class ExistingPassword { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Reset the User’s password using their existing password. + * @param data {@link PasswordsExistingPasswordResetRequest} + * @returns {@link PasswordsExistingPasswordResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset( + data: PasswordsExistingPasswordResetRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/existing_password/reset`, + data, + }); + } +} diff --git a/lib/b2c/passwords_session.ts b/lib/b2c/passwords_session.ts new file mode 100644 index 00000000..07eb6107 --- /dev/null +++ b/lib/b2c/passwords_session.ts @@ -0,0 +1,78 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; + +// Request type for `passwords.sessions.reset`. +export interface PasswordsSessionResetRequest { + // The password of the user + password: string; + // The `session_token` associated with a User's existing Session. + session_token?: string; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; +} + +// Response type for `passwords.sessions.reset`. +export interface PasswordsSessionResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; +} + +export class Sessions { + private fetchConfig: fetchConfig; + + constructor(fetchConfig: fetchConfig) { + this.fetchConfig = fetchConfig; + } + + /** + * Reset the user’s password using their existing session. The endpoint will error if the session does not + * have a password, email magic link, or email OTP authentication factor that has been issued within the + * last 5 minutes. This endpoint requires either a `session_jwt` or `session_token` be included in the + * request. + * @param data {@link PasswordsSessionResetRequest} + * @returns {@link PasswordsSessionResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset( + data: PasswordsSessionResetRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/passwords/session/reset`, + data, + }); + } +} diff --git a/lib/b2c/sessions.ts b/lib/b2c/sessions.ts index 2d6861d4..e5f25300 100644 --- a/lib/b2c/sessions.ts +++ b/lib/b2c/sessions.ts @@ -1,71 +1,467 @@ +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! + import * as jose from "jose"; -import { - Attributes, - Session, - B2CAuthenticationFactor, - User, -} from "./shared_b2c"; - -import { request, fetchConfig, BaseResponse } from "../shared"; import { authenticateJwtLocal, JwtConfig } from "../shared/sessions"; +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { User } from "./users"; -export interface B2CSessionsGetRequest { - user_id: string; +export interface AmazonOAuthFactor { + id: string; + email_id: string; + provider_subject: string; } -export interface B2CSessionsGetResponse extends BaseResponse { - sessions: Session[]; +export interface AppleOAuthFactor { + id: string; + email_id: string; + provider_subject: string; } -export interface B2CSessionsJwksResponse extends BaseResponse { - keys: JWK[]; +export interface AuthenticationFactor { + type: + | "magic_link" + | "otp" + | "oauth" + | "webauthn" + | "totp" + | "crypto" + | "password" + | "signature_challenge" + | "sso" + | string; + delivery_method: + | "email" + | "sms" + | "whatsapp" + | "embedded" + | "oauth_google" + | "oauth_microsoft" + | "oauth_apple" + | "webauthn_registration" + | "authenticator_app" + | "oauth_github" + | "recovery_code" + | "oauth_facebook" + | "crypto_wallet" + | "oauth_amazon" + | "oauth_bitbucket" + | "oauth_coinbase" + | "oauth_discord" + | "oauth_figma" + | "oauth_gitlab" + | "oauth_instagram" + | "oauth_linkedin" + | "oauth_shopify" + | "oauth_slack" + | "oauth_snapchat" + | "oauth_spotify" + | "oauth_steam" + | "oauth_tiktok" + | "oauth_twitch" + | "oauth_twitter" + | "knowledge" + | "biometric" + | "sso_saml" + | "sso_oidc" + | "oauth_salesforce" + | "oauth_yahoo" + | string; + last_authenticated_at?: string; + created_at?: string; + updated_at?: string; + email_factor?: EmailFactor; + phone_number_factor?: PhoneNumberFactor; + google_oauth_factor?: GoogleOAuthFactor; + microsoft_oauth_factor?: MicrosoftOAuthFactor; + apple_oauth_factor?: AppleOAuthFactor; + webauthn_factor?: WebAuthnFactor; + authenticator_app_factor?: AuthenticatorAppFactor; + github_oauth_factor?: GithubOAuthFactor; + recovery_code_factor?: RecoveryCodeFactor; + facebook_oauth_factor?: FacebookOAuthFactor; + crypto_wallet_factor?: CryptoWalletFactor; + amazon_oauth_factor?: AmazonOAuthFactor; + bitbucket_oauth_factor?: BitbucketOAuthFactor; + coinbase_oauth_factor?: CoinbaseOAuthFactor; + discord_oauth_factor?: DiscordOAuthFactor; + figma_oauth_factor?: FigmaOAuthFactor; + git_lab_oauth_factor?: GitLabOAuthFactor; + instagram_oauth_factor?: InstagramOAuthFactor; + linked_in_oauth_factor?: LinkedInOAuthFactor; + shopify_oauth_factor?: ShopifyOAuthFactor; + slack_oauth_factor?: SlackOAuthFactor; + snapchat_oauth_factor?: SnapchatOAuthFactor; + spotify_oauth_factor?: SpotifyOAuthFactor; + steam_oauth_factor?: SteamOAuthFactor; + tik_tok_oauth_factor?: TikTokOAuthFactor; + twitch_oauth_factor?: TwitchOAuthFactor; + twitter_oauth_factor?: TwitterOAuthFactor; + embeddable_magic_link_factor?: EmbeddableMagicLinkFactor; + biometric_factor?: BiometricFactor; + saml_sso_factor?: SAMLSSOFactor; + oidc_sso_factor?: OIDCSSOFactor; + salesforce_oauth_factor?: SalesforceOAuthFactor; + yahoo_oauth_factor?: YahooOAuthFactor; +} + +export interface AuthenticatorAppFactor { + totp_id: string; +} + +export interface BiometricFactor { + biometric_registration_id: string; +} + +export interface BitbucketOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface CoinbaseOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface CryptoWalletFactor { + crypto_wallet_id: string; + crypto_wallet_address: string; + crypto_wallet_type: string; +} + +export interface DiscordOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface EmailFactor { + email_id: string; + email_address: string; +} + +export interface EmbeddableMagicLinkFactor { + embedded_id: string; +} + +export interface FacebookOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface FigmaOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface GitLabOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface GithubOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface GoogleOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface InstagramOAuthFactor { + id: string; + email_id: string; + provider_subject: string; } export interface JWK { - alg: string; - key_ops: string[]; - kid: string; kty: string; use: string; + key_ops: string[]; + alg: string; + kid: string; x5c: string[]; - "x5t#S256": string; - + x5tS256: string; n: string; e: string; } -export interface B2CSessionsAuthenticateRequest { - session_duration_minutes?: number; +export interface LinkedInOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface MicrosoftOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface OIDCSSOFactor { + id: string; + provider_id: string; + external_id: string; +} + +export interface PhoneNumberFactor { + phone_id: string; + phone_number: string; +} + +export interface RecoveryCodeFactor { + totp_recovery_code_id: string; +} + +export interface SAMLSSOFactor { + id: string; + provider_id: string; + external_id: string; +} + +export interface SalesforceOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface Session { + // A unique identifier for a specific Session. + session_id: string; + // The unique ID of the affected User. + user_id: string; + // An array of different authentication factors that have initiated a Session. + authentication_factors: AuthenticationFactor[]; + /** + * The timestamp when the Session was created. Values conform to the RFC 3339 standard and are expressed in + * UTC, e.g. `2021-12-29T12:33:09Z`. + */ + started_at?: string; + /** + * The timestamp when the Session was last 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 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; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * The custom claims map for a Session. Claims can be added to a session during a Sessions authenticate + * call. + */ + custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +export interface ShopifyOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface SlackOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface SnapchatOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface SpotifyOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface SteamOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface TikTokOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface TwitchOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface TwitterOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +export interface WebAuthnFactor { + webauthn_registration_id: string; + domain: string; + user_agent: string; +} + +export interface YahooOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} + +// Request type for `sessions.authenticate`. +export interface SessionsAuthenticateRequest { + // The session token to authenticate. session_token?: string; + /** + * Set the session lifetime to be this many minutes from now; minimum of 5 and a maximum of 527040 minutes + * (366 days). Note that a successful authentication will continue to extend the session this many minutes. + */ + session_duration_minutes?: number; + /** + * The JWT to authenticate. You may provide a JWT that has expired according to its `exp` claim and needs + * to be refreshed. If the signature is valid and the underlying session is still active then Stytch will + * return a new JWT. + */ session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2CSessionsAuthenticateResponse extends BaseResponse { +// Response type for `sessions.authenticate`. +export interface SessionsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session: Session; - user: User; + // A secret token for a given Stytch Session. session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `sessions.getJWKS`. +export interface SessionsGetJWKSRequest { + // The `project_id` to get the JWKS for. + project_id: string; +} + +// Response type for `sessions.getJWKS`. +export interface SessionsGetJWKSResponse { + // The JWK + keys: JWK[]; + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; } -export interface B2CSessionsRevokeRequest { +// Request type for `sessions.get`. +export interface SessionsGetRequest { + // The `user_id` to get active Sessions for. + user_id: string; +} + +// Response type for `sessions.get`. +export interface SessionsGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // An array of Session objects. + sessions: Session[]; + /** + * 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; +} + +// Request type for `sessions.revoke`. +export interface SessionsRevokeRequest { + // The `session_id` to revoke. session_id?: string; + // The session token to revoke. session_token?: string; + // A JWT for the session to revoke. session_jwt?: string; } -export type B2CSessionsRevokeResponse = BaseResponse; +// Response type for `sessions.revoke`. +export interface SessionsRevokeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} export class Sessions { - base_path = "sessions"; private fetchConfig: fetchConfig; - private jwksClient: jose.JWTVerifyGetKey; private jwtOptions: jose.JWTVerifyOptions; constructor(fetchConfig: fetchConfig, jwtConfig: JwtConfig) { this.fetchConfig = fetchConfig; - this.jwksClient = jwtConfig.jwks; this.jwtOptions = { audience: jwtConfig.projectID, @@ -74,35 +470,80 @@ export class Sessions { }; } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - get(params: B2CSessionsGetRequest): Promise { - return request(this.fetchConfig, { + /** + * List all active Sessions for a given `user_id`. All timestamps are formatted according to the RFC 3339 + * standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. + * @param data {@link SessionsGetRequest} + * @returns {@link SessionsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: SessionsGetRequest): Promise { + return request(this.fetchConfig, { method: "GET", - url: this.base_path, + url: `/v1/sessions`, params: { ...params }, }); } - jwks(project_id: string): Promise { - return request(this.fetchConfig, { - method: "GET", - url: this.endpoint(`jwks/${project_id}`), + /** + * Authenticate a session token and retrieve associated session data. If `session_duration_minutes` is + * included, update the lifetime of the session to be that many minutes from now. All timestamps are + * formatted according to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. This + * endpoint requires exactly one `session_jwt` or `session_token` as part of the request. If both are + * included you will receive a `too_many_session_arguments` error. + * @param data {@link SessionsAuthenticateRequest} + * @returns {@link SessionsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate( + data: SessionsAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { + method: "POST", + url: `/v1/sessions/authenticate`, + data, }); } - authenticate( - data: B2CSessionsAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { + /** + * Revoke a Session, immediately invalidating all of its session tokens. You can revoke a session in three + * ways: using its ID, or using one of its session tokens, or one of its JWTs. This endpoint requires + * exactly one of those to be included in the request. It will return an error if multiple are present. + * @param data {@link SessionsRevokeRequest} + * @returns {@link SessionsRevokeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + revoke(data: SessionsRevokeRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/sessions/revoke`, data, }); } + /** + * Get the JSON Web Key Set (JWKS) for a Stytch Project. + * @param data {@link SessionsGetJWKSRequest} + * @returns {@link SessionsGetJWKSResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + getJWKS(params: SessionsGetJWKSRequest): Promise { + return request(this.fetchConfig, { + method: "GET", + url: `/v1/sessions/jwks/${params.project_id}`, + params: {}, + }); + } + + // MANUAL(authenticateJwt)(SERVICE_METHOD) /** Parse a JWT and verify the signature, preferring local verification over remote. * * If max_token_age_seconds is set, remote verification will be forced if the JWT was issued at @@ -162,7 +603,7 @@ export class Sessions { session_id: sess.session_id, attributes: sess.attributes as Attributes, authentication_factors: - sess.authentication_factors as B2CAuthenticationFactor[], + sess.authentication_factors as AuthenticationFactor[], user_id: sess.sub, started_at: sess.started_at, last_accessed_at: sess.last_accessed_at, @@ -170,12 +611,5 @@ export class Sessions { custom_claims: sess.custom_claims, }; } - - revoke(data: B2CSessionsRevokeRequest): Promise { - return request(this.fetchConfig, { - method: "POST", - url: this.endpoint("revoke"), - data, - }); - } + // ENDMANUAL(authenticateJwt) } diff --git a/lib/b2c/shared_b2c.ts b/lib/b2c/shared_b2c.ts deleted file mode 100644 index e860fbc4..00000000 --- a/lib/b2c/shared_b2c.ts +++ /dev/null @@ -1,388 +0,0 @@ -import { UserMetadata, UserID } from "./users"; - -export interface Attributes { - ip_address?: string; - user_agent?: string; -} - -export interface Name { - first_name?: string; - middle_name?: string; - last_name?: string; -} - -export interface Email { - email_id: string; - email: string; - verified: boolean; -} - -export interface PhoneNumber { - phone_id: string; - phone_number: string; - verified: boolean; -} - -export interface WebAuthnRegistration { - webauthn_registration_id: string; - domain: string; - user_agent: string; - verified: boolean; - authenticator_type: string; -} - -export interface BiometricRegistration { - biometric_registration_id: string; - verified: boolean; -} - -export interface TOTP { - totp_id: string; - verified: boolean; -} - -export interface Password { - password_id: string; - requires_reset: boolean; -} - -export interface User { - user_id: UserID; - created_at: string; - status: string; - name: Name; - emails: Email[]; - password?: Password; - phone_numbers: PhoneNumber[]; - providers: OAuthProvider[]; - webauthn_registrations: WebAuthnRegistration[]; - biometric_registrations: BiometricRegistration[]; - totps: TOTP[]; - crypto_wallets: CryptoWallet[]; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; -} - -export interface CryptoWallet { - crypto_wallet_id: string; - crypto_wallet_address: string; - crypto_wallet_type: string; - verified: boolean; -} - -export interface OAuthProvider { - oauth_user_registration_id: string; - provider_subject: string; - provider_type: string; - profile_picture_url: string; - locale: string; -} - -export interface EmailFactor { - delivery_method: "email" | "embedded"; - type: string; - last_authenticated_at: string; - email_factor: { - email_id: string; - email_address: string; - }; -} - -export interface PhoneNumberFactor { - delivery_method: "sms" | "whatsapp"; - type: string; - last_authenticated_at: string; - phone_number_factor: { - phone_id: string; - phone_number: string; - }; -} - -export interface GoogleOAuthFactor { - delivery_method: "oauth_google"; - type: string; - last_authenticated_at: string; - google_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface MicrosoftOAuthFactor { - delivery_method: "oauth_microsoft"; - type: string; - last_authenticated_at: string; - microsoft_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface AppleOAuthFactor { - delivery_method: "oauth_apple"; - type: string; - last_authenticated_at: string; - apple_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface GithubOAuthFactor { - delivery_method: "oauth_github"; - type: string; - last_authenticated_at: string; - github_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface GitLabOAuthFactor { - delivery_method: "oauth_gitlab"; - type: string; - last_authenticated_at: string; - gitlab_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface FacebookOAuthFactor { - delivery_method: "oauth_facebook"; - type: string; - last_authenticated_at: string; - facebook_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface DiscordOAuthFactor { - delivery_method: "oauth_discord"; - type: string; - last_authenticated_at: string; - discord_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface SalesforceOAuthFactor { - delivery_method: "oauth_salesforce"; - type: string; - last_authenticated_at: string; - salesforce_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface SlackOAuthFactor { - delivery_method: "oauth_slack"; - type: string; - last_authenticated_at: string; - slack_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface AmazonOAuthFactor { - delivery_method: "oauth_amazon"; - type: string; - last_authenticated_at: string; - amazon_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface BitbucketOAuthFactor { - delivery_method: "oauth_bitbucket"; - type: string; - last_authenticated_at: string; - bitbucket_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface LinkedInOAuthFactor { - delivery_method: "oauth_linkedin"; - type: string; - last_authenticated_at: string; - linkedin_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface CoinbaseOAuthFactor { - delivery_method: "oauth_coinbase"; - type: string; - last_authenticated_at: string; - coinbase_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface TwitchOAuthFactor { - delivery_method: "oauth_twitch"; - type: string; - last_authenticated_at: string; - twitch_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface TwitterOAuthFactor { - delivery_method: "oauth_twitter"; - type: string; - last_authenticated_at: string; - twitter_oauth_factor: { - id: string; - provider_subject: string; - }; -} - -export interface TikTokOAuthFactor { - delivery_method: "oauth_tiktok"; - type: string; - last_authenticated_at: string; - tiktok_oauth_factor: { - id: string; - provider_subject: string; - }; -} - -export interface FigmaOAuthFactor { - delivery_method: "oauth_figma"; - type: string; - last_authenticated_at: string; - figma_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} - -export interface SnapchatOAuthFactor { - delivery_method: "oauth_snapchat"; - type: string; - last_authenticated_at: string; - snapchat_oauth_factor: { - id: string; - provider_subject: string; - }; -} - -export interface WebAuthnFactor { - delivery_method: "webauthn_registration"; - type: string; - last_authenticated_at: string; - webauthn_factor: { - webauthn_registration_id: string; - domain: string; - user_agent: string; - }; -} - -export interface BiometricFactor { - delivery_method: "biometric"; - type: string; - last_authenticated_at: string; - biometric_factor: { - biometric_registration_id: string; - }; -} - -export interface AuthenticatorAppFactor { - delivery_method: "authenticator_app"; - type: string; - last_authenticated_at: string; - authenticator_app_factor: { - totp_id: string; - }; -} - -export interface RecoveryCodeFactor { - delivery_method: "recovery_code"; - type: string; - last_authenticated_at: string; - recovery_code_factor: { - totp_recovery_code_id: string; - }; -} - -export 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; - }; -} - -export interface PasswordFactor { - delivery_method: "knowledge"; - type: string; - last_authenticated_at: string; -} - -export type B2CAuthenticationFactor = - | EmailFactor - | PhoneNumberFactor - | GoogleOAuthFactor - | MicrosoftOAuthFactor - | AppleOAuthFactor - | GithubOAuthFactor - | GitLabOAuthFactor - | FacebookOAuthFactor - | DiscordOAuthFactor - | SalesforceOAuthFactor - | SlackOAuthFactor - | AmazonOAuthFactor - | BitbucketOAuthFactor - | LinkedInOAuthFactor - | CoinbaseOAuthFactor - | TwitchOAuthFactor - | TwitterOAuthFactor - | TikTokOAuthFactor - | SnapchatOAuthFactor - | FigmaOAuthFactor - | WebAuthnFactor - | BiometricFactor - | AuthenticatorAppFactor - | RecoveryCodeFactor - | CryptoWalletFactor - | PasswordFactor; - -export interface Session { - session_id: string; - user_id: string; - started_at: string; - last_accessed_at: string; - expires_at: string; - attributes: Attributes; - authentication_factors: B2CAuthenticationFactor[]; - custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any -} diff --git a/lib/b2c/totps.ts b/lib/b2c/totps.ts index 7ef8fa9e..74f65745 100644 --- a/lib/b2c/totps.ts +++ b/lib/b2c/totps.ts @@ -1,116 +1,309 @@ -import { Session, User } from "./shared_b2c"; -import { request, BaseResponse, fetchConfig } from "../shared"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export interface TOTP { - totp_id: string; - verified: boolean; - recovery_codes: string[]; -} - -export interface B2CTOTPsCreateRequest { - user_id: string; - expiration_minutes?: number; -} +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; -export interface B2CTOTPsCreateResponse extends BaseResponse { +export interface TOTPWithRecoveryCodes { + // The unique ID for a TOTP instance. totp_id: string; - secret: string; - qr_code: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; + // The recovery codes used to authenticate the user without an authenticator app. recovery_codes: string[]; - user: User; - user_id: string; } -export interface B2CTOTPsAuthenticateRequest { +// Request type for `totps.authenticate`. +export interface TOTPsAuthenticateRequest { + // The `user_id` of an active user the TOTP registration should be tied to. user_id: string; + // The TOTP code to authenticate. The TOTP code should consist of 6 digits. totp_code: string; + // The `session_token` associated with a User's existing Session. session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2CTOTPsAuthenticateResponse extends BaseResponse { +// Response type for `totps.authenticate`. +export interface TOTPsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. user_id: string; - user: User; + // A secret token for a given Stytch Session. + session_token: string; + // The unique ID for a TOTP instance. totp_id: string; - session_token?: string; - session_jwt?: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } -export interface B2CTOTPsRecoveryCodesRequest { +// Request type for `totps.create`. +export interface TOTPsCreateRequest { + // The `user_id` of an active user the TOTP registration should be tied to. user_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; } -export interface B2CTOTPsRecoveryCodesResponse extends BaseResponse { +// Response type for `totps.create`. +export interface TOTPsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID for a TOTP instance. + 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[]; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + // The unique ID of the affected User. user_id: string; - totps: TOTP[]; + /** + * 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; } -export interface B2CTOTPsRecoverRequest { +// Request type for `totps.recover`. +export interface TOTPsRecoverRequest { + // The `user_id` of an active user the TOTP registration should be tied to. user_id: string; + // The recovery code to authenticate. recovery_code: string; + // The `session_token` associated with a User's existing Session. session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2CTOTPsRecoverResponse extends BaseResponse { +// Response type for `totps.recover`. +export interface TOTPsRecoverResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID for a TOTP instance. + totp_id: string; + // The unique ID of the affected User. user_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - totp_id: string; - session_token?: string; - session_jwt?: 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } -export class TOTPs { - base_path = "totps"; +// Request type for `totps.recoveryCodes`. +export interface TOTPsRecoveryCodesRequest { + // The `user_id` of an active user the TOTP registration should be tied to. + user_id: string; +} + +// Response type for `totps.recoveryCodes`. +export interface TOTPsRecoveryCodesResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * An array containing a list of all TOTP instances (along with their recovery codes) for a given User in + * the Stytch API. + */ + totps: TOTPWithRecoveryCodes[]; + /** + * 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; +} +export class TOTPs { private fetchConfig: fetchConfig; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - create(data: B2CTOTPsCreateRequest): Promise { - return request(this.fetchConfig, { + /** + * 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. + * @param data {@link TOTPsCreateRequest} + * @returns {@link TOTPsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: TOTPsCreateRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.base_path, + url: `/v1/totps`, data, }); } + /** + * Authenticate a TOTP code entered by a user. + * @param data {@link TOTPsAuthenticateRequest} + * @returns {@link TOTPsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( - data: B2CTOTPsAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { + data: TOTPsAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/totps/authenticate`, data, }); } + /** + * Retrieve the recovery codes for a TOTP instance tied to a User. + * @param data {@link TOTPsRecoveryCodesRequest} + * @returns {@link TOTPsRecoveryCodesResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ recoveryCodes( - data: B2CTOTPsRecoveryCodesRequest - ): Promise { - return request(this.fetchConfig, { + data: TOTPsRecoveryCodesRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("recovery_codes"), + url: `/v1/totps/recovery_codes`, data, }); } - recover(data: B2CTOTPsRecoverRequest): Promise { - return request(this.fetchConfig, { + /** + * Authenticate a recovery code for a TOTP instance. + * @param data {@link TOTPsRecoverRequest} + * @returns {@link TOTPsRecoverResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + recover(data: TOTPsRecoverRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("recover"), + url: `/v1/totps/recover`, data, }); } diff --git a/lib/b2c/users.ts b/lib/b2c/users.ts index cfe7a7c9..20afa886 100644 --- a/lib/b2c/users.ts +++ b/lib/b2c/users.ts @@ -1,43 +1,657 @@ -import { BaseResponse, fetchConfig, request } from "../shared"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -import { - Attributes, - CryptoWallet, - Email, - Name, - PhoneNumber, - User, -} from "./shared_b2c"; +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { request } from "../shared"; -export type UserID = string; -export type UserMetadata = Record; // eslint-disable-line @typescript-eslint/no-explicit-any +export interface BiometricRegistration { + // The unique ID for a biometric registration. + biometric_registration_id: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} + +export interface CryptoWallet { + // The unique ID for a crypto wallet + crypto_wallet_id: string; + // The actual blockchain address of the User's crypto wallet. + crypto_wallet_address: string; + // 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 send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} + +export interface Email { + // The unique ID of a specific email address. + email_id: string; + // The email address. + email: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} + +export interface Name { + // The first name of the user. + first_name?: string; + // The middle name(s) of the user. + middle_name?: string; + // The last name of the user. + last_name?: string; +} + +export interface OAuthProvider { + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Facebook, GitHub + * etc. + */ + provider_type: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the "sub" or + * "Subject field" in OAuth protocols. + */ + provider_subject: 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 unique ID for an OAuth registration. + oauth_user_registration_id: string; +} -export interface B2CUsersCreateRequest { +export interface Password { + // The unique ID of a specific password + password_id: string; + // Indicates whether this password requires a password reset + requires_reset: boolean; +} + +export interface PhoneNumber { + // The unique ID for the phone number. + phone_id: string; + // The phone number. + phone_number: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} + +export interface SearchUsersQuery { + /** + * 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 search + * query. + */ + operands: SearchUsersQueryOperand[]; +} + +export interface TOTP { + // The unique ID for a TOTP instance. + totp_id: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} + +export interface User { + // The unique ID of the affected User. + user_id: string; + // An array of email objects for the User. + emails: Email[]; + // The status of the User. The possible values are `pending` and `active`. + status: string; + // An array of phone number objects linked to the User. + phone_numbers: PhoneNumber[]; + // An array that contains a list of all WebAuthn registrations for a given User in the Stytch API. + webauthn_registrations: WebAuthnRegistration[]; + // An array of OAuth `provider` objects linked to the User. + providers: OAuthProvider[]; + // An array containing a list of all TOTP instances for a given User in the Stytch API. + totps: TOTP[]; + // An array contains a list of all crypto wallets for a given User in the Stytch API. + crypto_wallets: CryptoWallet[]; + // An array that contains a list of all biometric registrations for a given User in the Stytch API. + biometric_registrations: BiometricRegistration[]; + // The name of the User. Each field in the `name` object is optional. + name?: Name; + /** + * 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 password object is returned for users with a password. + password?: Password; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +export interface UsersResultsMetadata { + // The total number of results returned by your search query. + 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; +} + +export interface WebAuthnRegistration { + // The unique ID for the WebAuthn registration. + webauthn_registration_id: string; + // 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. + user_agent: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; + /** + * 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; +} + +// Request type for `users.create`. +export interface UsersCreateRequest { + // The email address of the end user. email?: string; - phone_number?: string; + // The name of the user. Each field in the name object is optional. name?: Name; - create_user_as_pending?: boolean; + // Provided attributes help with fraud detection. attributes?: Attributes; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number?: string; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +// Response type for `users.create`. +export interface UsersCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID of a specific email address. + email_id: string; + // The status of the User. The possible values are `pending` and `active`. + status: string; + // The unique ID for the phone number. + phone_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.deleteBiometricRegistration`. +export interface UsersDeleteBiometricRegistrationRequest { + // The `biometric_registration_id` to be deleted. + biometric_registration_id: string; +} + +// Response type for `users.deleteBiometricRegistration`. +export interface UsersDeleteBiometricRegistrationResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.deleteCryptoWallet`. +export interface UsersDeleteCryptoWalletRequest { + // The `crypto_wallet_id` to be deleted. + crypto_wallet_id: string; } -export interface B2CUsersCreateResponse extends BaseResponse { - user_id: UserID; +// Response type for `users.deleteCryptoWallet`. +export interface UsersDeleteCryptoWalletResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; + /** + * 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; +} + +// Request type for `users.deleteEmail`. +export interface UsersDeleteEmailRequest { + // The `email_id` to be deleted. email_id: string; +} + +// Response type for `users.deleteEmail`. +export interface UsersDeleteEmailResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.deleteOAuthRegistration`. +export interface UsersDeleteOAuthRegistrationRequest { + // The `oauth_user_registration_id` to be deleted. + oauth_user_registration_id: string; +} + +// Response type for `users.deleteOAuthRegistration`. +export interface UsersDeleteOAuthRegistrationResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.deletePassword`. +export interface UsersDeletePasswordRequest { + // The `password_id` to be deleted. + password_id: string; +} + +// Response type for `users.deletePassword`. +export interface UsersDeletePasswordResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.deletePhoneNumber`. +export interface UsersDeletePhoneNumberRequest { + // The `phone_id` to be deleted. phone_id: string; +} + +// Response type for `users.deletePhoneNumber`. +export interface UsersDeletePhoneNumberResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.delete`. +export interface UsersDeleteRequest { + // The unique ID of a specific User. + user_id: string; +} + +// Response type for `users.delete`. +export interface UsersDeleteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the deleted User. + user_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; +} + +// Request type for `users.deleteTOTP`. +export interface UsersDeleteTOTPRequest { + // The `totp_id` to be deleted. + totp_id: string; +} + +// Response type for `users.deleteTOTP`. +export interface UsersDeleteTOTPResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.deleteWebAuthnRegistration`. +export interface UsersDeleteWebAuthnRegistrationRequest { + // The `webauthn_registration_id` to be deleted. + webauthn_registration_id: string; +} + +// Response type for `users.deleteWebAuthnRegistration`. +export interface UsersDeleteWebAuthnRegistrationResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// Request type for `users.get`. +export interface UsersGetRequest { + // The unique ID of a specific User. + user_id: string; +} + +// Response type for `users.get`. +export interface UsersGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the returned User. + user_id: string; + // An array of email objects for the User. + emails: Email[]; + // The status of the User. The possible values are `pending` and `active`. status: string; + // An array of phone number objects linked to the User. + phone_numbers: PhoneNumber[]; + // An array that contains a list of all WebAuthn registrations for a given User in the Stytch API. + webauthn_registrations: WebAuthnRegistration[]; + // An array of OAuth `provider` objects linked to the User. + providers: OAuthProvider[]; + // An array containing a list of all TOTP instances for a given User in the Stytch API. + totps: TOTP[]; + // An array contains a list of all crypto wallets for a given User in the Stytch API. + crypto_wallets: CryptoWallet[]; + // An array that contains a list of all biometric registrations for a given User in the Stytch API. + biometric_registrations: BiometricRegistration[]; + /** + * 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; + // The name of the User. Each field in the `name` object is optional. + name?: Name; + /** + * 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 password object is returned for users with a password. + password?: Password; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export type B2CUsersGetResponse = BaseResponse & User; +// Request type for `users.search`. +export interface UsersSearchRequest { + /** + * 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 results with no filtering applied. + */ + query?: SearchUsersQuery; +} + +// Response type for `users.search`. +export interface UsersSearchResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // An array of results that match your search query. + results: User[]; + /** + * The search `results_metadata` object contains metadata relevant to your specific query like total and + * `next_cursor`. + */ + results_metadata: UsersResultsMetadata; + /** + * 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; +} -export enum UserSearchOperator { - OR = "OR", - AND = "AND", +// Request type for `users.update`. +export interface UsersUpdateRequest { + // The unique ID of a specific User. + user_id: string; + // The name of the user. Each field in the name object is optional. + name?: Name; + // Provided attributes help with fraud detection. + attributes?: Attributes; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export type UserSearchOperand = +// Response type for `users.update`. +export interface UsersUpdateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the updated User. + user_id: string; + // An array of email objects for the User. + emails: Email[]; + // An array of phone number objects linked to the User. + phone_numbers: PhoneNumber[]; + // An array contains a list of all crypto wallets for a given User in the Stytch API. + crypto_wallets: CryptoWallet[]; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} + +// MANUAL(SearchUsersQueryOperand)(TYPES) +export type SearchUsersQueryOperand = | { filter_name: "created_at_greater_than"; // Timestamp in RFC 3339 Format @@ -136,87 +750,14 @@ export type UserSearchOperand = | { filter_name: "password_exists"; filter_value: boolean; + } + | { + filter_name: string; + [key: string]: unknown; }; +// ENDMANUAL(SearchUsersQueryOperand) -export interface B2CUsersSearchRequest { - limit?: number; - query?: { - operator: UserSearchOperator; - operands: UserSearchOperand[]; - }; - cursor?: string | null; -} - -export interface B2CUsersSearchResponse extends BaseResponse { - results: User[]; - results_metadata: { - next_cursor: string | null; - total: number; - }; -} - -export interface B2CUsersUpdateRequest { - name?: Name; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; - attributes?: Attributes; -} - -export interface B2CUsersUpdateResponse extends BaseResponse { - user_id: UserID; - user: User; - emails: Email[]; - phone_numbers: PhoneNumber[]; - crypto_wallets: CryptoWallet[]; -} - -export interface B2CUsersDeleteResponse extends BaseResponse { - user_id: UserID; -} - -export interface B2CUsersDeleteEmailResponse extends BaseResponse { - user_id: UserID; - user: User; -} - -export interface B2CUsersDeletePhoneNumberResponse extends BaseResponse { - user_id: UserID; - user: User; -} - -export interface B2CUsersDeleteWebAuthnRegistrationResponse - extends BaseResponse { - user_id: UserID; - user: User; -} - -export interface B2CUsersDeleteBiometricRegistrationResponse - extends BaseResponse { - user_id: UserID; - user: User; -} - -export interface B2CUsersDeleteTOTPResponse extends BaseResponse { - user_id: UserID; - user: User; -} - -export interface B2CUsersDeleteCryptoWalletResponse extends BaseResponse { - user_id: UserID; - user: User; -} - -export interface B2CUsersDeletePasswordResponse extends BaseResponse { - user_id: UserID; - user: User; -} - -export interface B2CUsersDeleteOAuthUserRegistrationResponse - extends BaseResponse { - user_id: UserID; - user: User; -} - +// MANUAL(UserSearchIterator)(FREE_FUNCTION) enum mode { pending, inProgress, @@ -226,7 +767,7 @@ enum mode { export class UserSearchIterator { private mode: mode; - constructor(private client: Users, private data: B2CUsersSearchRequest) { + constructor(private client: Users, private data: UsersSearchRequest) { this.mode = mode.pending; } @@ -254,127 +795,253 @@ export class UserSearchIterator { } } } +// ENDMANUAL(UserSearchIterator) export class Users { - base_path = "users"; private fetchConfig: fetchConfig; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - - create(data: B2CUsersCreateRequest): Promise { - return request(this.fetchConfig, { + /** + * Add a User to Stytch. A `user_id` is returned in the response that can then be used to perform other + * operations within Stytch. An `email` or a `phone_number` is required. + * @param data {@link UsersCreateRequest} + * @returns {@link UsersCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: UsersCreateRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.base_path, + url: `/v1/users`, data, }); } - get(userID: UserID): Promise { - return request(this.fetchConfig, { + /** + * Get information about a specific User. + * @param data {@link UsersGetRequest} + * @returns {@link UsersGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: UsersGetRequest): Promise { + return request(this.fetchConfig, { method: "GET", - url: this.endpoint(userID), + url: `/v1/users/${params.user_id}`, + params: {}, }); } - search(data: B2CUsersSearchRequest): Promise { - return request(this.fetchConfig, { + /** + * Search for Users within your Stytch Project. Submit an empty `query` in the request to return all Users. + * @param data {@link UsersSearchRequest} + * @returns {@link UsersSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + search(data: UsersSearchRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("search"), + url: `/v1/users/search`, data, }); } - searchAll(data: B2CUsersSearchRequest): UserSearchIterator { - return new UserSearchIterator(this, data); - } - - update( - userID: UserID, - data: B2CUsersUpdateRequest - ): Promise { - return request(this.fetchConfig, { + /** + * Update a User's attributes. + * + * **Note:** In order to add a new email address or phone number to an existing User object, pass the new + * email address or phone number into the respective `/send` endpoint for the authentication method of your + * choice. If you specify the existing User's `user_id` while calling the `/send` endpoint, the new email + * address or phone number will be added to the existing User object upon successful authentication. We + * require this process to guard against an account takeover vulnerability. + * @param data {@link UsersUpdateRequest} + * @returns {@link UsersUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + update(data: UsersUpdateRequest): Promise { + return request(this.fetchConfig, { method: "PUT", - url: this.endpoint(userID), - data, + url: `/v1/users/${data.user_id}`, + data: { + name: data.name, + attributes: data.attributes, + trusted_metadata: data.trusted_metadata, + untrusted_metadata: data.untrusted_metadata, + }, }); } - delete(userID: UserID): Promise { - return request(this.fetchConfig, { + /** + * Delete a User from Stytch. + * @param data {@link UsersDeleteRequest} + * @returns {@link UsersDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + delete(data: UsersDeleteRequest): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(userID), + url: `/v1/users/${data.user_id}`, + data: {}, }); } - deleteEmail(emailID: string): Promise { - return request(this.fetchConfig, { + /** + * Delete an email from a User. + * @param data {@link UsersDeleteEmailRequest} + * @returns {@link UsersDeleteEmailResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteEmail( + data: UsersDeleteEmailRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`emails/${emailID}`), + url: `/v1/users/emails/${data.email_id}`, + data: {}, }); } + /** + * Delete a phone number from a User. + * @param data {@link UsersDeletePhoneNumberRequest} + * @returns {@link UsersDeletePhoneNumberResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ deletePhoneNumber( - phoneID: string - ): Promise { - return request(this.fetchConfig, { + data: UsersDeletePhoneNumberRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`phone_numbers/${phoneID}`), + url: `/v1/users/phone_numbers/${data.phone_id}`, + data: {}, }); } + /** + * Delete a WebAuthn registration from a User. + * @param data {@link UsersDeleteWebAuthnRegistrationRequest} + * @returns {@link UsersDeleteWebAuthnRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ deleteWebAuthnRegistration( - webAuthnRegistrationID: string - ): Promise { - return request(this.fetchConfig, { + data: UsersDeleteWebAuthnRegistrationRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`webauthn_registrations/${webAuthnRegistrationID}`), + url: `/v1/users/webauthn_registrations/${data.webauthn_registration_id}`, + data: {}, }); } + /** + * Delete a biometric registration from a User. + * @param data {@link UsersDeleteBiometricRegistrationRequest} + * @returns {@link UsersDeleteBiometricRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ deleteBiometricRegistration( - biometricRegistrationID: string - ): Promise { - return request(this.fetchConfig, { + data: UsersDeleteBiometricRegistrationRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`biometric_registrations/${biometricRegistrationID}`), + url: `/v1/users/biometric_registrations/${data.biometric_registration_id}`, + data: {}, }); } - deleteTOTP(totpID: string): Promise { - return request(this.fetchConfig, { + /** + * Delete a TOTP from a User. + * @param data {@link UsersDeleteTOTPRequest} + * @returns {@link UsersDeleteTOTPResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteTOTP(data: UsersDeleteTOTPRequest): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`totps/${totpID}`), + url: `/v1/users/totps/${data.totp_id}`, + data: {}, }); } + /** + * Delete a crypto wallet from a User. + * @param data {@link UsersDeleteCryptoWalletRequest} + * @returns {@link UsersDeleteCryptoWalletResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ deleteCryptoWallet( - cryptoWalletID: string - ): Promise { - return request(this.fetchConfig, { + data: UsersDeleteCryptoWalletRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`crypto_wallets/${cryptoWalletID}`), + url: `/v1/users/crypto_wallets/${data.crypto_wallet_id}`, + data: {}, }); } - deletePassword(passwordID: string): Promise { - return request(this.fetchConfig, { + /** + * Delete a password from a User. + * @param data {@link UsersDeletePasswordRequest} + * @returns {@link UsersDeletePasswordResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deletePassword( + data: UsersDeletePasswordRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`passwords/${passwordID}`), + url: `/v1/users/passwords/${data.password_id}`, + data: {}, }); } - deleteOAuthUserRegistration( - oauthUserRegistrationID: string - ): Promise { - return request(this.fetchConfig, { + /** + * Delete an OAuth registration from a User. + * @param data {@link UsersDeleteOAuthRegistrationRequest} + * @returns {@link UsersDeleteOAuthRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteOAuthRegistration( + data: UsersDeleteOAuthRegistrationRequest + ): Promise { + return request(this.fetchConfig, { method: "DELETE", - url: this.endpoint(`oauth/${oauthUserRegistrationID}`), + url: `/v1/users/oauth/${data.oauth_user_registration_id}`, + data: {}, }); } + + // MANUAL(searchAll)(SERVICE_METHOD) + // Return an iterator over all search results. Submit an empty `query` in the request to return all Users. + searchAll(data: UsersSearchRequest): UserSearchIterator { + return new UserSearchIterator(this, data); + } + // ENDMANUAL(searchAll) } diff --git a/lib/b2c/webauthn.ts b/lib/b2c/webauthn.ts index b8e54074..a331a441 100644 --- a/lib/b2c/webauthn.ts +++ b/lib/b2c/webauthn.ts @@ -1,104 +1,285 @@ -import { Session, User } from "./shared_b2c"; -import { request, BaseResponse, fetchConfig } from "../shared"; -import { UserID } from "./users"; +// !!! +// WARNING: This file is autogenerated +// Only modify code within MANUAL() sections +// or your changes may be overwritten later! +// !!! -export interface B2CWebAuthnRegisterStartRequest { - user_id: UserID; - domain: string; - user_agent?: string; - authenticator_type?: string; -} +import { fetchConfig } from "../shared"; +import { request } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; -export interface B2CWebAuthnRegisterStartResponse extends BaseResponse { - user_id: UserID; - public_key_credential_creation_options: string; -} - -export interface B2CWebAuthnRegisterRequest { - user_id: UserID; +// Request type for `webauthn.authenticate`. +export interface WebAuthnAuthenticateRequest { + /** + * The response of the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential). + */ public_key_credential: string; + // The `session_token` associated with a User's existing Session. + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + // The `session_jwt` associated with a User's existing Session. + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2CWebAuthnRegisterResponse extends BaseResponse { - user_id: UserID; +// Response type for `webauthn.authenticate`. +export interface WebAuthnAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID for the WebAuthn registration. webauthn_registration_id: string; + // A secret token for a given Stytch Session. + session_token: string; + // The JSON Web Token (JWT) for a given Stytch Session. + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; } -export interface B2CWebAuthnAuthenticateStartRequest { - user_id: UserID; +// Request type for `webauthn.authenticateStart`. +export interface WebAuthnAuthenticateStartRequest { + // The `user_id` of an active user the WebAuthn registration should be tied to. + user_id: string; + // The domain for WebAuthn. Defaults to `window.location.hostname`. domain: string; } -export interface B2CWebAuthnAuthenticateStartResponse extends BaseResponse { - user_id: UserID; +// Response type for `webauthn.authenticateStart`. +export interface WebAuthnAuthenticateStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // Options used for WebAuthn authentication. public_key_credential_request_options: 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; } -export interface B2CWebAuthnAuthenticateRequest { +// Request type for `webauthn.register`. +export interface WebAuthnRegisterRequest { + // The `user_id` of an active user the WebAuthn registration should be tied to. + user_id: string; + /** + * The response of the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential). + */ public_key_credential: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; // eslint-disable-line @typescript-eslint/no-explicit-any } -export interface B2CWebAuthnAuthenticateResponse extends BaseResponse { - user_id: UserID; - user: User; +// Response type for `webauthn.register`. +export interface WebAuthnRegisterResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // The unique ID for the WebAuthn registration. webauthn_registration_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; + /** + * 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; +} + +// Request type for `webauthn.registerStart`. +export interface WebAuthnRegisterStartRequest { + // The `user_id` of an active user the WebAuthn registration should be tied to. + user_id: string; + // The domain for WebAuthn. Defaults to `window.location.hostname`. + domain: string; + // The user agent of the User. + user_agent?: string; + /** + * The requested authenticator type of the WebAuthn device. The two valid value are platform and + * cross-platform. If no value passed, we assume both values are allowed. + */ + authenticator_type?: string; +} + +// Response type for `webauthn.registerStart`. +export interface WebAuthnRegisterStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + // The unique ID of the affected User. + user_id: string; + // Options used for WebAuthn registration. + public_key_credential_creation_options: 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; } export class WebAuthn { - base_path = "webauthn"; private fetchConfig: fetchConfig; constructor(fetchConfig: fetchConfig) { this.fetchConfig = fetchConfig; } - private endpoint(path: string): string { - return `${this.base_path}/${path}`; - } - + /** + * Initiate the process of creating a new WebAuthn registration. After calling this endpoint, the browser + * will need to call + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) with the data + * from + * [public_key_credential_creation_options](https://w3c.github.io/webauthn/#dictionary-makecredentialoptions) + * passed to the [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) + * request via the public key argument. We recommend using the `create()` wrapper provided by the + * webauthn-json library. + * + * If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, the + * `public_key_credential_creation_options` will need to be converted to a suitable public key by + * unmarshalling the JSON, base64 decoding the user ID field, and converting user ID and the challenge + * fields into an array buffer. + * @param data {@link WebAuthnRegisterStartRequest} + * @returns {@link WebAuthnRegisterStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ registerStart( - data: B2CWebAuthnRegisterStartRequest - ): Promise { - return request(this.fetchConfig, { + data: WebAuthnRegisterStartRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("register/start"), + url: `/v1/webauthn/register/start`, data, }); } - register( - data: B2CWebAuthnRegisterRequest - ): Promise { - return request(this.fetchConfig, { + /** + * Complete the creation of a WebAuthn registration by passing the response from the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) request to + * this endpoint as the `public_key_credential` parameter. + * + * If the [webauthn-json](https://github.com/github/webauthn-json) library's `create()` method was used, + * the response can be passed directly to the + * [register endpoint](https://stytch.com/docs/api/webauthn-register). If not, some fields (the client data + * and the attestation object) from the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) response will + * need to be converted from array buffers to strings and marshalled into JSON. + * @param data {@link WebAuthnRegisterRequest} + * @returns {@link WebAuthnRegisterResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + register(data: WebAuthnRegisterRequest): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("register"), + url: `/v1/webauthn/register`, data, }); } + /** + * Initiate the authentication of a WebAuthn registration. After calling this endpoint, the browser will + * need to call [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) with the + * data from `public_key_credential_request_options` passed to the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request via the + * public key argument. We recommend using the `get()` wrapper provided by the webauthn-json library. + * + * If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, `the + * public_key_credential_request_options` will need to be converted to a suitable public key by + * unmarshalling the JSON and converting some the fields to array buffers. + * @param data {@link WebAuthnAuthenticateStartRequest} + * @returns {@link WebAuthnAuthenticateStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticateStart( - data: B2CWebAuthnAuthenticateStartRequest - ): Promise { - return request(this.fetchConfig, { + data: WebAuthnAuthenticateStartRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate/start"), + url: `/v1/webauthn/authenticate/start`, data, }); } + /** + * Complete the authentication of a WebAuthn registration by passing the response from the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request to the + * authenticate endpoint. + * + * If the [webauthn-json](https://github.com/github/webauthn-json) library's `get()` method was used, the + * response can be passed directly to the + * [authenticate endpoint](https://stytch.com/docs/api/webauthn-authenticate). If not some fields from the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) response will need to + * be converted from array buffers to strings and marshalled into JSON. + * @param data {@link WebAuthnAuthenticateRequest} + * @returns {@link WebAuthnAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate( - data: B2CWebAuthnAuthenticateRequest - ): Promise { - return request(this.fetchConfig, { + data: WebAuthnAuthenticateRequest + ): Promise { + return request(this.fetchConfig, { method: "POST", - url: this.endpoint("authenticate"), + url: `/v1/webauthn/authenticate`, data, }); } diff --git a/lib/index.ts b/lib/index.ts index e9b549b6..039883a7 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -3,6 +3,4 @@ export * from "./b2c/index"; export { B2BClient } from "./b2b/client"; export * from "./b2b/index"; export * as envs from "./shared/envs"; -export { UserSearchOperator } from "./b2c/users"; -export { SearchOperator } from "./b2b/shared_b2b"; export * from "./shared/errors"; diff --git a/lib/shared/envs.ts b/lib/shared/envs.ts index f0670520..2e301d8b 100644 --- a/lib/shared/envs.ts +++ b/lib/shared/envs.ts @@ -1,2 +1,2 @@ -export const test = "https://test.stytch.com/v1/"; -export const live = "https://api.stytch.com/v1/"; +export const test = "https://test.stytch.com/"; +export const live = "https://api.stytch.com/"; diff --git a/lib/shared/index.ts b/lib/shared/index.ts index 06299cc7..80f588ef 100644 --- a/lib/shared/index.ts +++ b/lib/shared/index.ts @@ -6,11 +6,6 @@ import * as fetchImport from "isomorphic-unfetch"; const fetch = (fetchImport.default || fetchImport) as typeof fetchImport.default; -export interface BaseResponse { - status_code: number; - request_id: string; -} - export interface fetchConfig { baseURL: string; headers: Record; diff --git a/package-lock.json b/package-lock.json index f1ef4564..50edc725 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "stytch", - "version": "7.5.1", + "version": "8.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "stytch", - "version": "7.5.1", + "version": "8.0.0", "license": "MIT", "dependencies": { "isomorphic-unfetch": "^3.1.0", diff --git a/package.json b/package.json index 19a7179b..50793d79 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stytch", - "version": "7.5.1", + "version": "8.0.0", "description": "A wrapper for the Stytch API", "types": "./types/lib/index.d.ts", "main": "./dist/index.js", diff --git a/test/b2b/client.test.ts b/test/b2b/client.test.ts index 1a5ec404..d2b64c7e 100644 --- a/test/b2b/client.test.ts +++ b/test/b2b/client.test.ts @@ -10,9 +10,7 @@ describe("B2B Client", () => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - expect(testClient.fetchConfig.baseURL).toBe( - "https://test.stytch.com/v1/b2b/" - ); + expect(testClient.fetchConfig.baseURL).toBe("https://test.stytch.com/"); const liveClient = new stytch.B2BClient({ project_id: "project-test-00000000-0000-4000-8000-000000000000", @@ -22,8 +20,6 @@ describe("B2B Client", () => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - expect(liveClient.fetchConfig.baseURL).toBe( - "https://api.stytch.com/v1/b2b/" - ); + expect(liveClient.fetchConfig.baseURL).toBe("https://api.stytch.com/"); }); }); diff --git a/test/b2b/discovery.test.ts b/test/b2b/discovery.test.ts index a41bd207..98b95e5d 100644 --- a/test/b2b/discovery.test.ts +++ b/test/b2b/discovery.test.ts @@ -27,7 +27,7 @@ describe("discovery.organizations.list", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "discovery/organizations", + path: "/v1/b2b/discovery/organizations", data: { intermediate_session_token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", @@ -56,7 +56,7 @@ describe("discovery.organizations.create", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "discovery/organizations/create", + path: "/v1/b2b/discovery/organizations/create", data: { intermediate_session_token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", @@ -87,7 +87,7 @@ describe("discovery.intermediateSessions.exchange", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "discovery/intermediate_sessions/exchange", + path: "/v1/b2b/discovery/intermediate_sessions/exchange", data: { intermediate_session_token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", diff --git a/test/b2b/magic_links.test.ts b/test/b2b/magic_links.test.ts index c2d02e7e..5523ad55 100644 --- a/test/b2b/magic_links.test.ts +++ b/test/b2b/magic_links.test.ts @@ -29,7 +29,7 @@ describe("magicLinks.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/authenticate", + path: "/v1/b2b/magic_links/authenticate", data: { magic_links_token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", @@ -45,7 +45,7 @@ describe("magicLinks.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/authenticate", + path: "/v1/b2b/magic_links/authenticate", data: { magic_links_token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", }, @@ -62,7 +62,7 @@ describe("magicLinks.email.loginOrSignup", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/login_or_signup", + path: "/v1/b2b/magic_links/email/login_or_signup", data: { email_address: "sandbox@stytch.com", organization_id: "organization-id-1234", @@ -83,7 +83,7 @@ describe("magicLinks.email.loginOrSignup", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/login_or_signup", + path: "/v1/b2b/magic_links/email/login_or_signup", data: { email_address: "sandbox@stytch.com", organization_id: "organization-id-1234", @@ -107,7 +107,7 @@ describe("magicLinks.email.invite", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/invite", + path: "/v1/b2b/magic_links/email/invite", data: { email_address: "sandbox@stytch.com", organization_id: "organization-id-1234", @@ -129,7 +129,7 @@ describe("magicLinks.email.invite", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/invite", + path: "/v1/b2b/magic_links/email/invite", data: { email_address: "sandbox@stytch.com", organization_id: "organization-id-1234", @@ -153,7 +153,7 @@ describe("magicLinks.email.discovery.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/discovery/send", + path: "/v1/b2b/magic_links/email/discovery/send", data: { email_address: "sandbox@stytch.com", }, @@ -170,7 +170,7 @@ describe("magicLinks.email.discovery.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/discovery/send", + path: "/v1/b2b/magic_links/email/discovery/send", data: { email_address: "sandbox@stytch.com", discovery_redirect_url: "http://localhost:8000/discover", @@ -191,7 +191,7 @@ describe("magicLinks.discovery.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/discovery/authenticate", + path: "/v1/b2b/magic_links/discovery/authenticate", data: { discovery_magic_links_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", @@ -207,7 +207,7 @@ describe("magicLinks.discovery.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/discovery/authenticate", + path: "/v1/b2b/magic_links/discovery/authenticate", data: { discovery_magic_links_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", diff --git a/test/b2b/members.test.ts b/test/b2b/members.test.ts index d7294335..e4277ba0 100644 --- a/test/b2b/members.test.ts +++ b/test/b2b/members.test.ts @@ -1,19 +1,17 @@ -import { Members } from "../../lib/b2b/members"; import { MOCK_FETCH_CONFIG, mockRequest } from "../helpers"; -import { SearchOperator } from "../../lib/b2b/shared_b2b"; +import { Organizations } from "../../lib/b2b/organizations"; jest.mock("../../lib/shared"); -const members = new Members(MOCK_FETCH_CONFIG, "organizations"); +const members = new Organizations(MOCK_FETCH_CONFIG).members; describe("members.create", () => { test("success", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "organizations/organization-id-1234/members", + path: "/v1/b2b/organizations/organization-id-1234/members", data: { - organization_id: "organization-id-1234", email_address: "test@stytch.com", create_member_as_pending: true, is_breakglass: false, @@ -52,7 +50,7 @@ describe("members.get", () => { mockRequest((req) => { expect(req).toEqual({ method: "GET", - path: "organizations/organization-id-1234/member", + path: "/v1/b2b/organizations/organization-id-1234/member", params: { organization_id: "organization-id-1234", email_address: "test@stytch.com", @@ -85,10 +83,8 @@ describe("members.update", () => { mockRequest((req) => { expect(req).toEqual({ method: "PUT", - path: "organizations/organization-id-1234/members/member-id-1234", + path: "/v1/b2b/organizations/organization-id-1234/members/member-id-1234", data: { - member_id: "member-id-1234", - organization_id: "organization-id-1234", name: "new name", is_breakglass: true, mfa_enrolled: true, @@ -126,12 +122,12 @@ describe("members.search", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "organizations/members/search", + path: "/v1/b2b/organizations/members/search", data: { organization_ids: ["organization_id"], limit: 200, query: { - operator: SearchOperator.OR, + operator: "OR", operands: [ { filter_name: "member_ids", filter_value: ["member-id-1234"] }, { filter_name: "statuses", filter_value: ["active", "invited"] }, @@ -161,7 +157,7 @@ describe("members.search", () => { organization_ids: ["organization_id"], limit: 200, query: { - operator: SearchOperator.OR, + operator: "OR", operands: [ { filter_name: "member_ids", filter_value: ["member-id-1234"] }, { filter_name: "statuses", filter_value: ["active", "invited"] }, @@ -189,7 +185,8 @@ describe("members.delete", () => { mockRequest((req) => { expect(req).toEqual({ method: "DELETE", - path: "organizations/organization-id-1234/members/member-id-1234", + path: "/v1/b2b/organizations/organization-id-1234/members/member-id-1234", + data: {}, }); const data = { @@ -218,7 +215,8 @@ describe("members.deletePhoneNumber", () => { mockRequest((req) => { expect(req).toEqual({ method: "DELETE", - path: "organizations/organization-id-1234/members/mfa_phone_numbers/member-id-1234", + path: "/v1/b2b/organizations/organization-id-1234/members/mfa_phone_numbers/member-id-1234", + data: {}, }); const data = { @@ -230,7 +228,7 @@ describe("members.deletePhoneNumber", () => { }); return expect( - members.deletePhoneNumber({ + members.deleteMFAPhoneNumber({ organization_id: "organization-id-1234", member_id: "member-id-1234", }) diff --git a/test/b2b/oauth.test.ts b/test/b2b/oauth.test.ts deleted file mode 100644 index b5b20d9a..00000000 --- a/test/b2b/oauth.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { OAuth } from "../../lib/b2b/oauth"; -import { MOCK_FETCH_CONFIG } from "../helpers"; -import { request } from "../../lib/shared"; - -jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); - -(request as jest.Mock).mockImplementation((_, config) => { - return Promise.resolve({ - method: config.method, - path: config.url, - data: config.data, - params: config.params, - }); -}); - -const oauth = new OAuth(MOCK_FETCH_CONFIG); - -describe("oauth.authenticate", () => { - test("session", () => { - const data = { - oauth_token: "fake-token", - }; - return expect(oauth.authenticate(data)).resolves.toMatchObject({ - method: "POST", - path: "oauth/authenticate", - data: { - oauth_token: "fake-token", - }, - }); - }); -}); - -describe("oauth.discovery.authenticate", () => { - test("session", () => { - const data = { - discovery_oauth_token: "fake-token", - }; - return expect(oauth.discovery.authenticate(data)).resolves.toMatchObject({ - method: "POST", - path: "oauth/discovery/authenticate", - data: { - discovery_oauth_token: "fake-token", - }, - }); - }); -}); diff --git a/test/b2b/oidc.test.ts b/test/b2b/oidc.test.ts index 3a407687..e2681712 100644 --- a/test/b2b/oidc.test.ts +++ b/test/b2b/oidc.test.ts @@ -1,4 +1,4 @@ -import { OIDC } from "../../lib/b2b/oidc"; +import { SSO } from "../../lib/b2b/sso"; import { MOCK_FETCH_CONFIG } from "../helpers"; import { request } from "../../lib/shared"; @@ -16,18 +16,18 @@ beforeEach(() => { }); }); -const oidc = new OIDC(MOCK_FETCH_CONFIG); +const oidc = new SSO(MOCK_FETCH_CONFIG).oidc; describe("oidc.create", () => { test("success", () => { return expect( - oidc.create({ + oidc.createConnection({ organization_id: "organization-id-1234", display_name: "Test Connection", }) ).resolves.toMatchObject({ method: "POST", - path: "sso/oidc/organization-id-1234", + path: "/v1/b2b/sso/oidc/organization-id-1234", data: { display_name: "Test Connection", }, @@ -38,7 +38,7 @@ describe("oidc.create", () => { describe("oidc.update", () => { test("success", () => { return expect( - oidc.update({ + oidc.updateConnection({ organization_id: "organization-id-1234", connection_id: "oidc-connection-5678", display_name: "Test Connection", @@ -52,7 +52,7 @@ describe("oidc.update", () => { }) ).resolves.toMatchObject({ method: "PUT", - path: "sso/oidc/organization-id-1234/connections/oidc-connection-5678", + path: "/v1/b2b/sso/oidc/organization-id-1234/connections/oidc-connection-5678", data: { display_name: "Test Connection", client_id: "client-id-1234", diff --git a/test/b2b/organizations.test.ts b/test/b2b/organizations.test.ts index 4ad947c0..21a30849 100644 --- a/test/b2b/organizations.test.ts +++ b/test/b2b/organizations.test.ts @@ -1,6 +1,5 @@ import { Organizations } from "../../lib/b2b/organizations"; import { MOCK_FETCH_CONFIG, mockRequest } from "../helpers"; -import { SearchOperator } from "../../lib/b2b/shared_b2b"; import { request } from "../../lib/shared"; jest.mock("../../lib/shared"); @@ -37,7 +36,7 @@ describe("organizations.create", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "organizations", + path: "/v1/b2b/organizations", data: { organization_name: "organization_name", organization_slug: "slug", @@ -61,7 +60,7 @@ describe("organizations.get", () => { organizations.get({ organization_id: "organization-id-1234" }) ).resolves.toMatchObject({ method: "GET", - path: "organizations/organization-id-1234", + path: "/v1/b2b/organizations/organization-id-1234", }); }); }); @@ -71,11 +70,11 @@ describe("organizations.search", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "organizations/search", + path: "/v1/b2b/organizations/search", data: { limit: 200, query: { - operator: SearchOperator.OR, + operator: "or", operands: [ { filter_name: "organization_ids", @@ -107,7 +106,7 @@ describe("organizations.search", () => { organizations.search({ limit: 200, query: { - operator: SearchOperator.OR, + operator: "or", operands: [ { filter_name: "organization_ids", @@ -154,7 +153,7 @@ describe("organizations.update", () => { }) ).resolves.toMatchObject({ method: "PUT", - path: "organizations/organization-id-1234", + path: "/v1/b2b/organizations/organization-id-1234", data: { organization_name: "organization_name", organization_slug: "slug", @@ -180,7 +179,7 @@ describe("organizations.delete", () => { organizations.delete({ organization_id: "organization-id-1234" }) ).resolves.toMatchObject({ method: "DELETE", - path: "organizations/organization-id-1234", + path: "/v1/b2b/organizations/organization-id-1234", }); }); }); diff --git a/test/b2b/otps.test.ts b/test/b2b/otps.test.ts index 2fe26d48..b20c4f1b 100644 --- a/test/b2b/otps.test.ts +++ b/test/b2b/otps.test.ts @@ -1,4 +1,4 @@ -import { OTPs } from "../../lib/b2b/otps"; +import { OTPs } from "../../lib/b2b/otp"; import { MOCK_FETCH_CONFIG } from "../helpers"; import { request } from "../../lib/shared"; @@ -29,7 +29,7 @@ describe("otps.sms.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/sms/send", + path: "/v1/b2b/otps/sms/send", data: { organization_id: "organization-id-1234", member_id: "member-id-1234", @@ -53,7 +53,7 @@ describe("otps.sms.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/sms/authenticate", + path: "/v1/b2b/otps/sms/authenticate", data: { organization_id: "organization-id-1234", member_id: "member-id-1234", @@ -76,7 +76,7 @@ describe("otps.sms.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/sms/authenticate", + path: "/v1/b2b/otps/sms/authenticate", data: { organization_id: "organization-id-1234", member_id: "member-id-1234", diff --git a/test/b2b/passwords.test.ts b/test/b2b/passwords.test.ts index f68c81b6..722c5601 100644 --- a/test/b2b/passwords.test.ts +++ b/test/b2b/passwords.test.ts @@ -3,7 +3,6 @@ import { request } from "../../lib/shared"; import { MOCK_FETCH_CONFIG } from "../helpers"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2b/shared_b2b"); beforeEach(() => { (request as jest.Mock).mockReset(); @@ -32,7 +31,7 @@ describe("passwords.authenticate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/authenticate", + path: "/v1/b2b/passwords/authenticate", data: { organization_id: "organization-id-1234", password: "not-a-real-password", @@ -53,7 +52,7 @@ describe("passwords.authenticate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/authenticate", + path: "/v1/b2b/passwords/authenticate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -67,13 +66,13 @@ describe("passwords.authenticate", () => { describe("passwords.emailResetStart", () => { test("basic", () => { return expect( - passwords.resetByEmailStart({ + passwords.email.resetStart({ organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", }) ).resolves.toEqual({ method: "POST", - path: "passwords/email/reset/start", + path: "/v1/b2b/passwords/email/reset/start", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -83,7 +82,7 @@ describe("passwords.emailResetStart", () => { }); test("pkce", () => { return expect( - passwords.resetByEmailStart({ + passwords.email.resetStart({ organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", code_challenge: "example_code_challenge", @@ -91,7 +90,7 @@ describe("passwords.emailResetStart", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/email/reset/start", + path: "/v1/b2b/passwords/email/reset/start", data: { organization_id: "organization-id-1234", code_challenge: "example_code_challenge", @@ -106,13 +105,13 @@ describe("passwords.emailResetStart", () => { describe("passwords.emailReset", () => { test("basic", () => { return expect( - passwords.resetByEmail({ + passwords.email.reset({ password_reset_token: "example-token", password: "not-a-real-password", }) ).resolves.toEqual({ method: "POST", - path: "passwords/email/reset", + path: "/v1/b2b/passwords/email/reset", data: { password_reset_token: "example-token", password: "not-a-real-password", @@ -122,14 +121,14 @@ describe("passwords.emailReset", () => { }); test("pkce", () => { return expect( - passwords.resetByEmail({ + passwords.email.reset({ password_reset_token: "example-token", password: "not-a-real-password", code_verifier: "example_code_verifier", }) ).resolves.toEqual({ method: "POST", - path: "passwords/email/reset", + path: "/v1/b2b/passwords/email/reset", data: { password_reset_token: "example-token", password: "not-a-real-password", @@ -143,7 +142,7 @@ describe("passwords.emailReset", () => { describe("passwords.existingPasswordReset", () => { test("basic", () => { return expect( - passwords.resetByExistingPassword({ + passwords.existingPassword.reset({ organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", existing_password: "existing_password", @@ -151,7 +150,7 @@ describe("passwords.existingPasswordReset", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/existing_password/reset", + path: "/v1/b2b/passwords/existing_password/reset", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -166,14 +165,14 @@ describe("passwords.existingPasswordReset", () => { describe("passwords.sessionReset", () => { test("basic", () => { return expect( - passwords.resetBySession({ + passwords.sessions.reset({ organization_id: "organization-id-1234", password: "new_password", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", }) ).resolves.toEqual({ method: "POST", - path: "passwords/session/reset", + path: "/v1/b2b/passwords/session/reset", data: { organization_id: "organization-id-1234", password: "new_password", @@ -193,7 +192,7 @@ describe("passwords.strengthCheck", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/strength_check", + path: "/v1/b2b/passwords/strength_check", data: { password: "not-a-real-password", email_address: "Ada_Lovelace@example.com", @@ -214,7 +213,7 @@ describe("passwords.migrate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -234,7 +233,7 @@ describe("passwords.migrate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -252,18 +251,20 @@ describe("passwords.migrate", () => { hash_type: "sha_1", hash: "not-a-real-password-hash", sha_1_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", hash_type: "sha_1", hash: "not-a-real-password-hash", sha_1_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }, @@ -279,11 +280,12 @@ describe("passwords.migrate", () => { hash: "not-a-real-password-hash", sha_1_config: { prepend_salt: "not-a-real-salt", + append_salt: "", }, }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -291,6 +293,7 @@ describe("passwords.migrate", () => { hash: "not-a-real-password-hash", sha_1_config: { prepend_salt: "not-a-real-salt", + append_salt: "", }, }, params: undefined, @@ -306,7 +309,7 @@ describe("passwords.migrate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -324,18 +327,20 @@ describe("passwords.migrate", () => { hash_type: "md_5", hash: "not-a-real-password-hash", md_5_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", hash_type: "md_5", hash: "not-a-real-password-hash", md_5_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }, @@ -351,11 +356,12 @@ describe("passwords.migrate", () => { hash: "not-a-real-password-hash", md_5_config: { prepend_salt: "not-a-real-salt", + append_salt: "", }, }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -363,6 +369,7 @@ describe("passwords.migrate", () => { hash: "not-a-real-password-hash", md_5_config: { prepend_salt: "not-a-real-salt", + append_salt: "", }, }, params: undefined, @@ -378,7 +385,7 @@ describe("passwords.migrate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -405,7 +412,7 @@ describe("passwords.migrate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -439,7 +446,7 @@ describe("passwords.migrate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -473,7 +480,7 @@ describe("passwords.migrate", () => { }) ).resolves.toEqual({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", @@ -505,7 +512,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/b2b/passwords/migrate", data: { organization_id: "organization-id-1234", email_address: "Ada_Lovelace@example.com", diff --git a/test/b2b/saml.test.ts b/test/b2b/saml.test.ts index 99761cd3..629f0513 100644 --- a/test/b2b/saml.test.ts +++ b/test/b2b/saml.test.ts @@ -1,4 +1,4 @@ -import { SAML } from "../../lib/b2b/saml"; +import { SSO } from "../../lib/b2b/sso"; import { MOCK_FETCH_CONFIG } from "../helpers"; import { request } from "../../lib/shared"; @@ -16,18 +16,18 @@ beforeEach(() => { }); }); -const saml = new SAML(MOCK_FETCH_CONFIG); +const saml = new SSO(MOCK_FETCH_CONFIG).saml; describe("saml.create", () => { test("success", () => { return expect( - saml.create({ + saml.createConnection({ organization_id: "organization-id-1234", display_name: "Test Connection", }) ).resolves.toMatchObject({ method: "POST", - path: "sso/saml/organization-id-1234", + path: "/v1/b2b/sso/saml/organization-id-1234", data: { display_name: "Test Connection", }, @@ -38,7 +38,7 @@ describe("saml.create", () => { describe("saml.update", () => { test("success", () => { return expect( - saml.update({ + saml.updateConnection({ organization_id: "organization-id-1234", connection_id: "saml-connection-5678", idp_entity_id: "https://example.com/sso", @@ -53,7 +53,7 @@ describe("saml.update", () => { }) ).resolves.toMatchObject({ method: "PUT", - path: "sso/saml/organization-id-1234/connections/saml-connection-5678", + path: "/v1/b2b/sso/saml/organization-id-1234/connections/saml-connection-5678", data: { idp_entity_id: "https://example.com/sso", display_name: "Test Connection", @@ -79,7 +79,7 @@ describe("saml.deleteVerificationCertificate", () => { }) ).resolves.toMatchObject({ method: "DELETE", - path: "sso/saml/organization-id-1234/connections/saml-connection-5678/verification_certificates/verification-certificate-9012", + path: "/v1/b2b/sso/saml/organization-id-1234/connections/saml-connection-5678/verification_certificates/verification-certificate-9012", }); }); }); diff --git a/test/b2b/sessions.test.ts b/test/b2b/sessions.test.ts index 32a01356..16ce64fe 100644 --- a/test/b2b/sessions.test.ts +++ b/test/b2b/sessions.test.ts @@ -17,7 +17,7 @@ describe("sessions.get", () => { mockRequest((req) => { expect(req).toEqual({ method: "GET", - path: "sessions", + path: "/v1/b2b/sessions", params: { organization_id: "organization-test-11111111-1111-4111-8111-111111111111", @@ -70,7 +70,7 @@ describe("sessions.authenticate", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "sessions/authenticate", + path: "/v1/b2b/sessions/authenticate", data: { session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", session_duration_minutes: 60, @@ -114,7 +114,7 @@ describe("sessions.revoke", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "sessions/revoke", + path: "/v1/b2b/sessions/revoke", data: { session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", }, @@ -139,7 +139,7 @@ describe("sessions.exchange", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "sessions/exchange", + path: "/v1/b2b/sessions/exchange", data: { organization_id: "organization-id-1234", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", @@ -159,12 +159,13 @@ describe("sessions.exchange", () => { }); }); -describe("sessions.jwks", () => { +describe("sessions.getJWKS", () => { test("success", () => { mockRequest((req) => { expect(req).toEqual({ method: "GET", - path: "sessions/jwks/project-test-11111111-1111-4111-8111-111111111111", + path: "/v1/b2b/sessions/jwks/project-test-11111111-1111-4111-8111-111111111111", + params: {}, }); return { status: 200, data: {} }; @@ -172,7 +173,9 @@ describe("sessions.jwks", () => { const sessions = new Sessions(MOCK_FETCH_CONFIG, jwtConfig()); return expect( - sessions.jwks("project-test-11111111-1111-4111-8111-111111111111") + sessions.getJWKS({ + project_id: "project-test-11111111-1111-4111-8111-111111111111", + }) ).resolves.toEqual({ status: 200 }); }); }); @@ -182,7 +185,7 @@ describe("sessions.authenticateJwt", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "sessions/authenticate", + path: "/v1/b2b/sessions/authenticate", data: { session_jwt: "stale_jwt", }, diff --git a/test/b2b/sso.test.ts b/test/b2b/sso.test.ts index 4a68d95e..ecdedd10 100644 --- a/test/b2b/sso.test.ts +++ b/test/b2b/sso.test.ts @@ -21,10 +21,10 @@ const sso = new SSO(MOCK_FETCH_CONFIG); describe("sso.get", () => { test("success", () => { return expect( - sso.get({ organization_id: "organization-id-1234" }) + sso.getConnections({ organization_id: "organization-id-1234" }) ).resolves.toMatchObject({ method: "GET", - path: "sso/organization-id-1234", + path: "/v1/b2b/sso/organization-id-1234", }); }); }); @@ -40,7 +40,7 @@ describe("sso.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "sso/authenticate", + path: "/v1/b2b/sso/authenticate", data: { sso_token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", @@ -56,7 +56,7 @@ describe("sso.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "sso/authenticate", + path: "/v1/b2b/sso/authenticate", data: { sso_token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", }, @@ -67,13 +67,13 @@ describe("sso.authenticate", () => { describe("sso.delete", () => { test("success", () => { return expect( - sso.delete({ + sso.deleteConnection({ organization_id: "organization-id-1234", connection_id: "saml-connection-id-1234", }) ).resolves.toMatchObject({ method: "DELETE", - path: "sso/organization-id-1234/connections/saml-connection-id-1234", + path: "/v1/b2b/sso/organization-id-1234/connections/saml-connection-id-1234", }); }); }); diff --git a/test/b2c/crypto_wallets.test.ts b/test/b2c/crypto_wallets.test.ts index 43b670a6..785c8650 100644 --- a/test/b2c/crypto_wallets.test.ts +++ b/test/b2c/crypto_wallets.test.ts @@ -2,14 +2,13 @@ import { CryptoWallets } from "../../lib/b2c/crypto_wallets"; import { MOCK_FETCH_CONFIG, mockRequest } from "../helpers"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); describe("cryptowallets.authenticateStart", () => { test("success", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "crypto_wallets/authenticate/start", + path: "/v1/crypto_wallets/authenticate/start", data: { crypto_wallet_address: "0x1234567890123456789012345678901234567890", crypto_wallet_type: "ethereum", @@ -45,7 +44,7 @@ describe("cryptowallets.authenticate", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "crypto_wallets/authenticate", + path: "/v1/crypto_wallets/authenticate", data: { crypto_wallet_address: "0x1234567890123456789012345678901234567890", crypto_wallet_type: "ethereum", diff --git a/test/b2c/index.test.ts b/test/b2c/index.test.ts index 230fea2f..0a7cbf26 100644 --- a/test/b2c/index.test.ts +++ b/test/b2c/index.test.ts @@ -1,8 +1,8 @@ import * as stytch from "../../lib"; test("pre-configured environment base URLs", () => { - expect(stytch.envs.test).toEqual("https://test.stytch.com/v1/"); - expect(stytch.envs.live).toEqual("https://api.stytch.com/v1/"); + expect(stytch.envs.test).toEqual("https://test.stytch.com/"); + expect(stytch.envs.live).toEqual("https://api.stytch.com/"); }); test("configuring a test client", () => { diff --git a/test/b2c/magic_links.test.ts b/test/b2c/magic_links.test.ts index fbd28574..52936925 100644 --- a/test/b2c/magic_links.test.ts +++ b/test/b2c/magic_links.test.ts @@ -3,7 +3,6 @@ import { MOCK_FETCH_CONFIG } from "../helpers"; import { request } from "../../lib/shared"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); beforeEach(() => { (request as jest.Mock).mockReset(); @@ -28,7 +27,7 @@ describe("magicLinks.create", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links", + path: "/v1/magic_links", data: { user_id: "user-test-22222222-2222-4222-8222-222222222222", expiration_minutes: 75, @@ -40,13 +39,14 @@ describe("magicLinks.create", () => { describe("magicLinks.authenticate", () => { test("session", () => { return expect( - magicLinks.authenticate("DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", { + magicLinks.authenticate({ + token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", session_duration_minutes: 60, }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/authenticate", + path: "/v1/magic_links/authenticate", data: { token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", @@ -56,10 +56,12 @@ describe("magicLinks.authenticate", () => { }); test("no session", () => { return expect( - magicLinks.authenticate("DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=") + magicLinks.authenticate({ + token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", + }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/authenticate", + path: "/v1/magic_links/authenticate", data: { token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", }, @@ -75,7 +77,7 @@ describe("magicLinks.email.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/send", + path: "/v1/magic_links/email/send", data: { email: "sandbox@stytch.com", }, @@ -97,7 +99,7 @@ describe("magicLinks.email.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/send", + path: "/v1/magic_links/email/send", data: { email: "sandbox@stytch.com", login_magic_link_url: "http://localhost:8000/login", @@ -121,7 +123,7 @@ describe("magicLinks.email.loginOrCreate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/login_or_create", + path: "/v1/magic_links/email/login_or_create", data: { email: "sandbox@stytch.com", }, @@ -144,7 +146,7 @@ describe("magicLinks.email.loginOrCreate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/login_or_create", + path: "/v1/magic_links/email/login_or_create", data: { email: "sandbox@stytch.com", login_magic_link_url: "http://localhost:8000/login", @@ -169,7 +171,7 @@ describe("magicLinks.email.invite", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/invite", + path: "/v1/magic_links/email/invite", data: { email: "sandbox@stytch.com", }, @@ -189,7 +191,7 @@ describe("magicLinks.email.invite", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/invite", + path: "/v1/magic_links/email/invite", data: { email: "sandbox@stytch.com", invite_magic_link_url: "http://localhost:8000/invite", @@ -211,7 +213,7 @@ describe("magicLinks.email.revokeInvite", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "magic_links/email/revoke_invite", + path: "/v1/magic_links/email/revoke_invite", data: { email: "sandbox@stytch.com", }, diff --git a/test/b2c/oauth.test.ts b/test/b2c/oauth.test.ts index 3e572fab..6065b00c 100644 --- a/test/b2c/oauth.test.ts +++ b/test/b2c/oauth.test.ts @@ -3,7 +3,6 @@ import { MOCK_FETCH_CONFIG } from "../helpers"; import { request } from "../../lib/shared"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); (request as jest.Mock).mockImplementation((_, config) => { return Promise.resolve({ @@ -18,9 +17,11 @@ const oauth = new OAuth(MOCK_FETCH_CONFIG); describe("oauth.authenticate", () => { test("session", () => { - return expect(oauth.authenticate("fake-token")).resolves.toMatchObject({ + return expect( + oauth.authenticate({ token: "fake-token" }) + ).resolves.toMatchObject({ method: "POST", - path: "oauth/authenticate", + path: "/v1/oauth/authenticate", data: { token: "fake-token", }, diff --git a/test/b2c/otps.test.ts b/test/b2c/otps.test.ts index 5f474198..fdb79fdd 100644 --- a/test/b2c/otps.test.ts +++ b/test/b2c/otps.test.ts @@ -3,7 +3,6 @@ import { MOCK_FETCH_CONFIG } from "../helpers"; import { request } from "../../lib/shared"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); beforeEach(() => { (request as jest.Mock).mockReset(); @@ -30,7 +29,7 @@ describe("otps.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/authenticate", + path: "/v1/otps/authenticate", data: { method_id: "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", code: "123456", @@ -47,7 +46,7 @@ describe("otps.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/authenticate", + path: "/v1/otps/authenticate", data: { method_id: "phone-number-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", code: "123456", @@ -65,7 +64,7 @@ describe("otps.email.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/email/send", + path: "/v1/otps/email/send", data: { email: "sandbox@stytch.com", }, @@ -82,7 +81,7 @@ describe("otps.email.loginOrCreate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/email/login_or_create", + path: "/v1/otps/email/login_or_create", data: { email: "sandbox@stytch.com", }, @@ -99,7 +98,7 @@ describe("otps.sms.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/sms/send", + path: "/v1/otps/sms/send", data: { phone_number: "+12025550162", }, @@ -116,7 +115,7 @@ describe("otps.sms.loginOrCreate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/sms/login_or_create", + path: "/v1/otps/sms/login_or_create", data: { phone_number: "+12025550162", }, @@ -133,7 +132,7 @@ describe("otps.whatsapp.send", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/whatsapp/send", + path: "/v1/otps/whatsapp/send", data: { phone_number: "+12025550162", }, @@ -150,7 +149,7 @@ describe("otps.whatsapp.loginOrCreate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "otps/whatsapp/login_or_create", + path: "/v1/otps/whatsapp/login_or_create", data: { phone_number: "+12025550162", }, diff --git a/test/b2c/password.test.ts b/test/b2c/password.test.ts index 502a08c3..42e51a8b 100644 --- a/test/b2c/password.test.ts +++ b/test/b2c/password.test.ts @@ -3,7 +3,6 @@ import { request } from "../../lib/shared"; import { MOCK_FETCH_CONFIG } from "../helpers"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); beforeEach(() => { (request as jest.Mock).mockReset(); @@ -28,7 +27,7 @@ describe("passwords.create", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords", + path: "/v1/passwords", data: { password: "not-a-real-password", email: "Ada_Lovelace@example.com", @@ -48,7 +47,7 @@ describe("passwords.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/authenticate", + path: "/v1/passwords/authenticate", data: { password: "not-a-real-password", email: "Ada_Lovelace@example.com", @@ -65,7 +64,7 @@ describe("passwords.authenticate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/authenticate", + path: "/v1/passwords/authenticate", data: { email: "Ada_Lovelace@example.com", password: "not-a-real-password", @@ -77,12 +76,12 @@ describe("passwords.authenticate", () => { describe("passwords.resetByEmailStart", () => { test("basic", () => { return expect( - passwords.resetByEmailStart({ + passwords.email.resetStart({ email: "Ada_Lovelace@example.com", }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/email/reset/start", + path: "/v1/passwords/email/reset/start", data: { email: "Ada_Lovelace@example.com", }, @@ -90,14 +89,14 @@ describe("passwords.resetByEmailStart", () => { }); test("pkce", () => { return expect( - passwords.resetByEmailStart({ + passwords.email.resetStart({ email: "Ada_Lovelace@example.com", code_challenge: "example_code_challenge", locale: "en", }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/email/reset/start", + path: "/v1/passwords/email/reset/start", data: { code_challenge: "example_code_challenge", email: "Ada_Lovelace@example.com", @@ -109,10 +108,13 @@ describe("passwords.resetByEmailStart", () => { describe("passwords.resetByEmail", () => { test("basic", () => { return expect( - passwords.resetByEmail("example-token", "not-a-real-password") + passwords.email.reset({ + token: "example-token", + password: "not-a-real-password", + }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/email/reset", + path: "/v1/passwords/email/reset", data: { token: "example-token", password: "not-a-real-password", @@ -121,12 +123,14 @@ describe("passwords.resetByEmail", () => { }); test("pkce", () => { return expect( - passwords.resetByEmail("example-token", "not-a-real-password", { + passwords.email.reset({ + token: "example-token", + password: "not-a-real-password", code_verifier: "example_code_verifier", }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/email/reset", + path: "/v1/passwords/email/reset", data: { token: "example-token", password: "not-a-real-password", @@ -139,14 +143,14 @@ describe("passwords.resetByEmail", () => { describe("passwords.resetByExistingPassword", () => { test("basic", () => { return expect( - passwords.resetByExistingPassword({ + passwords.existingPassword.reset({ email: "Ada_Lovelace@example.com", existing_password: "existing_password", new_password: "new_password", }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/existing_password/reset", + path: "/v1/passwords/existing_password/reset", data: { email: "Ada_Lovelace@example.com", existing_password: "existing_password", @@ -159,13 +163,13 @@ describe("passwords.resetByExistingPassword", () => { describe("passwords.resetBySession", () => { test("basic", () => { return expect( - passwords.resetBySession({ + passwords.sessions.reset({ password: "new_password", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/session/reset", + path: "/v1/passwords/session/reset", data: { password: "new_password", session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", @@ -183,7 +187,7 @@ describe("passwords.strengthCheck", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/strength_check", + path: "/v1/passwords/strength_check", data: { password: "not-a-real-password", email: "Ada_Lovelace@example.com", @@ -202,7 +206,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "phpass", @@ -219,7 +223,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "bcrypt", @@ -234,17 +238,19 @@ describe("passwords.migrate", () => { hash_type: "sha_1", hash: "not-a-real-password-hash", sha_1_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "sha_1", hash: "not-a-real-password-hash", sha_1_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }, @@ -258,11 +264,12 @@ describe("passwords.migrate", () => { hash: "not-a-real-password-hash", sha_1_config: { prepend_salt: "not-a-real-salt", + append_salt: "", }, }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "sha_1", @@ -282,7 +289,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "sha_1", @@ -297,17 +304,19 @@ describe("passwords.migrate", () => { hash_type: "md_5", hash: "not-a-real-password-hash", md_5_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "md_5", hash: "not-a-real-password-hash", md_5_config: { + prepend_salt: "", append_salt: "not-a-real-salt", }, }, @@ -321,11 +330,12 @@ describe("passwords.migrate", () => { hash: "not-a-real-password-hash", md_5_config: { prepend_salt: "not-a-real-salt", + append_salt: "", }, }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "md_5", @@ -345,7 +355,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "md_5", @@ -369,7 +379,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "argon_2i", @@ -400,7 +410,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "argon_2id", @@ -431,7 +441,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "scrypt", @@ -460,7 +470,7 @@ describe("passwords.migrate", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "passwords/migrate", + path: "/v1/passwords/migrate", data: { email: "Ada_Lovelace@example.com", hash_type: "pbkdf_2", diff --git a/test/b2c/sandbox.test.ts b/test/b2c/sandbox.test.ts index 3bfdeca3..f42a3656 100644 --- a/test/b2c/sandbox.test.ts +++ b/test/b2c/sandbox.test.ts @@ -35,7 +35,9 @@ describeIf( describe("magicLinks.authenticate", () => { test("success", () => { return client.magicLinks - .authenticate("DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=") + .authenticate({ + token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", + }) .then((res) => { expect(res.status_code).toEqual(200); expect(res.user_id).toEqual( @@ -46,7 +48,9 @@ describeIf( test("magic link not authorized", () => { return client.magicLinks - .authenticate("3pzjQpgksDlGKWEwUq2Up--hCHC_0oamfLHyfspKDFU=") + .authenticate({ + token: "3pzjQpgksDlGKWEwUq2Up--hCHC_0oamfLHyfspKDFU=", + }) .catch((err) => { expect(err.status_code).toEqual(401); expect(err.error_type).toEqual("unable_to_auth_magic_link"); @@ -61,7 +65,9 @@ describeIf( test("magic link not found", () => { return client.magicLinks - .authenticate("CprTtwhnRNiMBiUS2jSLcWYrfuO2POeBNdo5HhW6qTM=") + .authenticate({ + token: "CprTtwhnRNiMBiUS2jSLcWYrfuO2POeBNdo5HhW6qTM=", + }) .catch((err) => { expect(err.status_code).toEqual(404); expect(err.error_type).toEqual("magic_link_not_found"); @@ -140,7 +146,9 @@ describeIf( describe("sessions.authenticate", () => { test("success", async () => { // Make sure there's a key that can be used to sign the sandbox JWT. - const jwks = await client.sessions.jwks(env("PROJECT_ID")); + const jwks = await client.sessions.getJWKS({ + project_id: env("PROJECT_ID"), + }); expect(jwks.keys.length).toBeGreaterThan(0); await expect( @@ -183,9 +191,9 @@ describeIf( agent, }); - await client.magicLinks.authenticate( - "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=" - ); + await client.magicLinks.authenticate({ + token: "DOYoip3rvIMMW5lgItikFK-Ak1CfMsgjuiCyI7uuU94=", + }); expect(lookupSpy).toHaveBeenCalledWith( "test.stytch.com", diff --git a/test/b2c/sessions.test.ts b/test/b2c/sessions.test.ts index 5d882edb..5c9b2204 100644 --- a/test/b2c/sessions.test.ts +++ b/test/b2c/sessions.test.ts @@ -11,14 +11,13 @@ function jwtConfig(projectID: string) { } jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); describe("sessions.get", () => { test("success", () => { mockRequest((req) => { expect(req).toEqual({ method: "GET", - path: "sessions", + path: "/v1/sessions", params: { user_id: "user-test-22222222-2222-4222-8222-222222222222", }, @@ -66,7 +65,7 @@ describe("sessions.authenticate", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "sessions/authenticate", + path: "/v1/sessions/authenticate", data: { session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", session_duration_minutes: 60, @@ -113,7 +112,7 @@ describe("sessions.revoke", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "sessions/revoke", + path: "/v1/sessions/revoke", data: { session_token: "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q", }, @@ -136,12 +135,13 @@ describe("sessions.revoke", () => { }); }); -describe("sessions.jwks", () => { +describe("sessions.getJWKS", () => { test("success", () => { mockRequest((req) => { expect(req).toEqual({ method: "GET", - path: "sessions/jwks/project-test-11111111-1111-4111-8111-111111111111", + path: "/v1/sessions/jwks/project-test-11111111-1111-4111-8111-111111111111", + params: {}, }); return { status: 200, data: {} }; @@ -152,7 +152,9 @@ describe("sessions.jwks", () => { ); return expect( - sessions.jwks("project-test-11111111-1111-4111-8111-111111111111") + sessions.getJWKS({ + project_id: "project-test-11111111-1111-4111-8111-111111111111", + }) ).resolves.toEqual({ status: 200 }); }); }); @@ -162,7 +164,7 @@ describe("sessions.authenticateJwt", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "sessions/authenticate", + path: "/v1/sessions/authenticate", data: { session_jwt: "stale_jwt", }, diff --git a/test/b2c/totps.test.ts b/test/b2c/totps.test.ts index c91596bc..abb98bc1 100644 --- a/test/b2c/totps.test.ts +++ b/test/b2c/totps.test.ts @@ -2,14 +2,13 @@ import { TOTPs } from "../../lib/b2c/totps"; import { MOCK_FETCH_CONFIG, mockRequest } from "../helpers"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); describe("totps.create", () => { test("only required fields", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "totps", + path: "/v1/totps", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", }, @@ -68,7 +67,7 @@ describe("totps.create", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "totps", + path: "/v1/totps", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", expiration_minutes: 10, @@ -132,7 +131,7 @@ describe("totps.authenticate", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "totps/authenticate", + path: "/v1/totps/authenticate", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", totp_code: "111111", @@ -164,7 +163,7 @@ describe("totps.authenticate", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "totps/authenticate", + path: "/v1/totps/authenticate", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", totp_code: "111111", @@ -214,7 +213,7 @@ describe("totps.recovery_codes", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "totps/recovery_codes", + path: "/v1/totps/recovery_codes", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", }, @@ -282,7 +281,7 @@ describe("totp.recover", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "totps/recover", + path: "/v1/totps/recover", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", recovery_code: "1111-1111-1111", @@ -315,7 +314,7 @@ describe("totp.recover", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "totps/recover", + path: "/v1/totps/recover", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", recovery_code: "1111-1111-1111", diff --git a/test/b2c/users.test.ts b/test/b2c/users.test.ts index ddbb6609..9f80476e 100644 --- a/test/b2c/users.test.ts +++ b/test/b2c/users.test.ts @@ -1,8 +1,4 @@ -import { - Users, - UserSearchIterator, - UserSearchOperator, -} from "../../lib/b2c/users"; +import { Users, UserSearchIterator } from "../../lib/b2c/users"; import { MOCK_FETCH_CONFIG, mockRequest } from "../helpers"; import { request } from "../../lib/shared"; @@ -10,7 +6,6 @@ import { request } from "../../lib/shared"; const users = new Users(MOCK_FETCH_CONFIG); jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); beforeEach(() => { (request as jest.Mock).mockReset(); @@ -33,7 +28,7 @@ describe("users.create", () => { }) ).resolves.toMatchObject({ method: "POST", - path: "users", + path: "/v1/users", data: { email: "sandbox@stytch.com", trusted_metadata: { key1: "value1" }, @@ -45,10 +40,10 @@ describe("users.create", () => { describe("users.get", () => { test("success", () => { return expect( - users.get("user-test-22222222-2222-4222-8222-222222222222") + users.get({ user_id: "user-test-22222222-2222-4222-8222-222222222222" }) ).resolves.toMatchObject({ method: "GET", - path: "users/user-test-22222222-2222-4222-8222-222222222222", + path: "/v1/users/user-test-22222222-2222-4222-8222-222222222222", }); }); }); @@ -58,11 +53,11 @@ describe("users.search", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "users/search", + path: "/v1/users/search", data: { limit: 200, query: { - operator: UserSearchOperator.OR, + operator: "OR", operands: [ { filter_name: "status", filter_value: "active" }, { filter_name: "phone_number_fuzzy", filter_value: "1234" }, @@ -98,7 +93,7 @@ describe("users.search", () => { users.search({ limit: 200, query: { - operator: UserSearchOperator.OR, + operator: "OR", operands: [ { filter_name: "status", filter_value: "active" }, { filter_name: "phone_number_fuzzy", filter_value: "1234" }, @@ -192,7 +187,8 @@ describe("User Search iteration", () => { describe("users.update", () => { test("success", () => { return expect( - users.update("user-test-22222222-2222-4222-8222-222222222222", { + users.update({ + user_id: "user-test-22222222-2222-4222-8222-222222222222", name: { first_name: "First", last_name: "Last", @@ -206,7 +202,7 @@ describe("users.update", () => { }) ).resolves.toMatchObject({ method: "PUT", - path: "users/user-test-22222222-2222-4222-8222-222222222222", + path: "/v1/users/user-test-22222222-2222-4222-8222-222222222222", data: { name: { first_name: "First", @@ -226,10 +222,12 @@ describe("users.update", () => { describe("users.delete", () => { test("success", () => { return expect( - users.delete("user-test-22222222-2222-4222-8222-222222222222") + users.delete({ + user_id: "user-test-22222222-2222-4222-8222-222222222222", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/user-test-22222222-2222-4222-8222-222222222222", + path: "/v1/users/user-test-22222222-2222-4222-8222-222222222222", }); }); }); @@ -237,10 +235,12 @@ describe("users.delete", () => { describe("users.deleteEmail", () => { test("success", () => { return expect( - users.deleteEmail("email-test-33333333-3333-4333-8333-333333333333") + users.deleteEmail({ + email_id: "email-test-33333333-3333-4333-8333-333333333333", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/emails/email-test-33333333-3333-4333-8333-333333333333", + path: "/v1/users/emails/email-test-33333333-3333-4333-8333-333333333333", }); }); }); @@ -248,12 +248,12 @@ describe("users.deleteEmail", () => { describe("users.deletePhoneNumber", () => { test("success", () => { return expect( - users.deletePhoneNumber( - "phone-number-test-33333333-3333-4333-8333-333333333333" - ) + users.deletePhoneNumber({ + phone_id: "phone-number-test-33333333-3333-4333-8333-333333333333", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/phone_numbers/phone-number-test-33333333-3333-4333-8333-333333333333", + path: "/v1/users/phone_numbers/phone-number-test-33333333-3333-4333-8333-333333333333", }); }); }); @@ -261,12 +261,13 @@ describe("users.deletePhoneNumber", () => { describe("users.deleteWebAuthnRegistration", () => { test("success", () => { return expect( - users.deleteWebAuthnRegistration( - "webauthn-registration-test-33333333-3333-4333-8333-333333333333" - ) + users.deleteWebAuthnRegistration({ + webauthn_registration_id: + "webauthn-registration-test-33333333-3333-4333-8333-333333333333", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/webauthn_registrations/webauthn-registration-test-33333333-3333-4333-8333-333333333333", + path: "/v1/users/webauthn_registrations/webauthn-registration-test-33333333-3333-4333-8333-333333333333", }); }); }); @@ -274,12 +275,13 @@ describe("users.deleteWebAuthnRegistration", () => { describe("users.deleteBiometricRegistration", () => { test("success", () => { return expect( - users.deleteBiometricRegistration( - "biometric-registration-test-33333333-3333-4333-8333-333333333333" - ) + users.deleteBiometricRegistration({ + biometric_registration_id: + "biometric-registration-test-33333333-3333-4333-8333-333333333333", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/biometric_registrations/biometric-registration-test-33333333-3333-4333-8333-333333333333", + path: "/v1/users/biometric_registrations/biometric-registration-test-33333333-3333-4333-8333-333333333333", }); }); }); @@ -287,10 +289,12 @@ describe("users.deleteBiometricRegistration", () => { describe("users.deleteTOTP", () => { test("success", () => { return expect( - users.deleteTOTP("totp-test-33333333-3333-4333-8333-333333333333") + users.deleteTOTP({ + totp_id: "totp-test-33333333-3333-4333-8333-333333333333", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/totps/totp-test-33333333-3333-4333-8333-333333333333", + path: "/v1/users/totps/totp-test-33333333-3333-4333-8333-333333333333", }); }); }); @@ -298,12 +302,13 @@ describe("users.deleteTOTP", () => { describe("users.deleteCryptoWallet", () => { test("success", () => { return expect( - users.deleteCryptoWallet( - "crypto-wallet-test-33333333-3333-4333-8333-333333333333" - ) + users.deleteCryptoWallet({ + crypto_wallet_id: + "crypto-wallet-test-33333333-3333-4333-8333-333333333333", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/crypto_wallets/crypto-wallet-test-33333333-3333-4333-8333-333333333333", + path: "/v1/users/crypto_wallets/crypto-wallet-test-33333333-3333-4333-8333-333333333333", }); }); }); @@ -311,10 +316,12 @@ describe("users.deleteCryptoWallet", () => { describe("users.deletePassword", () => { test("success", () => { return expect( - users.deletePassword("password-test-33333333-3333-4333-8333-333333333333") + users.deletePassword({ + password_id: "password-test-33333333-3333-4333-8333-333333333333", + }) ).resolves.toMatchObject({ method: "DELETE", - path: "users/passwords/password-test-33333333-3333-4333-8333-333333333333", + path: "/v1/users/passwords/password-test-33333333-3333-4333-8333-333333333333", }); }); }); diff --git a/test/b2c/webauthn.test.ts b/test/b2c/webauthn.test.ts index cc2ef3a8..b5b22e31 100644 --- a/test/b2c/webauthn.test.ts +++ b/test/b2c/webauthn.test.ts @@ -2,14 +2,13 @@ import { WebAuthn } from "../../lib/b2c/webauthn"; import { MOCK_FETCH_CONFIG, mockRequest } from "../helpers"; jest.mock("../../lib/shared"); -jest.mock("../../lib/b2c/shared_b2c"); describe("webauthn.registerStart", () => { test("authenticator_type & user_agent", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "webauthn/register/start", + path: "/v1/webauthn/register/start", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", domain: "example.com", @@ -49,7 +48,7 @@ describe("webauthn.registerStart", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "webauthn/register/start", + path: "/v1/webauthn/register/start", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", domain: "example.com", @@ -86,7 +85,7 @@ describe("webauthn.register", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "webauthn/register", + path: "/v1/webauthn/register", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", public_key_credential: @@ -125,7 +124,7 @@ describe("webauthn.authenticateStart", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "webauthn/authenticate/start", + path: "/v1/webauthn/authenticate/start", data: { user_id: "user-test-d5a3b680-e8a3-40c0-b815-ab79986666d0", domain: "example.com", @@ -162,7 +161,7 @@ describe("webauthn.authenticate", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "webauthn/authenticate", + path: "/v1/webauthn/authenticate", data: { public_key_credential: '{"type": "public-key","id": "Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY","rawId": "Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY","response": {"authenticatorData": "SZYN5YgOjGh7NBcPZHZgW1_krrmihjLHmVzzuoNcl2MFYZKokg","clientDataJSON": "eyJ2eXBlOjopo2ViYBx0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiWEtEWDVJa25EWEU3by1KQlRkYTNfS1NiTXdmb3dMWDQxMldlNEFDY04tYWgiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjMwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9","signature": "MEYCIQDU1FGXEBrq3hsQ2ye1pBcYLMu7zmzLVVdcbs6R21hGyAIhAJmpdBo2Hd7P4Ks9VFKBUYbKSIioMdhl2XIIjWHNKD77","userHandle": "dXNlus1kZXZlbG9wLBC2M2E1MGI0LWEwMGEtNGU3NC89NTJmLTFlOGRhODE2nDBnMw"},"clientExtensionResults": {}}', @@ -196,7 +195,7 @@ describe("webauthn.authenticate", () => { mockRequest((req) => { expect(req).toEqual({ method: "POST", - path: "webauthn/authenticate", + path: "/v1/webauthn/authenticate", data: { public_key_credential: '{"type": "public-key","id": "Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY","rawId": "Ab6y28pCs5bVRIzSmrlufidfR57gRlEZ-KSTVGJYdkwAfR_SeaVXvdW6ND_XljM25cXYI-dSwrhjuNsj1L3uC0BHqN3mBQIzSswJneTv08RbDNZOLhjiwOEnQ03uPbL5eA7EcyinClOU_qwPMf5lowW1NSTWtaFvOlY","response": {"authenticatorData": "SZYN5YgOjGh7NBcPZHZgW1_krrmihjLHmVzzuoNcl2MFYZKokg","clientDataJSON": "eyJ2eXBlOjopo2ViYBx0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiWEtEWDVJa25EWEU3by1KQlRkYTNfS1NiTXdmb3dMWDQxMldlNEFDY04tYWgiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjMwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9","signature": "MEYCIQDU1FGXEBrq3hsQ2ye1pBcYLMu7zmzLVVdcbs6R21hGyAIhAJmpdBo2Hd7P4Ks9VFKBUYbKSIioMdhl2XIIjWHNKD77","userHandle": "dXNlus1kZXZlbG9wLBC2M2E1MGI0LWEwMGEtNGU3NC89NTJmLTFlOGRhODE2nDBnMw"},"clientExtensionResults": {}}', diff --git a/types/lib/b2b/client.d.ts b/types/lib/b2b/client.d.ts index 339255af..162c6680 100644 --- a/types/lib/b2b/client.d.ts +++ b/types/lib/b2b/client.d.ts @@ -1,22 +1,22 @@ -import { MagicLinks } from "./magic_links"; -import { Sessions } from "./sessions"; -import { Organizations } from "./organizations"; -import { SSO } from "./sso"; import { BaseClient, ClientConfig } from "../shared/client"; -import { JwtConfig } from "../shared/sessions"; import { Discovery } from "./discovery"; -import { Passwords } from "./passwords"; +import { JwtConfig } from "../shared/sessions"; +import { MagicLinks } from "./magic_links"; import { OAuth } from "./oauth"; -import { OTPs } from "./otps"; +import { Organizations } from "./organizations"; +import { OTPs } from "./otp"; +import { Passwords } from "./passwords"; +import { Sessions } from "./sessions"; +import { SSO } from "./sso"; export declare class B2BClient extends BaseClient { protected jwtConfig: JwtConfig; + discovery: Discovery; magicLinks: MagicLinks; - sessions: Sessions; oauth: OAuth; + otps: OTPs; organizations: Organizations; - sso: SSO; - discovery: Discovery; passwords: Passwords; - otps: OTPs; + sso: SSO; + sessions: Sessions; constructor(config: ClientConfig); } diff --git a/types/lib/b2b/discovery.d.ts b/types/lib/b2b/discovery.d.ts index 5fe62a04..9a4af500 100644 --- a/types/lib/b2b/discovery.d.ts +++ b/types/lib/b2b/discovery.d.ts @@ -1,71 +1,46 @@ -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import { BaseResponse, fetchConfig } from "../shared"; -import { DiscoveredOrganization } from "./organizations"; +import { fetchConfig } from "../shared"; +import { IntermediateSessions } from "./discovery_intermediate_sessions"; +import { Member, Organization } from "./organizations"; import { MfaRequired } from "./mfa"; -export interface B2BDiscoveryOrganizationsRequest { - intermediate_session_token?: string; - session_token?: string; - session_jwt?: string; -} -export interface B2BDiscoveryOrganizationsResponse extends BaseResponse { - email_address: string; - discovered_organizations: DiscoveredOrganization[]; - organization_id_hint: string | null; -} -export interface B2BDiscoveryOrganizationCreateRequest { - intermediate_session_token: string; - session_duration_minutes?: number; - session_custom_claims?: Record; - organization_name?: string; - organization_slug?: string; - organization_logo_url?: string; - trusted_metadata?: Record; - sso_jit_provisioning?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - email_allowed_domains?: string[]; - email_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; - email_invites?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - auth_methods?: "ALL_ALLOWED" | "RESTRICTED"; - allowed_auth_methods?: string[]; - mfa_policy?: "OPTIONAL" | "REQUIRED_FOR_ALL"; -} -export interface B2BDiscoveryOrganizationCreateResponse extends ResponseWithMember { - member_session: MemberSession | null; - session_token: string; - session_jwt: string; +import { Organizations } from "./discovery_organizations"; +export interface DiscoveredOrganization { + /** + * Indicates whether the Member has all of the factors needed to fully authenticate to this Organization. + * If false, the Member may need to complete an MFA step or complete a different primary authentication + * flow. See the `primary_required` and `mfa_required` fields for more details on each. + */ member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; -} -export interface B2BDiscoveryIntermediateSessionExchangeRequest { - intermediate_session_token: string; - organization_id: string; - session_duration_minutes?: number; - session_custom_claims?: Record; - locale?: "en" | "es" | "pt-br" | string; -} -export interface B2BDiscoveryIntermediateSessionExchangeResponse extends ResponseWithMember { - member_session: MemberSession | null; - session_token: string; - session_jwt: string; - member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; -} -declare class Organizations { - private fetchConfig; - constructor(fetchConfig: fetchConfig); - list(data: B2BDiscoveryOrganizationsRequest): Promise; - create(data: B2BDiscoveryOrganizationCreateRequest): Promise; -} -declare class IntermediateSessions { - private fetchConfig; - constructor(fetchConfig: fetchConfig); - exchange(data: B2BDiscoveryIntermediateSessionExchangeRequest): Promise; + organization?: Organization; + membership?: Membership; + primary_required?: PrimaryRequired; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} +export interface Membership { + type: string; + details?: Record; + /** + * The [Member object](https://stytch.com/docs/b2b/api/member-object) if one already exists, or null if one + * does not. + */ + member?: Member; +} +export interface PrimaryRequired { + /** + * If non-empty, indicates that the Organization restricts the authentication methods it allows for login + * (such as `sso` or `password`), and the end user must complete one of those authentication methods to log + * in. If empty, indicates that the Organization does not restrict the authentication method it allows for + * login, but the end user does not have any transferrable primary factors. Only email magic link and OAuth + * factors can be transferred between Organizations. + */ + allowed_auth_methods: string[]; } export declare class Discovery { private fetchConfig; - organizations: Organizations; intermediateSessions: IntermediateSessions; + organizations: Organizations; constructor(fetchConfig: fetchConfig); } -export {}; diff --git a/types/lib/b2b/discovery_intermediate_sessions.d.ts b/types/lib/b2b/discovery_intermediate_sessions.d.ts new file mode 100644 index 00000000..2d2fdf81 --- /dev/null +++ b/types/lib/b2b/discovery_intermediate_sessions.d.ts @@ -0,0 +1,138 @@ +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +export interface B2BDiscoveryIntermediateSessionsExchangeRequest { + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface B2BDiscoveryIntermediateSessionsExchangeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + session_token: string; + session_jwt: string; + member: Member; + organization: Organization; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * The returned Intermediate Session Token is identical to the one that was originally passed in to the + * request. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ + intermediate_session_token: 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; + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} +export declare class IntermediateSessions { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Exchange an Intermediate Session for a fully realized + * [Member Session](https://stytch.com/docs/b2b/api/session-object) in a desired + * [Organization](https://stytch.com/docs/b2b/api/organization-object). + * This operation consumes the Intermediate Session. + * + * This endpoint can be used to accept invites and create new members via domain matching. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`. + * The `intermediate_session_token` will not be consumed and instead will be returned in the response. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BDiscoveryIntermediateSessionsExchangeRequest} + * @returns {@link B2BDiscoveryIntermediateSessionsExchangeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + exchange(data: B2BDiscoveryIntermediateSessionsExchangeRequest): Promise; +} diff --git a/types/lib/b2b/discovery_organizations.d.ts b/types/lib/b2b/discovery_organizations.d.ts new file mode 100644 index 00000000..9b2e0a12 --- /dev/null +++ b/types/lib/b2b/discovery_organizations.d.ts @@ -0,0 +1,299 @@ +import { DiscoveredOrganization } from "./discovery"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +export interface B2BDiscoveryOrganizationsCreateRequest { + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + /** + * The name of the Organization. If the name is not specified, a default name will be created based on the + * email used to initiate the discovery flow. If the email domain is a common email provider such as + * gmail.com, or if the email is a .edu email, the organization name will be generated based on the name + * portion of the email. Otherwise, the organization name will be generated based on the email domain. + */ + 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: `-` `.` `_` `~`. If the slug is not + * specified, a default slug will be created based on the email used to initiate the discovery flow. If the + * email domain is a common email provider such as gmail.com, or if the email is a .edu email, the + * organization slug will be generated based on the name portion of the email. Otherwise, the organization + * slug will be generated based on the email domain. + */ + organization_slug: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; + organization_logo_url?: string; + trusted_metadata?: Record; + /** + * 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 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ + 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: + * + * `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?: string; + /** + * 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?: string; + /** + * 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`, and `microsoft_oauth`. + * + */ + allowed_auth_methods?: string[]; + /** + * (Coming Soon) 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; +} +export interface B2BDiscoveryOrganizationsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + session_token: string; + session_jwt: string; + member: Member; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * The returned Intermediate Session Token is identical to the one that was originally passed in to the + * request. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ + intermediate_session_token: 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; + member_session?: MemberSession; + organization?: Organization; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} +export interface B2BDiscoveryOrganizationsListRequest { + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token?: string; + session_token?: string; + session_jwt?: string; +} +export interface B2BDiscoveryOrganizationsListResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + email_address: string; + /** + * An array of `discovered_organization` objects tied to the `intermediate_session_token`, `session_token`, + * or `session_jwt`. See the + * [Discovered Organization Object](https://stytch.com/docs/b2b/api/discovered-organization-object) for + * complete details. + * + * Note that Organizations will only appear here under any of the following conditions: + * 1. The end user is already a Member of the Organization. + * 2. The end user is invited to the Organization. + * 3. The end user can join the Organization because: + * + * a) The Organization allows JIT provisioning. + * + * b) The Organizations' allowed domains list contains the Member's email domain. + * + * c) The Organization has at least one other Member with a verified email address with the same + * domain as the end user (to prevent phishing attacks). + */ + discovered_organizations: DiscoveredOrganization[]; + /** + * 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; + /** + * If the intermediate session token is associated with a specific Organization, that Organization ID will + * be returned here. The Organization ID will be null if the intermediate session token was generated by a + * email magic link discovery or OAuth discovery flow. If a session token or session JWT is provided, the + * Organization ID hint will be null. + */ + organization_id_hint?: string; +} +export declare class Organizations { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * If an end user does not want to join any already-existing organization, or has no possible organizations + * to join, this endpoint can be used to create a new + * [Organization](https://stytch.com/docs/b2b/api/organization-object) and + * [Member](https://stytch.com/docs/b2b/api/member-object). + * + * This operation consumes the Intermediate Session. + * + * This endpoint can also be used to start an initial session for the newly created member and organization. + * + * (Coming Soon) If the new Organization is created with a `mfa_policy` of `REQUIRED_FOR_ALL`, the newly + * created Member will need to complete an MFA step to log in to the Organization. + * The `intermediate_session_token` will not be consumed and instead will be returned in the response. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BDiscoveryOrganizationsCreateRequest} + * @returns {@link B2BDiscoveryOrganizationsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: B2BDiscoveryOrganizationsCreateRequest): Promise; + /** + * List all possible organization relationships connected to a + * [Member Session](https://stytch.com/docs/b2b/api/session-object) or Intermediate Session. + * + * When a Member Session is passed in, relationships with a type of `active_member`, `pending_member`, or + * `invited_member` + * will be returned, and any membership can be assumed by calling the + * [Exchange Session](https://stytch.com/docs/b2b/api/exchange-session) endpoint. + * + * When an Intermediate Session is passed in, all relationship types - `active_member`, `pending_member`, + * `invited_member`, + * and `eligible_to_join_by_email_domain` - will be returned, + * and any membership can be assumed by calling the + * [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) endpoint. + * + * This endpoint requires either an `intermediate_session_token`, `session_jwt` or `session_token` be + * included in the request. + * It will return an error if multiple are present. + * + * This operation does not consume the Intermediate Session or Session Token passed in. + * @param data {@link B2BDiscoveryOrganizationsListRequest} + * @returns {@link B2BDiscoveryOrganizationsListResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + list(data: B2BDiscoveryOrganizationsListRequest): Promise; +} diff --git a/types/lib/b2b/index.d.ts b/types/lib/b2b/index.d.ts index c54469e3..9c069e4f 100644 --- a/types/lib/b2b/index.d.ts +++ b/types/lib/b2b/index.d.ts @@ -1,12 +1,22 @@ -export type { B2BAuthenticationFactor, MemberSession, Member, SSORegistration, OAuthRegistration, } from "./shared_b2b"; -export type { B2BDiscoveryIntermediateSessionExchangeRequest, B2BDiscoveryIntermediateSessionExchangeResponse, B2BDiscoveryOrganizationCreateRequest, B2BDiscoveryOrganizationCreateResponse, B2BDiscoveryOrganizationsRequest, B2BDiscoveryOrganizationsResponse, } from "./discovery"; -export type { B2BMagicLinksAuthenticateRequest, B2BMagicLinksAuthenticateResponse, B2BMagicLinksInviteByEmailRequest, B2BMagicLinksInviteByEmailResponse, B2BMagicLinksDiscoveryAuthenticateRequest, B2BMagicLinksDiscoveryAuthenticateResponse, B2BMagicLinksDiscoveryByEmailRequest, B2BMagicLinksDiscoveryByEmailResponse, B2BMagicLinksLoginOrSignupByEmailRequest, B2BMagicLinksLoginOrSignupByEmailResponse, } from "./magic_links"; -export type { B2BMemberCreateRequest, B2BMemberCreateResponse, B2BMemberGetRequest, B2BMemberGetResponse, B2BMemberUpdateRequest, B2BMemberUpdateResponse, B2BMemberDeleteRequest, B2BMemberDeleteResponse, B2BMemberSearchRequest, B2BMemberSearchResponse, } from "./members"; -export type { B2BOIDCCreateConnectionRequest, B2BOIDCCreateConnectionResponse, B2BOIDCUpdateConnectionRequest, B2BOIDCUpdateConnectionResponse, } from "./oidc"; -export type { B2BOAuthAuthenticateRequest, B2BOAuthAuthenticateResponse, B2BDiscoveryOAuthAuthenticateRequest, B2BDiscoveryOAuthAuthenticateResponse, } from "./oauth"; -export type { B2BOrganizationCreateRequest, B2BOrganizationCreateResponse, B2BOrganizationGetRequest, B2BOrganizationGetResponse, B2BOrganizationUpdateRequest, B2BOrganizationUpdateResponse, B2BOrganizationSearchRequest, B2BOrganizationSearchResponse, B2BOrganizationDeleteRequest, B2BOrganizationDeleteResponse, Organization, DiscoveredOrganization, } from "./organizations"; -export type { B2BPasswordsAuthenticateRequest, B2BPasswordsAuthenticateResponse, B2BPasswordsMigrateRequest, B2BPasswordsMigrateResponse, B2BPasswordsStrengthCheckRequest, B2BPasswordsStrengthCheckResponse, B2BPasswordsEmailResetStartRequest, B2BPasswordsEmailResetStartResponse, B2BPasswordsEmailResetRequest, B2BPasswordsEmailResetResponse, B2BPasswordsExistingPasswordResetRequest, B2BPasswordsExistingPasswordResetResponse, B2BPasswordsSessionResetRequest, B2BPasswordsSessionResetResponse, } from "./passwords"; -export type { B2BSAMLCreateConnectionRequest, B2BSAMLCreateConnectionResponse, B2BSAMLUpdateConnectionRequest, B2BSAMLUpdateConnectionResponse, B2BSAMLDeleteVerificationCertificateRequest, B2BSAMLDeleteVerificationCertificateResponse, } from "./saml"; -export type { B2BSessionsAuthenticateRequest, B2BSessionsAuthenticateResponse, B2BSessionsGetRequest, B2BSessionsGetResponse, B2BSessionsExchangeRequest, B2BSessionsExchangeResponse, B2BSessionsRevokeRequest, B2BSessionsRevokeResponse, B2BSessionsJwksResponse, } from "./sessions"; -export type { B2BSSOAuthenticateRequest, B2BSSOAuthenticateResponse, B2BSSOGetConnectionsRequest, B2BSSOGetConnectionsResponse, B2BSSODeleteConnectionRequest, B2BSSODeleteConnectionResponse, X509Certificate, SAMLConnection, OIDCConnection, } from "./sso"; -export type { B2BOTPsSMSSendRequest, B2BOTPsSMSSendResponse, B2BOTPsSMSAuthenticateRequest, B2BOTPsSMSAuthenticateResponse, } from "./otps"; +export type { SearchQueryOperand } from "./organizations"; +export type { MemberOptions, MfaRequired } from "./mfa"; +export type { ActiveSSOConnection, Member, OAuthRegistration, Organization, B2BOrganizationsResultsMetadata, SSORegistration, SearchQuery, B2BOrganizationsCreateRequest, B2BOrganizationsCreateResponse, B2BOrganizationsDeleteRequest, B2BOrganizationsDeleteResponse, B2BOrganizationsGetRequest, B2BOrganizationsGetResponse, B2BOrganizationsSearchRequest, B2BOrganizationsSearchResponse, B2BOrganizationsUpdateRequest, B2BOrganizationsUpdateResponse, } from "./organizations"; +export type { B2BOrganizationsMembersCreateRequest, B2BOrganizationsMembersCreateResponse, B2BOrganizationsMembersDeleteMFAPhoneNumberRequest, B2BOrganizationsMembersDeleteMFAPhoneNumberResponse, B2BOrganizationsMembersDeletePasswordRequest, B2BOrganizationsMembersDeletePasswordResponse, B2BOrganizationsMembersDeleteRequest, B2BOrganizationsMembersDeleteResponse, B2BOrganizationsMembersGetRequest, B2BOrganizationsMembersGetResponse, B2BOrganizationsMembersSearchRequest, B2BOrganizationsMembersSearchResponse, B2BOrganizationsMembersUpdateRequest, B2BOrganizationsMembersUpdateResponse, } from "./organizations_members"; +export type { MemberSession, B2BSessionsAuthenticateRequest, B2BSessionsAuthenticateResponse, B2BSessionsExchangeRequest, B2BSessionsExchangeResponse, B2BSessionsGetJWKSRequest, B2BSessionsGetJWKSResponse, B2BSessionsGetRequest, B2BSessionsGetResponse, B2BSessionsRevokeRequest, B2BSessionsRevokeResponse, } from "./sessions"; +export type { DiscoveredOrganization, Membership, PrimaryRequired, } from "./discovery"; +export type { B2BDiscoveryIntermediateSessionsExchangeRequest, B2BDiscoveryIntermediateSessionsExchangeResponse, } from "./discovery_intermediate_sessions"; +export type { B2BDiscoveryOrganizationsCreateRequest, B2BDiscoveryOrganizationsCreateResponse, B2BDiscoveryOrganizationsListRequest, B2BDiscoveryOrganizationsListResponse, } from "./discovery_organizations"; +export type { B2BMagicLinksAuthenticateRequest, B2BMagicLinksAuthenticateResponse, } from "./magic_links"; +export type { B2BMagicLinksEmailInviteRequest, B2BMagicLinksEmailInviteResponse, B2BMagicLinksEmailLoginOrSignupRequest, B2BMagicLinksEmailLoginOrSignupResponse, } from "./magic_links_email"; +export type { B2BMagicLinksEmailDiscoverySendRequest, B2BMagicLinksEmailDiscoverySendResponse, } from "./magic_links_email_discovery"; +export type { B2BMagicLinksDiscoveryAuthenticateRequest, B2BMagicLinksDiscoveryAuthenticateResponse, } from "./magic_links_discovery"; +export type { B2BOAuthProviderValues, B2BOAuthAuthenticateRequest, B2BOAuthAuthenticateResponse, } from "./oauth"; +export type { B2BOAuthDiscoveryAuthenticateRequest, B2BOAuthDiscoveryAuthenticateResponse, } from "./oauth_discovery"; +export type { B2BOTPSmsAuthenticateRequest, B2BOTPSmsAuthenticateResponse, B2BOTPSmsSendRequest, B2BOTPSmsSendResponse, } from "./otp_sms"; +export type { LudsFeedback, ZxcvbnFeedback, B2BPasswordsAuthenticateRequest, B2BPasswordsAuthenticateResponse, B2BPasswordsMigrateRequest, B2BPasswordsMigrateResponse, B2BPasswordsStrengthCheckRequest, B2BPasswordsStrengthCheckResponse, } from "./passwords"; +export type { B2BPasswordsEmailResetRequest, B2BPasswordsEmailResetResponse, B2BPasswordsEmailResetStartRequest, B2BPasswordsEmailResetStartResponse, } from "./passwords_email"; +export type { B2BPasswordsSessionResetRequest, B2BPasswordsSessionResetResponse, } from "./passwords_session"; +export type { B2BPasswordsExistingPasswordResetRequest, B2BPasswordsExistingPasswordResetResponse, } from "./passwords_existing_password"; +export type { OIDCConnection, SAMLConnection, X509Certificate, B2BSSOAuthenticateRequest, B2BSSOAuthenticateResponse, B2BSSODeleteConnectionRequest, B2BSSODeleteConnectionResponse, B2BSSOGetConnectionsRequest, B2BSSOGetConnectionsResponse, } from "./sso"; +export type { B2BSSOOIDCCreateConnectionRequest, B2BSSOOIDCCreateConnectionResponse, B2BSSOOIDCUpdateConnectionRequest, B2BSSOOIDCUpdateConnectionResponse, } from "./sso_oidc"; +export type { B2BSSOSAMLCreateConnectionRequest, B2BSSOSAMLCreateConnectionResponse, B2BSSOSAMLDeleteVerificationCertificateRequest, B2BSSOSAMLDeleteVerificationCertificateResponse, B2BSSOSAMLUpdateConnectionRequest, B2BSSOSAMLUpdateConnectionResponse, } from "./sso_saml"; diff --git a/types/lib/b2b/magic_links.d.ts b/types/lib/b2b/magic_links.d.ts index 19ef47ff..9ff8f378 100644 --- a/types/lib/b2b/magic_links.d.ts +++ b/types/lib/b2b/magic_links.d.ts @@ -1,96 +1,156 @@ -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import { BaseResponse, fetchConfig } from "../shared"; -import { DiscoveredOrganization } from "./organizations"; +import { Discovery } from "./magic_links_discovery"; +import { Email } from "./magic_links_email"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; import { MfaRequired } from "./mfa"; -export interface B2BMagicLinksLoginOrSignupByEmailRequest { - organization_id: string; - email_address: string; - login_redirect_url?: string; - signup_redirect_url?: string; - pkce_code_challenge?: string; - login_template_id?: string; - signup_template_id?: string; - locale?: "en" | "es" | "pt-br" | string; -} -export interface B2BMagicLinksLoginOrSignupByEmailResponse extends ResponseWithMember { - member_created: boolean; -} -export interface B2BMagicLinksInviteByEmailRequest { - organization_id: string; - email_address: string; - name?: string; - invite_redirect_url?: string; - invited_by_member_id?: string; - invite_template_id?: string; - trusted_metadata?: Record; - untrusted_metadata?: Record; - locale?: "en" | "es" | "pt-br" | string; -} -export declare type B2BMagicLinksInviteByEmailResponse = ResponseWithMember; export interface B2BMagicLinksAuthenticateRequest { magic_links_token: string; + pkce_code_verifier?: string; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_token`, Stytch will + * update the session. + * If the `session_token` and `magic_links_token` belong to different Members, the `session_token` + * will be ignored. This endpoint will error if + * both `session_token` and `session_jwt` are provided. + */ session_token?: string; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_jwt`, Stytch will + * update the session. If the `session_jwt` + * and `magic_links_token` belong to different Members, the `session_jwt` will be ignored. This + * endpoint will error if both `session_token` and `session_jwt` + * are provided. + */ session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; - pkce_code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BMagicLinksAuthenticateResponse extends ResponseWithMember { - organization_id: string; +export interface B2BMagicLinksAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; method_id: string; - member_session: MemberSession | null; - session_token?: string; - session_jwt?: string; + /** + * Indicates if all Sessions linked to the Member need to be reset. You should check this field if you + * aren't using + * Stytch's Session product. If you are using Stytch's Session product, we revoke the Member’s other + * Sessions for you. + */ reset_sessions: boolean; - member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; -} -export interface B2BMagicLinksDiscoveryByEmailRequest { - email_address: string; - discovery_redirect_url?: string; - pkce_code_challenge?: string; - login_template_id?: string; - locale?: "en" | "es" | "pt-br" | string; -} -export declare type B2BMagicLinksDiscoveryByEmailResponse = BaseResponse; -export interface B2BMagicLinksDiscoveryAuthenticateRequest { - discovery_magic_links_token: string; - pkce_code_verifier?: string; -} -export interface B2BMagicLinksDiscoveryAuthenticateResponse extends BaseResponse { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + member: Member; + session_token: string; + session_jwt: string; + member_session: MemberSession; + organization: Organization; + /** + * The returned Intermediate Session Token contains an Email Magic Link factor associated with the Member's + * email address. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization that allows login with Email Magic Links, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ intermediate_session_token: string; - email_address: string; - discovered_organizations: DiscoveredOrganization[]; -} -declare class EmailDiscovery { - private fetchConfig; - constructor(fetchConfig: fetchConfig); - send(data: B2BMagicLinksDiscoveryByEmailRequest): Promise; -} -declare class Discovery { - private fetchConfig; - constructor(fetchConfig: fetchConfig); - authenticate(data: B2BMagicLinksDiscoveryAuthenticateRequest): Promise; -} -declare class Email { - private base_path; - private delivery; - private fetchConfig; - discovery: EmailDiscovery; - constructor(fetchConfig: fetchConfig, parent_path: string); - private endpoint; - loginOrSignup(data: B2BMagicLinksLoginOrSignupByEmailRequest): Promise; - invite(data: B2BMagicLinksInviteByEmailRequest): Promise; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } export declare class MagicLinks { - private base_path; + private fetchConfig; email: Email; discovery: Discovery; - private fetchConfig; constructor(fetchConfig: fetchConfig); - private endpoint; + /** + * Authenticate a Member with a Magic Link. This endpoint requires a Magic Link token that is not expired + * or previously used. If the Member’s status is `pending` or `invited`, they will be updated to `active`. + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. If the + * `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 minute + * duration. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BMagicLinksAuthenticateRequest} + * @returns {@link B2BMagicLinksAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate(data: B2BMagicLinksAuthenticateRequest): Promise; } -export {}; diff --git a/types/lib/b2b/magic_links_discovery.d.ts b/types/lib/b2b/magic_links_discovery.d.ts new file mode 100644 index 00000000..7c4851b3 --- /dev/null +++ b/types/lib/b2b/magic_links_discovery.d.ts @@ -0,0 +1,65 @@ +import { DiscoveredOrganization } from "./discovery"; +import { fetchConfig } from "../shared"; +export interface B2BMagicLinksDiscoveryAuthenticateRequest { + discovery_magic_links_token: string; + pkce_code_verifier?: string; +} +export interface B2BMagicLinksDiscoveryAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + email_address: string; + /** + * An array of `discovered_organization` objects tied to the `intermediate_session_token`, `session_token`, + * or `session_jwt`. See the + * [Discovered Organization Object](https://stytch.com/docs/b2b/api/discovered-organization-object) for + * complete details. + * + * Note that Organizations will only appear here under any of the following conditions: + * 1. The end user is already a Member of the Organization. + * 2. The end user is invited to the Organization. + * 3. The end user can join the Organization because: + * + * a) The Organization allows JIT provisioning. + * + * b) The Organizations' allowed domains list contains the Member's email domain. + * + * c) The Organization has at least one other Member with a verified email address with the same + * domain as the end user (to prevent phishing attacks). + */ + discovered_organizations: DiscoveredOrganization[]; + /** + * 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; +} +export declare class Discovery { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Authenticates the Discovery Magic Link token and exchanges it for an Intermediate Session Token. + * Intermediate Session Tokens can be used for various Discovery login flows and are valid for 10 minutes. + * @param data {@link B2BMagicLinksDiscoveryAuthenticateRequest} + * @returns {@link B2BMagicLinksDiscoveryAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: B2BMagicLinksDiscoveryAuthenticateRequest): Promise; +} diff --git a/types/lib/b2b/magic_links_email.d.ts b/types/lib/b2b/magic_links_email.d.ts new file mode 100644 index 00000000..c5180335 --- /dev/null +++ b/types/lib/b2b/magic_links_email.d.ts @@ -0,0 +1,165 @@ +import { Discovery } from "./magic_links_email_discovery"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +export interface B2BMagicLinksEmailInviteRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + 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; + invited_by_member_id?: string; + name?: string; + trusted_metadata?: Record; + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; + /** + * 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; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface B2BMagicLinksEmailInviteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + /** + * 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; +} +export interface B2BMagicLinksEmailLoginOrSignupRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + email_address: string; + /** + * The URL that the Member clicks from the login 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 login. 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 Member clicks from the signup 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 login. 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; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + pkce_code_challenge?: string; + /** + * Use a custom template for login emails. By default, it will use your default email template. The + * template must be from Stytch's + * built-in customizations or a custom HTML email for Magic Links - Login. + */ + login_template_id?: string; + /** + * Use a custom template for signup emails. By default, it will use your default email template. The + * template must be from Stytch's + * built-in customizations or a custom HTML email for Magic Links - Signup. + */ + 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface B2BMagicLinksEmailLoginOrSignupResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + /** + * A flag indicating `true` if a new Member object was created and `false` if the Member object already + * existed. + */ + member_created: boolean; + member: Member; + organization: Organization; + /** + * 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; +} +export declare class Email { + private fetchConfig; + discovery: Discovery; + constructor(fetchConfig: fetchConfig); + /** + * Send either a login or signup magic link to a Member. A new, pending, or invited Member will receive a + * signup Email Magic Link. Members will have a `pending` status until they successfully authenticate. An + * active Member will receive a login Email Magic Link. + * @param data {@link B2BMagicLinksEmailLoginOrSignupRequest} + * @returns {@link B2BMagicLinksEmailLoginOrSignupResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrSignup(data: B2BMagicLinksEmailLoginOrSignupRequest): Promise; + /** + * Send an invite email to a new Member to join an Organization. The Member will be created with an + * `invited` status until they successfully authenticate. Sending invites to `pending` Members will update + * their status to `invited`. Sending invites to already `active` Members will return an error. + * @param data {@link B2BMagicLinksEmailInviteRequest} + * @returns {@link B2BMagicLinksEmailInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + invite(data: B2BMagicLinksEmailInviteRequest): Promise; +} diff --git a/types/lib/b2b/magic_links_email_discovery.d.ts b/types/lib/b2b/magic_links_email_discovery.d.ts new file mode 100644 index 00000000..50ff4819 --- /dev/null +++ b/types/lib/b2b/magic_links_email_discovery.d.ts @@ -0,0 +1,61 @@ +import { fetchConfig } from "../shared"; +export interface B2BMagicLinksEmailDiscoverySendRequest { + email_address: string; + /** + * The URL that the end user clicks from the discovery Magic Link. This URL should be an endpoint in the + * backend server that + * verifies the request by querying Stytch's discovery authenticate endpoint and continues the flow. 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; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + pkce_code_challenge?: string; + /** + * Use a custom template for discovery emails. By default, it will use your default email template. The + * template must be from Stytch's + * built-in customizations or a custom HTML email for Magic Links - Login. + */ + login_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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface B2BMagicLinksEmailDiscoverySendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} +export declare class Discovery { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Send a discovery magic link to an email address. + * @param data {@link B2BMagicLinksEmailDiscoverySendRequest} + * @returns {@link B2BMagicLinksEmailDiscoverySendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: B2BMagicLinksEmailDiscoverySendRequest): Promise; +} diff --git a/types/lib/b2b/members.d.ts b/types/lib/b2b/members.d.ts deleted file mode 100644 index a55226f8..00000000 --- a/types/lib/b2b/members.d.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { Member, SearchOperator, ResultsMetadata, ResponseWithMember } from "./shared_b2b"; -import { BaseResponse, fetchConfig } from "../shared"; -import { Organization } from "./organizations"; -export interface B2BMemberCreateRequest { - organization_id: string; - email_address: string; - name?: string; - trusted_metadata?: Record; - untrusted_metadata?: Record; - create_member_as_pending?: boolean; - is_breakglass?: boolean; - mfa_phone_number?: string; - mfa_enrolled?: boolean; -} -export declare type B2BMemberCreateResponse = ResponseWithMember; -export interface B2BMemberGetRequest { - organization_id: string; - member_id?: string; - email_address?: string; -} -export declare type B2BMemberGetResponse = ResponseWithMember; -export interface B2BMemberUpdateRequest { - organization_id: string; - member_id: string; - name?: string; - trusted_metadata?: Record; - untrusted_metadata?: Record; - is_breakglass?: boolean; - mfa_phone_number?: string; - mfa_enrolled?: boolean; -} -export declare type B2BMemberUpdateResponse = ResponseWithMember; -export declare type MemberSearchOperand = { - 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; -}; -export interface B2BMemberSearchRequest { - organization_ids: string[]; - limit?: number; - query?: { - operator: SearchOperator; - operands: MemberSearchOperand[]; - }; - cursor?: string | null; -} -export interface B2BMemberSearchResponse extends BaseResponse { - members: Member[]; - results_metadata: ResultsMetadata; - organizations: Record; -} -export interface B2BMemberDeleteRequest { - member_id: string; - organization_id: string; -} -export interface B2BMemberDeleteResponse extends BaseResponse { - member_id: string; -} -export interface B2BMemberDeletePhoneNumberRequest { - organization_id: string; - member_id: string; -} -export declare type B2BMemberDeletePhoneNumberResponse = ResponseWithMember; -export declare class Members { - private base_path; - private fetchConfig; - constructor(fetchConfig: fetchConfig, parent_path: string); - create(data: B2BMemberCreateRequest): Promise; - get(params: B2BMemberGetRequest): Promise; - update(data: B2BMemberUpdateRequest): Promise; - delete(data: B2BMemberDeleteRequest): Promise; - search(data: B2BMemberSearchRequest): Promise; - deletePhoneNumber(data: B2BMemberDeletePhoneNumberRequest): Promise; -} diff --git a/types/lib/b2b/mfa.d.ts b/types/lib/b2b/mfa.d.ts index 3cc87b71..b3cae9e6 100644 --- a/types/lib/b2b/mfa.d.ts +++ b/types/lib/b2b/mfa.d.ts @@ -2,6 +2,12 @@ export interface MemberOptions { mfa_phone_number: string; } export interface MfaRequired { - member_options: MemberOptions; - secondary_auth_initiated: "sms_otp" | null; + member_options?: MemberOptions; + /** + * If null, indicates that no secondary authentication has been initiated. If equal to "sms_otp", indicates + * that the Member has a phone number, and a one time passcode has been sent to the Member's phone number. + * No secondary authentication will be initiated during calls to the discovery authenticate or list + * organizations endpoints, even if the Member has a phone number. + */ + secondary_auth_initiated?: string; } diff --git a/types/lib/b2b/oauth.d.ts b/types/lib/b2b/oauth.d.ts index d2b936f9..a083fb62 100644 --- a/types/lib/b2b/oauth.d.ts +++ b/types/lib/b2b/oauth.d.ts @@ -1,58 +1,168 @@ -import { MemberSession, Member } from "./shared_b2b"; -import { BaseResponse, fetchConfig } from "../shared"; -import { DiscoveredOrganization, Organization } from "./organizations"; +import { Discovery } from "./oauth_discovery"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; import { MfaRequired } from "./mfa"; +export interface B2BOAuthProviderValues { + access_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[]; + refresh_token?: string; + expires_at?: 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 [OpenID Connect](https://openid.net/foundation/) + * specification, which is based on OAuth. + */ + id_token?: string; +} export interface B2BOAuthAuthenticateRequest { oauth_token: string; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; pkce_code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BDiscoveryOAuthAuthenticateRequest { - discovery_oauth_token: string; - pkce_code_verifier?: string; -} -export interface B2BDiscoveryOAuthAuthenticateResponse extends BaseResponse { - intermediate_session_token: string; - email_address: string; - discovered_organizations: DiscoveredOrganization[]; -} -export interface B2BOAuthAuthenticateResponse extends BaseResponse { +export interface B2BOAuthAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; member_id: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the `sub` or + * "Subject field" in OAuth protocols. + */ + provider_subject: string; + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Microsoft, GitHub + * etc. + */ + provider_type: string; + session_token: string; + session_jwt: string; member: Member; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; organization: Organization; - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; - provider_values: ProvidersValues; + reset_sessions: boolean; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ member_authenticated: boolean; + /** + * The returned Intermediate Session Token contains an OAuth factor associated with the Member's email + * address. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization that allows login with OAuth, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; -} -export interface ProvidersValues { - access_token?: string; - refresh_token?: string; - id_token?: string; - expires_at?: number; - scopes: string[]; -} -declare class Discovery { - private base_path; - private fetchConfig; - constructor(fetchConfig: fetchConfig); - private endpoint; - authenticate(data: B2BDiscoveryOAuthAuthenticateRequest): Promise; + /** + * 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; + member_session?: MemberSession; + /** + * 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` is only + * returned by Microsoft. + */ + provider_values?: B2BOAuthProviderValues; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } export declare class OAuth { - private base_path; - discovery: Discovery; private fetchConfig; + discovery: Discovery; constructor(fetchConfig: fetchConfig); - private endpoint; + /** + * Authenticate a Member given a `token`. This endpoint verifies that the member completed the OAuth flow + * by verifying that the token is valid and hasn't expired. Provide the `session_duration_minutes` + * parameter to set the lifetime of the session. If the `session_duration_minutes` parameter is not + * specified, a Stytch session will be created with a 60 minute duration. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BOAuthAuthenticateRequest} + * @returns {@link B2BOAuthAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate(data: B2BOAuthAuthenticateRequest): Promise; } -export {}; diff --git a/types/lib/b2b/oauth_discovery.d.ts b/types/lib/b2b/oauth_discovery.d.ts new file mode 100644 index 00000000..c27c1558 --- /dev/null +++ b/types/lib/b2b/oauth_discovery.d.ts @@ -0,0 +1,69 @@ +import { DiscoveredOrganization } from "./discovery"; +import { fetchConfig } from "../shared"; +export interface B2BOAuthDiscoveryAuthenticateRequest { + discovery_oauth_token: string; + session_token?: string; + session_duration_minutes?: number; + session_jwt?: string; + session_custom_claims?: Record; + pkce_code_verifier?: string; +} +export interface B2BOAuthDiscoveryAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token: string; + email_address: string; + /** + * An array of `discovered_organization` objects tied to the `intermediate_session_token`, `session_token`, + * or `session_jwt`. See the + * [Discovered Organization Object](https://stytch.com/docs/b2b/api/discovered-organization-object) for + * complete details. + * + * Note that Organizations will only appear here under any of the following conditions: + * 1. The end user is already a Member of the Organization. + * 2. The end user is invited to the Organization. + * 3. The end user can join the Organization because: + * + * a) The Organization allows JIT provisioning. + * + * b) The Organizations' allowed domains list contains the Member's email domain. + * + * c) The Organization has at least one other Member with a verified email address with the same + * domain as the end user (to prevent phishing attacks). + */ + discovered_organizations: DiscoveredOrganization[]; + /** + * 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; +} +export declare class Discovery { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Authenticates the Discovery OAuth token and exchanges it for an Intermediate Session Token. Intermediate + * Session Tokens can be used for various Discovery login flows and are valid for 10 minutes. + * @param data {@link B2BOAuthDiscoveryAuthenticateRequest} + * @returns {@link B2BOAuthDiscoveryAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: B2BOAuthDiscoveryAuthenticateRequest): Promise; +} diff --git a/types/lib/b2b/oidc.d.ts b/types/lib/b2b/oidc.d.ts deleted file mode 100644 index bd5b0cfc..00000000 --- a/types/lib/b2b/oidc.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { BaseResponse, fetchConfig } from "../shared"; -import { OIDCConnection } from "./sso"; -export interface B2BOIDCCreateConnectionRequest { - organization_id: string; - display_name?: string; -} -export interface B2BOIDCCreateConnectionResponse extends BaseResponse { - connection: OIDCConnection; -} -export interface B2BOIDCUpdateConnectionRequest { - organization_id: string; - connection_id: string; - display_name?: string; - client_id?: string; - client_secret?: string; - issuer?: string; - authorization_url?: string; - token_url?: string; - userinfo_url?: string; - jwks_url?: string; -} -export interface B2BOIDCUpdateConnectionResponse extends BaseResponse { - connection: OIDCConnection; -} -export declare class OIDC { - private readonly fetchConfig; - constructor(fetchConfig: fetchConfig); - create({ organization_id, ...data }: B2BOIDCCreateConnectionRequest): Promise; - update({ organization_id, connection_id, ...data }: B2BOIDCUpdateConnectionRequest): Promise; -} diff --git a/types/lib/b2b/organizations.d.ts b/types/lib/b2b/organizations.d.ts index 74ff6306..6eaf5f8d 100644 --- a/types/lib/b2b/organizations.d.ts +++ b/types/lib/b2b/organizations.d.ts @@ -1,139 +1,602 @@ -import { SearchOperator, ResultsMetadata, Member } from "./shared_b2b"; -import { BaseResponse, fetchConfig } from "../shared"; -import { Members } from "./members"; -import { MfaRequired } from "./mfa"; -export declare type OrganizationSearchOperand = { - filter_name: "organization_ids"; - filter_value: string[]; -} | { - filter_name: "organization_slugs"; - filter_value: string[]; -} | { - filter_name: "organization_name_fuzzy"; - filter_value: string; -} | { - filter_name: "organization_slug_fuzzy"; - filter_value: string; -} | { - filter_name: "member_emails"; - filter_value: string[]; -} | { - filter_name: "member_email_fuzzy"; - filter_value: string; -} | { - filter_name: "allowed_domains"; - filter_value: string[]; -} | { - filter_name: "allowed_domain_fuzzy"; - filter_value: string; -}; +import { fetchConfig } from "../shared"; +import { Members } from "./organizations_members"; +export interface ActiveSSOConnection { + connection_id: string; + display_name: string; +} +export interface B2BOrganizationsResultsMetadata { + 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; +} +export interface Member { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + member_id: string; + email_address: string; + status: string; + name: string; + /** + * An array of registered [SAML Connection](saml-connection-object) objects the Member has authenticated + * with. + */ + 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. Refer to the + * [Organization object](organization-object) and its `auth_methods` and `allowed_auth_methods` fields for + * more details. + */ + is_breakglass: boolean; + member_password_id: string; + oauth_registrations: OAuthRegistration[]; + /** + * (Coming Soon) 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; + mfa_phone_number: string; + trusted_metadata?: Record; + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; +} +export interface OAuthRegistration { + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Microsoft, GitHub + * etc. + */ + provider_type: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the `sub` or + * "Subject field" in OAuth protocols. + */ + provider_subject: string; + member_oauth_registration_id: 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. Google profile picture. + */ + profile_picture_url?: string; + /** + * If available, the `locale` is the Member's locale set in the OAuth identity provider that the user has + * authenticated with. + */ + locale?: string; +} export interface Organization { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; organization_name: string; - organization_slug: string; organization_logo_url: string; - trusted_metadata: Record; - sso_default_connection_id: string | null; - sso_jit_provisioning: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; + /** + * 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 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_id`s that reference + * [SAML Connection objects](https://stytch.com/docs/b2b/api/saml-connection-object). + * 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[]; - sso_active_connections: Array<{ - connection_id: string; - display_name: string; - }>; + sso_active_connections: ActiveSSOConnection[]; + /** + * 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ email_allowed_domains: string[]; - email_jit_provisioning: "RESTRICTED" | "NOT_ALLOWED"; - email_invites: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - auth_methods: "ALL_ALLOWED" | "RESTRICTED"; + /** + * The authentication setting that controls how a new Member can be provisioned by authenticating via Email + * Magic Link. The accepted values are: + * + * `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: string; + /** + * 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: string; + /** + * 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`, and `microsoft_oauth`. + * + */ allowed_auth_methods: string[]; - mfa_policy: "OPTIONAL" | "REQUIRED_FOR_ALL"; + mfa_policy: string; + trusted_metadata?: Record; + sso_default_connection_id?: string; } -export 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; - }; - member_authenticated: boolean; - primary_required: { - allowed_auth_methods: string[]; - } | null; - mfa_required: MfaRequired | null; -} -export interface B2BOrganizationCreateRequest { +export interface SSORegistration { + connection_id: string; + external_id: string; + registration_id: string; + sso_attributes?: Record; +} +export interface SearchQuery { + /** + * 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; + operands: SearchQueryOperand[]; +} +export interface B2BOrganizationsCreateRequest { organization_name: string; - organization_slug: 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; organization_logo_url?: string; trusted_metadata?: Record; - sso_jit_provisioning?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; + /** + * 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 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ email_allowed_domains?: string[]; - email_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; - email_invites?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - auth_methods?: "ALL_ALLOWED" | "RESTRICTED"; + /** + * The authentication setting that controls how a new Member can be provisioned by authenticating via Email + * Magic Link. The accepted values are: + * + * `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?: string; + /** + * 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?: string; + /** + * 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`, and `microsoft_oauth`. + * + */ allowed_auth_methods?: string[]; - mfa_policy?: "OPTIONAL" | "REQUIRED_FOR_ALL"; + /** + * (Coming Soon) 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; } -export interface B2BOrganizationCreateResponse extends BaseResponse { +export interface B2BOrganizationsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; organization: Organization; + /** + * 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; } -export interface B2BOrganizationGetRequest { +export interface B2BOrganizationsDeleteRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; } -export interface B2BOrganizationGetResponse extends BaseResponse { +export interface B2BOrganizationsDeleteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_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; +} +export interface B2BOrganizationsGetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; +} +export interface B2BOrganizationsGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; organization: Organization; + /** + * 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; } -export interface B2BOrganizationSearchRequest { +export interface B2BOrganizationsSearchRequest { + /** + * 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; - query?: { - operator: SearchOperator; - operands: OrganizationSearchOperand[]; - }; - cursor?: string | null; + /** + * 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 Organizations with no filtering applied. + */ + query?: SearchQuery; } -export interface B2BOrganizationSearchResponse extends BaseResponse { +export interface B2BOrganizationsSearchResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; organizations: Organization[]; - results_metadata: ResultsMetadata; -} -export interface B2BOrganizationDeleteRequest { - organization_id: string; + /** + * The search `results_metadata` object contains metadata relevant to your specific query like `total` and + * `next_cursor`. + */ + results_metadata: B2BOrganizationsResultsMetadata; + /** + * 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; } -export interface B2BOrganizationDeleteResponse extends BaseResponse { - organization_id: string; -} -export interface B2BOrganizationUpdateRequest { +export interface B2BOrganizationsUpdateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; 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; organization_logo_url?: string; trusted_metadata?: Record; sso_default_connection_id?: string; - sso_jit_provisioning?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; + /** + * 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_id`s that reference + * [SAML Connection objects](https://stytch.com/docs/b2b/api/saml-connection-object). + * 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. See the + * [common email domains resource](https://stytch.com/docs/b2b/api/common-email-domains) for the full list. + */ email_allowed_domains?: string[]; - email_jit_provisioning?: "RESTRICTED" | "NOT_ALLOWED"; - email_invites?: "ALL_ALLOWED" | "RESTRICTED" | "NOT_ALLOWED"; - auth_methods?: "ALL_ALLOWED" | "RESTRICTED"; + /** + * The authentication setting that controls how a new Member can be provisioned by authenticating via Email + * Magic Link. The accepted values are: + * + * `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?: string; + /** + * 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?: string; + /** + * 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`, and `microsoft_oauth`. + * + */ allowed_auth_methods?: string[]; - mfa_policy?: "OPTIONAL" | "REQUIRED_FOR_ALL"; + /** + * (Coming Soon) 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; } -export interface B2BOrganizationUpdateResponse extends BaseResponse { +export interface B2BOrganizationsUpdateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; organization: Organization; + /** + * 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; } +export declare type OrganizationSearchOperand = { + filter_name: "organization_ids"; + filter_value: string[]; +} | { + filter_name: "organization_slugs"; + filter_value: string[]; +} | { + filter_name: "organization_name_fuzzy"; + filter_value: string; +} | { + filter_name: "organization_slug_fuzzy"; + filter_value: string; +} | { + filter_name: "member_emails"; + filter_value: string[]; +} | { + filter_name: "member_email_fuzzy"; + filter_value: string; +} | { + filter_name: "allowed_domains"; + filter_value: string[]; +} | { + filter_name: "allowed_domain_fuzzy"; + filter_value: string; +}; +export declare type MemberSearchOperand = { + 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_phone_numbers"; + filter_value: string[]; +} | { + filter_name: "member_phone_number_fuzzy"; + filter_value: string; +}; +export declare type SearchQueryOperand = OrganizationSearchOperand | MemberSearchOperand | { + filter_name: string; + [key: string]: unknown; +}; export declare class Organizations { - private base_path; - members: Members; private fetchConfig; + members: Members; constructor(fetchConfig: fetchConfig); - private endpoint; - create(data: B2BOrganizationCreateRequest): Promise; - get({ organization_id, }: B2BOrganizationGetRequest): Promise; - search(data: B2BOrganizationSearchRequest): Promise; - update(data: B2BOrganizationUpdateRequest): Promise; - delete({ organization_id, }: B2BOrganizationDeleteRequest): Promise; + /** + * Creates an Organization. An `organization_name` and a unique `organization_slug` are required. + * + * By default, `email_invites` and `sso_jit_provisioning` will be set to `ALL_ALLOWED`, and `mfa_policy` + * will be set to `OPTIONAL` if no Organization authentication settings are explicitly defined in the + * request. + * + * *See the [Organization authentication settings](https://stytch.com/docs/b2b/api/org-auth-settings) + * resource to learn more about fields like `email_jit_provisioning`, `email_invites`, + * `sso_jit_provisioning`, etc., and their behaviors. + * @param data {@link B2BOrganizationsCreateRequest} + * @returns {@link B2BOrganizationsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: B2BOrganizationsCreateRequest): Promise; + /** + * Returns an Organization specified by `organization_id`. + * @param data {@link B2BOrganizationsGetRequest} + * @returns {@link B2BOrganizationsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: B2BOrganizationsGetRequest): Promise; + /** + * Updates an Organization specified by `organization_id`. An Organization must always have at least one + * auth setting set to either `RESTRICTED` or `ALL_ALLOWED` in order to provision new Members. test + * + * *See the [Organization authentication settings](https://stytch.com/docs/b2b/api/org-auth-settings) + * resource to learn more about fields like `email_jit_provisioning`, `email_invites`, + * `sso_jit_provisioning`, etc., and their behaviors. + * @param data {@link B2BOrganizationsUpdateRequest} + * @returns {@link B2BOrganizationsUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + update(data: B2BOrganizationsUpdateRequest): Promise; + /** + * Deletes an Organization specified by `organization_id`. All Members of the Organization will also be + * deleted. + * @param data {@link B2BOrganizationsDeleteRequest} + * @returns {@link B2BOrganizationsDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + delete(data: B2BOrganizationsDeleteRequest): Promise; + /** + * Search for Organizations. If you send a request with no body params, no filtering will be applied and + * the endpoint will return all Organizations. All fuzzy search filters require a minimum of three + * characters. + * @param data {@link B2BOrganizationsSearchRequest} + * @returns {@link B2BOrganizationsSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + search(data: B2BOrganizationsSearchRequest): Promise; } diff --git a/types/lib/b2b/organizations_members.d.ts b/types/lib/b2b/organizations_members.d.ts new file mode 100644 index 00000000..281d52b1 --- /dev/null +++ b/types/lib/b2b/organizations_members.d.ts @@ -0,0 +1,310 @@ +import { B2BOrganizationsResultsMetadata, Member, Organization, SearchQuery } from "./organizations"; +import { fetchConfig } from "../shared"; +export interface B2BOrganizationsMembersCreateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + email_address: string; + name?: string; + trusted_metadata?: Record; + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + 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. Refer to the + * [Organization object](organization-object) and its `auth_methods` and `allowed_auth_methods` fields for + * more details. + */ + is_breakglass?: boolean; + mfa_phone_number?: string; + /** + * (Coming Soon) 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; +} +export interface B2BOrganizationsMembersCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + /** + * 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; +} +export interface B2BOrganizationsMembersDeleteMFAPhoneNumberRequest { + organization_id: string; + member_id: string; +} +export interface B2BOrganizationsMembersDeleteMFAPhoneNumberResponse { + request_id: string; + member_id: string; + member: Member; + organization: Organization; + status_code: number; +} +export interface B2BOrganizationsMembersDeletePasswordRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + member_password_id: string; +} +export interface B2BOrganizationsMembersDeletePasswordResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + /** + * 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; +} +export interface B2BOrganizationsMembersDeleteRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; +} +export interface B2BOrganizationsMembersDeleteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_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; +} +export interface B2BOrganizationsMembersGetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id?: string; + email_address?: string; +} +export interface B2BOrganizationsMembersGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + /** + * 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; +} +export interface B2BOrganizationsMembersSearchRequest { + organization_ids: string[]; + /** + * 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?: SearchQuery; +} +export interface B2BOrganizationsMembersSearchResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + members: Member[]; + /** + * The search `results_metadata` object contains metadata relevant to your specific query like `total` and + * `next_cursor`. + */ + results_metadata: B2BOrganizationsResultsMetadata; + /** + * 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; + /** + * 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; +} +export interface B2BOrganizationsMembersUpdateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; + name?: string; + trusted_metadata?: Record; + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + 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. Refer to the + * [Organization object](organization-object) and its `auth_methods` and `allowed_auth_methods` fields for + * more details. + */ + is_breakglass?: boolean; + mfa_phone_number?: string; + /** + * (Coming Soon) 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; +} +export interface B2BOrganizationsMembersUpdateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + /** + * 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; +} +export declare class Members { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Updates a Member specified by `organization_id` and `member_id`. + * @param data {@link B2BOrganizationsMembersUpdateRequest} + * @returns {@link B2BOrganizationsMembersUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + update(data: B2BOrganizationsMembersUpdateRequest): Promise; + /** + * Deletes a Member specified by `organization_id` and `member_id`. + * @param data {@link B2BOrganizationsMembersDeleteRequest} + * @returns {@link B2BOrganizationsMembersDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + delete(data: B2BOrganizationsMembersDeleteRequest): Promise; + /** + * @param data {@link B2BOrganizationsMembersDeleteMFAPhoneNumberRequest} + * @returns {@link B2BOrganizationsMembersDeleteMFAPhoneNumberResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteMFAPhoneNumber(data: B2BOrganizationsMembersDeleteMFAPhoneNumberRequest): Promise; + /** + * Search for Members within specified Organizations. An array with at least one `organization_id` is + * required. Submitting an empty `query` returns all Members within the specified Organizations. + * + * *All fuzzy search filters require a minimum of three characters. + * @param data {@link B2BOrganizationsMembersSearchRequest} + * @returns {@link B2BOrganizationsMembersSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + search(data: B2BOrganizationsMembersSearchRequest): Promise; + /** + * Delete a Member's password. + * @param data {@link B2BOrganizationsMembersDeletePasswordRequest} + * @returns {@link B2BOrganizationsMembersDeletePasswordResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deletePassword(data: B2BOrganizationsMembersDeletePasswordRequest): Promise; + /** + * Creates a Member. An `organization_id` and `email_address` are required. + * @param data {@link B2BOrganizationsMembersCreateRequest} + * @returns {@link B2BOrganizationsMembersCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: B2BOrganizationsMembersCreateRequest): Promise; + /** + * Get a Member by `member_id` or `email_address`. + * @param data {@link B2BOrganizationsMembersGetRequest} + * @returns {@link B2BOrganizationsMembersGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: B2BOrganizationsMembersGetRequest): Promise; +} diff --git a/types/lib/b2b/otp.d.ts b/types/lib/b2b/otp.d.ts new file mode 100644 index 00000000..2f211daf --- /dev/null +++ b/types/lib/b2b/otp.d.ts @@ -0,0 +1,7 @@ +import { fetchConfig } from "../shared"; +import { Sms } from "./otp_sms"; +export declare class OTPs { + private fetchConfig; + sms: Sms; + constructor(fetchConfig: fetchConfig); +} diff --git a/types/lib/b2b/otp_sms.d.ts b/types/lib/b2b/otp_sms.d.ts new file mode 100644 index 00000000..a158b89d --- /dev/null +++ b/types/lib/b2b/otp_sms.d.ts @@ -0,0 +1,179 @@ +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +export interface B2BOTPSmsAuthenticateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; + code: string; + /** + * The Intermediate Session Token. This token does not necessarily belong to a specific instance of a + * Member, but represents a bag of factors that may be converted to a member session. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete an MFA + * flow; + * the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a specific Organization that allows the factors represented by the intermediate session token; + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member. + */ + intermediate_session_token?: string; + session_token?: string; + session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; + /** + * Optionally sets the Member’s MFA enrollment status upon a successful authentication. If the + * Organization’s MFA policy is `REQUIRED_FOR_ALL`, this field will be ignored. If this field is not passed + * in, the Member’s `mfa_enrolled` boolean will not be affected. The options are: + * + * `enroll` – sets the Member's `mfa_enrolled` boolean to `true`. The Member will be required to complete + * an MFA step upon subsequent logins to the Organization. + * + * `unenroll` – sets the Member's `mfa_enrolled` boolean to `false`. The Member will no longer be + * required to complete MFA steps when logging in to the Organization. + * + */ + set_mfa_enrollment?: string; +} +export interface B2BOTPSmsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + session_token: string; + session_jwt: 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; + member_session?: MemberSession; +} +export interface B2BOTPSmsSendRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; + mfa_phone_number?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface B2BOTPSmsSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + /** + * 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; +} +export declare class Sms { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Send a one-time passcode (OTP) to a Member's phone number. If the Member already has a phone number, + * this will send an OTP to the number associated with their `member_id`. If not, then this will send an + * OTP to the `phone_number` provided and link the `phone_number` with the Member. + * An error will be thrown if the Member already has a phone number and the provided `phone_number` does + * not match the existing one. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * If a Member has a phone number and is enrolled in MFA, then after a successful primary authentication + * event (e.g. [email magic link](https://stytch.com/docs/b2b/api/authenticate-magic-link) or + * [SSO](https://stytch.com/docs/b2b/api/sso-authenticate) login is complete), an SMS OTP will + * automatically be sent to their phone number. In that case, this endpoint should only be used for + * subsequent authentication events, such as prompting a Member for an OTP again after a period of + * inactivity. + * @param data {@link B2BOTPSmsSendRequest} + * @returns {@link B2BOTPSmsSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: B2BOTPSmsSendRequest): Promise; + /** + * Authenticates a Member's OTP code. This endpoint verifies that the code is valid and hasn't expired or + * been previously used. A given Member may only have a single active OTP code at any given time. If a + * Member requests another OTP code before the first one has expired, the first one will be invalidated. + * + * Exactly one of `intermediate_session_token`, `session_token`, or `session_jwt` must be provided in the + * request. + * If an intermediate session token is provided, this operation will consume it. + * + * If the Organization's MFA policy is `REQUIRED_FOR_ALL`, a successful OTP authentication will change the + * Member's `mfa_enrolled` status to `true` if it is not already `true`. + * If the Organization's MFA policy is `OPTIONAL`, the Member's MFA enrollment can be toggled by passing in + * a value for the `set_mfa_enrollment` field. + * + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. If the + * `session_duration_minutes` parameter is not specified, a Stytch session will be created with a duration + * of 60 minutes. + * @param data {@link B2BOTPSmsAuthenticateRequest} + * @returns {@link B2BOTPSmsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: B2BOTPSmsAuthenticateRequest): Promise; +} diff --git a/types/lib/b2b/otps.d.ts b/types/lib/b2b/otps.d.ts deleted file mode 100644 index f276b3d9..00000000 --- a/types/lib/b2b/otps.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import { fetchConfig } from "../shared"; -export interface B2BOTPsSMSSendRequest { - organization_id: string; - member_id: string; - mfa_phone_number?: string; - locale?: "en" | "es" | "pt-br" | string; -} -export declare type B2BOTPsSMSSendResponse = ResponseWithMember; -export interface B2BOTPsSMSAuthenticateRequest { - organization_id: string; - member_id: string; - code: string; - intermediate_session_token?: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; - set_mfa_enrollment?: "enroll" | "unenroll"; -} -export interface B2BOTPsSMSAuthenticateResponse extends ResponseWithMember { - session_token: string; - session_jwt: string; - member_session: MemberSession; -} -declare class SMS { - base_path: string; - delivery: string; - private fetchConfig; - constructor(fetchConfig: fetchConfig, base_path: string); - private endpoint; - send(data: B2BOTPsSMSSendRequest): Promise; - authenticate(data: B2BOTPsSMSAuthenticateRequest): Promise; -} -export declare class OTPs { - base_path: string; - sms: SMS; - constructor(fetchConfig: fetchConfig); -} -export {}; diff --git a/types/lib/b2b/passwords.d.ts b/types/lib/b2b/passwords.d.ts index 78b3b171..4ccf9a41 100644 --- a/types/lib/b2b/passwords.d.ts +++ b/types/lib/b2b/passwords.d.ts @@ -1,135 +1,325 @@ -import { BaseResponse, fetchConfig } from "../shared"; -import { MemberSession, ResponseWithMember } from "./shared_b2b"; -import * as shared from "../shared/passwords"; +import { Argon2Config, MD5Config, PBKDF2Config, SHA1Config, ScryptConfig } from "../b2c/passwords"; +import { Email } from "./passwords_email"; +import { ExistingPassword } from "./passwords_existing_password"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; import { MfaRequired } from "./mfa"; -export interface B2BPasswordsAuthenticateRequest { - organization_id: string; - email_address: string; - password: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; - locale?: "en" | "es" | "pt-br" | string; +import { Sessions } from "./passwords_session"; +export interface LudsFeedback { + has_lower_case: boolean; + has_upper_case: boolean; + has_digit: boolean; + /** + * For LUDS validation, whether the password contains at least one symbol. Any UTF8 character outside of + * a-z or A-Z may count as a valid symbol. + */ + has_symbol: boolean; + /** + * For LUDS validation, the number of complexity requirements that are missing from the password. + * Check the complexity fields to see which requirements are missing. + */ + missing_complexity: number; + /** + * For LUDS validation, this is the required length of the password that you've set minus the length of the + * password being checked. + * The user will need to add this many characters to the password to make it valid. + */ + missing_characters: number; } -export interface B2BPasswordsAuthenticateResponse extends ResponseWithMember { - organization_id: string; - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; - member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; +export interface ZxcvbnFeedback { + /** + * For zxcvbn validation, contains an end user consumable warning if the password is valid but not strong + * enough. + */ + warning: string; + /** + * For zxcvbn validation, contains end user consumable suggestions on how to improve the strength of the + * password. + */ + suggestions: string[]; } -export interface B2BPasswordsEmailResetStartRequest { +export interface B2BPasswordsAuthenticateRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; email_address: string; - login_redirect_url?: string; - reset_password_redirect_url?: string; - reset_password_expiration_minutes?: number; - reset_password_template_id?: string; - code_challenge?: string; - locale?: string; -} -export interface B2BPasswordsEmailResetStartResponse extends BaseResponse { - member_id: string; - member_email_id: string; -} -export interface B2BPasswordsEmailResetRequest { - password_reset_token: string; password: string; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; - code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BPasswordsEmailResetResponse extends ResponseWithMember { - member_email_id: string; +export interface B2BPasswordsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; - member_authenticated: boolean; + member: Member; + session_token: string; + session_jwt: string; + organization: Organization; + /** + * The returned Intermediate Session Token contains a password factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * Password factors are not transferable between Organizations, so the intermediate session token is + * not valid for use with discovery endpoints. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; -} -export interface B2BPasswordsExistingPasswordResetRequest { - email_address: string; - existing_password: string; - new_password: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; - organization_id: string; - locale?: "en" | "es" | "pt-br" | string; -} -export interface B2BPasswordsExistingPasswordResetResponse extends ResponseWithMember { - session_token?: string; - session_jwt?: string; - member_session: MemberSession | null; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ member_authenticated: boolean; - intermediate_session_token: string; - mfa_required: MfaRequired | null; + /** + * 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; + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; } -export interface B2BPasswordsSessionResetRequest { - password: string; +export interface B2BPasswordsMigrateRequest { + email_address: string; + hash: string; + /** + * The password hash used. Currently `bcrypt`, `scrypt`, `argon2i`, `argon2id`, `md_5`, `sha_1`, and + * `pbkdf_2` are supported. + */ + hash_type: "bcrypt" | "md_5" | "argon_2i" | "argon_2id" | "sha_1" | "scrypt" | "phpass" | "pbkdf_2" | string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; - session_token?: string; - session_jwt?: string; + md_5_config?: MD5Config; + argon_2_config?: Argon2Config; + sha_1_config?: SHA1Config; + scrypt_config?: ScryptConfig; + /** + * Required additional parameters for PBKDF2 hash keys. Note that we use the SHA-256 by default, please + * contact [support@stytch.com](mailto:support@stytch.com) if you use another hashing function. + */ + pbkdf_2_config?: PBKDF2Config; + name?: string; + trusted_metadata?: Record; + /** + * 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. See the + * [Metadata resource](https://stytch.com/docs/b2b/api/metadata) + * for complete field behavior details. + */ + untrusted_metadata?: Record; } -export interface B2BPasswordsSessionResetResponse extends ResponseWithMember { - member_session?: MemberSession; +export interface B2BPasswordsMigrateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + /** + * A flag indicating `true` if a new Member object was created and `false` if the Member object already + * existed. + */ + member_created: boolean; + member: Member; + organization: Organization; + /** + * 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; } export interface B2BPasswordsStrengthCheckRequest { - email_address?: string; password: string; + email_address?: string; } -export interface B2BPasswordsStrengthCheckResponse extends BaseResponse { +export interface B2BPasswordsStrengthCheckResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * Returns `true` if the password passes our password validation. We offer two validation options, + * [zxcvbn](https://stytch.com/docs/passwords#strength-requirements) is the default option which offers a + * high level of sophistication. + * We also offer [LUDS](https://stytch.com/docs/passwords#strength-requirements). If an email address is + * included in the call we also + * require that the password hasn't been compromised using built-in breach detection powered by + * [HaveIBeenPwned](https://haveibeenpwned.com/) + */ valid_password: boolean; + /** + * The score of the password determined by [zxcvbn](https://github.com/dropbox/zxcvbn). Values will be + * between 1 and 4, a 3 or greater is required to pass validation. + */ score: number; + /** + * Returns `true` if the password has been breached. Powered by + * [HaveIBeenPwned](https://haveibeenpwned.com/). + */ breached_password: boolean; strength_policy: string; + /** + * 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](mailto:support@stytch.com?subject=Password%20strength%20configuration). + * If this value is false then `breached_password` will always be `false` as well. + */ breach_detection_on_create: boolean; - zxcvbn_feedback: { - suggestions: string[]; - warning: string; - }; - luds_feedback: { - has_lower_case: boolean; - has_upper_case: boolean; - has_digit: boolean; - has_symbol: boolean; - missing_complexity: number; - missing_characters: number; - }; -} -interface MigrateRequestBase { - organization_id: string; - email_address: string; - hash: string; - name?: string; - trusted_metadata?: Record; - untrusted_metadata?: Record; -} -export declare type B2BPasswordsMigrateRequest = (shared.MD5MigrateRequest & MigrateRequestBase) | (shared.BcryptMigrateRequest & MigrateRequestBase) | (shared.Argon2IMigrateRequest & MigrateRequestBase) | (shared.Argon2IDMigrateRequest & MigrateRequestBase) | (shared.SHA1MigrateRequest & MigrateRequestBase) | (shared.ScryptMigrateRequest & MigrateRequestBase) | (shared.PHPassMigrateRequest & MigrateRequestBase) | (shared.PBKDF2MigrateRequest & MigrateRequestBase); -export interface B2BPasswordsMigrateResponse extends ResponseWithMember { - organization_id: string; - member_created: boolean; + /** + * 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; + /** + * Feedback for how to improve the password's strength using + * [luds](https://stytch.com/docs/passwords#strength-requirements). + */ + luds_feedback?: LudsFeedback; + /** + * Feedback for how to improve the password's strength using + * [zxcvbn](https://stytch.com/docs/passwords#strength-requirements). + */ + zxcvbn_feedback?: ZxcvbnFeedback; } export declare class Passwords { - base_path: string; private fetchConfig; + email: Email; + sessions: Sessions; + existingPassword: ExistingPassword; constructor(fetchConfig: fetchConfig); - private endpoint; - authenticate(data?: B2BPasswordsAuthenticateRequest): Promise; - resetByEmailStart(data: B2BPasswordsEmailResetStartRequest): Promise; - resetByEmail(data?: B2BPasswordsEmailResetRequest): Promise; - resetByExistingPassword(data: B2BPasswordsExistingPasswordResetRequest): Promise; - resetBySession(data: B2BPasswordsSessionResetRequest): Promise; + /** + * This API allows you to check whether the user’s provided password is valid, and to provide feedback to + * the user on how to increase the strength of their password. + * + * This endpoint adapts to your Project's password strength configuration. If you're using + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your passwords are + * considered valid if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are considered valid if + * they meet the requirements that you've set with Stytch. You may update your password strength + * configuration in the [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * ## Password feedback + * The zxcvbn_feedback and luds_feedback objects contains relevant fields for you to relay feedback to + * users that failed to create a strong enough password. + * + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the feedback object + * will contain warning and suggestions for any password that does not meet the + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy) strength requirements. You can return + * these strings directly to the user to help them craft a strong password. + * + * If you're using [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), the feedback object + * will contain a collection of fields that the user failed or passed. You'll want to prompt the user to + * create a password that meets all requirements that they failed. + * @param data {@link B2BPasswordsStrengthCheckRequest} + * @returns {@link B2BPasswordsStrengthCheckResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ strengthCheck(data: B2BPasswordsStrengthCheckRequest): Promise; + /** + * Adds an existing password to a member's email that doesn't have a password yet. We support migrating + * members from passwords stored with bcrypt, scrypt, argon2, MD-5, SHA-1, and PBKDF2. This endpoint has a + * rate limit of 100 requests per second. + * @param data {@link B2BPasswordsMigrateRequest} + * @returns {@link B2BPasswordsMigrateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ migrate(data: B2BPasswordsMigrateRequest): Promise; + /** + * Authenticate a member with their email address and password. This endpoint verifies that the member has + * a password currently set, and that the entered password is correct. There are two instances where the + * endpoint will return a reset_password error even if they enter their previous password: + * * The member’s credentials appeared in the HaveIBeenPwned dataset. + * * We force a password reset to ensure that the member is the legitimate owner of the email address, + * and not a malicious actor abusing the compromised credentials. + * * A member that has previously authenticated with email/password uses a passwordless authentication + * method tied to the same email address (e.g. Magic Links) for the first time. Any subsequent + * email/password authentication attempt will result in this error. + * * We force a password reset in this instance in order to safely deduplicate the account by email + * address, without introducing the risk of a pre-hijack account takeover attack. + * * Imagine a bad actor creates many accounts using passwords and the known email addresses of their + * victims. If a victim comes to the site and logs in for the first time with an email-based passwordless + * authentication method then both the victim and the bad actor have credentials to access to the same + * account. To prevent this, any further email/password login attempts first require a password reset which + * can only be accomplished by someone with access to the underlying email address. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsAuthenticateRequest} + * @returns {@link B2BPasswordsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: B2BPasswordsAuthenticateRequest): Promise; } -export {}; diff --git a/types/lib/b2b/passwords_email.d.ts b/types/lib/b2b/passwords_email.d.ts new file mode 100644 index 00000000..c6815594 --- /dev/null +++ b/types/lib/b2b/passwords_email.d.ts @@ -0,0 +1,223 @@ +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +export interface B2BPasswordsEmailResetRequest { + password_reset_token: string; + password: string; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_token`, Stytch will + * update the session. + * If the `session_token` and `magic_links_token` belong to different Members, the `session_token` + * will be ignored. This endpoint will error if + * both `session_token` and `session_jwt` are provided. + */ + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + /** + * Reuse an existing session instead of creating a new one. If you provide a `session_jwt`, Stytch will + * update the session. If the `session_jwt` + * and `magic_links_token` belong to different Members, the `session_jwt` will be ignored. This + * endpoint will error if both `session_token` and `session_jwt` + * are provided. + */ + session_jwt?: string; + code_verifier?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface B2BPasswordsEmailResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member_email_id: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + member: Member; + session_token: string; + session_jwt: string; + organization: Organization; + /** + * The returned Intermediate Session Token contains a password factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * Password factors are not transferable between Organizations, so the intermediate session token is + * not valid for use with discovery endpoints. + */ + intermediate_session_token: string; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} +export interface B2BPasswordsEmailResetStartRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + email_address: string; + /** + * The URL that the Member clicks from the reset password link. This URL should be an endpoint in the + * backend server that verifies the request by querying + * Stytch's authenticate endpoint and finishes the reset password flow. 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; + reset_password_expiration_minutes?: number; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: string; + /** + * The URL that the member clicks from the reset without password link. This URL should be an endpoint in + * the backend server + * that verifies the request by querying Stytch's authenticate endpoint and finishes the magic link + * flow. If this value is not passed, the + * default `login_redirect_url` that you set in your Dashboard is used. This value is only used if + * magic links are enabled for the member. If + * you have not set a default `login_redirect_url` and magic links are not enabled for the member, an + * error is returned. + */ + login_redirect_url?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for reset password 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 + * - Reset Password. + */ + reset_password_template_id?: string; +} +export interface B2BPasswordsEmailResetStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member_email_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; +} +export declare class Email { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * 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. + * + * This endpoint adapts to your Project's password strength configuration. + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your + * passwords are considered valid + * if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are + * considered valid if they meet the requirements that you've set with Stytch. + * You may update your password strength configuration in the + * [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * @param data {@link B2BPasswordsEmailResetStartRequest} + * @returns {@link B2BPasswordsEmailResetStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + resetStart(data: B2BPasswordsEmailResetStartRequest): Promise; + /** + * Reset the member's password and authenticate them. This endpoint checks that the password reset 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 password strength endpoint. If the token and password are accepted, the password is securely + * stored for future authentication and the user is authenticated. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsEmailResetRequest} + * @returns {@link B2BPasswordsEmailResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset(data: B2BPasswordsEmailResetRequest): Promise; +} diff --git a/types/lib/b2b/passwords_existing_password.d.ts b/types/lib/b2b/passwords_existing_password.d.ts new file mode 100644 index 00000000..c1481387 --- /dev/null +++ b/types/lib/b2b/passwords_existing_password.d.ts @@ -0,0 +1,128 @@ +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +import { MfaRequired } from "./mfa"; +export interface B2BPasswordsExistingPasswordResetRequest { + email_address: string; + existing_password: string; + new_password: string; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface B2BPasswordsExistingPasswordResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + session_token: string; + session_jwt: string; + organization: Organization; + /** + * The returned Intermediate Session Token contains a password factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * Password factors are not transferable between Organizations, so the intermediate session token is + * not valid for use with discovery endpoints. + */ + intermediate_session_token: string; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} +export declare class ExistingPassword { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Reset the member’s password using their existing password. + * + * This endpoint adapts to your Project's password strength configuration. + * If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your + * passwords are considered valid + * if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are + * considered valid if they meet the requirements that you've set with Stytch. + * You may update your password strength configuration in the + * [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BPasswordsExistingPasswordResetRequest} + * @returns {@link B2BPasswordsExistingPasswordResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset(data: B2BPasswordsExistingPasswordResetRequest): Promise; +} diff --git a/types/lib/b2b/passwords_session.d.ts b/types/lib/b2b/passwords_session.d.ts new file mode 100644 index 00000000..c5a81181 --- /dev/null +++ b/types/lib/b2b/passwords_session.d.ts @@ -0,0 +1,44 @@ +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; +export interface B2BPasswordsSessionResetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + password: string; + session_token?: string; + session_jwt?: string; +} +export interface B2BPasswordsSessionResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_id: string; + member: Member; + organization: Organization; + /** + * 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; + member_session?: MemberSession; +} +export declare class Sessions { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Reset the Member's password using their existing session. The endpoint will error if the session does + * not contain an authentication factor that has been issued within the last 5 minutes. Either + * `session_token` or `session_jwt` should be provided. + * @param data {@link B2BPasswordsSessionResetRequest} + * @returns {@link B2BPasswordsSessionResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset(data: B2BPasswordsSessionResetRequest): Promise; +} diff --git a/types/lib/b2b/saml.d.ts b/types/lib/b2b/saml.d.ts deleted file mode 100644 index 9b4ee1d3..00000000 --- a/types/lib/b2b/saml.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { BaseResponse, fetchConfig } from "../shared"; -import { SAMLConnection } from "./sso"; -export interface B2BSAMLCreateConnectionRequest { - organization_id: string; - display_name?: string; -} -export interface B2BSAMLCreateConnectionResponse extends BaseResponse { - connection: SAMLConnection; -} -export interface B2BSAMLUpdateConnectionRequest { - organization_id: string; - connection_id: string; - idp_entity_id?: string; - display_name?: string; - attribute_mapping?: Record; - x509_certificate?: string; - idp_sso_url?: string; -} -export interface B2BSAMLUpdateConnectionResponse extends BaseResponse { - connection: SAMLConnection; -} -export interface B2BSAMLDeleteVerificationCertificateRequest { - organization_id: string; - connection_id: string; - certificate_id: string; -} -export interface B2BSAMLDeleteVerificationCertificateResponse extends BaseResponse { - certificate_id: string; -} -export declare class SAML { - private readonly fetchConfig; - constructor(fetchConfig: fetchConfig); - create({ organization_id, ...data }: B2BSAMLCreateConnectionRequest): Promise; - update({ organization_id, connection_id, ...data }: B2BSAMLUpdateConnectionRequest): Promise; - deleteVerificationCertificate({ organization_id, connection_id, certificate_id, }: B2BSAMLDeleteVerificationCertificateRequest): Promise; -} diff --git a/types/lib/b2b/sessions.d.ts b/types/lib/b2b/sessions.d.ts index 726d30aa..518c0367 100644 --- a/types/lib/b2b/sessions.d.ts +++ b/types/lib/b2b/sessions.d.ts @@ -1,81 +1,325 @@ -import { BaseResponse, fetchConfig } from "../shared"; -import { Member, MemberSession } from "./shared_b2b"; import { JwtConfig } from "../shared/sessions"; -import { Organization } from "./organizations"; +import { AuthenticationFactor, JWK } from "../b2c/sessions"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; import { MfaRequired } from "./mfa"; -export interface B2BSessionsGetRequest { - organization_id: string; +export interface MemberSession { + member_session_id: string; member_id: string; -} -export interface B2BSessionsGetResponse extends BaseResponse { - member_sessions: MemberSession[]; -} -export interface B2BSessionsJwksResponse extends BaseResponse { - keys: JWK[]; -} -export interface JWK { - alg: string; - key_ops: string[]; - kid: string; - kty: string; - use: string; - x5c: string[]; - "x5t#S256": string; - n: string; - e: string; + /** + * The timestamp when the Session was created. Values conform to the RFC 3339 standard and are expressed in + * UTC, e.g. `2021-12-29T12:33:09Z`. + */ + started_at: string; + /** + * The timestamp when the Session was last 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 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; + authentication_factors: AuthenticationFactor[]; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * The custom claims map for a Session. Claims can be added to a session during a Sessions authenticate + * call. + */ + custom_claims?: Record; } export interface B2BSessionsAuthenticateRequest { - session_duration_minutes?: number; session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ + session_duration_minutes?: number; session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; } -export interface B2BSessionsAuthenticateResponse extends BaseResponse { +export interface B2BSessionsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; member_session: MemberSession; - member: Member; session_token: string; session_jwt: string; + member: Member; organization: Organization; + /** + * 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; } -export declare type B2BSessionsRevokeRequest = { - member_session_id: string; -} | { - session_token: string; -} | { - session_jwt: string; -} | { - member_id: string; -}; -export declare type B2BSessionsRevokeResponse = BaseResponse; export interface B2BSessionsExchangeRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; session_token?: string; session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BSessionsExchangeResponse extends BaseResponse { +export interface B2BSessionsExchangeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; member_id: string; - member_session: MemberSession | null; + member_session: MemberSession; session_token: string; session_jwt: string; member: Member; organization: Organization; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ member_authenticated: boolean; + /** + * The returned Intermediate Session Token contains any Email Magic Link or OAuth factors from the original + * member session that are valid for the target Organization. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the target Organization. + * It can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * to join a different existing Organization, + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; + /** + * 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; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} +export interface B2BSessionsGetJWKSRequest { + project_id: string; +} +export interface B2BSessionsGetJWKSResponse { + keys: JWK[]; + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} +export interface B2BSessionsGetRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id: string; +} +export interface B2BSessionsGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + member_sessions: MemberSession[]; + /** + * 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; +} +export interface B2BSessionsRevokeRequest { + /** + * Globally unique UUID that identifies a specific Session in the Stytch API. The `member_session_id` is + * critical to perform operations on an Session, so be sure to preserve this value. + */ + member_session_id?: string; + session_token?: string; + session_jwt?: string; + /** + * Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform + * operations on a Member, so be sure to preserve this value. + */ + member_id?: string; +} +export interface B2BSessionsRevokeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; } export declare class Sessions { - private base_path; private fetchConfig; private jwksClient; private jwtOptions; constructor(fetchConfig: fetchConfig, jwtConfig: JwtConfig); - private endpoint; - get({ organization_id, member_id, }: B2BSessionsGetRequest): Promise; - jwks(project_id: string): Promise; + /** + * Retrieves all active Sessions for a Member. + * @param data {@link B2BSessionsGetRequest} + * @returns {@link B2BSessionsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: B2BSessionsGetRequest): Promise; + /** + * Authenticates a Session and updates its lifetime by the specified `session_duration_minutes`. If the + * `session_duration_minutes` is not specified, a Session will not be extended. This endpoint requires + * either a `session_jwt` or `session_token` be included in the request. It will return an error if both + * are present. + * + * You may provide a JWT that needs to be refreshed and is expired according to its `exp` claim. A new JWT + * will be returned if both the signature and the underlying Session are still valid. + * @param data {@link B2BSessionsAuthenticateRequest} + * @returns {@link B2BSessionsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate(data: B2BSessionsAuthenticateRequest): Promise; + /** + * Revoke a Session and immediately invalidate all its tokens. To revoke a specific Session, pass either + * the `member_session_id`, `session_token`, or `session_jwt`. To revoke all Sessions for a Member, pass + * the `member_id`. + * @param data {@link B2BSessionsRevokeRequest} + * @returns {@link B2BSessionsRevokeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + revoke(data: B2BSessionsRevokeRequest): Promise; + /** + * Use this endpoint to exchange a Member's existing session for another session in a different + * Organization. This can be used to accept an invite, but not to create a new member via domain matching. + * + * To create a new member via domain matching, use the + * [Exchange Intermediate Session](https://stytch.com/docs/b2b/api/exchange-intermediate-session) flow + * instead. + * + * Only Email Magic Link, OAuth, and SMS OTP factors can be transferred between sessions. Other + * authentication factors, such as password factors, will not be transferred to the new session. + * SMS OTP factors can be used to fulfill MFA requirements for the target Organization if both the original + * and target Member have the same phone number and the phone number is verified for both Members. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `intermediate_session_token` can also be used with the + * [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) + * or the + * [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to join a different Organization or create a new one. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * @param data {@link B2BSessionsExchangeRequest} + * @returns {@link B2BSessionsExchangeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + exchange(data: B2BSessionsExchangeRequest): Promise; + /** + * Get the JSON Web Key Set (JWKS) for a project. + * @param data {@link B2BSessionsGetJWKSRequest} + * @returns {@link B2BSessionsGetJWKSResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + getJWKS(params: B2BSessionsGetJWKSRequest): Promise; /** Parse a JWT and verify the signature, preferring local verification over remote. * * If max_token_age_seconds is set, remote verification will be forced if the JWT was issued at @@ -109,6 +353,4 @@ export declare class Sessions { max_token_age_seconds?: number; current_date?: Date; }): Promise; - exchange(data: B2BSessionsExchangeRequest): Promise; - revoke(data: B2BSessionsRevokeRequest): Promise; } diff --git a/types/lib/b2b/shared_b2b.d.ts b/types/lib/b2b/shared_b2b.d.ts deleted file mode 100644 index 6eaaa802..00000000 --- a/types/lib/b2b/shared_b2b.d.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { BaseResponse } from "../shared"; -import { Organization } from "./organizations"; -export interface EmailFactor { - delivery_method: "email"; - type: string; - last_authenticated_at: string; - email_factor: { - email_id: string; - email_address: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} -export interface PhoneNumberFactor { - delivery_method: "sms" | "whatsapp"; - type: string; - last_authenticated_at: string; - phone_number_factor: { - phone_id: string; - phone_number: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} -export interface GoogleOAuthFactor { - delivery_method: "oauth_google"; - type: string; - last_authenticated_at: string; - google_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} -export interface MicrosoftOAuthFactor { - delivery_method: "oauth_microsoft"; - type: string; - last_authenticated_at: string; - microsoft_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; - sequence_order: "PRIMARY" | "SECONDARY"; -} -export declare type B2BAuthenticationFactor = EmailFactor | GoogleOAuthFactor | MicrosoftOAuthFactor | PhoneNumberFactor; -export interface MemberSession { - member_session_id: string; - member_id: string; - organization_id: string; - started_at: string; - last_accessed_at: string; - expires_at: string; - authentication_factors: B2BAuthenticationFactor[]; - custom_claims?: Record; -} -export interface Member { - organization_id: string; - member_id: string; - email_address: string; - status: string; - name: string; - oauth_registrations: OAuthRegistration[]; - sso_registrations: SSORegistration[]; - trusted_metadata: Record; - untrusted_metadata: Record; - is_breakglass: boolean; - member_password_id: string; - mfa_enrolled: boolean; - mfa_phone_number: string; -} -export interface SSORegistration { - connection_id: string; - external_id: string; - registration_id: string; - sso_attributes: Record; -} -export interface OAuthRegistration { - provider_subject: string; - provider_type: string; - member_oauth_registration_id: string; - locale?: string | null; - profile_picture_url?: string | null; -} -export interface ResultsMetadata { - total: number; - next_cursor: string; -} -export declare enum SearchOperator { - OR = "OR", - AND = "AND" -} -export interface ResponseWithMember extends BaseResponse { - member_id: string; - member: Member; - organization: Organization; -} diff --git a/types/lib/b2b/sso.d.ts b/types/lib/b2b/sso.d.ts index 6f23ee32..54c4ec10 100644 --- a/types/lib/b2b/sso.d.ts +++ b/types/lib/b2b/sso.d.ts @@ -1,16 +1,9 @@ -import { BaseResponse, fetchConfig } from "../shared"; -import { Member, MemberSession } from "./shared_b2b"; -import { SAML } from "./saml"; -import { Organization } from "./organizations"; -import { OIDC } from "./oidc"; +import { fetchConfig } from "../shared"; +import { Member, Organization } from "./organizations"; +import { MemberSession } from "./sessions"; import { MfaRequired } from "./mfa"; -export interface X509Certificate { - certificate_id: string; - certificate: string; - issuer: string; - created_at: string; - expires_at: string; -} +import { OIDC } from "./sso_oidc"; +import { SAML } from "./sso_saml"; export interface OIDCConnection { organization_id: string; connection_id: string; @@ -29,7 +22,6 @@ export interface SAMLConnection { organization_id: string; connection_id: string; status: string; - attribute_mapping: Record; idp_entity_id: string; display_name: string; idp_sso_url: string; @@ -37,50 +29,206 @@ export interface SAMLConnection { audience_uri: string; signing_certificates: X509Certificate[]; verification_certificates: X509Certificate[]; + attribute_mapping?: Record; } -export interface B2BSSOGetConnectionsRequest { - organization_id: string; -} -export interface B2BSSOGetConnectionsResponse extends BaseResponse { - saml_connections: SAMLConnection[]; - oidc_connections: OIDCConnection[]; -} -export interface B2BSSODeleteConnectionRequest { - organization_id: string; - connection_id: string; -} -export interface B2BSSODeleteConnectionResponse extends BaseResponse { - connection_id: string; +export interface X509Certificate { + certificate_id: string; + certificate: string; + issuer: string; + created_at?: string; + expires_at?: string; } export interface B2BSSOAuthenticateRequest { sso_token: string; + pkce_code_verifier?: string; session_token?: string; session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a + * 60 minute duration. If you don't want + * to use the Stytch session product, you can ignore the session fields in the response. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in + * `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a + * key in an existing Session, supply a new value. To + * delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, + * `exp`, `nbf`, `iat`, `jti`) will be ignored. + * Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; - pkce_code_verifier?: string; + /** + * (Coming Soon) If the Member needs to complete an MFA step, and the Member has a phone number, this + * endpoint will pre-emptively send a one-time passcode (OTP) to the Member's phone number. The locale + * argument will be used to determine which language to use when sending the passcode. + * + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ locale?: "en" | "es" | "pt-br" | string; } -export interface B2BSSOAuthenticateResponse extends BaseResponse { +export interface B2BSSOAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; member_id: string; - member: Member; + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ organization_id: string; - method_id: string; - session_token?: string; - session_jwt?: string; - session: MemberSession | null; + member: Member; + session_token: string; + session_jwt: string; + /** + * Indicates if all Sessions linked to the Member need to be reset. You should check this field if you + * aren't using + * Stytch's Session product. If you are using Stytch's Session product, we revoke the Member’s other + * Sessions for you. + */ reset_session: boolean; organization: Organization; - member_authenticated: boolean; + /** + * The returned Intermediate Session Token contains an SSO factor associated with the Member. + * The token can be used with the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA flow and log in to the Organization. + * SSO factors are not transferable between Organizations, so the intermediate session token is not + * valid for use with discovery endpoints. + */ intermediate_session_token: string; - mfa_required: MfaRequired | null; + /** + * Indicates whether the Member is fully authenticated. If false, the Member needs to complete an MFA step + * to log in to the Organization. + */ + member_authenticated: boolean; + /** + * 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; + member_session?: MemberSession; + /** + * (Coming Soon) Information about the MFA requirements of the Organization and the Member's options for + * fulfilling MFA. + */ + mfa_required?: MfaRequired; +} +export interface B2BSSODeleteConnectionRequest { + organization_id: string; + connection_id: string; +} +export interface B2BSSODeleteConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + connection_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; +} +export interface B2BSSOGetConnectionsRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; +} +export interface B2BSSOGetConnectionsResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * The list of [SAML Connections](https://stytch.com/docs/b2b/api/saml-connection-object) owned by this + * organization. + */ + saml_connections: SAMLConnection[]; + /** + * The list of [OIDC Connections](https://stytch.com/docs/b2b/api/oidc-connection-object) owned by this + * organization. + */ + oidc_connections: OIDCConnection[]; + /** + * 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; } export declare class SSO { - private readonly fetchConfig; - saml: SAML; + private fetchConfig; oidc: OIDC; + saml: SAML; constructor(fetchConfig: fetchConfig); - get({ organization_id, }: B2BSSOGetConnectionsRequest): Promise; - delete({ organization_id, connection_id, }: B2BSSODeleteConnectionRequest): Promise; + /** + * Get all SSO Connections owned by the organization. + * @param data {@link B2BSSOGetConnectionsRequest} + * @returns {@link B2BSSOGetConnectionsResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + getConnections(params: B2BSSOGetConnectionsRequest): Promise; + /** + * Delete an existing SSO connection. + * @param data {@link B2BSSODeleteConnectionRequest} + * @returns {@link B2BSSODeleteConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteConnection(data: B2BSSODeleteConnectionRequest): Promise; + /** + * Authenticate a user given a token. + * This endpoint verifies that the user completed the SSO Authentication flow by verifying that the token + * is valid and hasn't expired. + * Provide the `session_duration_minutes` parameter to set the lifetime of the session. + * If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 + * minute duration. + * To link this authentication event to an existing Stytch session, include either the `session_token` or + * `session_jwt` param. + * + * (Coming Soon) If the Member is required to complete MFA to log in to the Organization, the returned + * value of `member_authenticated` will be `false`, and an `intermediate_session_token` will be returned. + * The `intermediate_session_token` can be passed into the + * [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms) to complete the + * MFA step and acquire a full member session. + * The `session_duration_minutes` and `session_custom_claims` parameters will be ignored. + * + * If a valid `session_token` or `session_jwt` is passed in, the Member will not be required to complete an + * MFA step. + * @param data {@link B2BSSOAuthenticateRequest} + * @returns {@link B2BSSOAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ authenticate(data: B2BSSOAuthenticateRequest): Promise; } diff --git a/types/lib/b2b/sso_oidc.d.ts b/types/lib/b2b/sso_oidc.d.ts new file mode 100644 index 00000000..3404f6de --- /dev/null +++ b/types/lib/b2b/sso_oidc.d.ts @@ -0,0 +1,132 @@ +import { fetchConfig } from "../shared"; +import { OIDCConnection } from "./sso"; +export interface B2BSSOOIDCCreateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + display_name?: string; +} +export interface B2BSSOOIDCCreateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `OIDC Connection` object affected by this API call. See the + * [OIDC Connection Object](https://stytch.com/docs/b2b/api/oidc-connection-object) for complete response + * field details. + */ + connection?: OIDCConnection; +} +export interface B2BSSOOIDCUpdateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + connection_id: string; + display_name?: string; + 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; + issuer?: string; + 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](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). 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; +} +export interface B2BSSOOIDCUpdateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `OIDC Connection` object affected by this API call. See the + * [OIDC Connection Object](https://stytch.com/docs/b2b/api/oidc-connection-object) for complete response + * field details. + */ + 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; +} +export declare class OIDC { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Create a new OIDC Connection. + * @param data {@link B2BSSOOIDCCreateConnectionRequest} + * @returns {@link B2BSSOOIDCCreateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + createConnection(data: B2BSSOOIDCCreateConnectionRequest): Promise; + /** + * Updates an existing OIDC connection. + * + * 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 `$/.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. + * + * Note that a newly created connection will not become active until all of the following fields are + * provided: + * * `issuer` + * * `client_id` + * * `client_secret` + * * `authorization_url` + * * `token_url` + * * `userinfo_url` + * * `jwks_url` + * @param data {@link B2BSSOOIDCUpdateConnectionRequest} + * @returns {@link B2BSSOOIDCUpdateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + updateConnection(data: B2BSSOOIDCUpdateConnectionRequest): Promise; +} diff --git a/types/lib/b2b/sso_saml.d.ts b/types/lib/b2b/sso_saml.d.ts new file mode 100644 index 00000000..00376995 --- /dev/null +++ b/types/lib/b2b/sso_saml.d.ts @@ -0,0 +1,127 @@ +import { fetchConfig } from "../shared"; +import { SAMLConnection } from "./sso"; +export interface B2BSSOSAMLCreateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + display_name?: string; +} +export interface B2BSSOSAMLCreateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `SAML Connection` object affected by this API call. See the + * [SAML Connection Object](https://stytch.com/docs/b2b/api/saml-connection-object) for complete response + * field details. + */ + connection?: SAMLConnection; +} +export interface B2BSSOSAMLDeleteVerificationCertificateRequest { + organization_id: string; + connection_id: string; + certificate_id: string; +} +export interface B2BSSOSAMLDeleteVerificationCertificateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + certificate_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; +} +export interface B2BSSOSAMLUpdateConnectionRequest { + /** + * Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to + * perform operations on an Organization, so be sure to preserve this value. + */ + organization_id: string; + connection_id: string; + idp_entity_id?: string; + 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; + /** + * A certificate that Stytch will use to verify the sign-in assertion sent by the IdP, in + * [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format. See our + * [X509 guide](https://stytch.com/docs/b2b/api/saml-certificates) for more info. + */ + x509_certificate?: string; + idp_sso_url?: string; +} +export interface B2BSSOSAMLUpdateConnectionResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; + /** + * The `SAML Connection` object affected by this API call. See the + * [SAML Connection Object](https://stytch.com/docs/b2b/api/saml-connection-object) for complete response + * field details. + */ + connection?: SAMLConnection; +} +export declare class SAML { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Create a new SAML Connection. + * @param data {@link B2BSSOSAMLCreateConnectionRequest} + * @returns {@link B2BSSOSAMLCreateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + createConnection(data: B2BSSOSAMLCreateConnectionRequest): Promise; + /** + * Updates an existing SAML connection. + * + * Note that a newly created connection will not become active until all of the following are provided: + * * `idp_sso_url` + * * `attribute_mapping` + * * `idp_entity_id` + * * `x509_certificate` + * @param data {@link B2BSSOSAMLUpdateConnectionRequest} + * @returns {@link B2BSSOSAMLUpdateConnectionResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + updateConnection(data: B2BSSOSAMLUpdateConnectionRequest): Promise; + /** + * Delete a SAML verification certificate. + * + * 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. + * @param data {@link B2BSSOSAMLDeleteVerificationCertificateRequest} + * @returns {@link B2BSSOSAMLDeleteVerificationCertificateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteVerificationCertificate(data: B2BSSOSAMLDeleteVerificationCertificateRequest): Promise; +} diff --git a/types/lib/b2c/attribute.d.ts b/types/lib/b2c/attribute.d.ts new file mode 100644 index 00000000..01ea4ebc --- /dev/null +++ b/types/lib/b2c/attribute.d.ts @@ -0,0 +1,4 @@ +export interface Attributes { + ip_address?: string; + user_agent?: string; +} diff --git a/types/lib/b2c/client.d.ts b/types/lib/b2c/client.d.ts index 840f5425..2fb5e571 100644 --- a/types/lib/b2c/client.d.ts +++ b/types/lib/b2c/client.d.ts @@ -1,4 +1,6 @@ +import { BaseClient, ClientConfig } from "../shared/client"; import { CryptoWallets } from "./crypto_wallets"; +import { JwtConfig } from "../shared/sessions"; import { MagicLinks } from "./magic_links"; import { OAuth } from "./oauth"; import { OTPs } from "./otps"; @@ -7,18 +9,16 @@ import { Sessions } from "./sessions"; import { TOTPs } from "./totps"; import { Users } from "./users"; import { WebAuthn } from "./webauthn"; -import { BaseClient, ClientConfig } from "../shared/client"; -import { JwtConfig } from "../shared/sessions"; export declare class Client extends BaseClient { protected jwtConfig: JwtConfig; - users: Users; + cryptoWallets: CryptoWallets; magicLinks: MagicLinks; - otps: OTPs; oauth: OAuth; + otps: OTPs; passwords: Passwords; sessions: Sessions; totps: TOTPs; + users: Users; webauthn: WebAuthn; - cryptoWallets: CryptoWallets; constructor(config: ClientConfig); } diff --git a/types/lib/b2c/crypto_wallets.d.ts b/types/lib/b2c/crypto_wallets.d.ts index db4f8464..13bbbd2d 100644 --- a/types/lib/b2c/crypto_wallets.d.ts +++ b/types/lib/b2c/crypto_wallets.d.ts @@ -1,39 +1,118 @@ -import { Session, User } from "./shared_b2c"; -import { fetchConfig, BaseResponse } from "../shared"; -import { UserID } from "./users"; -export interface B2CCryptoWalletsAuthenticateStartRequest { - crypto_wallet_address: string; +import { fetchConfig } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface CryptoWalletsAuthenticateRequest { + /** + * The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. Wallets for any + * EVM-compatible chains (such as Polygon or BSC) are also supported and are grouped under the `ethereum` + * type. + */ crypto_wallet_type: string; - user_id?: UserID; - session_token?: string; - session_jwt?: string; -} -export interface B2CCryptoWalletsAuthenticateStartResponse extends BaseResponse { - user_id: UserID; - challenge: string; - user_created: boolean; -} -export interface B2CCryptoWalletsAuthenticateRequest { crypto_wallet_address: string; - crypto_wallet_type: string; signature: string; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; } -export interface B2CCryptoWalletsAuthenticateResponse extends BaseResponse { - user_id: UserID; +export interface CryptoWalletsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; +} +export interface CryptoWalletsAuthenticateStartRequest { + /** + * The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. Wallets for any + * EVM-compatible chains (such as Polygon or BSC) are also supported and are grouped under the `ethereum` + * type. + */ + crypto_wallet_type: string; + crypto_wallet_address: string; + user_id?: string; session_token?: string; session_jwt?: string; - session?: Session; +} +export interface CryptoWalletsAuthenticateStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + challenge: string; + user_created: boolean; + /** + * 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; } export declare class CryptoWallets { - base_path: string; private fetchConfig; constructor(fetchConfig: fetchConfig); - private endpoint; - authenticateStart(data: B2CCryptoWalletsAuthenticateStartRequest): Promise; - authenticate(data: B2CCryptoWalletsAuthenticateRequest): Promise; + /** + * Initiate the authentication of a crypto wallet. After calling this endpoint, the user will need to sign + * a message containing only the returned `challenge` field. + * @param data {@link CryptoWalletsAuthenticateStartRequest} + * @returns {@link CryptoWalletsAuthenticateStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticateStart(data: CryptoWalletsAuthenticateStartRequest): Promise; + /** + * Complete the authentication of a crypto wallet by passing the signature. + * @param data {@link CryptoWalletsAuthenticateRequest} + * @returns {@link CryptoWalletsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: CryptoWalletsAuthenticateRequest): Promise; } diff --git a/types/lib/b2c/index.d.ts b/types/lib/b2c/index.d.ts index 59da270f..6b4ec7ca 100644 --- a/types/lib/b2c/index.d.ts +++ b/types/lib/b2c/index.d.ts @@ -1,10 +1,18 @@ -export type { User, Name, Email, Password, PhoneNumber, OAuthProvider, WebAuthnRegistration, BiometricRegistration, TOTP, CryptoWallet, Session, B2CAuthenticationFactor, Attributes, } from "./shared_b2c"; -export type { B2CCryptoWalletsAuthenticateStartRequest, B2CCryptoWalletsAuthenticateStartResponse, B2CCryptoWalletsAuthenticateRequest, B2CCryptoWalletsAuthenticateResponse, } from "./crypto_wallets"; -export type { B2CMagicLinksRevokePendingInviteByEmailRequest, B2CMagicLinksRevokePendingInviteByEmailResponse, B2CMagicLinksAuthenticateRequest, B2CMagicLinksAuthenticateResponse, B2CMagicLinksInviteByEmailResponse, B2CMagicLinksInviteByEmailRequest, B2CMagicLinksSendByEmailRequest, B2CMagicLinksSendByEmailResponse, B2CMagicLinksLoginOrCreateByEmailRequest, B2CMagicLinksLoginOrCreateByEmailResponse, B2CMagicLinksCreateRequest, B2CMagicLinksCreateResponse, } from "./magic_links"; -export type { B2COAuthAuthenticateRequest, B2COAuthAuthenticateResponse, B2COAuthAttachRequest, B2COAuthAttachResponse, } from "./oauth"; -export type { B2COTPsAuthenticateRequest, B2COTPsAuthenticateResponse, B2COTPsSMSSendRequest, B2COTPsSMSSendResponse, B2COTPsSMSLoginOrCreateRequest, B2COTPsSMSLoginOrCreateResponse, B2COTPsEmailSendRequest, B2COTPsEmailSendResponse, B2COTPsEmailLoginOrCreateRequest, B2COTPsEmailLoginOrCreateResponse, B2COTPsWhatsAppSendRequest, B2COTPsWhatsAppSendResponse, B2COTPsWhatsAppLoginOrCreateRequest, B2COTPsWhatsAppLoginOrCreateResponse, } from "./otps"; -export type { B2CPasswordsAuthenticateRequest, B2CPasswordsAuthenticateResponse, B2CPasswordsCreateRequest, B2CPasswordsCreateResponse, B2CPasswordsResetByEmailRequest, B2CPasswordsResetByEmailResponse, B2CPasswordsResetByEmailStartRequest, B2CPasswordsResetByEmailStartResponse, B2CPasswordsResetByExistingPasswordRequest, B2CPasswordsResetByExistingPasswordResponse, B2CPasswordsMigrateRequest, B2CPasswordsMigrateResponse, B2CPasswordsResetBySessionRequest, B2CPasswordsResetBySessionResponse, B2CPasswordsStrengthCheckRequest, B2CPasswordsStrengthCheckResponse, } from "./passwords"; -export type { B2CSessionsAuthenticateRequest, B2CSessionsAuthenticateResponse, B2CSessionsRevokeRequest, B2CSessionsRevokeResponse, B2CSessionsGetRequest, B2CSessionsGetResponse, B2CSessionsJwksResponse, } from "./sessions"; -export type { B2CTOTPsAuthenticateRequest, B2CTOTPsAuthenticateResponse, B2CTOTPsCreateRequest, B2CTOTPsCreateResponse, B2CTOTPsRecoverRequest, B2CTOTPsRecoverResponse, B2CTOTPsRecoveryCodesRequest, B2CTOTPsRecoveryCodesResponse, } from "./totps"; -export type { B2CUsersCreateRequest, B2CUsersCreateResponse, B2CUsersSearchRequest, B2CUsersSearchResponse, B2CUsersGetResponse, B2CUsersUpdateRequest, B2CUsersUpdateResponse, B2CUsersDeleteCryptoWalletResponse, B2CUsersDeleteTOTPResponse, B2CUsersDeleteWebAuthnRegistrationResponse, B2CUsersDeletePhoneNumberResponse, B2CUsersDeleteEmailResponse, B2CUsersDeleteBiometricRegistrationResponse, B2CUsersDeleteOAuthUserRegistrationResponse, B2CUsersDeletePasswordResponse, B2CUsersDeleteResponse, } from "./users"; -export type { B2CWebAuthnRegisterStartRequest, B2CWebAuthnRegisterStartResponse, B2CWebAuthnRegisterRequest, B2CWebAuthnRegisterResponse, B2CWebAuthnAuthenticateStartRequest, B2CWebAuthnAuthenticateStartResponse, B2CWebAuthnAuthenticateRequest, B2CWebAuthnAuthenticateResponse, } from "./webauthn"; +export type { SearchUsersQueryOperand } from "./users"; +export type { Attributes } from "./attribute"; +export type { BiometricRegistration, CryptoWallet, Email, Name, OAuthProvider, Password, PhoneNumber, UsersResultsMetadata, SearchUsersQuery, TOTP, User, WebAuthnRegistration, UsersCreateRequest, UsersCreateResponse, UsersDeleteBiometricRegistrationRequest, UsersDeleteBiometricRegistrationResponse, UsersDeleteCryptoWalletRequest, UsersDeleteCryptoWalletResponse, UsersDeleteEmailRequest, UsersDeleteEmailResponse, UsersDeleteOAuthRegistrationRequest, UsersDeleteOAuthRegistrationResponse, UsersDeletePasswordRequest, UsersDeletePasswordResponse, UsersDeletePhoneNumberRequest, UsersDeletePhoneNumberResponse, UsersDeleteRequest, UsersDeleteResponse, UsersDeleteTOTPRequest, UsersDeleteTOTPResponse, UsersDeleteWebAuthnRegistrationRequest, UsersDeleteWebAuthnRegistrationResponse, UsersGetRequest, UsersGetResponse, UsersSearchRequest, UsersSearchResponse, UsersUpdateRequest, UsersUpdateResponse, } from "./users"; +export type { AmazonOAuthFactor, AppleOAuthFactor, AuthenticationFactor, AuthenticatorAppFactor, BiometricFactor, BitbucketOAuthFactor, CoinbaseOAuthFactor, CryptoWalletFactor, DiscordOAuthFactor, EmailFactor, EmbeddableMagicLinkFactor, FacebookOAuthFactor, FigmaOAuthFactor, GitLabOAuthFactor, GithubOAuthFactor, GoogleOAuthFactor, InstagramOAuthFactor, JWK, LinkedInOAuthFactor, MicrosoftOAuthFactor, OIDCSSOFactor, PhoneNumberFactor, RecoveryCodeFactor, SAMLSSOFactor, SalesforceOAuthFactor, Session, ShopifyOAuthFactor, SlackOAuthFactor, SnapchatOAuthFactor, SpotifyOAuthFactor, SteamOAuthFactor, TikTokOAuthFactor, TwitchOAuthFactor, TwitterOAuthFactor, WebAuthnFactor, YahooOAuthFactor, SessionsAuthenticateRequest, SessionsAuthenticateResponse, SessionsGetJWKSRequest, SessionsGetJWKSResponse, SessionsGetRequest, SessionsGetResponse, SessionsRevokeRequest, SessionsRevokeResponse, } from "./sessions"; +export type { CryptoWalletsAuthenticateRequest, CryptoWalletsAuthenticateResponse, CryptoWalletsAuthenticateStartRequest, CryptoWalletsAuthenticateStartResponse, } from "./crypto_wallets"; +export type { Options, MagicLinksAuthenticateRequest, MagicLinksAuthenticateResponse, MagicLinksCreateRequest, MagicLinksCreateResponse, } from "./magic_links"; +export type { MagicLinksEmailInviteRequest, MagicLinksEmailInviteResponse, MagicLinksEmailLoginOrCreateRequest, MagicLinksEmailLoginOrCreateResponse, MagicLinksEmailRevokeInviteRequest, MagicLinksEmailRevokeInviteResponse, MagicLinksEmailSendRequest, MagicLinksEmailSendResponse, } from "./magic_links_email"; +export type { Argon2Config, Feedback, LUDSRequirements, MD5Config, PBKDF2Config, SHA1Config, ScryptConfig, PasswordsAuthenticateRequest, PasswordsAuthenticateResponse, PasswordsCreateRequest, PasswordsCreateResponse, PasswordsMigrateRequest, PasswordsMigrateResponse, PasswordsStrengthCheckRequest, PasswordsStrengthCheckResponse, } from "./passwords"; +export type { PasswordsEmailResetRequest, PasswordsEmailResetResponse, PasswordsEmailResetStartRequest, PasswordsEmailResetStartResponse, } from "./passwords_email"; +export type { PasswordsExistingPasswordResetRequest, PasswordsExistingPasswordResetResponse, } from "./passwords_existing_password"; +export type { PasswordsSessionResetRequest, PasswordsSessionResetResponse, } from "./passwords_session"; +export type { OAuthProviderValues, OAuthAttachRequest, OAuthAttachResponse, OAuthAuthenticateRequest, OAuthAuthenticateResponse, } from "./oauth"; +export type { OTPsAuthenticateRequest, OTPsAuthenticateResponse } from "./otps"; +export type { OTPsSmsLoginOrCreateRequest, OTPsSmsLoginOrCreateResponse, OTPsSmsSendRequest, OTPsSmsSendResponse, } from "./otps_sms"; +export type { OTPsWhatsappLoginOrCreateRequest, OTPsWhatsappLoginOrCreateResponse, OTPsWhatsappSendRequest, OTPsWhatsappSendResponse, } from "./otps_whatsapp"; +export type { OTPsEmailLoginOrCreateRequest, OTPsEmailLoginOrCreateResponse, OTPsEmailSendRequest, OTPsEmailSendResponse, } from "./otps_email"; +export type { TOTPWithRecoveryCodes, TOTPsAuthenticateRequest, TOTPsAuthenticateResponse, TOTPsCreateRequest, TOTPsCreateResponse, TOTPsRecoverRequest, TOTPsRecoverResponse, TOTPsRecoveryCodesRequest, TOTPsRecoveryCodesResponse, } from "./totps"; +export type { WebAuthnAuthenticateRequest, WebAuthnAuthenticateResponse, WebAuthnAuthenticateStartRequest, WebAuthnAuthenticateStartResponse, WebAuthnRegisterRequest, WebAuthnRegisterResponse, WebAuthnRegisterStartRequest, WebAuthnRegisterStartResponse, } from "./webauthn"; diff --git a/types/lib/b2c/magic_links.d.ts b/types/lib/b2c/magic_links.d.ts index 5693b65d..083796dd 100644 --- a/types/lib/b2c/magic_links.d.ts +++ b/types/lib/b2c/magic_links.d.ts @@ -1,108 +1,132 @@ -import { BaseResponse, fetchConfig } from "../shared"; -import { Attributes, Name, Session, User } from "./shared_b2c"; -export interface B2CMagicLinksSendByEmailRequest { - email: string; - login_magic_link_url?: string; - signup_magic_link_url?: string; - login_expiration_minutes?: number; - signup_expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - attributes?: Attributes; - code_challenge?: string; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} -export interface B2CMagicLinksSendByEmailResponse extends BaseResponse { - user_id: string; - email_id: string; -} -export interface B2CMagicLinksLoginOrCreateByEmailRequest { - email: string; - login_magic_link_url?: string; - signup_magic_link_url?: string; - login_expiration_minutes?: number; - signup_expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - create_user_as_pending?: boolean; - attributes?: Attributes; - code_challenge?: string; - locale?: string; -} -export interface B2CMagicLinksLoginOrCreateByEmailResponse extends BaseResponse { - user_id: string; - email_id: string; - user_created: boolean; +import { Attributes } from "./attribute"; +import { Email } from "./magic_links_email"; +import { fetchConfig } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface Options { + ip_match_required: boolean; + user_agent_match_required: boolean; } -export interface B2CMagicLinksInviteByEmailRequest { - email: string; - invite_magic_link_url?: string; - invite_expiration_minutes?: number; - invite_template_id?: string; - name?: Name; - attributes?: Attributes; - locale?: string; -} -export interface B2CMagicLinksInviteByEmailResponse extends BaseResponse { - user_id: string; - email_id: string; -} -export interface B2CMagicLinksCreateRequest { - user_id: string; - expiration_minutes?: number; - attributes?: Attributes; -} -export interface B2CMagicLinksCreateResponse extends BaseResponse { +export interface MagicLinksAuthenticateRequest { token: string; - user_id: string; -} -export interface B2CMagicLinksAuthenticateRequest { - options?: { - ip_match_required?: boolean; - user_agent_match_required?: boolean; - }; attributes?: Attributes; + options?: Options; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; code_verifier?: string; } -export interface B2CMagicLinksAuthenticateResponse extends BaseResponse { +export interface MagicLinksAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; user_id: string; - user: User; method_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * Indicates if all other of the User's Sessions need to be reset. You should check this field if you + * aren't using Stytch's Session product. If you are using Stytch's Session product, we revoke the User's + * other sessions for you. + */ reset_sessions: boolean; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; } -export interface B2CMagicLinksRevokePendingInviteByEmailRequest { - email: string; -} -export interface B2CMagicLinksRevokePendingInviteByEmailResponse extends BaseResponse { +export interface MagicLinksCreateRequest { + user_id: string; + /** + * Set the expiration for the Magic Link `token` in minutes. By default, it expires in 1 hour. The minimum + * expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + expiration_minutes?: number; + attributes?: Attributes; } -declare class Email { - base_path: string; - delivery: string; - private fetchConfig; - constructor(fetchConfig: fetchConfig, parent_path: string); - private endpoint; - send(data: B2CMagicLinksSendByEmailRequest): Promise; - loginOrCreate(data: B2CMagicLinksLoginOrCreateByEmailRequest): Promise; - invite(data: B2CMagicLinksInviteByEmailRequest): Promise; - revokeInvite(data: B2CMagicLinksRevokePendingInviteByEmailRequest): Promise; +export interface MagicLinksCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + token: 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; } export declare class MagicLinks { - base_path: string; - email: Email; private fetchConfig; + email: Email; constructor(fetchConfig: fetchConfig); - private endpoint; - create(data: B2CMagicLinksCreateRequest): Promise; - authenticate(token: string, data?: B2CMagicLinksAuthenticateRequest): Promise; + /** + * Authenticate a User given a Magic Link. This endpoint verifies that the Magic Link token is valid, + * hasn't expired or been previously used, and any optional security settings such as IP match or user + * agent match are satisfied. + * @param data {@link MagicLinksAuthenticateRequest} + * @returns {@link MagicLinksAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: MagicLinksAuthenticateRequest): Promise; + /** + * Create an embeddable Magic Link token for a User. Access to this endpoint is restricted. To enable it, + * please send us a note at support@stytch.com. + * + * ### Next steps + * Send the returned `token` value to the end user in a link which directs to your application. When the + * end user follows your link, collect the token, and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksCreateRequest} + * @returns {@link MagicLinksCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: MagicLinksCreateRequest): Promise; } -export {}; diff --git a/types/lib/b2c/magic_links_email.d.ts b/types/lib/b2c/magic_links_email.d.ts new file mode 100644 index 00000000..64919261 --- /dev/null +++ b/types/lib/b2c/magic_links_email.d.ts @@ -0,0 +1,297 @@ +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { Name } from "./users"; +export interface MagicLinksEmailInviteRequest { + email: 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; + attributes?: Attributes; + name?: Name; + /** + * The URL the end user clicks from the Email Magic Link. This should be a URL that your app receives and + * parses and subsequently sends an API request to authenticate the Magic Link and log in the User. 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 sign-up redirect URL, an error is returned. + */ + invite_magic_link_url?: string; + /** + * Set the expiration for the email magic link, in minutes. By default, it expires in 1 hour. The minimum + * expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + invite_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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface MagicLinksEmailInviteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + email_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; +} +export interface MagicLinksEmailLoginOrCreateRequest { + email: string; + /** + * The URL the end 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; + /** + * The URL the end 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 login email magic link, in minutes. By default, it expires in 1 hour. The + * minimum expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + login_expiration_minutes?: number; + /** + * 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 7 days (10080 mins). + */ + signup_expiration_minutes?: number; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface MagicLinksEmailLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + email_id: string; + user_created: boolean; + /** + * 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; +} +export interface MagicLinksEmailRevokeInviteRequest { + email: string; +} +export interface MagicLinksEmailRevokeInviteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} +export interface MagicLinksEmailSendRequest { + email: string; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + attributes?: Attributes; + /** + * The URL the end 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; + /** + * The URL the end 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 login email magic link, in minutes. By default, it expires in 1 hour. The + * minimum expiration is 5 minutes and the maximum is 7 days (10080 mins). + */ + login_expiration_minutes?: number; + /** + * 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 7 days (10080 mins). + */ + signup_expiration_minutes?: number; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: string; + user_id?: string; + session_token?: string; + session_jwt?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; +} +export interface MagicLinksEmailSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + email_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; +} +export declare class Email { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Send a magic link to an existing Stytch user using their email address. If you'd like to create a user + * and send them a magic link by email with one request, use our + * [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email). + * + * ### Add an email to an existing user + * This endpoint also allows you to add a new email to an existing Stytch User. Including a `user_id`, + * `session_token`, or `session_jwt` in the request will add the email to the pre-existing Stytch User upon + * successful authentication. + * + * Adding a new email to an existing Stytch User requires the user to be present and validate the email via + * magic link. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * The user is emailed a magic link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/guides/magic-links/email-magic-links/redirect-routing). Collect + * the `token` from the URL query parameters, and call + * [Authenticate magic link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailSendRequest} + * @returns {@link MagicLinksEmailSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: MagicLinksEmailSendRequest): Promise; + /** + * Send either a login or signup Magic Link to the User based on if the email is associated with a User + * already. A new or pending User will receive a signup Magic Link. An active User will receive a login + * Magic Link. For more information on how to control the status your Users are created in see the + * `create_user_as_pending` flag. + * + * ### Next steps + * The User is emailed a Magic Link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/magic-links#email-magic-links_redirect-routing). Collect the + * `token` from the URL query parameters and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailLoginOrCreateRequest} + * @returns {@link MagicLinksEmailLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate(data: MagicLinksEmailLoginOrCreateRequest): Promise; + /** + * Create a User and send an invite Magic Link to the provided `email`. The User will be created with a + * `pending` status until they click the Magic Link in the invite email. + * + * ### Next steps + * The User is emailed a Magic Link which redirects them to the provided + * [redirect URL](https://stytch.com/docs/magic-links#email-magic-links_redirect-routing). Collect the + * `token` from the URL query parameters and call + * [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete + * authentication. + * @param data {@link MagicLinksEmailInviteRequest} + * @returns {@link MagicLinksEmailInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + invite(data: MagicLinksEmailInviteRequest): Promise; + /** + * Revoke a pending invite based on the `email` provided. + * @param data {@link MagicLinksEmailRevokeInviteRequest} + * @returns {@link MagicLinksEmailRevokeInviteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + revokeInvite(data: MagicLinksEmailRevokeInviteRequest): Promise; +} diff --git a/types/lib/b2c/oauth.d.ts b/types/lib/b2c/oauth.d.ts index 620d1be0..cf6c6ae3 100644 --- a/types/lib/b2c/oauth.d.ts +++ b/types/lib/b2c/oauth.d.ts @@ -1,46 +1,178 @@ -import { Session, User } from "./shared_b2c"; -import { BaseResponse, fetchConfig } from "../shared"; -export interface B2COAuthAuthenticateRequest { +import { fetchConfig } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface OAuthProviderValues { + access_token: string; + refresh_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 [OpenID Connect](https://openid.net/foundation/) + * specification, which is based on OAuth. + */ + id_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; +} +export interface OAuthAttachRequest { + provider: string; + user_id?: string; session_token?: string; session_jwt?: string; +} +export interface OAuthAttachResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * A single-use token for connecting the Stytch User selection from an OAuth Attach request to the + * corresponding OAuth Start request. + */ + oauth_attach_token: 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; +} +export interface OAuthAuthenticateRequest { + token: string; + /** + * Reuse an existing session instead of creating a new one. If you provide us with a `session_token`, then + * we'll update the session represented by this session token with this OAuth factor. If this + * `session_token` belongs to a different user than the OAuth token, the session_jwt will be ignored. This + * endpoint will error if both `session_token` and `session_jwt` are provided. + */ + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + /** + * Reuse an existing session instead of creating a new one. If you provide us with a `session_jwt`, then + * we'll update the session represented by this JWT with this OAuth factor. If this `session_jwt` belongs + * to a different user than the OAuth token, the session_jwt will be ignored. This endpoint will error if + * both `session_token` and `session_jwt` are provided. + */ + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; code_verifier?: string; } -export interface B2COAuthAuthenticateResponse extends BaseResponse { +export interface OAuthAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; user_id: string; - user: User; - oauth_user_registration_id: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the "sub" or + * "Subject field" in OAuth protocols. + */ provider_subject: string; + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Facebook, GitHub + * etc. + */ provider_type: string; - session_token?: string; - session_jwt?: string; - session?: Session; - provider_values: ProvidersValues; + session_token: string; + session_jwt: 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` is only + * returned by OIDC complaint identity providers. + */ + provider_values: OAuthProviderValues; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * Indicates if all other of the User's Sessions need to be reset. You should check this field if you + * aren't using Stytch's Session product. If you are using Stytch's Session product, we revoke the User's + * other sessions for you. + */ reset_sessions: boolean; -} -export interface ProvidersValues { - access_token?: string; - refresh_token?: string; - id_token?: string; - expires_at?: number; - scopes: string[]; -} -export interface B2COAuthAttachRequest { - provider: string; - /** Exactly one of these user-selection fields must be provided. */ - user_id?: string; - session_token?: string; - session_jwt?: string; -} -export interface B2COAuthAttachResponse extends BaseResponse { - oauth_attach_token: string; + oauth_user_registration_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; + /** + * A `Session` object. For backwards compatibility reasons, the session from an OAuth authenticate call is + * labeled as `user_session`, but is otherwise just a standard stytch `Session` object. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + user_session?: Session; } export declare class OAuth { - base_path: string; private fetchConfig; constructor(fetchConfig: fetchConfig); - private endpoint; - authenticate(token: string, data?: B2COAuthAuthenticateRequest): Promise; - attach(data?: B2COAuthAttachRequest): Promise; + /** + * Generate an OAuth Attach Token to pre-associate an OAuth flow with an existing Stytch User. 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 for a new user. + * + * Exactly one of `user_id`, `session_token`, or `session_jwt` must be provided to identify the target + * Stytch User. + * + * This is an optional step in the OAuth flow. Stytch can often determine whether to create a new user or + * log in an existing one based on verified identity provider information. This endpoint is useful for + * cases where we can't, such as missing or unverified provider information. + * @param data {@link OAuthAttachRequest} + * @returns {@link OAuthAttachResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + attach(data: OAuthAttachRequest): Promise; + /** + * Authenticate a User given a `token`. This endpoint verifies that the user completed the OAuth flow by + * verifying that the token is valid and hasn't expired. To initiate a Stytch session for the user while + * authenticating their OAuth token, include `session_duration_minutes`; a session with the identity + * provider, e.g. Google or Facebook, will always be initiated upon successful authentication. + * @param data {@link OAuthAuthenticateRequest} + * @returns {@link OAuthAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: OAuthAuthenticateRequest): Promise; } diff --git a/types/lib/b2c/otps.d.ts b/types/lib/b2c/otps.d.ts index 52429cce..1d6cd6db 100644 --- a/types/lib/b2c/otps.d.ts +++ b/types/lib/b2c/otps.d.ts @@ -1,141 +1,96 @@ -import { Attributes, Session, User } from "./shared_b2c"; -import { BaseResponse, fetchConfig } from "../shared"; -export interface B2COTPsEmailSendRequest { - email: string; - expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - attributes?: Attributes; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} -export interface B2COTPsEmailSendResponse extends BaseResponse { - user_id: string; - email_id: string; -} -export interface B2COTPsEmailLoginOrCreateRequest { - email: string; - expiration_minutes?: number; - login_template_id?: string; - signup_template_id?: string; - attributes?: Attributes; - create_user_as_pending?: boolean; - locale?: string; -} -export interface B2COTPsEmailLoginOrCreateResponse extends BaseResponse { - user_id: string; - email_id: string; - user_created: boolean; -} -export interface B2COTPsSMSSendRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} -export interface B2COTPsSMSSendResponse extends BaseResponse { - user_id: string; - phone_id: string; -} -export interface B2COTPsSMSLoginOrCreateRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - create_user_as_pending?: boolean; - locale?: string; -} -export interface B2COTPsSMSLoginOrCreateResponse extends BaseResponse { - user_id: string; - phone_id: string; - user_created: boolean; -} -export interface B2COTPsWhatsAppSendRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - user_id?: string; - session_token?: string; - session_jwt?: string; - locale?: string; -} -export interface B2COTPsWhatsAppSendResponse extends BaseResponse { - user_id: string; - phone_id: string; -} -export interface B2COTPsWhatsAppLoginOrCreateRequest { - phone_number: string; - expiration_minutes?: number; - attributes?: Attributes; - create_user_as_pending?: boolean; - locale?: string; -} -export interface B2COTPsWhatsAppLoginOrCreateResponse extends BaseResponse { - user_id: string; - phone_id: string; - user_created: boolean; -} -export interface B2COTPsAuthenticateRequest { +import { Attributes } from "./attribute"; +import { Email } from "./otps_email"; +import { fetchConfig } from "../shared"; +import { Options } from "./magic_links"; +import { Session } from "./sessions"; +import { Sms } from "./otps_sms"; +import { User } from "./users"; +import { Whatsapp } from "./otps_whatsapp"; +export interface OTPsAuthenticateRequest { method_id: string; code: string; attributes?: Attributes; - options?: { - ip_match_required?: boolean; - user_agent_match_required?: boolean; - }; + options?: Options; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; } -export interface B2COTPsAuthenticateResponse extends BaseResponse { +export interface OTPsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; user_id: string; - user: User; method_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * Indicates if all other of the User's Sessions need to be reset. You should check this field if you + * aren't using Stytch's Session product. If you are using Stytch's Session product, we revoke the User's + * other sessions for you. + */ reset_sessions: boolean; -} -declare class Email { - base_path: string; - delivery: string; - private fetchConfig; - constructor(fetchConfig: fetchConfig, base_path: string); - private endpoint; - send(data: B2COTPsEmailSendRequest): Promise; - loginOrCreate(data: B2COTPsEmailLoginOrCreateRequest): Promise; -} -declare class SMS { - base_path: string; - delivery: string; - private fetchConfig; - constructor(fetchConfig: fetchConfig, base_path: string); - private endpoint; - send(data: B2COTPsSMSSendRequest): Promise; - loginOrCreate(data: B2COTPsSMSLoginOrCreateRequest): Promise; -} -declare class WhatsApp { - base_path: string; - delivery: string; - private fetchConfig; - constructor(fetchConfig: fetchConfig, base_path: string); - private endpoint; - send(data: B2COTPsWhatsAppSendRequest): Promise; - loginOrCreate(data: B2COTPsWhatsAppLoginOrCreateRequest): Promise; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; } export declare class OTPs { - base_path: string; - email: Email; - sms: SMS; - whatsapp: WhatsApp; private fetchConfig; + sms: Sms; + whatsapp: Whatsapp; + email: Email; constructor(fetchConfig: fetchConfig); - private endpoint; - authenticate(data: B2COTPsAuthenticateRequest): Promise; + /** + * Authenticate a User given a `method_id` (the associated `email_id` or `phone_id`) and a `code`. This + * endpoint verifies that the code is valid, hasn't expired or been previously used, and any optional + * security settings such as IP match or user agent match are satisfied. A given `method_id` may only have + * a single active OTP code at any given time, if a User requests another OTP code before the first one has + * expired, the first one will be invalidated. + * @param data {@link OTPsAuthenticateRequest} + * @returns {@link OTPsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: OTPsAuthenticateRequest): Promise; } -export {}; diff --git a/types/lib/b2c/otps_email.d.ts b/types/lib/b2c/otps_email.d.ts new file mode 100644 index 00000000..0390d30e --- /dev/null +++ b/types/lib/b2c/otps_email.d.ts @@ -0,0 +1,161 @@ +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +export interface OTPsEmailLoginOrCreateRequest { + /** + * The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test + * this endpoint, see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + email: string; + /** + * 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; + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; +} +export interface OTPsEmailLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + email_id: string; + user_created: boolean; + /** + * 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; +} +export interface OTPsEmailSendRequest { + /** + * The email address of the user to send the one-time passcode to. You may use sandbox@stytch.com to test + * this endpoint, see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + email: string; + /** + * 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; + attributes?: Attributes; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + user_id?: string; + session_token?: string; + session_jwt?: string; + /** + * Use a custom template for login 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 - + * Login. + */ + login_template_id?: string; + /** + * Use a custom template for sign-up 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 - + * Sign-up. + */ + signup_template_id?: string; +} +export interface OTPsEmailSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + email_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; +} +export declare class Email { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Send a one-time passcode (OTP) to a User using their email. If you'd like to create a user and send them + * a passcode with one request, use our + * [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email-otp). + * + * ### Add an email to an existing user + * This endpoint also allows you to add a new email to an existing Stytch User. Including a `user_id`, + * `session_token`, or `session_jwt` in the request will add the email to the pre-existing Stytch User upon + * successful authentication. + * + * Adding a new email to an existing Stytch User requires the User to be present and validate the email via + * OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsEmailSendRequest} + * @returns {@link OTPsEmailSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: OTPsEmailSendRequest): Promise; + /** + * Send a one-time passcode (OTP) to a User using their email. If the email is not associated with a User + * already, a User will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsEmailLoginOrCreateRequest} + * @returns {@link OTPsEmailLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate(data: OTPsEmailLoginOrCreateRequest): Promise; +} diff --git a/types/lib/b2c/otps_sms.d.ts b/types/lib/b2c/otps_sms.d.ts new file mode 100644 index 00000000..7a159793 --- /dev/null +++ b/types/lib/b2c/otps_sms.d.ts @@ -0,0 +1,143 @@ +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +export interface OTPsSmsLoginOrCreateRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface OTPsSmsLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + phone_id: string; + user_created: boolean; + /** + * 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; +} +export interface OTPsSmsSendRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + attributes?: Attributes; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + user_id?: string; + session_token?: string; + session_jwt?: string; +} +export interface OTPsSmsSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + phone_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; +} +export declare class Sms { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Send a one-time passcode (OTP) to a user's phone number. If you'd like to create a user and send them a + * passcode with one request, use our + * [log in or create](https://stytch.com/docs/api/log-in-or-create-user-by-sms) endpoint. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * ### Add a phone number to an existing user + * + * This endpoint also allows you to add a new phone number to an existing Stytch User. Including a + * `user_id`, `session_token`, or `session_jwt` in the request will add the phone number to the + * pre-existing Stytch User upon successful authentication. + * + * Adding a new phone number to an existing Stytch User requires the user to be present and validate the + * phone number via OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsSmsSendRequest} + * @returns {@link OTPsSmsSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: OTPsSmsSendRequest): Promise; + /** + * Send a one-time passcode (OTP) to a User using their phone number. If the phone number is not associated + * with a user already, a user will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsSmsLoginOrCreateRequest} + * @returns {@link OTPsSmsLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate(data: OTPsSmsLoginOrCreateRequest): Promise; +} diff --git a/types/lib/b2c/otps_whatsapp.d.ts b/types/lib/b2c/otps_whatsapp.d.ts new file mode 100644 index 00000000..761e630f --- /dev/null +++ b/types/lib/b2c/otps_whatsapp.d.ts @@ -0,0 +1,143 @@ +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +export interface OTPsWhatsappLoginOrCreateRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + attributes?: Attributes; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; +} +export interface OTPsWhatsappLoginOrCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + phone_id: string; + user_created: boolean; + /** + * 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; +} +export interface OTPsWhatsappSendRequest { + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number: string; + /** + * 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; + attributes?: Attributes; + /** + * 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + user_id?: string; + session_token?: string; + session_jwt?: string; +} +export interface OTPsWhatsappSendResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + phone_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; +} +export declare class Whatsapp { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Send a one-time passcode (OTP) to a User's WhatsApp. If you'd like to create a user and send them a + * passcode with one request, use our + * [log in or create](https://stytch.com/docs/api/whatsapp-login-or-create) endpoint. + * + * Note that sending another OTP code before the first has expired will invalidate the first code. + * + * ### Add a phone number to an existing user + * + * This endpoint also allows you to add a new phone number to an existing Stytch User. Including a + * `user_id`, `session_token`, or `session_jwt` in the request will add the phone number to the + * pre-existing Stytch User upon successful authentication. + * + * Adding a new phone number to an existing Stytch User requires the user to be present and validate the + * phone number via OTP. This requirement is in place to prevent account takeover attacks. + * + * ### Next steps + * + * Collect the OTP which was delivered to the user. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsWhatsappSendRequest} + * @returns {@link OTPsWhatsappSendResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + send(data: OTPsWhatsappSendRequest): Promise; + /** + * Send a one-time passcode (OTP) to a User's WhatsApp using their phone number. If the phone number is not + * associated with a User already, a User will be created. + * + * ### Next steps + * + * Collect the OTP which was delivered to the User. Call + * [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the + * `phone_id` found in the response as the `method_id`. + * @param data {@link OTPsWhatsappLoginOrCreateRequest} + * @returns {@link OTPsWhatsappLoginOrCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + loginOrCreate(data: OTPsWhatsappLoginOrCreateRequest): Promise; +} diff --git a/types/lib/b2c/passwords.d.ts b/types/lib/b2c/passwords.d.ts index fc9f44e2..3af64546 100644 --- a/types/lib/b2c/passwords.d.ts +++ b/types/lib/b2c/passwords.d.ts @@ -1,146 +1,393 @@ -import { Attributes, Name, Session, User } from "./shared_b2c"; -import { BaseResponse, fetchConfig } from "../shared"; -import { UserMetadata } from "./users"; -import * as shared from "../shared/passwords"; -export interface B2CPasswordsCreateRequest { - email: string; - password: string; - name?: Name; - session_duration_minutes?: number; - session_custom_claims?: Record; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; +import { Email } from "./passwords_email"; +import { ExistingPassword } from "./passwords_existing_password"; +import { fetchConfig } from "../shared"; +import { Name, User } from "./users"; +import { Session } from "./sessions"; +import { Sessions } from "./passwords_session"; +export interface Argon2Config { + salt: string; + iteration_amount: number; + memory: number; + threads: number; + key_length: number; } -export interface B2CPasswordsCreateResponse extends BaseResponse { - user_id: string; - user: User; - email_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; +export interface Feedback { + /** + * For `zxcvbn` validation, contains an end user consumable warning if the password is valid but not strong + * enough. + */ + warning: string; + /** + * For `zxcvbn` validation, contains end user consumable suggestions on how to improve the strength of the + * password. + */ + suggestions: 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?: LUDSRequirements; +} +export interface LUDSRequirements { + has_lower_case: boolean; + has_upper_case: boolean; + has_digit: boolean; + /** + * For LUDS validation, whether the password contains at least one symbol. Any UTF8 character outside of + * a-z or A-Z may count as a valid symbol. + */ + has_symbol: boolean; + /** + * For LUDS validation, the number of complexity requirements that are missing from the password. Check the + * complexity fields to see which requirements are missing. + */ + missing_complexity: number; + /** + * For LUDS validation, this is the required length of the password that you've set minus the length of the + * password being checked. The user will need to add this many characters to the password to make it valid. + */ + missing_characters: number; +} +export interface MD5Config { + prepend_salt: string; + append_salt: string; +} +export interface PBKDF2Config { + salt: string; + iteration_amount: number; + key_length: number; } -export interface B2CPasswordsAuthenticateRequest { +export interface SHA1Config { + prepend_salt: string; + append_salt: string; +} +export interface ScryptConfig { + salt: string; + /** + * The N value, also known as the iterations count. It must be a power of two greater than 1 and less than + * 262,145. + * If your applicaiton's N parameter is larger than 262,144, please reach out to + * [support@stytch.com](mailto:support@stytch.com) + */ + n_parameter: number; + r_parameter: number; + p_parameter: number; + key_length: number; +} +export interface PasswordsAuthenticateRequest { email: string; password: string; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; } -export interface B2CPasswordsAuthenticateResponse extends BaseResponse { +export interface PasswordsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; user_id: string; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - session_token?: string; - session_jwt?: 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } -export interface B2CPasswordsResetByEmailStartRequest { +export interface PasswordsCreateRequest { email: string; - login_redirect_url?: string; - reset_password_redirect_url?: string; - reset_password_expiration_minutes?: number; - reset_password_template_id?: string; - attributes?: Attributes; - code_challenge?: string; - locale?: string; -} -export interface B2CPasswordsResetByEmailStartResponse extends BaseResponse { - user_id: string; - email_id: string; -} -export interface B2CPasswordsResetByEmailRequest { - options?: { - ip_match_required?: boolean; - user_agent_match_required?: boolean; - }; - attributes?: Attributes; - session_token?: string; - session_jwt?: string; + password: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; - code_verifier?: string; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; + name?: Name; } -export interface B2CPasswordsResetByEmailResponse extends BaseResponse { +export interface PasswordsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; user_id: string; + email_id: string; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - session_token?: string; - session_jwt?: 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } -export interface B2CPasswordsResetByExistingPasswordRequest { +export interface PasswordsMigrateRequest { email: string; - existing_password: string; - new_password: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; + hash: string; + /** + * The password hash used. Currently `bcrypt`, `scrypt`, `argon_2i`, `argon_2id`, `md_5`, `sha_1`, and + * `pbkdf_2` are supported. + */ + hash_type: "bcrypt" | "md_5" | "argon_2i" | "argon_2id" | "sha_1" | "scrypt" | "phpass" | "pbkdf_2" | string; + md_5_config?: MD5Config; + argon_2_config?: Argon2Config; + sha_1_config?: SHA1Config; + /** + * Required parameters if the scrypt is not provided in a + * [PHC encoded form](https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#phc-string-format). + */ + scrypt_config?: ScryptConfig; + pbkdf_2_config?: PBKDF2Config; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; + name?: Name; } -export interface B2CPasswordsResetByExistingPasswordResponse extends BaseResponse { +export interface PasswordsMigrateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; user_id: string; + email_id: string; + user_created: boolean; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - session_token?: string; - session_jwt?: string; - session?: Session; + /** + * 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; } -export interface B2CPasswordsResetBySessionRequest { +export interface PasswordsStrengthCheckRequest { password: string; - session_token?: string; - session_jwt?: string; -} -export interface B2CPasswordsResetBySessionResponse extends BaseResponse { - user_id: string; - user: User; - session: Session; -} -export interface B2CPasswordsStrengthCheckRequest { email?: string; - password: string; } -export interface B2CPasswordsStrengthCheckResponse extends BaseResponse { +export interface PasswordsStrengthCheckResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * Returns `true` if the password passes our password validation. We offer two validation options, + * [zxcvbn](https://stytch.com/docs/passwords#strength-requirements) is the default option which offers a + * high level of sophistication. We also offer + * [LUDS](https://stytch.com/docs/passwords#strength-requirements). If an email address is included in the + * call we also require that the password hasn't been compromised using built-in breach detection powered + * by [HaveIBeenPwned](https://haveibeenpwned.com/). + */ valid_password: boolean; + /** + * The score of the password determined by [zxcvbn](https://github.com/dropbox/zxcvbn). Values will be + * between 1 and 4, a 3 or greater is required to pass validation. + */ score: number; + /** + * Returns `true` if the password has been breached. Powered by + * [HaveIBeenPwned](https://haveibeenpwned.com/). + */ breached_password: boolean; strength_policy: string; + /** + * 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](mailto:support@stytch.com?subject=Password%20strength%20configuration). If this + * value is `false` then `breached_password` will always be `false` as well. + */ breach_detection_on_create: boolean; - feedback: { - suggestions: string[]; - warning: string; - luds_requirements: { - has_lower_case: boolean; - has_upper_case: boolean; - has_digit: boolean; - has_symbol: boolean; - missing_complexity: number; - missing_characters: number; - }; - }; -} -interface MigrateRequestBase { - email: string; - hash: string; - name?: Name; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; -} -export declare type B2CPasswordsMigrateRequest = (shared.MD5MigrateRequest & MigrateRequestBase) | (shared.BcryptMigrateRequest & MigrateRequestBase) | (shared.Argon2IMigrateRequest & MigrateRequestBase) | (shared.Argon2IDMigrateRequest & MigrateRequestBase) | (shared.SHA1MigrateRequest & MigrateRequestBase) | (shared.ScryptMigrateRequest & MigrateRequestBase) | (shared.PHPassMigrateRequest & MigrateRequestBase) | (shared.PBKDF2MigrateRequest & MigrateRequestBase); -export interface B2CPasswordsMigrateResponse extends BaseResponse { - user_id: string; - email_id: string; - user_created: boolean; + /** + * 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; + feedback?: Feedback; } export declare class Passwords { - base_path: string; private fetchConfig; + email: Email; + existingPassword: ExistingPassword; + sessions: Sessions; constructor(fetchConfig: fetchConfig); - private endpoint; - create(data: B2CPasswordsCreateRequest): Promise; - authenticate(data?: B2CPasswordsAuthenticateRequest): Promise; - resetByEmailStart(data: B2CPasswordsResetByEmailStartRequest): Promise; - resetByEmail(token: string, password: string, data?: B2CPasswordsResetByEmailRequest): Promise; - resetByExistingPassword(data: B2CPasswordsResetByExistingPasswordRequest): Promise; - resetBySession(data: B2CPasswordsResetBySessionRequest): Promise; - strengthCheck(data: B2CPasswordsStrengthCheckRequest): Promise; - migrate(data: B2CPasswordsMigrateRequest): Promise; -} -export {}; + /** + * Create a new user with a password and an authenticated session for the user if requested. 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 password strength endpoint. + * @param data {@link PasswordsCreateRequest} + * @returns {@link PasswordsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: PasswordsCreateRequest): Promise; + /** + * Authenticate a user with their email address and password. This endpoint verifies that the user has a + * password currently set, and that the entered password is correct. There are two instances where the + * endpoint will return a `reset_password` error even if they enter their previous password: + * + * **One:** The user’s credentials appeared in the HaveIBeenPwned dataset. We force a password reset to + * ensure that the user is the legitimate owner of the email address, and not a malicious actor abusing the + * compromised credentials. + * + * **Two:** A user that has previously authenticated with email/password uses a passwordless authentication + * method tied to the same email address (e.g. Magic Links, Google OAuth) for the first time. Any + * subsequent email/password authentication attempt will result in this error. We force a password reset in + * this instance in order to safely deduplicate the account by email address, without introducing the risk + * of a pre-hijack account takeover attack. + * + * Imagine a bad actor creates many accounts using passwords and the known email addresses of their + * victims. If a victim comes to the site and logs in for the first time with an email-based passwordless + * authentication method then both the victim and the bad actor have credentials to access to the same + * account. To prevent this, any further email/password login attempts first require a password reset which + * can only be accomplished by someone with access to the underlying email address. + * @param data {@link PasswordsAuthenticateRequest} + * @returns {@link PasswordsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: PasswordsAuthenticateRequest): Promise; + /** + * This API 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. + * + * This endpoint adapts to your Project's password strength configuration. If you're using + * [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your passwords are + * considered valid if the strength score is >= 3. If you're using + * [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are considered valid if + * they meet the requirements that you've set with Stytch. You may update your password strength + * configuration in the [stytch dashboard](https://stytch.com/dashboard/password-strength-config). + * + * + * ### Password feedback + * + * The `feedback` object contains relevant fields for you to relay feedback to users that failed to create + * a strong enough password. + * + * If you're using zxcvbn, the `feedback` object will contain `warning` and `suggestions` for any password + * that does not meet the zxcvbn strength requirements. You can return these strings directly to the user + * to help them craft a strong password. + * + * If you're using LUDS, the `feedback` object will contain an object named `luds_requirements` which + * contain a collection of fields that the user failed or passed. You'll want to prompt the user to create + * a password that meets all of the requirements that they failed. + * @param data {@link PasswordsStrengthCheckRequest} + * @returns {@link PasswordsStrengthCheckResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + strengthCheck(data: PasswordsStrengthCheckRequest): Promise; + /** + * Adds an existing password to a User's email that doesn't have a password yet. We support migrating users + * from passwords stored with `bcrypt`, `scrypt`, `argon2`, `MD-5`, `SHA-1`, or `PBKDF2`. This endpoint has + * a rate limit of 100 requests per second. + * @param data {@link PasswordsMigrateRequest} + * @returns {@link PasswordsMigrateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + migrate(data: PasswordsMigrateRequest): Promise; +} diff --git a/types/lib/b2c/passwords_email.d.ts b/types/lib/b2c/passwords_email.d.ts new file mode 100644 index 00000000..46ea5d1b --- /dev/null +++ b/types/lib/b2c/passwords_email.d.ts @@ -0,0 +1,161 @@ +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { Options } from "./magic_links"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface PasswordsEmailResetRequest { + token: string; + password: string; + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + session_jwt?: string; + code_verifier?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; + attributes?: Attributes; + options?: Options; +} +export interface PasswordsEmailResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; +} +export interface PasswordsEmailResetStartRequest { + email: string; + /** + * 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; + /** + * A base64url encoded SHA256 hash of a one time secret used to validate that the request starts and ends + * on the same device. + */ + code_challenge?: string; + attributes?: Attributes; + /** + * The URL Stytch redirects to after the OAuth flow is completed for a user that already exists. This URL + * should be a route in your application which will run `oauth.authenticate` (see below) and finish the + * login. + * + * The URL must be configured as a Login URL in the [Redirect URL page](/dashboard/redirect-urls). If the + * field is not specified, the default Login URL will be used. + */ + login_redirect_url?: 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. + * + * Request support for additional languages + * [here](https://docs.google.com/forms/d/e/1FAIpQLScZSpAu_m2AmLXRT3F3kap-s_mcV6UTBitYn6CdyWP0-o7YjQ/viewform?usp=sf_link")! + * + */ + locale?: "en" | "es" | "pt-br" | string; + /** + * Use a custom template for password reset 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 Passwords + * - Password reset. + */ + reset_password_template_id?: string; +} +export interface PasswordsEmailResetStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + email_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; +} +export declare class Email { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * 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. + * @param data {@link PasswordsEmailResetStartRequest} + * @returns {@link PasswordsEmailResetStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + resetStart(data: PasswordsEmailResetStartRequest): Promise; + /** + * Reset the user’s password and authenticate them. This endpoint checks that the magic link `token` is + * valid, hasn’t expired, or already been used – and can optionally require additional security settings, + * such as the IP address and user agent matching the initial reset request. + * + * The provided password needs to meet our password strength requirements, which can be checked in advance + * with the password strength endpoint. If the token and password are accepted, the password is securely + * stored for future authentication and the user is authenticated. + * @param data {@link PasswordsEmailResetRequest} + * @returns {@link PasswordsEmailResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset(data: PasswordsEmailResetRequest): Promise; +} diff --git a/types/lib/b2c/passwords_existing_password.d.ts b/types/lib/b2c/passwords_existing_password.d.ts new file mode 100644 index 00000000..92503d58 --- /dev/null +++ b/types/lib/b2c/passwords_existing_password.d.ts @@ -0,0 +1,76 @@ +import { fetchConfig } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface PasswordsExistingPasswordResetRequest { + email: string; + existing_password: string; + new_password: string; + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; +} +export interface PasswordsExistingPasswordResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; +} +export declare class ExistingPassword { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Reset the User’s password using their existing password. + * @param data {@link PasswordsExistingPasswordResetRequest} + * @returns {@link PasswordsExistingPasswordResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset(data: PasswordsExistingPasswordResetRequest): Promise; +} diff --git a/types/lib/b2c/passwords_session.d.ts b/types/lib/b2c/passwords_session.d.ts new file mode 100644 index 00000000..fb1b8db7 --- /dev/null +++ b/types/lib/b2c/passwords_session.d.ts @@ -0,0 +1,50 @@ +import { fetchConfig } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface PasswordsSessionResetRequest { + password: string; + session_token?: string; + session_jwt?: string; +} +export interface PasswordsSessionResetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; +} +export declare class Sessions { + private fetchConfig; + constructor(fetchConfig: fetchConfig); + /** + * Reset the user’s password using their existing session. The endpoint will error if the session does not + * have a password, email magic link, or email OTP authentication factor that has been issued within the + * last 5 minutes. This endpoint requires either a `session_jwt` or `session_token` be included in the + * request. + * @param data {@link PasswordsSessionResetRequest} + * @returns {@link PasswordsSessionResetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + reset(data: PasswordsSessionResetRequest): Promise; +} diff --git a/types/lib/b2c/sessions.d.ts b/types/lib/b2c/sessions.d.ts index 777a4393..fe9879bb 100644 --- a/types/lib/b2c/sessions.d.ts +++ b/types/lib/b2c/sessions.d.ts @@ -1,54 +1,387 @@ -import { Session, User } from "./shared_b2c"; -import { fetchConfig, BaseResponse } from "../shared"; import { JwtConfig } from "../shared/sessions"; -export interface B2CSessionsGetRequest { - user_id: string; +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +import { User } from "./users"; +export interface AmazonOAuthFactor { + id: string; + email_id: string; + provider_subject: string; } -export interface B2CSessionsGetResponse extends BaseResponse { - sessions: Session[]; +export interface AppleOAuthFactor { + id: string; + email_id: string; + provider_subject: string; } -export interface B2CSessionsJwksResponse extends BaseResponse { - keys: JWK[]; +export interface AuthenticationFactor { + type: "magic_link" | "otp" | "oauth" | "webauthn" | "totp" | "crypto" | "password" | "signature_challenge" | "sso" | string; + delivery_method: "email" | "sms" | "whatsapp" | "embedded" | "oauth_google" | "oauth_microsoft" | "oauth_apple" | "webauthn_registration" | "authenticator_app" | "oauth_github" | "recovery_code" | "oauth_facebook" | "crypto_wallet" | "oauth_amazon" | "oauth_bitbucket" | "oauth_coinbase" | "oauth_discord" | "oauth_figma" | "oauth_gitlab" | "oauth_instagram" | "oauth_linkedin" | "oauth_shopify" | "oauth_slack" | "oauth_snapchat" | "oauth_spotify" | "oauth_steam" | "oauth_tiktok" | "oauth_twitch" | "oauth_twitter" | "knowledge" | "biometric" | "sso_saml" | "sso_oidc" | "oauth_salesforce" | "oauth_yahoo" | string; + last_authenticated_at?: string; + created_at?: string; + updated_at?: string; + email_factor?: EmailFactor; + phone_number_factor?: PhoneNumberFactor; + google_oauth_factor?: GoogleOAuthFactor; + microsoft_oauth_factor?: MicrosoftOAuthFactor; + apple_oauth_factor?: AppleOAuthFactor; + webauthn_factor?: WebAuthnFactor; + authenticator_app_factor?: AuthenticatorAppFactor; + github_oauth_factor?: GithubOAuthFactor; + recovery_code_factor?: RecoveryCodeFactor; + facebook_oauth_factor?: FacebookOAuthFactor; + crypto_wallet_factor?: CryptoWalletFactor; + amazon_oauth_factor?: AmazonOAuthFactor; + bitbucket_oauth_factor?: BitbucketOAuthFactor; + coinbase_oauth_factor?: CoinbaseOAuthFactor; + discord_oauth_factor?: DiscordOAuthFactor; + figma_oauth_factor?: FigmaOAuthFactor; + git_lab_oauth_factor?: GitLabOAuthFactor; + instagram_oauth_factor?: InstagramOAuthFactor; + linked_in_oauth_factor?: LinkedInOAuthFactor; + shopify_oauth_factor?: ShopifyOAuthFactor; + slack_oauth_factor?: SlackOAuthFactor; + snapchat_oauth_factor?: SnapchatOAuthFactor; + spotify_oauth_factor?: SpotifyOAuthFactor; + steam_oauth_factor?: SteamOAuthFactor; + tik_tok_oauth_factor?: TikTokOAuthFactor; + twitch_oauth_factor?: TwitchOAuthFactor; + twitter_oauth_factor?: TwitterOAuthFactor; + embeddable_magic_link_factor?: EmbeddableMagicLinkFactor; + biometric_factor?: BiometricFactor; + saml_sso_factor?: SAMLSSOFactor; + oidc_sso_factor?: OIDCSSOFactor; + salesforce_oauth_factor?: SalesforceOAuthFactor; + yahoo_oauth_factor?: YahooOAuthFactor; +} +export interface AuthenticatorAppFactor { + totp_id: string; +} +export interface BiometricFactor { + biometric_registration_id: string; +} +export interface BitbucketOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface CoinbaseOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface CryptoWalletFactor { + crypto_wallet_id: string; + crypto_wallet_address: string; + crypto_wallet_type: string; +} +export interface DiscordOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface EmailFactor { + email_id: string; + email_address: string; +} +export interface EmbeddableMagicLinkFactor { + embedded_id: string; +} +export interface FacebookOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface FigmaOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface GitLabOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface GithubOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface GoogleOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface InstagramOAuthFactor { + id: string; + email_id: string; + provider_subject: string; } export interface JWK { - alg: string; - key_ops: string[]; - kid: string; kty: string; use: string; + key_ops: string[]; + alg: string; + kid: string; x5c: string[]; - "x5t#S256": string; + x5tS256: string; n: string; e: string; } -export interface B2CSessionsAuthenticateRequest { - session_duration_minutes?: number; +export interface LinkedInOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface MicrosoftOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface OIDCSSOFactor { + id: string; + provider_id: string; + external_id: string; +} +export interface PhoneNumberFactor { + phone_id: string; + phone_number: string; +} +export interface RecoveryCodeFactor { + totp_recovery_code_id: string; +} +export interface SAMLSSOFactor { + id: string; + provider_id: string; + external_id: string; +} +export interface SalesforceOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface Session { + session_id: string; + user_id: string; + authentication_factors: AuthenticationFactor[]; + /** + * The timestamp when the Session was created. Values conform to the RFC 3339 standard and are expressed in + * UTC, e.g. `2021-12-29T12:33:09Z`. + */ + started_at?: string; + /** + * The timestamp when the Session was last 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 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; + attributes?: Attributes; + /** + * The custom claims map for a Session. Claims can be added to a session during a Sessions authenticate + * call. + */ + custom_claims?: Record; +} +export interface ShopifyOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface SlackOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface SnapchatOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface SpotifyOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface SteamOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface TikTokOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface TwitchOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface TwitterOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface WebAuthnFactor { + webauthn_registration_id: string; + domain: string; + user_agent: string; +} +export interface YahooOAuthFactor { + id: string; + email_id: string; + provider_subject: string; +} +export interface SessionsAuthenticateRequest { session_token?: string; + /** + * Set the session lifetime to be this many minutes from now; minimum of 5 and a maximum of 527040 minutes + * (366 days). Note that a successful authentication will continue to extend the session this many minutes. + */ + session_duration_minutes?: number; + /** + * The JWT to authenticate. You may provide a JWT that has expired according to its `exp` claim and needs + * to be refreshed. If the signature is valid and the underlying session is still active then Stytch will + * return a new JWT. + */ session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; } -export interface B2CSessionsAuthenticateResponse extends BaseResponse { +export interface SessionsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session: Session; - user: User; session_token: string; session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface SessionsGetJWKSRequest { + project_id: string; +} +export interface SessionsGetJWKSResponse { + keys: JWK[]; + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} +export interface SessionsGetRequest { + user_id: string; } -export interface B2CSessionsRevokeRequest { +export interface SessionsGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + sessions: Session[]; + /** + * 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; +} +export interface SessionsRevokeRequest { session_id?: string; session_token?: string; session_jwt?: string; } -export declare type B2CSessionsRevokeResponse = BaseResponse; +export interface SessionsRevokeResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we 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; +} export declare class Sessions { - base_path: string; private fetchConfig; private jwksClient; private jwtOptions; constructor(fetchConfig: fetchConfig, jwtConfig: JwtConfig); - private endpoint; - get(params: B2CSessionsGetRequest): Promise; - jwks(project_id: string): Promise; - authenticate(data: B2CSessionsAuthenticateRequest): Promise; + /** + * List all active Sessions for a given `user_id`. All timestamps are formatted according to the RFC 3339 + * standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. + * @param data {@link SessionsGetRequest} + * @returns {@link SessionsGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: SessionsGetRequest): Promise; + /** + * Authenticate a session token and retrieve associated session data. If `session_duration_minutes` is + * included, update the lifetime of the session to be that many minutes from now. All timestamps are + * formatted according to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. This + * endpoint requires exactly one `session_jwt` or `session_token` as part of the request. If both are + * included you will receive a `too_many_session_arguments` error. + * @param data {@link SessionsAuthenticateRequest} + * @returns {@link SessionsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: SessionsAuthenticateRequest): Promise; + /** + * Revoke a Session, immediately invalidating all of its session tokens. You can revoke a session in three + * ways: using its ID, or using one of its session tokens, or one of its JWTs. This endpoint requires + * exactly one of those to be included in the request. It will return an error if multiple are present. + * @param data {@link SessionsRevokeRequest} + * @returns {@link SessionsRevokeResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + revoke(data: SessionsRevokeRequest): Promise; + /** + * Get the JSON Web Key Set (JWKS) for a Stytch Project. + * @param data {@link SessionsGetJWKSRequest} + * @returns {@link SessionsGetJWKSResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + getJWKS(params: SessionsGetJWKSRequest): Promise; /** Parse a JWT and verify the signature, preferring local verification over remote. * * If max_token_age_seconds is set, remote verification will be forced if the JWT was issued at @@ -82,5 +415,4 @@ export declare class Sessions { max_token_age_seconds?: number; current_date?: Date; }): Promise; - revoke(data: B2CSessionsRevokeRequest): Promise; } diff --git a/types/lib/b2c/shared_b2c.d.ts b/types/lib/b2c/shared_b2c.d.ts deleted file mode 100644 index 74928425..00000000 --- a/types/lib/b2c/shared_b2c.d.ts +++ /dev/null @@ -1,323 +0,0 @@ -import { UserMetadata, UserID } from "./users"; -export interface Attributes { - ip_address?: string; - user_agent?: string; -} -export interface Name { - first_name?: string; - middle_name?: string; - last_name?: string; -} -export interface Email { - email_id: string; - email: string; - verified: boolean; -} -export interface PhoneNumber { - phone_id: string; - phone_number: string; - verified: boolean; -} -export interface WebAuthnRegistration { - webauthn_registration_id: string; - domain: string; - user_agent: string; - verified: boolean; - authenticator_type: string; -} -export interface BiometricRegistration { - biometric_registration_id: string; - verified: boolean; -} -export interface TOTP { - totp_id: string; - verified: boolean; -} -export interface Password { - password_id: string; - requires_reset: boolean; -} -export interface User { - user_id: UserID; - created_at: string; - status: string; - name: Name; - emails: Email[]; - password?: Password; - phone_numbers: PhoneNumber[]; - providers: OAuthProvider[]; - webauthn_registrations: WebAuthnRegistration[]; - biometric_registrations: BiometricRegistration[]; - totps: TOTP[]; - crypto_wallets: CryptoWallet[]; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; -} -export interface CryptoWallet { - crypto_wallet_id: string; - crypto_wallet_address: string; - crypto_wallet_type: string; - verified: boolean; -} -export interface OAuthProvider { - oauth_user_registration_id: string; - provider_subject: string; - provider_type: string; - profile_picture_url: string; - locale: string; -} -export interface EmailFactor { - delivery_method: "email" | "embedded"; - type: string; - last_authenticated_at: string; - email_factor: { - email_id: string; - email_address: string; - }; -} -export interface PhoneNumberFactor { - delivery_method: "sms" | "whatsapp"; - type: string; - last_authenticated_at: string; - phone_number_factor: { - phone_id: string; - phone_number: string; - }; -} -export interface GoogleOAuthFactor { - delivery_method: "oauth_google"; - type: string; - last_authenticated_at: string; - google_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface MicrosoftOAuthFactor { - delivery_method: "oauth_microsoft"; - type: string; - last_authenticated_at: string; - microsoft_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface AppleOAuthFactor { - delivery_method: "oauth_apple"; - type: string; - last_authenticated_at: string; - apple_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface GithubOAuthFactor { - delivery_method: "oauth_github"; - type: string; - last_authenticated_at: string; - github_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface GitLabOAuthFactor { - delivery_method: "oauth_gitlab"; - type: string; - last_authenticated_at: string; - gitlab_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface FacebookOAuthFactor { - delivery_method: "oauth_facebook"; - type: string; - last_authenticated_at: string; - facebook_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface DiscordOAuthFactor { - delivery_method: "oauth_discord"; - type: string; - last_authenticated_at: string; - discord_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface SalesforceOAuthFactor { - delivery_method: "oauth_salesforce"; - type: string; - last_authenticated_at: string; - salesforce_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface SlackOAuthFactor { - delivery_method: "oauth_slack"; - type: string; - last_authenticated_at: string; - slack_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface AmazonOAuthFactor { - delivery_method: "oauth_amazon"; - type: string; - last_authenticated_at: string; - amazon_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface BitbucketOAuthFactor { - delivery_method: "oauth_bitbucket"; - type: string; - last_authenticated_at: string; - bitbucket_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface LinkedInOAuthFactor { - delivery_method: "oauth_linkedin"; - type: string; - last_authenticated_at: string; - linkedin_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface CoinbaseOAuthFactor { - delivery_method: "oauth_coinbase"; - type: string; - last_authenticated_at: string; - coinbase_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface TwitchOAuthFactor { - delivery_method: "oauth_twitch"; - type: string; - last_authenticated_at: string; - twitch_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface TwitterOAuthFactor { - delivery_method: "oauth_twitter"; - type: string; - last_authenticated_at: string; - twitter_oauth_factor: { - id: string; - provider_subject: string; - }; -} -export interface TikTokOAuthFactor { - delivery_method: "oauth_tiktok"; - type: string; - last_authenticated_at: string; - tiktok_oauth_factor: { - id: string; - provider_subject: string; - }; -} -export interface FigmaOAuthFactor { - delivery_method: "oauth_figma"; - type: string; - last_authenticated_at: string; - figma_oauth_factor: { - id: string; - email_id: string; - provider_subject: string; - }; -} -export interface SnapchatOAuthFactor { - delivery_method: "oauth_snapchat"; - type: string; - last_authenticated_at: string; - snapchat_oauth_factor: { - id: string; - provider_subject: string; - }; -} -export interface WebAuthnFactor { - delivery_method: "webauthn_registration"; - type: string; - last_authenticated_at: string; - webauthn_factor: { - webauthn_registration_id: string; - domain: string; - user_agent: string; - }; -} -export interface BiometricFactor { - delivery_method: "biometric"; - type: string; - last_authenticated_at: string; - biometric_factor: { - biometric_registration_id: string; - }; -} -export interface AuthenticatorAppFactor { - delivery_method: "authenticator_app"; - type: string; - last_authenticated_at: string; - authenticator_app_factor: { - totp_id: string; - }; -} -export interface RecoveryCodeFactor { - delivery_method: "recovery_code"; - type: string; - last_authenticated_at: string; - recovery_code_factor: { - totp_recovery_code_id: string; - }; -} -export 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; - }; -} -export interface PasswordFactor { - delivery_method: "knowledge"; - type: string; - last_authenticated_at: string; -} -export declare type B2CAuthenticationFactor = EmailFactor | PhoneNumberFactor | GoogleOAuthFactor | MicrosoftOAuthFactor | AppleOAuthFactor | GithubOAuthFactor | GitLabOAuthFactor | FacebookOAuthFactor | DiscordOAuthFactor | SalesforceOAuthFactor | SlackOAuthFactor | AmazonOAuthFactor | BitbucketOAuthFactor | LinkedInOAuthFactor | CoinbaseOAuthFactor | TwitchOAuthFactor | TwitterOAuthFactor | TikTokOAuthFactor | SnapchatOAuthFactor | FigmaOAuthFactor | WebAuthnFactor | BiometricFactor | AuthenticatorAppFactor | RecoveryCodeFactor | CryptoWalletFactor | PasswordFactor; -export interface Session { - session_id: string; - user_id: string; - started_at: string; - last_accessed_at: string; - expires_at: string; - attributes: Attributes; - authentication_factors: B2CAuthenticationFactor[]; - custom_claims?: Record; -} diff --git a/types/lib/b2c/totps.d.ts b/types/lib/b2c/totps.d.ts index 51aeab25..941e62dd 100644 --- a/types/lib/b2c/totps.d.ts +++ b/types/lib/b2c/totps.d.ts @@ -1,68 +1,224 @@ -import { Session, User } from "./shared_b2c"; -import { BaseResponse, fetchConfig } from "../shared"; -export interface TOTP { +import { fetchConfig } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface TOTPWithRecoveryCodes { totp_id: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ verified: boolean; recovery_codes: string[]; } -export interface B2CTOTPsCreateRequest { - user_id: string; - expiration_minutes?: number; -} -export interface B2CTOTPsCreateResponse extends BaseResponse { - totp_id: string; - secret: string; - qr_code: string; - recovery_codes: string[]; - user: User; - user_id: string; -} -export interface B2CTOTPsAuthenticateRequest { +export interface TOTPsAuthenticateRequest { user_id: string; totp_code: string; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; } -export interface B2CTOTPsAuthenticateResponse extends BaseResponse { +export interface TOTPsAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; user_id: string; - user: User; + session_token: string; totp_id: string; - session_token?: string; - session_jwt?: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } -export interface B2CTOTPsRecoveryCodesRequest { +export interface TOTPsCreateRequest { user_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; } -export interface B2CTOTPsRecoveryCodesResponse extends BaseResponse { +export interface TOTPsCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + totp_id: string; + secret: string; + qr_code: string; + recovery_codes: string[]; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; user_id: string; - totps: TOTP[]; + /** + * 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; } -export interface B2CTOTPsRecoverRequest { +export interface TOTPsRecoverRequest { user_id: string; recovery_code: string; session_token?: string; - session_jwt?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ session_custom_claims?: Record; } -export interface B2CTOTPsRecoverResponse extends BaseResponse { +export interface TOTPsRecoverResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + totp_id: string; user_id: string; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; - totp_id: string; - session_token?: string; - session_jwt?: 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ session?: Session; } +export interface TOTPsRecoveryCodesRequest { + user_id: string; +} +export interface TOTPsRecoveryCodesResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * An array containing a list of all TOTP instances (along with their recovery codes) for a given User in + * the Stytch API. + */ + totps: TOTPWithRecoveryCodes[]; + /** + * 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; +} export declare class TOTPs { - base_path: string; private fetchConfig; constructor(fetchConfig: fetchConfig); - private endpoint; - create(data: B2CTOTPsCreateRequest): Promise; - authenticate(data: B2CTOTPsAuthenticateRequest): Promise; - recoveryCodes(data: B2CTOTPsRecoveryCodesRequest): Promise; - recover(data: B2CTOTPsRecoverRequest): Promise; + /** + * 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. + * @param data {@link TOTPsCreateRequest} + * @returns {@link TOTPsCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: TOTPsCreateRequest): Promise; + /** + * Authenticate a TOTP code entered by a user. + * @param data {@link TOTPsAuthenticateRequest} + * @returns {@link TOTPsAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: TOTPsAuthenticateRequest): Promise; + /** + * Retrieve the recovery codes for a TOTP instance tied to a User. + * @param data {@link TOTPsRecoveryCodesRequest} + * @returns {@link TOTPsRecoveryCodesResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + recoveryCodes(data: TOTPsRecoveryCodesRequest): Promise; + /** + * Authenticate a recovery code for a TOTP instance. + * @param data {@link TOTPsRecoverRequest} + * @returns {@link TOTPsRecoverResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + recover(data: TOTPsRecoverRequest): Promise; } diff --git a/types/lib/b2c/users.d.ts b/types/lib/b2c/users.d.ts index 3ffcf04c..b2ae0399 100644 --- a/types/lib/b2c/users.d.ts +++ b/types/lib/b2c/users.d.ts @@ -1,29 +1,509 @@ -import { BaseResponse, fetchConfig } from "../shared"; -import { Attributes, CryptoWallet, Email, Name, PhoneNumber, User } from "./shared_b2c"; -export declare type UserID = string; -export declare type UserMetadata = Record; -export interface B2CUsersCreateRequest { +import { Attributes } from "./attribute"; +import { fetchConfig } from "../shared"; +export interface BiometricRegistration { + biometric_registration_id: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} +export interface CryptoWallet { + crypto_wallet_id: string; + crypto_wallet_address: string; + crypto_wallet_type: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} +export interface Email { + email_id: string; + email: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} +export interface Name { + first_name?: string; + middle_name?: string; + last_name?: string; +} +export interface OAuthProvider { + /** + * Denotes the OAuth identity provider that the user has authenticated with, e.g. Google, Facebook, GitHub + * etc. + */ + provider_type: string; + /** + * The unique identifier for the User within a given OAuth provider. Also commonly called the "sub" or + * "Subject field" in OAuth protocols. + */ + provider_subject: 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; + oauth_user_registration_id: string; +} +export interface Password { + password_id: string; + requires_reset: boolean; +} +export interface PhoneNumber { + phone_id: string; + phone_number: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} +export interface SearchUsersQuery { + /** + * 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 search + * query. + */ + operands: SearchUsersQueryOperand[]; +} +export interface TOTP { + totp_id: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; +} +export interface User { + user_id: string; + emails: Email[]; + status: string; + phone_numbers: PhoneNumber[]; + webauthn_registrations: WebAuthnRegistration[]; + providers: OAuthProvider[]; + totps: TOTP[]; + crypto_wallets: CryptoWallet[]; + biometric_registrations: BiometricRegistration[]; + name?: Name; + /** + * 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; + password?: Password; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; +} +export interface UsersResultsMetadata { + 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; +} +export interface WebAuthnRegistration { + webauthn_registration_id: string; + domain: string; + user_agent: string; + /** + * The verified boolean denotes whether or not this send method, e.g. phone number, email address, etc., + * has been successfully authenticated by the User. + */ + verified: boolean; + /** + * 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; +} +export interface UsersCreateRequest { email?: string; - phone_number?: string; name?: Name; - create_user_as_pending?: boolean; attributes?: Attributes; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; + /** + * The phone number to use for one-time passcodes. The phone number should be in E.164 format. The phone + * number should be in E.164 format (i.e. +1XXXXXXXXXX). You may use +10000000000 to test this endpoint, + * see [Testing](https://stytch.com/docs/home#resources_testing) for more detail. + */ + phone_number?: string; + /** + * Flag for whether or not to save a user as pending vs active in Stytch. Defaults to false. + * If true, users will be saved with status pending in Stytch's backend until authenticated. + * If false, users will be created as active. An example usage of + * a true flag would be to require users to verify their phone by entering the OTP code before + * creating + * an account for them. + */ + create_user_as_pending?: boolean; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; } -export interface B2CUsersCreateResponse extends BaseResponse { - user_id: UserID; +export interface UsersCreateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + email_id: string; + status: string; + phone_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ user: User; + /** + * 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; +} +export interface UsersDeleteBiometricRegistrationRequest { + biometric_registration_id: string; +} +export interface UsersDeleteBiometricRegistrationResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersDeleteCryptoWalletRequest { + crypto_wallet_id: string; +} +export interface UsersDeleteCryptoWalletResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersDeleteEmailRequest { email_id: string; +} +export interface UsersDeleteEmailResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersDeleteOAuthRegistrationRequest { + oauth_user_registration_id: string; +} +export interface UsersDeleteOAuthRegistrationResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersDeletePasswordRequest { + password_id: string; +} +export interface UsersDeletePasswordResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersDeletePhoneNumberRequest { phone_id: string; +} +export interface UsersDeletePhoneNumberResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersDeleteRequest { + user_id: string; +} +export interface UsersDeleteResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_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; +} +export interface UsersDeleteTOTPRequest { + totp_id: string; +} +export interface UsersDeleteTOTPResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersDeleteWebAuthnRegistrationRequest { + webauthn_registration_id: string; +} +export interface UsersDeleteWebAuthnRegistrationResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export interface UsersGetRequest { + user_id: string; +} +export interface UsersGetResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + emails: Email[]; status: string; + phone_numbers: PhoneNumber[]; + webauthn_registrations: WebAuthnRegistration[]; + providers: OAuthProvider[]; + totps: TOTP[]; + crypto_wallets: CryptoWallet[]; + biometric_registrations: BiometricRegistration[]; + /** + * 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; + name?: Name; + /** + * 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; + password?: Password; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; } -export declare type B2CUsersGetResponse = BaseResponse & User; -export declare enum UserSearchOperator { - OR = "OR", - AND = "AND" +export interface UsersSearchRequest { + /** + * 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 results with no filtering applied. + */ + query?: SearchUsersQuery; +} +export interface UsersSearchResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + results: User[]; + /** + * The search `results_metadata` object contains metadata relevant to your specific query like total and + * `next_cursor`. + */ + results_metadata: UsersResultsMetadata; + /** + * 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; +} +export interface UsersUpdateRequest { + user_id: string; + name?: Name; + attributes?: Attributes; + /** + * The `trusted_metadata` field contains an arbitrary JSON object of application-specific data. See the + * [Metadata](https://stytch.com/docs/api/metadata) reference for complete field behavior details. + */ + trusted_metadata?: Record; + /** + * The `untrusted_metadata` field contains an arbitrary JSON object of application-specific data. Untrusted + * metadata can be edited by end users directly via the SDK, and **cannot be used to store critical + * information.** See the [Metadata](https://stytch.com/docs/api/metadata) reference for complete field + * behavior details. + */ + untrusted_metadata?: Record; } -export declare type UserSearchOperand = { +export interface UsersUpdateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + emails: Email[]; + phone_numbers: PhoneNumber[]; + crypto_wallets: CryptoWallet[]; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; +} +export declare type SearchUsersQueryOperand = { filter_name: "created_at_greater_than"; filter_value: string; } | { @@ -95,96 +575,145 @@ export declare type UserSearchOperand = { } | { filter_name: "password_exists"; filter_value: boolean; +} | { + filter_name: string; + [key: string]: unknown; }; -export interface B2CUsersSearchRequest { - limit?: number; - query?: { - operator: UserSearchOperator; - operands: UserSearchOperand[]; - }; - cursor?: string | null; -} -export interface B2CUsersSearchResponse extends BaseResponse { - results: User[]; - results_metadata: { - next_cursor: string | null; - total: number; - }; -} -export interface B2CUsersUpdateRequest { - name?: Name; - trusted_metadata?: UserMetadata; - untrusted_metadata?: UserMetadata; - attributes?: Attributes; -} -export interface B2CUsersUpdateResponse extends BaseResponse { - user_id: UserID; - user: User; - emails: Email[]; - phone_numbers: PhoneNumber[]; - crypto_wallets: CryptoWallet[]; -} -export interface B2CUsersDeleteResponse extends BaseResponse { - user_id: UserID; -} -export interface B2CUsersDeleteEmailResponse extends BaseResponse { - user_id: UserID; - user: User; -} -export interface B2CUsersDeletePhoneNumberResponse extends BaseResponse { - user_id: UserID; - user: User; -} -export interface B2CUsersDeleteWebAuthnRegistrationResponse extends BaseResponse { - user_id: UserID; - user: User; -} -export interface B2CUsersDeleteBiometricRegistrationResponse extends BaseResponse { - user_id: UserID; - user: User; -} -export interface B2CUsersDeleteTOTPResponse extends BaseResponse { - user_id: UserID; - user: User; -} -export interface B2CUsersDeleteCryptoWalletResponse extends BaseResponse { - user_id: UserID; - user: User; -} -export interface B2CUsersDeletePasswordResponse extends BaseResponse { - user_id: UserID; - user: User; -} -export interface B2CUsersDeleteOAuthUserRegistrationResponse extends BaseResponse { - user_id: UserID; - user: User; -} export declare class UserSearchIterator { private client; private data; private mode; - constructor(client: Users, data: B2CUsersSearchRequest); + constructor(client: Users, data: UsersSearchRequest); next(): Promise; hasNext(): boolean; [Symbol.asyncIterator](): AsyncIterator; } export declare class Users { - base_path: string; private fetchConfig; constructor(fetchConfig: fetchConfig); - private endpoint; - create(data: B2CUsersCreateRequest): Promise; - get(userID: UserID): Promise; - search(data: B2CUsersSearchRequest): Promise; - searchAll(data: B2CUsersSearchRequest): UserSearchIterator; - update(userID: UserID, data: B2CUsersUpdateRequest): Promise; - delete(userID: UserID): Promise; - deleteEmail(emailID: string): Promise; - deletePhoneNumber(phoneID: string): Promise; - deleteWebAuthnRegistration(webAuthnRegistrationID: string): Promise; - deleteBiometricRegistration(biometricRegistrationID: string): Promise; - deleteTOTP(totpID: string): Promise; - deleteCryptoWallet(cryptoWalletID: string): Promise; - deletePassword(passwordID: string): Promise; - deleteOAuthUserRegistration(oauthUserRegistrationID: string): Promise; + /** + * Add a User to Stytch. A `user_id` is returned in the response that can then be used to perform other + * operations within Stytch. An `email` or a `phone_number` is required. + * @param data {@link UsersCreateRequest} + * @returns {@link UsersCreateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + create(data: UsersCreateRequest): Promise; + /** + * Get information about a specific User. + * @param data {@link UsersGetRequest} + * @returns {@link UsersGetResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + get(params: UsersGetRequest): Promise; + /** + * Search for Users within your Stytch Project. Submit an empty `query` in the request to return all Users. + * @param data {@link UsersSearchRequest} + * @returns {@link UsersSearchResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + search(data: UsersSearchRequest): Promise; + /** + * Update a User's attributes. + * + * **Note:** In order to add a new email address or phone number to an existing User object, pass the new + * email address or phone number into the respective `/send` endpoint for the authentication method of your + * choice. If you specify the existing User's `user_id` while calling the `/send` endpoint, the new email + * address or phone number will be added to the existing User object upon successful authentication. We + * require this process to guard against an account takeover vulnerability. + * @param data {@link UsersUpdateRequest} + * @returns {@link UsersUpdateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + update(data: UsersUpdateRequest): Promise; + /** + * Delete a User from Stytch. + * @param data {@link UsersDeleteRequest} + * @returns {@link UsersDeleteResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + delete(data: UsersDeleteRequest): Promise; + /** + * Delete an email from a User. + * @param data {@link UsersDeleteEmailRequest} + * @returns {@link UsersDeleteEmailResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteEmail(data: UsersDeleteEmailRequest): Promise; + /** + * Delete a phone number from a User. + * @param data {@link UsersDeletePhoneNumberRequest} + * @returns {@link UsersDeletePhoneNumberResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deletePhoneNumber(data: UsersDeletePhoneNumberRequest): Promise; + /** + * Delete a WebAuthn registration from a User. + * @param data {@link UsersDeleteWebAuthnRegistrationRequest} + * @returns {@link UsersDeleteWebAuthnRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteWebAuthnRegistration(data: UsersDeleteWebAuthnRegistrationRequest): Promise; + /** + * Delete a biometric registration from a User. + * @param data {@link UsersDeleteBiometricRegistrationRequest} + * @returns {@link UsersDeleteBiometricRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteBiometricRegistration(data: UsersDeleteBiometricRegistrationRequest): Promise; + /** + * Delete a TOTP from a User. + * @param data {@link UsersDeleteTOTPRequest} + * @returns {@link UsersDeleteTOTPResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteTOTP(data: UsersDeleteTOTPRequest): Promise; + /** + * Delete a crypto wallet from a User. + * @param data {@link UsersDeleteCryptoWalletRequest} + * @returns {@link UsersDeleteCryptoWalletResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteCryptoWallet(data: UsersDeleteCryptoWalletRequest): Promise; + /** + * Delete a password from a User. + * @param data {@link UsersDeletePasswordRequest} + * @returns {@link UsersDeletePasswordResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deletePassword(data: UsersDeletePasswordRequest): Promise; + /** + * Delete an OAuth registration from a User. + * @param data {@link UsersDeleteOAuthRegistrationRequest} + * @returns {@link UsersDeleteOAuthRegistrationResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + deleteOAuthRegistration(data: UsersDeleteOAuthRegistrationRequest): Promise; + searchAll(data: UsersSearchRequest): UserSearchIterator; } diff --git a/types/lib/b2c/webauthn.d.ts b/types/lib/b2c/webauthn.d.ts index 9b2424d4..6d8eb53a 100644 --- a/types/lib/b2c/webauthn.d.ts +++ b/types/lib/b2c/webauthn.d.ts @@ -1,54 +1,207 @@ -import { Session, User } from "./shared_b2c"; -import { BaseResponse, fetchConfig } from "../shared"; -import { UserID } from "./users"; -export interface B2CWebAuthnRegisterStartRequest { - user_id: UserID; - domain: string; - user_agent?: string; - authenticator_type?: string; -} -export interface B2CWebAuthnRegisterStartResponse extends BaseResponse { - user_id: UserID; - public_key_credential_creation_options: string; -} -export interface B2CWebAuthnRegisterRequest { - user_id: UserID; +import { fetchConfig } from "../shared"; +import { Session } from "./sessions"; +import { User } from "./users"; +export interface WebAuthnAuthenticateRequest { + /** + * The response of the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential). + */ public_key_credential: string; + session_token?: string; + /** + * Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't + * already exist, + * returning both an opaque `session_token` and `session_jwt` for this session. Remember that the + * `session_jwt` will have a fixed lifetime of + * five minutes regardless of the underlying session duration, and will need to be refreshed over time. + * + * This value must be a minimum of 5 and a maximum of 527040 minutes (366 days). + * + * If a `session_token` or `session_jwt` is provided then a successful authentication will continue to + * extend the session this many minutes. + * + * If the `session_duration_minutes` parameter is not specified, a Stytch session will not be created. + */ + session_duration_minutes?: number; + session_jwt?: string; + /** + * Add a custom claims map to the Session being authenticated. Claims are only created if a Session is + * initialized by providing a value in `session_duration_minutes`. Claims will be included on the Session + * object and in the JWT. To update a key in an existing Session, supply a new value. To delete a key, + * supply a null value. + * + * Custom claims made with reserved claims ("iss", "sub", "aud", "exp", "nbf", "iat", "jti") will be + * ignored. Total custom claims size cannot exceed four kilobytes. + */ + session_custom_claims?: Record; } -export interface B2CWebAuthnRegisterResponse extends BaseResponse { - user_id: UserID; +export interface WebAuthnAuthenticateResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; webauthn_registration_id: string; + session_token: string; + session_jwt: string; + /** + * The `user` object affected by this API call. See the + * [Get user endpoint](https://stytch.com/docs/api/get-user) for complete response field details. + */ + user: User; + /** + * 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; + /** + * If you initiate a Session, by including `session_duration_minutes` in your authenticate call, you'll + * receive a full Session object in the response. + * + * See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields. + * + */ + session?: Session; } -export interface B2CWebAuthnAuthenticateStartRequest { - user_id: UserID; +export interface WebAuthnAuthenticateStartRequest { + user_id: string; domain: string; } -export interface B2CWebAuthnAuthenticateStartResponse extends BaseResponse { - user_id: UserID; +export interface WebAuthnAuthenticateStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; public_key_credential_request_options: 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; } -export interface B2CWebAuthnAuthenticateRequest { +export interface WebAuthnRegisterRequest { + user_id: string; + /** + * The response of the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential). + */ public_key_credential: string; - session_token?: string; - session_jwt?: string; - session_duration_minutes?: number; - session_custom_claims?: Record; } -export interface B2CWebAuthnAuthenticateResponse extends BaseResponse { - user_id: UserID; - user: User; +export interface WebAuthnRegisterResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; webauthn_registration_id: string; - session_token?: string; - session_jwt?: string; - session?: Session; + /** + * 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; +} +export interface WebAuthnRegisterStartRequest { + user_id: string; + domain: string; + user_agent?: string; + /** + * The requested authenticator type of the WebAuthn device. The two valid value are platform and + * cross-platform. If no value passed, we assume both values are allowed. + */ + authenticator_type?: string; +} +export interface WebAuthnRegisterStartResponse { + /** + * Globally unique UUID that is returned with every API call. This value is important to log for debugging + * purposes; we may ask for this value to help identify a specific API call when helping you debug an issue. + */ + request_id: string; + user_id: string; + public_key_credential_creation_options: 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; } export declare class WebAuthn { - base_path: string; private fetchConfig; constructor(fetchConfig: fetchConfig); - private endpoint; - registerStart(data: B2CWebAuthnRegisterStartRequest): Promise; - register(data: B2CWebAuthnRegisterRequest): Promise; - authenticateStart(data: B2CWebAuthnAuthenticateStartRequest): Promise; - authenticate(data: B2CWebAuthnAuthenticateRequest): Promise; + /** + * Initiate the process of creating a new WebAuthn registration. After calling this endpoint, the browser + * will need to call + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) with the data + * from + * [public_key_credential_creation_options](https://w3c.github.io/webauthn/#dictionary-makecredentialoptions) + * passed to the [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) + * request via the public key argument. We recommend using the `create()` wrapper provided by the + * webauthn-json library. + * + * If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, the + * `public_key_credential_creation_options` will need to be converted to a suitable public key by + * unmarshalling the JSON, base64 decoding the user ID field, and converting user ID and the challenge + * fields into an array buffer. + * @param data {@link WebAuthnRegisterStartRequest} + * @returns {@link WebAuthnRegisterStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + registerStart(data: WebAuthnRegisterStartRequest): Promise; + /** + * Complete the creation of a WebAuthn registration by passing the response from the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) request to + * this endpoint as the `public_key_credential` parameter. + * + * If the [webauthn-json](https://github.com/github/webauthn-json) library's `create()` method was used, + * the response can be passed directly to the + * [register endpoint](https://stytch.com/docs/api/webauthn-register). If not, some fields (the client data + * and the attestation object) from the + * [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) response will + * need to be converted from array buffers to strings and marshalled into JSON. + * @param data {@link WebAuthnRegisterRequest} + * @returns {@link WebAuthnRegisterResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + register(data: WebAuthnRegisterRequest): Promise; + /** + * Initiate the authentication of a WebAuthn registration. After calling this endpoint, the browser will + * need to call [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) with the + * data from `public_key_credential_request_options` passed to the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request via the + * public key argument. We recommend using the `get()` wrapper provided by the webauthn-json library. + * + * If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, `the + * public_key_credential_request_options` will need to be converted to a suitable public key by + * unmarshalling the JSON and converting some the fields to array buffers. + * @param data {@link WebAuthnAuthenticateStartRequest} + * @returns {@link WebAuthnAuthenticateStartResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticateStart(data: WebAuthnAuthenticateStartRequest): Promise; + /** + * Complete the authentication of a WebAuthn registration by passing the response from the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request to the + * authenticate endpoint. + * + * If the [webauthn-json](https://github.com/github/webauthn-json) library's `get()` method was used, the + * response can be passed directly to the + * [authenticate endpoint](https://stytch.com/docs/api/webauthn-authenticate). If not some fields from the + * [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) response will need to + * be converted from array buffers to strings and marshalled into JSON. + * @param data {@link WebAuthnAuthenticateRequest} + * @returns {@link WebAuthnAuthenticateResponse} + * @async + * @throws A {@link StytchError} on a non-2xx response from the Stytch API + * @throws A {@link RequestError} when the Stytch API cannot be reached + */ + authenticate(data: WebAuthnAuthenticateRequest): Promise; } diff --git a/types/lib/index.d.ts b/types/lib/index.d.ts index e9b549b6..039883a7 100644 --- a/types/lib/index.d.ts +++ b/types/lib/index.d.ts @@ -3,6 +3,4 @@ export * from "./b2c/index"; export { B2BClient } from "./b2b/client"; export * from "./b2b/index"; export * as envs from "./shared/envs"; -export { UserSearchOperator } from "./b2c/users"; -export { SearchOperator } from "./b2b/shared_b2b"; export * from "./shared/errors"; diff --git a/types/lib/shared/envs.d.ts b/types/lib/shared/envs.d.ts index 92115f90..ab43b0f6 100644 --- a/types/lib/shared/envs.d.ts +++ b/types/lib/shared/envs.d.ts @@ -1,2 +1,2 @@ -export declare const test = "https://test.stytch.com/v1/"; -export declare const live = "https://api.stytch.com/v1/"; +export declare const test = "https://test.stytch.com/"; +export declare const live = "https://api.stytch.com/"; diff --git a/types/lib/shared/index.d.ts b/types/lib/shared/index.d.ts index 85e54db3..b7078913 100644 --- a/types/lib/shared/index.d.ts +++ b/types/lib/shared/index.d.ts @@ -1,9 +1,5 @@ /// import * as http from "http"; -export interface BaseResponse { - status_code: number; - request_id: string; -} export interface fetchConfig { baseURL: string; headers: Record;