From 7772020761129eba5715a4b28a935a4eaf8895df Mon Sep 17 00:00:00 2001 From: Bhumil Date: Fri, 23 Dec 2022 18:13:05 +0530 Subject: [PATCH 01/82] recipe interface changes for account linking --- lib/build/recipe/accountlinking/types.d.ts | 24 +++++++++++++ lib/build/supertokens.js | 41 +++++++++++++++++++++- lib/ts/recipe/accountlinking/types.ts | 24 +++++++++++++ lib/ts/supertokens.ts | 41 +++++++++++++++++++++- 4 files changed, 128 insertions(+), 2 deletions(-) diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index d1659e6e0..3d3837d5b 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -54,6 +54,30 @@ export declare type TypeNormalisedInput = { }; export declare type APIInterface = {}; export declare type RecipeInterface = { + getRecipeUserIdsForPrimaryUserIds: (input: { + primaryUserIds: string[]; + }) => Promise<{ + [primaryUserId: string]: string[]; + }>; + getPrimaryUserIdsforRecipeUserIds: (input: { + recipeUserIds: string[]; + }) => Promise<{ + [recipeUserId: string]: string | null; + }>; + addNewRecipeUserIdWithoutPrimaryUserId: (input: { + recipeUserId: string; + recipeId: string; + timeJoined: number; + }) => Promise; + getUsers: (input: { + timeJoinedOrder: "ASC" | "DESC"; + limit?: number; + paginationToken?: string; + includeRecipeIds?: string[]; + }) => Promise<{ + users: User[]; + nextPaginationToken?: string; + }>; canCreatePrimaryUserId: (input: { recipeUserId: string; userContext: any; diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index 5bb716d50..ab3dff692 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -341,7 +341,46 @@ class SuperTokens { }); this.listUsersByAccountInfo = (_input) => __awaiter(this, void 0, void 0, function* () { - // TODO + /** + * if input is only email: + * let emailPasswordUser = emailpassword.getUserByEmail(email); + * + * let thirdpartyUsers = thirdparty.getUsersByEmail(email); + * + * let passwordlessUser = passwordless.getUserByEmail(email); + * + * let recipeUsers = []; + * + * if (emailPasswordUser !== undefined) { + * recipeUsers.push(emailPasswordUser); + * } + * + * recipeUsers.push(...thirdpartyUsers); + * + * if (passwordlessUser !== undefined) { + * recipeUsers.push(passwordlessUser); + * } + * + * let recipeUserIds = recipeUsers.map(r => r.id); + * + * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); + * + * let result: {id: User | User[]} = {}; + * + * for (let i = 0; i < recipeUsers.length; i++) { + * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { + * result[recipeUsers[i].id] = recipeUsers[i]; + * } else { + * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; + * if (result[pUserId] === undefined) { + * result[pUserId] = []; + * } + * result[pUserId].push(recipeUsers[i]); + * } + * } + * + * + */ return; }); this.getUserByAccountInfoAndRecipeId = (_input) => diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 0a6fe6885..fbe9156b4 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -72,6 +72,30 @@ export type TypeNormalisedInput = { export type APIInterface = {}; export type RecipeInterface = { + getRecipeUserIdsForPrimaryUserIds: (input: { + primaryUserIds: string[]; + }) => Promise<{ + [primaryUserId: string]: string[]; // recipeUserIds + }>; + getPrimaryUserIdsforRecipeUserIds: (input: { + recipeUserIds: string[]; + }) => Promise<{ + [recipeUserId: string]: string | null; + }>; + addNewRecipeUserIdWithoutPrimaryUserId: (input: { + recipeUserId: string; + recipeId: string; + timeJoined: number; + }) => Promise; + getUsers: (input: { + timeJoinedOrder: "ASC" | "DESC"; + limit?: number; + paginationToken?: string; + includeRecipeIds?: string[]; + }) => Promise<{ + users: User[]; + nextPaginationToken?: string; + }>; canCreatePrimaryUserId: (input: { recipeUserId: string; userContext: any; diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index 653a70e10..aae817f7a 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -447,7 +447,46 @@ export default class SuperTokens { }; listUsersByAccountInfo = async (_input: { info: AccountInfo }): Promise => { - // TODO + /** + * if input is only email: + * let emailPasswordUser = emailpassword.getUserByEmail(email); + * + * let thirdpartyUsers = thirdparty.getUsersByEmail(email); + * + * let passwordlessUser = passwordless.getUserByEmail(email); + * + * let recipeUsers = []; + * + * if (emailPasswordUser !== undefined) { + * recipeUsers.push(emailPasswordUser); + * } + * + * recipeUsers.push(...thirdpartyUsers); + * + * if (passwordlessUser !== undefined) { + * recipeUsers.push(passwordlessUser); + * } + * + * let recipeUserIds = recipeUsers.map(r => r.id); + * + * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); + * + * let result: {id: User | User[]} = {}; + * + * for (let i = 0; i < recipeUsers.length; i++) { + * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { + * result[recipeUsers[i].id] = recipeUsers[i]; + * } else { + * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; + * if (result[pUserId] === undefined) { + * result[pUserId] = []; + * } + * result[pUserId].push(recipeUsers[i]); + * } + * } + * + * + */ return; }; From 3db3a017dc9bd126533ab1742cfca4f8e4ff4066 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Sun, 25 Dec 2022 19:16:14 +0530 Subject: [PATCH 02/82] account linking implementation --- lib/build/recipe/accountlinking/index.d.ts | 5 + lib/build/recipe/accountlinking/index.js | 22 ++ lib/build/recipe/accountlinking/recipe.d.ts | 31 ++- lib/build/recipe/accountlinking/recipe.js | 72 ++++-- .../accountlinking/recipeImplementation.d.ts | 4 + .../accountlinking/recipeImplementation.js | 141 ++++++++++++ lib/build/recipe/accountlinking/types.d.ts | 8 +- lib/build/recipe/accountlinking/types.js | 2 +- lib/build/recipe/accountlinking/utils.d.ts | 4 + lib/build/recipe/accountlinking/utils.js | 74 +++++++ lib/ts/recipe/accountlinking/index.ts | 22 ++ lib/ts/recipe/accountlinking/recipe.ts | 99 ++++++++- .../accountlinking/recipeImplementation.ts | 205 ++++++++++++++++++ lib/ts/recipe/accountlinking/types.ts | 10 +- lib/ts/recipe/accountlinking/utils.ts | 60 +++++ 15 files changed, 715 insertions(+), 44 deletions(-) create mode 100644 lib/build/recipe/accountlinking/index.d.ts create mode 100644 lib/build/recipe/accountlinking/index.js create mode 100644 lib/build/recipe/accountlinking/recipeImplementation.d.ts create mode 100644 lib/build/recipe/accountlinking/recipeImplementation.js create mode 100644 lib/build/recipe/accountlinking/utils.d.ts create mode 100644 lib/build/recipe/accountlinking/utils.js create mode 100644 lib/ts/recipe/accountlinking/index.ts create mode 100644 lib/ts/recipe/accountlinking/recipeImplementation.ts create mode 100644 lib/ts/recipe/accountlinking/utils.ts diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts new file mode 100644 index 000000000..86168f84a --- /dev/null +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -0,0 +1,5 @@ +// @ts-nocheck +import Recipe from "./recipe"; +export default class Wrapper { + static init: typeof Recipe.init; +} diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js new file mode 100644 index 000000000..5e235c4f1 --- /dev/null +++ b/lib/build/recipe/accountlinking/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const recipe_1 = require("./recipe"); +// import { RecipeInterface } from "./types"; +// import { User } from "../../types"; +class Wrapper {} +exports.default = Wrapper; +Wrapper.init = recipe_1.default.init; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 6f0d2265b..2e8d81bb1 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -3,10 +3,31 @@ import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; -import { AccountInfoWithRecipeId, APIHandled, HTTPMethod } from "../../types"; +import type { + AccountInfoWithRecipeId, + APIHandled, + HTTPMethod, + NormalisedAppinfo, + RecipeListFunction, +} from "../../types"; import { SessionContainer } from "../session"; -import { AccountInfoAndEmailWithRecipeId } from "./types"; -export default class AccountLinkingRecipe extends RecipeModule { +import type { AccountInfoAndEmailWithRecipeId, TypeNormalisedInput, RecipeInterface, TypeInput } from "./types"; +export default class Recipe extends RecipeModule { + private static instance; + static RECIPE_ID: string; + config: TypeNormalisedInput; + recipeInterfaceImpl: RecipeInterface; + isInServerlessEnv: boolean; + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + _recipes: {}, + _ingredients: {} + ); + static init(config: TypeInput): RecipeListFunction; + static getInstanceOrThrowError(): Recipe; getAPIsHandled(): APIHandled[]; handleAPIRequest( _id: string, @@ -15,9 +36,9 @@ export default class AccountLinkingRecipe extends RecipeModule { _path: normalisedURLPath, _method: HTTPMethod ): Promise; - handleError(_error: error, _request: BaseRequest, _response: BaseResponse): Promise; + handleError(error: error, _request: BaseRequest, _response: BaseResponse): Promise; getAllCORSHeaders(): string[]; - isErrorFromThisRecipe(_err: any): _err is error; + isErrorFromThisRecipe(err: any): err is error; isSignUpAllowed: (input: { info: AccountInfoWithRecipeId }) => Promise; createPrimaryUserIdOrLinkAccountPostSignUp: (_input: { identifyinInfo: AccountInfoAndEmailWithRecipeId; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 4df9ae614..850491a6b 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -1,5 +1,5 @@ "use strict"; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the * "License") as published by the Apache Software Foundation. @@ -47,10 +47,15 @@ var __awaiter = Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); const __1 = require("../.."); -class AccountLinkingRecipe extends recipeModule_1.default { - constructor() { - // recipeInterfaceImpl: RecipeInterface; TODO - super(...arguments); +const supertokens_1 = require("../../supertokens"); +const utils_1 = require("./utils"); +const supertokens_js_override_1 = require("supertokens-js-override"); +const recipeImplementation_1 = require("./recipeImplementation"); +const querier_1 = require("../../querier"); +const error_1 = require("../../error"); +class Recipe extends recipeModule_1.default { + constructor(recipeId, appInfo, isInServerlessEnv, config, _recipes, _ingredients) { + super(recipeId, appInfo); this.isSignUpAllowed = (input) => __awaiter(this, void 0, void 0, function* () { let user = yield __1.default.getUserByAccountInfo(input); @@ -80,21 +85,62 @@ class AccountLinkingRecipe extends recipeModule_1.default { createRecipeUser: true, }; }); + this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); + this.isInServerlessEnv = isInServerlessEnv; + { + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + ); + this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); + } + } + static init(config) { + return (appInfo, isInServerlessEnv) => { + if (Recipe.instance === undefined) { + Recipe.instance = new Recipe( + Recipe.RECIPE_ID, + appInfo, + isInServerlessEnv, + config, + {}, + { + emailDelivery: undefined, + } + ); + return Recipe.instance; + } else { + throw new Error("AccountLinking recipe has already been initialised. Please check your code for bugs."); + } + }; + } + static getInstanceOrThrowError() { + if (Recipe.instance === undefined) { + Recipe.init({})( + supertokens_1.default.getInstanceOrThrowError().appInfo, + supertokens_1.default.getInstanceOrThrowError().isInServerlessEnv + ); + } + if (Recipe.instance !== undefined) { + return Recipe.instance; + } + throw new Error("Initialisation not done. Did you forget to call the SuperTokens.init function?"); } getAPIsHandled() { - throw new Error("Method not implemented."); + return []; } handleAPIRequest(_id, _req, _response, _path, _method) { - throw new Error("Method not implemented."); + throw new Error("Should never come here"); } - handleError(_error, _request, _response) { - throw new Error("Method not implemented."); + handleError(error, _request, _response) { + throw error; } getAllCORSHeaders() { - throw new Error("Method not implemented."); + return []; } - isErrorFromThisRecipe(_err) { - throw new Error("Method not implemented."); + isErrorFromThisRecipe(err) { + return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; } } -exports.default = AccountLinkingRecipe; +exports.default = Recipe; +Recipe.instance = undefined; +Recipe.RECIPE_ID = "accountlinking"; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.d.ts b/lib/build/recipe/accountlinking/recipeImplementation.d.ts new file mode 100644 index 000000000..7d1180bfb --- /dev/null +++ b/lib/build/recipe/accountlinking/recipeImplementation.d.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +import { RecipeInterface } from "./types"; +import { Querier } from "../../querier"; +export default function getRecipeImplementation(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js new file mode 100644 index 000000000..8c2cec8d2 --- /dev/null +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -0,0 +1,141 @@ +"use strict"; +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +Object.defineProperty(exports, "__esModule", { value: true }); +const querier_1 = require("../../querier"); +const normalisedURLPath_1 = require("../../normalisedURLPath"); +const utils_1 = require("../../utils"); +function getRecipeImplementation(querier) { + return { + getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { + return __awaiter(this, void 0, void 0, function* () { + return querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { + primaryUserIds: primaryUserIds.join(","), + }); + }); + }, + getPrimaryUserIdsforRecipeUserIds: function ({ recipeUserIds }) { + return __awaiter(this, void 0, void 0, function* () { + return querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { + recipeUserIds: recipeUserIds.join(","), + }); + }); + }, + addNewRecipeUserIdWithoutPrimaryUserId: function ({ recipeUserId, recipeId, timeJoined }) { + return __awaiter(this, void 0, void 0, function* () { + return querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user"), { + recipeUserId, + recipeId, + timeJoined, + }); + }); + }, + getUsers: function ({ timeJoinedOrder, limit, paginationToken, includeRecipeIds }) { + return __awaiter(this, void 0, void 0, function* () { + let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); + let apiVersion = yield querier.getAPIVersion(); + if (utils_1.maxVersion(apiVersion, "2.7") === "2.7") { + throw new Error( + "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUsersOldestFirst() or .getUsersNewestFirst() instead (for example, EmailPassword.getUsersOldestFirst())" + ); + } + let includeRecipeIdsStr = undefined; + if (includeRecipeIds !== undefined) { + includeRecipeIdsStr = includeRecipeIds.join(","); + } + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users"), { + includeRecipeIds: includeRecipeIdsStr, + timeJoinedOrder: timeJoinedOrder, + limit: limit, + paginationToken: paginationToken, + }); + return { + users: response.users, + nextPaginationToken: response.nextPaginationToken, + }; + }); + }, + canCreatePrimaryUserId: function (_input) { + return __awaiter(this, void 0, void 0, function* () { + return { + status: "OK", + }; + }); + }, + createPrimaryUser: function (_input) { + return __awaiter(this, void 0, void 0, function* () { + return { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: "", + description: "", + }; + }); + }, + canLinkAccounts: function (_input) { + return __awaiter(this, void 0, void 0, function* () { + return { + status: "OK", + }; + }); + }, + linkAccounts: function (_input) { + return __awaiter(this, void 0, void 0, function* () { + return { + status: "OK", + }; + }); + }, + unlinkAccounts: function (_ipnut) { + return __awaiter(this, void 0, void 0, function* () { + return { + status: "OK", + wasRecipeUserDeleted: false, + }; + }); + }, + }; +} +exports.default = getRecipeImplementation; diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 3d3837d5b..af9777a32 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -1,6 +1,6 @@ // @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; -import { User } from "../../types"; +import type { User } from "../../types"; import { SessionContainer } from "../session"; export declare type TypeInput = { onAccountLinked?: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; @@ -24,7 +24,6 @@ export declare type TypeInput = { originalImplementation: RecipeInterface, builder?: OverrideableBuilder ) => RecipeInterface; - apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { @@ -49,10 +48,8 @@ export declare type TypeNormalisedInput = { originalImplementation: RecipeInterface, builder?: OverrideableBuilder ) => RecipeInterface; - apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; -export declare type APIInterface = {}; export declare type RecipeInterface = { getRecipeUserIdsForPrimaryUserIds: (input: { primaryUserIds: string[]; @@ -163,7 +160,7 @@ export declare type RecipeInterface = { wasRecipeUserDeleted: boolean; }>; }; -declare type RecipeLevelUser = { +export declare type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; id: string; timeJoined: number; @@ -184,4 +181,3 @@ export declare type AccountInfoAndEmailWithRecipeId = { userId: string; }; }; -export {}; diff --git a/lib/build/recipe/accountlinking/types.js b/lib/build/recipe/accountlinking/types.js index a098ca1d7..8749b03ea 100644 --- a/lib/build/recipe/accountlinking/types.js +++ b/lib/build/recipe/accountlinking/types.js @@ -1,5 +1,5 @@ "use strict"; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the * "License") as published by the Apache Software Foundation. diff --git a/lib/build/recipe/accountlinking/utils.d.ts b/lib/build/recipe/accountlinking/utils.d.ts new file mode 100644 index 000000000..687c0db39 --- /dev/null +++ b/lib/build/recipe/accountlinking/utils.d.ts @@ -0,0 +1,4 @@ +// @ts-nocheck +import type { NormalisedAppinfo } from "../../types"; +import type { TypeInput, TypeNormalisedInput } from "./types"; +export declare function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/accountlinking/utils.js b/lib/build/recipe/accountlinking/utils.js new file mode 100644 index 000000000..79d6256ba --- /dev/null +++ b/lib/build/recipe/accountlinking/utils.js @@ -0,0 +1,74 @@ +"use strict"; +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +Object.defineProperty(exports, "__esModule", { value: true }); +function defaultOnAccountLinked(_user, _newAccountInfo, _userContext) { + return __awaiter(this, void 0, void 0, function* () {}); +} +function defaultOnAccountUnlinked(_user, _unlinkedAccount, _userContext) { + return __awaiter(this, void 0, void 0, function* () {}); +} +function defaultShouldDoAutomaticAccountLinking(_newAccountInfo, _user, _session, _userContext) { + return __awaiter(this, void 0, void 0, function* () { + return { + shouldAutomaticallyLink: false, + }; + }); +} +function validateAndNormaliseUserInput(_, config) { + let onAccountLinked = config.onAccountLinked || defaultOnAccountLinked; + let onAccountUnlinked = config.onAccountUnlinked || defaultOnAccountUnlinked; + let shouldDoAutomaticAccountLinking = + config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; + let override = Object.assign({ functions: (originalImplementation) => originalImplementation }, config.override); + return { + override, + onAccountLinked, + onAccountUnlinked, + shouldDoAutomaticAccountLinking, + }; +} +exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts new file mode 100644 index 000000000..fabee246a --- /dev/null +++ b/lib/ts/recipe/accountlinking/index.ts @@ -0,0 +1,22 @@ +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import Recipe from "./recipe"; +// import { RecipeInterface } from "./types"; +// import { User } from "../../types"; + +export default class Wrapper { + static init = Recipe.init; +} diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index ca82af0db..8a282090f 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -1,4 +1,4 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the * "License") as published by the Apache Software Foundation. @@ -18,17 +18,89 @@ import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; import SuperTokens from "../.."; -import { AccountInfoWithRecipeId, APIHandled, HTTPMethod } from "../../types"; +import SuperTokensModule from "../../supertokens"; +import type { + AccountInfoWithRecipeId, + APIHandled, + HTTPMethod, + NormalisedAppinfo, + RecipeListFunction, +} from "../../types"; import { SessionContainer } from "../session"; -import { AccountInfoAndEmailWithRecipeId } from "./types"; +import type { AccountInfoAndEmailWithRecipeId, TypeNormalisedInput, RecipeInterface, TypeInput } from "./types"; import { User } from "../../types"; +import { validateAndNormaliseUserInput } from "./utils"; +import OverrideableBuilder from "supertokens-js-override"; +import RecipeImplementation from "./recipeImplementation"; +import { Querier } from "../../querier"; +import SuperTokensError from "../../error"; -export default class AccountLinkingRecipe extends RecipeModule { - // recipeInterfaceImpl: RecipeInterface; TODO +export default class Recipe extends RecipeModule { + private static instance: Recipe | undefined = undefined; + + static RECIPE_ID = "accountlinking"; + + config: TypeNormalisedInput; + + recipeInterfaceImpl: RecipeInterface; + + isInServerlessEnv: boolean; + + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + _recipes: {}, + _ingredients: {} + ) { + super(recipeId, appInfo); + this.config = validateAndNormaliseUserInput(appInfo, config); + this.isInServerlessEnv = isInServerlessEnv; + + { + let builder = new OverrideableBuilder(RecipeImplementation(Querier.getNewInstanceOrThrowError(recipeId))); + this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); + } + } + + static init(config: TypeInput): RecipeListFunction { + return (appInfo, isInServerlessEnv) => { + if (Recipe.instance === undefined) { + Recipe.instance = new Recipe( + Recipe.RECIPE_ID, + appInfo, + isInServerlessEnv, + config, + {}, + { + emailDelivery: undefined, + } + ); + return Recipe.instance; + } else { + throw new Error("AccountLinking recipe has already been initialised. Please check your code for bugs."); + } + }; + } + + static getInstanceOrThrowError(): Recipe { + if (Recipe.instance === undefined) { + Recipe.init({})( + SuperTokensModule.getInstanceOrThrowError().appInfo, + SuperTokensModule.getInstanceOrThrowError().isInServerlessEnv + ); + } + if (Recipe.instance !== undefined) { + return Recipe.instance; + } + throw new Error("Initialisation not done. Did you forget to call the SuperTokens.init function?"); + } getAPIsHandled(): APIHandled[] { - throw new Error("Method not implemented."); + return []; } + handleAPIRequest( _id: string, _req: BaseRequest, @@ -36,18 +108,21 @@ export default class AccountLinkingRecipe extends RecipeModule { _path: normalisedURLPath, _method: HTTPMethod ): Promise { - throw new Error("Method not implemented."); + throw new Error("Should never come here"); } - handleError(_error: error, _request: BaseRequest, _response: BaseResponse): Promise { - throw new Error("Method not implemented."); + + handleError(error: error, _request: BaseRequest, _response: BaseResponse): Promise { + throw error; } getAllCORSHeaders(): string[] { - throw new Error("Method not implemented."); + return []; } - isErrorFromThisRecipe(_err: any): _err is error { - throw new Error("Method not implemented."); + + isErrorFromThisRecipe(err: any): err is error { + return SuperTokensError.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; } + isSignUpAllowed = async (input: { info: AccountInfoWithRecipeId }): Promise => { let user: User | undefined = await SuperTokens.getUserByAccountInfo(input); if (user === undefined || !user.isPrimaryUser) { diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts new file mode 100644 index 000000000..9cbf996be --- /dev/null +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -0,0 +1,205 @@ +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import { RecipeInterface } from "./types"; +import { Querier } from "../../querier"; +import type { User } from "../../types"; +import NormalisedURLPath from "../../normalisedURLPath"; +import { maxVersion } from "../../utils"; + +export default function getRecipeImplementation(querier: Querier): RecipeInterface { + return { + getRecipeUserIdsForPrimaryUserIds: async function ({ + primaryUserIds, + }: { + primaryUserIds: string[]; + }): Promise<{ + [primaryUserId: string]: string[]; + }> { + return querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/users"), { + primaryUserIds: primaryUserIds.join(","), + }); + }, + getPrimaryUserIdsforRecipeUserIds: async function ({ + recipeUserIds, + }: { + recipeUserIds: string[]; + }): Promise<{ + [recipeUserId: string]: string | null; + }> { + return querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/users"), { + recipeUserIds: recipeUserIds.join(","), + }); + }, + addNewRecipeUserIdWithoutPrimaryUserId: async function ({ + recipeUserId, + recipeId, + timeJoined, + }: { + recipeUserId: string; + recipeId: string; + timeJoined: number; + }): Promise { + return querier.sendPutRequest(new NormalisedURLPath("/recipe/accountlinking/user"), { + recipeUserId, + recipeId, + timeJoined, + }); + }, + getUsers: async function ({ + timeJoinedOrder, + limit, + paginationToken, + includeRecipeIds, + }: { + timeJoinedOrder: "ASC" | "DESC"; + limit?: number; + paginationToken?: string; + includeRecipeIds?: string[]; + }): Promise<{ + users: User[]; + nextPaginationToken?: string; + }> { + let querier = Querier.getNewInstanceOrThrowError(undefined); + let apiVersion = await querier.getAPIVersion(); + if (maxVersion(apiVersion, "2.7") === "2.7") { + throw new Error( + "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUsersOldestFirst() or .getUsersNewestFirst() instead (for example, EmailPassword.getUsersOldestFirst())" + ); + } + let includeRecipeIdsStr = undefined; + if (includeRecipeIds !== undefined) { + includeRecipeIdsStr = includeRecipeIds.join(","); + } + let response = await querier.sendGetRequest(new NormalisedURLPath("/users"), { + includeRecipeIds: includeRecipeIdsStr, + timeJoinedOrder: timeJoinedOrder, + limit: limit, + paginationToken: paginationToken, + }); + return { + users: response.users, + nextPaginationToken: response.nextPaginationToken, + }; + }, + canCreatePrimaryUserId: async function (_input: { + recipeUserId: string; + userContext: any; + }): Promise< + | { + status: "OK"; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + > { + return { + status: "OK", + }; + }, + createPrimaryUser: async function (_input: { + recipeUserId: string; + userContext: any; + }): Promise< + | { + status: "OK"; + user: User; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + > { + return { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: "", + description: "", + }; + }, + canLinkAccounts: async function (_input: { + recipeUserId: string; + primaryUserId: string; + userContext: any; + }): Promise< + | { + status: "OK"; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } + | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + > { + return { + status: "OK", + }; + }, + linkAccounts: async function (_input: { + recipeUserId: string; + primaryUserId: string; + userContext: any; + }): Promise< + | { + status: "OK"; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + > { + return { + status: "OK", + }; + }, + unlinkAccounts: async function (_ipnut: { + recipeUserId: string; + userContext: any; + }): Promise<{ + status: "OK"; + wasRecipeUserDeleted: boolean; + }> { + return { + status: "OK", + wasRecipeUserDeleted: false, + }; + }, + }; +} diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index fbe9156b4..4bf2ee949 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -1,4 +1,4 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the * "License") as published by the Apache Software Foundation. @@ -14,7 +14,7 @@ */ import OverrideableBuilder from "supertokens-js-override"; -import { User } from "../../types"; +import type { User } from "../../types"; import { SessionContainer } from "../session"; export type TypeInput = { @@ -39,7 +39,6 @@ export type TypeInput = { originalImplementation: RecipeInterface, builder?: OverrideableBuilder ) => RecipeInterface; - apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -65,12 +64,9 @@ export type TypeNormalisedInput = { originalImplementation: RecipeInterface, builder?: OverrideableBuilder ) => RecipeInterface; - apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; -export type APIInterface = {}; - export type RecipeInterface = { getRecipeUserIdsForPrimaryUserIds: (input: { primaryUserIds: string[]; @@ -182,7 +178,7 @@ export type RecipeInterface = { }>; }; -type RecipeLevelUser = { +export type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; id: string; // can be recipeUserId or primaryUserId timeJoined: number; diff --git a/lib/ts/recipe/accountlinking/utils.ts b/lib/ts/recipe/accountlinking/utils.ts new file mode 100644 index 000000000..45969c41f --- /dev/null +++ b/lib/ts/recipe/accountlinking/utils.ts @@ -0,0 +1,60 @@ +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import type { NormalisedAppinfo, User } from "../../types"; +import { SessionContainer } from "../session"; +import type { + TypeInput, + RecipeLevelUser, + RecipeInterface, + TypeNormalisedInput, + AccountInfoAndEmailWithRecipeId, +} from "./types"; + +async function defaultOnAccountLinked(_user: User, _newAccountInfo: RecipeLevelUser, _userContext: any) {} + +async function defaultOnAccountUnlinked(_user: User, _unlinkedAccount: RecipeLevelUser, _userContext: any) {} + +async function defaultShouldDoAutomaticAccountLinking( + _newAccountInfo: AccountInfoAndEmailWithRecipeId, + _user: User | undefined, + _session: SessionContainer | undefined, + _userContext: any +): Promise<{ + shouldAutomaticallyLink: false; +}> { + return { + shouldAutomaticallyLink: false, + }; +} + +export function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput { + let onAccountLinked = config.onAccountLinked || defaultOnAccountLinked; + let onAccountUnlinked = config.onAccountUnlinked || defaultOnAccountUnlinked; + let shouldDoAutomaticAccountLinking = + config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; + + let override = { + functions: (originalImplementation: RecipeInterface) => originalImplementation, + ...config.override, + }; + + return { + override, + onAccountLinked, + onAccountUnlinked, + shouldDoAutomaticAccountLinking, + }; +} From 65f34af6a70abfad31ace5e6be0aa519a68fcc8a Mon Sep 17 00:00:00 2001 From: Bhumil Date: Sun, 25 Dec 2022 19:19:34 +0530 Subject: [PATCH 03/82] user context update --- lib/build/recipe/accountlinking/types.d.ts | 4 ++++ lib/ts/recipe/accountlinking/types.ts | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 3d3837d5b..102086f9f 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -56,11 +56,13 @@ export declare type APIInterface = {}; export declare type RecipeInterface = { getRecipeUserIdsForPrimaryUserIds: (input: { primaryUserIds: string[]; + userContext: any; }) => Promise<{ [primaryUserId: string]: string[]; }>; getPrimaryUserIdsforRecipeUserIds: (input: { recipeUserIds: string[]; + userContext: any; }) => Promise<{ [recipeUserId: string]: string | null; }>; @@ -68,12 +70,14 @@ export declare type RecipeInterface = { recipeUserId: string; recipeId: string; timeJoined: number; + userContext: any; }) => Promise; getUsers: (input: { timeJoinedOrder: "ASC" | "DESC"; limit?: number; paginationToken?: string; includeRecipeIds?: string[]; + userContext: any; }) => Promise<{ users: User[]; nextPaginationToken?: string; diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index fbe9156b4..21d3d60af 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -74,11 +74,13 @@ export type APIInterface = {}; export type RecipeInterface = { getRecipeUserIdsForPrimaryUserIds: (input: { primaryUserIds: string[]; + userContext: any; }) => Promise<{ [primaryUserId: string]: string[]; // recipeUserIds }>; getPrimaryUserIdsforRecipeUserIds: (input: { recipeUserIds: string[]; + userContext: any; }) => Promise<{ [recipeUserId: string]: string | null; }>; @@ -86,12 +88,14 @@ export type RecipeInterface = { recipeUserId: string; recipeId: string; timeJoined: number; + userContext: any; }) => Promise; getUsers: (input: { timeJoinedOrder: "ASC" | "DESC"; limit?: number; paginationToken?: string; includeRecipeIds?: string[]; + userContext: any; }) => Promise<{ users: User[]; nextPaginationToken?: string; From 90e2f288e17c7f5666ecc5c124f5238a989fdbe2 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 26 Dec 2022 04:32:00 +0530 Subject: [PATCH 04/82] code udpate --- lib/build/index.d.ts | 4 +- lib/build/index.js | 4 +- lib/build/recipe/accountlinking/recipe.d.ts | 66 ++- lib/build/recipe/accountlinking/recipe.js | 325 +++++++++++++- .../accountlinking/recipeImplementation.d.ts | 4 +- .../accountlinking/recipeImplementation.js | 233 +++++++++- lib/ts/index.ts | 4 +- lib/ts/recipe/accountlinking/recipe.ts | 397 ++++++++++++++++-- .../accountlinking/recipeImplementation.ts | 289 ++++++++++++- 9 files changed, 1230 insertions(+), 96 deletions(-) diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index cd2e01d6e..499c7827e 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -75,7 +75,7 @@ export default class SuperTokensWrapper { }>; static getUser(input: { userId: string }): Promise; static listUsersByAccountInfo(input: { info: AccountInfo }): Promise; - static getUserByAccountInfo(input: { info: AccountInfoWithRecipeId }): Promise; + static getUserByAccountInfoAndRecipeId(input: { info: AccountInfoWithRecipeId }): Promise; } export declare let init: typeof SuperTokens.init; export declare let getAllCORSHeaders: typeof SuperTokensWrapper.getAllCORSHeaders; @@ -89,5 +89,5 @@ export declare let deleteUserIdMapping: typeof SuperTokensWrapper.deleteUserIdMa export declare let updateOrDeleteUserIdMappingInfo: typeof SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; export declare let getUser: typeof SuperTokensWrapper.getUser; export declare let listUsersByAccountInfo: typeof SuperTokensWrapper.listUsersByAccountInfo; -export declare let getUserByAccountInfo: typeof SuperTokensWrapper.getUserByAccountInfo; +export declare let getUserByAccountInfoAndRecipeId: typeof SuperTokensWrapper.getUserByAccountInfoAndRecipeId; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/index.js b/lib/build/index.js index 405bda00e..a51f91065 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -58,7 +58,7 @@ class SuperTokensWrapper { static listUsersByAccountInfo(input) { return supertokens_1.default.getInstanceOrThrowError().listUsersByAccountInfo(input); } - static getUserByAccountInfo(input) { + static getUserByAccountInfoAndRecipeId(input) { return supertokens_1.default.getInstanceOrThrowError().getUserByAccountInfoAndRecipeId(input); } } @@ -77,5 +77,5 @@ exports.deleteUserIdMapping = SuperTokensWrapper.deleteUserIdMapping; exports.updateOrDeleteUserIdMappingInfo = SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; exports.getUser = SuperTokensWrapper.getUser; exports.listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; -exports.getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; +exports.getUserByAccountInfoAndRecipeId = SuperTokensWrapper.getUserByAccountInfoAndRecipeId; exports.Error = SuperTokensWrapper.Error; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 2e8d81bb1..8610afb11 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -3,15 +3,9 @@ import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; -import type { - AccountInfoWithRecipeId, - APIHandled, - HTTPMethod, - NormalisedAppinfo, - RecipeListFunction, -} from "../../types"; +import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction } from "../../types"; import { SessionContainer } from "../session"; -import type { AccountInfoAndEmailWithRecipeId, TypeNormalisedInput, RecipeInterface, TypeInput } from "./types"; +import type { TypeNormalisedInput, RecipeInterface, TypeInput, AccountInfoAndEmailWithRecipeId } from "./types"; export default class Recipe extends RecipeModule { private static instance; static RECIPE_ID: string; @@ -39,22 +33,64 @@ export default class Recipe extends RecipeModule { handleError(error: error, _request: BaseRequest, _response: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; - isSignUpAllowed: (input: { info: AccountInfoWithRecipeId }) => Promise; - createPrimaryUserIdOrLinkAccountPostSignUp: (_input: { - identifyinInfo: AccountInfoAndEmailWithRecipeId; - shouldRequireVerification: boolean; - }) => Promise; - accountLinkPostSignInViaSession: (_input: { + getIdentitiesForPrimaryUserId: ( + primaryUserId: string + ) => Promise<{ + verified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; + }[]; + }; + unverified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; + }[]; + }; + }>; + isSignUpAllowed: ({ + info, + userContext, + }: { + info: AccountInfoAndEmailWithRecipeId; + userContext: any; + }) => Promise; + createPrimaryUserIdOrLinkAccountPostSignUp: ({ + info, + infoVerified, + recipeUserId, + userContext, + }: { + info: AccountInfoAndEmailWithRecipeId; + infoVerified: boolean; + recipeUserId: string; + userContext: any; + }) => Promise; + accountLinkPostSignInViaSession: ({ + session, + info, + infoVerified, + userContext, + }: { session: SessionContainer; - identifyinInfo: AccountInfoAndEmailWithRecipeId; + info: AccountInfoAndEmailWithRecipeId; + infoVerified: boolean; + userContext: any; }) => Promise< | { createRecipeUser: true; + updateVerificationClaim: boolean; } | ({ createRecipeUser: false; } & { accountsLinked: true; + updateVerificationClaim: boolean; }) | ({ createRecipeUser: false; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 850491a6b..b2fb46d8f 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -53,43 +53,334 @@ const supertokens_js_override_1 = require("supertokens-js-override"); const recipeImplementation_1 = require("./recipeImplementation"); const querier_1 = require("../../querier"); const error_1 = require("../../error"); +const normalisedURLPath_1 = require("../../normalisedURLPath"); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config, _recipes, _ingredients) { super(recipeId, appInfo); - this.isSignUpAllowed = (input) => + this.getIdentitiesForPrimaryUserId = (primaryUserId) => __awaiter(this, void 0, void 0, function* () { - let user = yield __1.default.getUserByAccountInfo(input); - if (user === undefined || !user.isPrimaryUser) { + return yield querier_1.Querier.getNewInstanceOrThrowError(this.getRecipeId()).sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/identities"), + { + primaryUserId, + } + ); + }); + this.isSignUpAllowed = ({ info, userContext }) => + __awaiter(this, void 0, void 0, function* () { + let identifier; + if (info.email !== undefined) { + identifier = { + email: info.email, + }; + } else if (info.phoneNumber !== undefined) { + identifier = { + phoneNumber: info.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let users = yield __1.default.listUsersByAccountInfo({ + info: identifier, + }); + if (users === undefined || users.length === 0) { return true; } - let shouldRequireVerification = false; // TOOD: call shouldRequireVerification from config + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser === undefined) { + return true; + } + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + info, + primaryUser, + undefined, + userContext + ); + let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink + ? shouldDoAccountLinking.shouldRequireVerification + : false; if (!shouldRequireVerification) { return true; } - // /** - // * for each linked recipes, get all the verified identifying info - // * - // * if the input identifyingInfo is found in the above generated list - // * of verified identifyingInfos, return true else false. - // */ - return true; + /** + * DISCUSS: new API in core which returns all the verified identities for primaryUserId + */ + let identitiesForPrimaryUser = yield this.getIdentitiesForPrimaryUserId(primaryUser.id); + if (info.email !== undefined) { + return identitiesForPrimaryUser.verified.emails.includes(info.email); + } + if (info.phoneNumber !== undefined) { + return identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber); + } + throw Error("it should never reach here"); }); - this.createPrimaryUserIdOrLinkAccountPostSignUp = (_input) => + this.createPrimaryUserIdOrLinkAccountPostSignUp = ({ info, infoVerified, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { - // TODO + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + info, + undefined, + undefined, + userContext + ); + if ( + shouldDoAccountLinking.shouldAutomaticallyLink && + shouldDoAccountLinking.shouldRequireVerification + ) { + if (!infoVerified) { + return recipeUserId; + } + } + let canCreatePrimaryUserId = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId, + userContext, + }); + if (canCreatePrimaryUserId) { + let user = yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId, + userContext, + }); + if (user.status !== "OK") { + throw Error(user.status); + } + return user.user.id; + } + let identifier; + if (info.email !== undefined) { + identifier = { + email: info.email, + }; + } else if (info.phoneNumber !== undefined) { + identifier = { + phoneNumber: info.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let users = yield __1.default.listUsersByAccountInfo({ + info: identifier, + }); + if (users === undefined || users.length === 0) { + throw Error("this error should never be thrown"); + } + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser === undefined) { + throw Error("this error should never be thrown"); + } + shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + info, + primaryUser, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } + yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId, + primaryUserId: primaryUser.id, + userContext, + }); + return primaryUser.id; }); - this.accountLinkPostSignInViaSession = (_input) => + // TODO: account linking failures needs to be improved + this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => __awaiter(this, void 0, void 0, function* () { - // let userId = session.getUserId(); + let userId = session.getUserId(); + let user = yield __1.getUser({ + userId, + }); + if (user === undefined) { + throw Error("this should not be thrown"); + } + if (!user.isPrimaryUser) { + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + info, + undefined, + session, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + throw Error("Acount linking failure"); + } + let recipeId = user.linkedRecipes[0].recipeId; + let querier = querier_1.Querier.getNewInstanceOrThrowError(recipeId); + let recipeUser = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { + userId: user.id, + }); + shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + recipeUser.user, + undefined, + session, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + throw Error("Acount linking failure"); + } + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + throw Error("Account link failure"); + } + } + let canCreatePrimaryUser = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId: user.id, + userContext, + }); + if (canCreatePrimaryUser.status !== "OK") { + throw canCreatePrimaryUser; + } + let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: user.id, + userContext, + }); + if (createPrimaryUserResult.status !== "OK") { + throw createPrimaryUserResult; + } + user = createPrimaryUserResult.user; + } + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + info, + user, + session, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + throw Error("account linking failure"); + } + let recipeInfo; + if (info.recipeId === "emailpassword" && info.email !== undefined) { + recipeInfo = { + recipeId: "emailpassword", + email: info.email, + }; + } else if (info.recipeId === "thirdparty" && info.thirdParty !== undefined) { + recipeInfo = { + recipeId: "thirdparty", + thirdpartyId: info.thirdParty.id, + thirdpartyUserId: info.thirdParty.userId, + }; + } else if (info.recipeId === "passwordless" && info.email !== undefined) { + recipeInfo = { + recipeId: "passwordless", + email: info.email, + }; + } else if (info.recipeId === "passwordless" && info.phoneNumber !== undefined) { + recipeInfo = { + recipeId: "passwordless", + phoneNumber: info.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let recipeUser = yield __1.getUserByAccountInfoAndRecipeId({ + info: recipeInfo, + }); + if (recipeUser === undefined) { + let identitiesForPrimaryUser = yield this.getIdentitiesForPrimaryUserId(user.id); + if (info.email !== undefined) { + let result = + identitiesForPrimaryUser.verified.emails.includes(info.email) || + identitiesForPrimaryUser.unverified.emails.includes(info.email); + if (result) { + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } + } + if (info.phoneNumber !== undefined) { + let result = + identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || + identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + if (result) { + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } + } + let existingRecipeUserForInputInfo = yield __1.listUsersByAccountInfo({ + info: recipeInfo, + }); + if (existingRecipeUserForInputInfo !== undefined) { + let doesPrimaryUserIdAlreadyExists = + existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; + if (doesPrimaryUserIdAlreadyExists) { + throw Error("account linking failure"); + } + } + if (!infoVerified) { + if (shouldDoAccountLinking.shouldRequireVerification) { + return { + createRecipeUser: true, + updateVerificationClaim: true, + }; + } + } + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } + let canLinkAccounts = yield this.recipeInterfaceImpl.canLinkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); + if (canLinkAccounts.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { + return { + createRecipeUser: false, + accountsLinked: true, + updateVerificationClaim: false, + }; + } + if (canLinkAccounts.status !== "OK") { + return { + createRecipeUser: false, + accountsLinked: false, + reason: canLinkAccounts.status, + }; + } + let identitiesForPrimaryUser = yield this.getIdentitiesForPrimaryUserId(user.id); + let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; + if (info.email !== undefined) { + recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = + identitiesForPrimaryUser.verified.emails.includes(info.email) || + identitiesForPrimaryUser.unverified.emails.includes(info.email); + } + if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { + recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = + identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || + identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + } + if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { + /** + * TODO: let's Ly belongs to P1 such that Ly equal to Lx. + * if LY verified, mark Lx as verified. If Lx is verfied, + * then mark all Ly as verified + */ + } else { + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + throw Error("account link failure"); + } + } + } + yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); return { - createRecipeUser: true, + createRecipeUser: false, + accountsLinked: true, + updateVerificationClaim: true, }; }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config) ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } diff --git a/lib/build/recipe/accountlinking/recipeImplementation.d.ts b/lib/build/recipe/accountlinking/recipeImplementation.d.ts index 7d1180bfb..7e4369ba3 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.d.ts +++ b/lib/build/recipe/accountlinking/recipeImplementation.d.ts @@ -1,4 +1,4 @@ // @ts-nocheck -import { RecipeInterface } from "./types"; +import { RecipeInterface, TypeNormalisedInput } from "./types"; import { Querier } from "../../querier"; -export default function getRecipeImplementation(querier: Querier): RecipeInterface; +export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 8c2cec8d2..057964a2b 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -48,7 +48,9 @@ Object.defineProperty(exports, "__esModule", { value: true }); const querier_1 = require("../../querier"); const normalisedURLPath_1 = require("../../normalisedURLPath"); const utils_1 = require("../../utils"); -function getRecipeImplementation(querier) { +const __1 = require("../../"); +const session_1 = require("../session"); +function getRecipeImplementation(querier, config) { return { getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { return __awaiter(this, void 0, void 0, function* () { @@ -98,38 +100,241 @@ function getRecipeImplementation(querier) { }; }); }, - canCreatePrimaryUserId: function (_input) { + canCreatePrimaryUserId: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { + let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsforRecipeUserIds({ + recipeUserIds: [recipeUserId], + }); + if ( + recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== undefined && + recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== null + ) { + return { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: recipeUserIdToPrimaryUserIdMapping[recipeUserId], + description: "Recipe user is already linked with another primary user id", + }; + } + let user = yield __1.getUser({ + userId: recipeUserId, + }); + if (user === undefined) { + // QUESTION: should we throw an error here instead? + return { + status: "OK", + }; + } + let usersForAccountInfo = []; + let promises = []; + for (let i = 0; i < user.emails.length; i++) { + promises.push( + __1.listUsersByAccountInfo({ + info: { + email: user.emails[i], + }, + }) + ); + } + for (let i = 0; i < user.thirdpartyInfo.length; i++) { + promises.push( + __1.listUsersByAccountInfo({ + info: Object.assign({}, user.thirdpartyInfo[i]), + }) + ); + } + for (let i = 0; i < user.phoneNumbers.length; i++) { + promises.push( + __1.listUsersByAccountInfo({ + info: { + phoneNumber: user.phoneNumbers[i], + }, + }) + ); + } + for (let i = 0; i < promises.length; i++) { + let result = yield promises[i]; + if (result !== undefined) { + usersForAccountInfo.push(...result); + } + } + let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); + if (primaryUser !== undefined) { + return { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUser.id, + description: + "Account info related to recipe user is already linked with another primary user id", + }; + } return { status: "OK", }; }); }, - createPrimaryUser: function (_input) { + createPrimaryUser: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: "", - description: "", - }; + let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ + recipeUserId, + }); + if (canCreatePrimaryUser.status !== "OK") { + return canCreatePrimaryUser; + } + let primaryUser = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), + { + recipeUserId, + } + ); + return primaryUser; }); }, - canLinkAccounts: function (_input) { + canLinkAccounts: function ({ recipeUserId, primaryUserId }) { return __awaiter(this, void 0, void 0, function* () { + let primaryUser = yield __1.getUser({ + userId: primaryUserId, + }); + if (primaryUser === undefined) { + throw Error("primary user not found"); + } + let recipeUser = yield __1.getUser({ + userId: recipeUserId, + }); + if (recipeUser === undefined) { + throw Error("recipe user not found"); + } + let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ + recipeUserId, + }); + if ( + canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + if (canCreatePrimaryUser.primaryUserId === primaryUserId) { + return { + status: "ACCOUNTS_ALREADY_LINKED_ERROR", + description: "accounts are already linked", + }; + } + return canCreatePrimaryUser; + } + if (canCreatePrimaryUser.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + /** + * if canCreatePrimaryUser.status is + * ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR and + * canCreatePrimaryUser.primaryUserId is equal to the input primaryUserId, + * we don't return ACCOUNTS_ALREADY_LINKED_ERROR cause here the accounts + * are not yet linked. It's just that the identifyingInfo associated with the + * recipeUser is linked to the primaryUser. Input recipeUser still needs + * to be linked with the input primaryUserId + */ + if (canCreatePrimaryUser.primaryUserId !== primaryUserId) { + return canCreatePrimaryUser; + } + } return { status: "OK", }; }); }, - linkAccounts: function (_input) { + linkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { - return { - status: "OK", - }; + let canLinkAccountsResult = yield this.canLinkAccounts({ + recipeUserId, + primaryUserId, + }); + if (canLinkAccountsResult.status !== "OK") { + return canLinkAccountsResult; + } + let accountsLinkingResult = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), + { + recipeUserId, + primaryUserId, + } + ); + if (accountsLinkingResult.status === "OK") { + yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); + let user = yield __1.getUser({ + userId: primaryUserId, + }); + if (user === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); + if (recipeUser === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUserInfo = yield querier_1.Querier.getNewInstanceOrThrowError( + recipeUser.recipeId + ).sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { + userId: recipeUserId, + }); + yield config.onAccountLinked(user, recipeUserInfo.user, userContext); + } + return accountsLinkingResult; }); }, - unlinkAccounts: function (_ipnut) { + unlinkAccounts: function ({ recipeUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { + let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsforRecipeUserIds({ + recipeUserIds: [recipeUserId], + }); + if ( + recipeUserIdToPrimaryUserIdMapping[recipeUserId] === undefined || + recipeUserIdToPrimaryUserIdMapping[recipeUserId] === null + ) { + return { + status: "OK", + wasRecipeUserDeleted: false, + }; + } + let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; + let user = yield __1.getUser({ + userId: primaryUserId, + }); + if (user === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); + if (recipeUser === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUserInfo = yield querier_1.Querier.getNewInstanceOrThrowError( + recipeUser.recipeId + ).sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { + userId: recipeUserId, + }); + /** + * primaryUserId === recipeUserId + */ + if (primaryUserId === recipeUserId) { + let user = yield __1.getUser({ + userId: primaryUserId, + }); + if (user === undefined) { + return { + status: "OK", + wasRecipeUserDeleted: false, + }; + } + if (user.linkedRecipes.length > 1) { + yield __1.deleteUser(recipeUserId, false); + return { + status: "OK", + wasRecipeUserDeleted: true, + }; + } + } + let accountsUnlinkingResult = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/unlink"), + { + recipeUserId, + primaryUserId, + } + ); + if (accountsUnlinkingResult.status === "OK") { + yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); + } + yield config.onAccountUnlinked(user, recipeUserInfo.user, userContext); return { status: "OK", wasRecipeUserDeleted: false, diff --git a/lib/ts/index.ts b/lib/ts/index.ts index 657bb9947..a09c272a8 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -103,7 +103,7 @@ export default class SuperTokensWrapper { return SuperTokens.getInstanceOrThrowError().listUsersByAccountInfo(input); } - static getUserByAccountInfo(input: { info: AccountInfoWithRecipeId }) { + static getUserByAccountInfoAndRecipeId(input: { info: AccountInfoWithRecipeId }) { return SuperTokens.getInstanceOrThrowError().getUserByAccountInfoAndRecipeId(input); } } @@ -132,6 +132,6 @@ export let getUser = SuperTokensWrapper.getUser; export let listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; -export let getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; +export let getUserByAccountInfoAndRecipeId = SuperTokensWrapper.getUserByAccountInfoAndRecipeId; export let Error = SuperTokensWrapper.Error; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 8a282090f..2513d4bb7 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -17,7 +17,7 @@ import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; -import SuperTokens from "../.."; +import SuperTokens, { getUser, getUserByAccountInfoAndRecipeId, listUsersByAccountInfo } from "../.."; import SuperTokensModule from "../../supertokens"; import type { AccountInfoWithRecipeId, @@ -27,13 +27,13 @@ import type { RecipeListFunction, } from "../../types"; import { SessionContainer } from "../session"; -import type { AccountInfoAndEmailWithRecipeId, TypeNormalisedInput, RecipeInterface, TypeInput } from "./types"; -import { User } from "../../types"; +import type { TypeNormalisedInput, RecipeInterface, TypeInput, AccountInfoAndEmailWithRecipeId } from "./types"; import { validateAndNormaliseUserInput } from "./utils"; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; import SuperTokensError from "../../error"; +import NormalisedURLPath from "../../normalisedURLPath"; export default class Recipe extends RecipeModule { private static instance: Recipe | undefined = undefined; @@ -59,7 +59,9 @@ export default class Recipe extends RecipeModule { this.isInServerlessEnv = isInServerlessEnv; { - let builder = new OverrideableBuilder(RecipeImplementation(Querier.getNewInstanceOrThrowError(recipeId))); + let builder = new OverrideableBuilder( + RecipeImplementation(Querier.getNewInstanceOrThrowError(recipeId), this.config) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } } @@ -123,41 +125,198 @@ export default class Recipe extends RecipeModule { return SuperTokensError.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; } - isSignUpAllowed = async (input: { info: AccountInfoWithRecipeId }): Promise => { - let user: User | undefined = await SuperTokens.getUserByAccountInfo(input); - if (user === undefined || !user.isPrimaryUser) { + getIdentitiesForPrimaryUserId = async ( + primaryUserId: string + ): Promise<{ + verified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; + }[]; + }; + unverified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; + }[]; + }; + }> => { + return await Querier.getNewInstanceOrThrowError(this.getRecipeId()).sendGetRequest( + new NormalisedURLPath("/recipe/accountlinking/user/identities"), + { + primaryUserId, + } + ); + }; + + isSignUpAllowed = async ({ + info, + userContext, + }: { + info: AccountInfoAndEmailWithRecipeId; + userContext: any; + }): Promise => { + let identifier: + | { + email: string; + } + | { + phoneNumber: string; + }; + if (info.email !== undefined) { + identifier = { + email: info.email, + }; + } else if (info.phoneNumber !== undefined) { + identifier = { + phoneNumber: info.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let users = await SuperTokens.listUsersByAccountInfo({ + info: identifier, + }); + if (users === undefined || users.length === 0) { return true; } - let shouldRequireVerification = false; // TOOD: call shouldRequireVerification from config + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser === undefined) { + return true; + } + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + info, + primaryUser, + undefined, + userContext + ); + let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink + ? shouldDoAccountLinking.shouldRequireVerification + : false; if (!shouldRequireVerification) { return true; } - // /** - // * for each linked recipes, get all the verified identifying info - // * - // * if the input identifyingInfo is found in the above generated list - // * of verified identifyingInfos, return true else false. - // */ - return true; + + /** + * DISCUSS: new API in core which returns all the verified identities for primaryUserId + */ + let identitiesForPrimaryUser = await this.getIdentitiesForPrimaryUserId(primaryUser.id); + + if (info.email !== undefined) { + return identitiesForPrimaryUser.verified.emails.includes(info.email); + } + if (info.phoneNumber !== undefined) { + return identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber); + } + throw Error("it should never reach here"); }; - createPrimaryUserIdOrLinkAccountPostSignUp = async (_input: { - identifyinInfo: AccountInfoAndEmailWithRecipeId; - shouldRequireVerification: boolean; - }) => { - // TODO + createPrimaryUserIdOrLinkAccountPostSignUp = async ({ + info, + infoVerified, + recipeUserId, + userContext, + }: { + info: AccountInfoAndEmailWithRecipeId; + infoVerified: boolean; + recipeUserId: string; + userContext: any; + }): Promise => { + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + info, + undefined, + undefined, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink && shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + return recipeUserId; + } + } + let canCreatePrimaryUserId = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId, + userContext, + }); + if (canCreatePrimaryUserId) { + let user = await this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId, + userContext, + }); + if (user.status !== "OK") { + throw Error(user.status); + } + return user.user.id; + } + let identifier: + | { + email: string; + } + | { + phoneNumber: string; + }; + if (info.email !== undefined) { + identifier = { + email: info.email, + }; + } else if (info.phoneNumber !== undefined) { + identifier = { + phoneNumber: info.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let users = await SuperTokens.listUsersByAccountInfo({ + info: identifier, + }); + if (users === undefined || users.length === 0) { + throw Error("this error should never be thrown"); + } + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser === undefined) { + throw Error("this error should never be thrown"); + } + shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + info, + primaryUser, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } + await this.recipeInterfaceImpl.linkAccounts({ + recipeUserId, + primaryUserId: primaryUser.id, + userContext, + }); + return primaryUser.id; }; - accountLinkPostSignInViaSession = async (_input: { + + // TODO: account linking failures needs to be improved + accountLinkPostSignInViaSession = async ({ + session, + info, + infoVerified, + userContext, + }: { session: SessionContainer; - identifyinInfo: AccountInfoAndEmailWithRecipeId; + info: AccountInfoAndEmailWithRecipeId; + infoVerified: boolean; + userContext: any; }): Promise< | { createRecipeUser: true; + updateVerificationClaim: boolean; } | ({ createRecipeUser: false; } & ( | { accountsLinked: true; + updateVerificationClaim: boolean; } | { accountsLinked: false; @@ -165,9 +324,199 @@ export default class Recipe extends RecipeModule { } )) > => { - // let userId = session.getUserId(); + let userId = session.getUserId(); + let user = await getUser({ + userId, + }); + if (user === undefined) { + throw Error("this should not be thrown"); + } + if (!user.isPrimaryUser) { + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + info, + undefined, + session, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + throw Error("Acount linking failure"); + } + + let recipeId = user.linkedRecipes[0].recipeId; + let querier = Querier.getNewInstanceOrThrowError(recipeId); + let recipeUser = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { + userId: user.id, + }); + + shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + recipeUser.user, + undefined, + session, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + throw Error("Acount linking failure"); + } + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + throw Error("Account link failure"); + } + } + let canCreatePrimaryUser = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId: user.id, + userContext, + }); + if (canCreatePrimaryUser.status !== "OK") { + throw canCreatePrimaryUser; + } + let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: user.id, + userContext, + }); + if (createPrimaryUserResult.status !== "OK") { + throw createPrimaryUserResult; + } + user = createPrimaryUserResult.user; + } + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + info, + user, + session, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + throw Error("account linking failure"); + } + let recipeInfo: AccountInfoWithRecipeId; + if (info.recipeId === "emailpassword" && info.email !== undefined) { + recipeInfo = { + recipeId: "emailpassword", + email: info.email, + }; + } else if (info.recipeId === "thirdparty" && info.thirdParty !== undefined) { + recipeInfo = { + recipeId: "thirdparty", + thirdpartyId: info.thirdParty.id, + thirdpartyUserId: info.thirdParty.userId, + }; + } else if (info.recipeId === "passwordless" && info.email !== undefined) { + recipeInfo = { + recipeId: "passwordless", + email: info.email, + }; + } else if (info.recipeId === "passwordless" && info.phoneNumber !== undefined) { + recipeInfo = { + recipeId: "passwordless", + phoneNumber: info.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let recipeUser = await getUserByAccountInfoAndRecipeId({ + info: recipeInfo, + }); + if (recipeUser === undefined) { + let identitiesForPrimaryUser = await this.getIdentitiesForPrimaryUserId(user.id); + if (info.email !== undefined) { + let result = + identitiesForPrimaryUser.verified.emails.includes(info.email) || + identitiesForPrimaryUser.unverified.emails.includes(info.email); + if (result) { + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } + } + if (info.phoneNumber !== undefined) { + let result = + identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || + identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + if (result) { + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } + } + + let existingRecipeUserForInputInfo = await listUsersByAccountInfo({ + info: recipeInfo, + }); + if (existingRecipeUserForInputInfo !== undefined) { + let doesPrimaryUserIdAlreadyExists = + existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; + if (doesPrimaryUserIdAlreadyExists) { + throw Error("account linking failure"); + } + } + if (!infoVerified) { + if (shouldDoAccountLinking.shouldRequireVerification) { + return { + createRecipeUser: true, + updateVerificationClaim: true, + }; + } + } + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } + let canLinkAccounts = await this.recipeInterfaceImpl.canLinkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); + if (canLinkAccounts.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { + return { + createRecipeUser: false, + accountsLinked: true, + updateVerificationClaim: false, + }; + } + if (canLinkAccounts.status !== "OK") { + return { + createRecipeUser: false, + accountsLinked: false, + reason: canLinkAccounts.status, + }; + } + + let identitiesForPrimaryUser = await this.getIdentitiesForPrimaryUserId(user.id); + let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; + if (info.email !== undefined) { + recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = + identitiesForPrimaryUser.verified.emails.includes(info.email) || + identitiesForPrimaryUser.unverified.emails.includes(info.email); + } + if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { + recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = + identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || + identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + } + if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { + /** + * TODO: let's Ly belongs to P1 such that Ly equal to Lx. + * if LY verified, mark Lx as verified. If Lx is verfied, + * then mark all Ly as verified + */ + } else { + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + throw Error("account link failure"); + } + } + } + await this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); return { - createRecipeUser: true, + createRecipeUser: false, + accountsLinked: true, + updateVerificationClaim: true, }; }; } diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 9cbf996be..f8957b47f 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -13,13 +13,15 @@ * under the License. */ -import { RecipeInterface } from "./types"; +import { RecipeInterface, TypeNormalisedInput } from "./types"; import { Querier } from "../../querier"; import type { User } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; import { maxVersion } from "../../utils"; +import { getUser, listUsersByAccountInfo, deleteUser } from "../../"; +import Session from "../session"; -export default function getRecipeImplementation(querier: Querier): RecipeInterface { +export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface { return { getRecipeUserIdsForPrimaryUserIds: async function ({ primaryUserIds, @@ -94,9 +96,10 @@ export default function getRecipeImplementation(querier: Querier): RecipeInterfa nextPaginationToken: response.nextPaginationToken, }; }, - canCreatePrimaryUserId: async function (_input: { + canCreatePrimaryUserId: async function ({ + recipeUserId, + }: { recipeUserId: string; - userContext: any; }): Promise< | { status: "OK"; @@ -109,13 +112,91 @@ export default function getRecipeImplementation(querier: Querier): RecipeInterfa description: string; } > { + let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsforRecipeUserIds({ + recipeUserIds: [recipeUserId], + }); + + if ( + recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== undefined && + recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== null + ) { + return { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: recipeUserIdToPrimaryUserIdMapping[recipeUserId], + description: "Recipe user is already linked with another primary user id", + }; + } + + let user = await getUser({ + userId: recipeUserId, + }); + + if (user === undefined) { + // QUESTION: should we throw an error here instead? + return { + status: "OK", + }; + } + + let usersForAccountInfo = []; + + let promises = []; + + for (let i = 0; i < user.emails.length; i++) { + promises.push( + listUsersByAccountInfo({ + info: { + email: user.emails[i], + }, + }) + ); + } + + for (let i = 0; i < user.thirdpartyInfo.length; i++) { + promises.push( + listUsersByAccountInfo({ + info: { + ...user.thirdpartyInfo[i], + }, + }) + ); + } + + for (let i = 0; i < user.phoneNumbers.length; i++) { + promises.push( + listUsersByAccountInfo({ + info: { + phoneNumber: user.phoneNumbers[i], + }, + }) + ); + } + + for (let i = 0; i < promises.length; i++) { + let result = await promises[i]; + if (result !== undefined) { + usersForAccountInfo.push(...result); + } + } + + let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); + + if (primaryUser !== undefined) { + return { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUser.id, + description: "Account info related to recipe user is already linked with another primary user id", + }; + } + return { status: "OK", }; }, - createPrimaryUser: async function (_input: { + createPrimaryUser: async function ({ + recipeUserId, + }: { recipeUserId: string; - userContext: any; }): Promise< | { status: "OK"; @@ -129,16 +210,38 @@ export default function getRecipeImplementation(querier: Querier): RecipeInterfa description: string; } > { - return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: "", - description: "", - }; + let canCreatePrimaryUser: + | { + status: "OK"; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } = await this.canCreatePrimaryUserId({ + recipeUserId, + }); + if (canCreatePrimaryUser.status !== "OK") { + return canCreatePrimaryUser; + } + + let primaryUser = await querier.sendPostRequest( + new NormalisedURLPath("/recipe/accountlinking/user/primary"), + { + recipeUserId, + } + ); + + return primaryUser; }, - canLinkAccounts: async function (_input: { + canLinkAccounts: async function ({ + recipeUserId, + primaryUserId, + }: { recipeUserId: string; primaryUserId: string; - userContext: any; }): Promise< | { status: "OK"; @@ -158,11 +261,63 @@ export default function getRecipeImplementation(querier: Querier): RecipeInterfa description: string; } > { + let primaryUser = await getUser({ + userId: primaryUserId, + }); + if (primaryUser === undefined) { + throw Error("primary user not found"); + } + let recipeUser = await getUser({ + userId: recipeUserId, + }); + if (recipeUser === undefined) { + throw Error("recipe user not found"); + } + let canCreatePrimaryUser: + | { + status: "OK"; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } = await this.canCreatePrimaryUserId({ + recipeUserId, + }); + if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + if (canCreatePrimaryUser.primaryUserId === primaryUserId) { + return { + status: "ACCOUNTS_ALREADY_LINKED_ERROR", + description: "accounts are already linked", + }; + } + return canCreatePrimaryUser; + } + if (canCreatePrimaryUser.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + /** + * if canCreatePrimaryUser.status is + * ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR and + * canCreatePrimaryUser.primaryUserId is equal to the input primaryUserId, + * we don't return ACCOUNTS_ALREADY_LINKED_ERROR cause here the accounts + * are not yet linked. It's just that the identifyingInfo associated with the + * recipeUser is linked to the primaryUser. Input recipeUser still needs + * to be linked with the input primaryUserId + */ + if (canCreatePrimaryUser.primaryUserId !== primaryUserId) { + return canCreatePrimaryUser; + } + } return { status: "OK", }; }, - linkAccounts: async function (_input: { + linkAccounts: async function ({ + recipeUserId, + primaryUserId, + userContext, + }: { recipeUserId: string; primaryUserId: string; userContext: any; @@ -185,17 +340,115 @@ export default function getRecipeImplementation(querier: Querier): RecipeInterfa description: string; } > { - return { - status: "OK", - }; + let canLinkAccountsResult = await this.canLinkAccounts({ + recipeUserId, + primaryUserId, + }); + if (canLinkAccountsResult.status !== "OK") { + return canLinkAccountsResult; + } + let accountsLinkingResult = await querier.sendPostRequest( + new NormalisedURLPath("/recipe/accountlinking/user/link"), + { + recipeUserId, + primaryUserId, + } + ); + if (accountsLinkingResult.status === "OK") { + await Session.revokeAllSessionsForUser(recipeUserId, userContext); + let user = await getUser({ + userId: primaryUserId, + }); + if (user === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); + if (recipeUser === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUserInfo = await Querier.getNewInstanceOrThrowError(recipeUser.recipeId).sendGetRequest( + new NormalisedURLPath("/recipe/user"), + { + userId: recipeUserId, + } + ); + await config.onAccountLinked(user, recipeUserInfo.user, userContext); + } + return accountsLinkingResult; }, - unlinkAccounts: async function (_ipnut: { + unlinkAccounts: async function ({ + recipeUserId, + userContext, + }: { recipeUserId: string; userContext: any; }): Promise<{ status: "OK"; wasRecipeUserDeleted: boolean; }> { + let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsforRecipeUserIds({ + recipeUserIds: [recipeUserId], + }); + if ( + recipeUserIdToPrimaryUserIdMapping[recipeUserId] === undefined || + recipeUserIdToPrimaryUserIdMapping[recipeUserId] === null + ) { + return { + status: "OK", + wasRecipeUserDeleted: false, + }; + } + let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; + let user = await getUser({ + userId: primaryUserId, + }); + if (user === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); + if (recipeUser === undefined) { + throw Error("this error should never be thrown"); + } + let recipeUserInfo = await Querier.getNewInstanceOrThrowError(recipeUser.recipeId).sendGetRequest( + new NormalisedURLPath("/recipe/user"), + { + userId: recipeUserId, + } + ); + /** + * primaryUserId === recipeUserId + */ + if (primaryUserId === recipeUserId) { + let user = await getUser({ + userId: primaryUserId, + }); + + if (user === undefined) { + return { + status: "OK", + wasRecipeUserDeleted: false, + }; + } + if (user.linkedRecipes.length > 1) { + await deleteUser(recipeUserId, false); + return { + status: "OK", + wasRecipeUserDeleted: true, + }; + } + } + let accountsUnlinkingResult = await querier.sendPostRequest( + new NormalisedURLPath("/recipe/accountlinking/user/unlink"), + { + recipeUserId, + primaryUserId, + } + ); + if (accountsUnlinkingResult.status === "OK") { + await Session.revokeAllSessionsForUser(recipeUserId, userContext); + } + + await config.onAccountUnlinked(user, recipeUserInfo.user, userContext); return { status: "OK", wasRecipeUserDeleted: false, From 5531c2451e4d347ad24470fd205dc835292af795 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 26 Dec 2022 11:00:51 +0530 Subject: [PATCH 05/82] types update --- lib/ts/recipe/accountlinking/recipe.ts | 2 +- lib/ts/recipe/accountlinking/types.ts | 10 +++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index ca82af0db..20196eb42 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -1,4 +1,4 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the * "License") as published by the Apache Software Foundation. diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 21d3d60af..2bd747855 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -1,4 +1,4 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the * "License") as published by the Apache Software Foundation. @@ -14,7 +14,7 @@ */ import OverrideableBuilder from "supertokens-js-override"; -import { User } from "../../types"; +import type { User } from "../../types"; import { SessionContainer } from "../session"; export type TypeInput = { @@ -39,7 +39,6 @@ export type TypeInput = { originalImplementation: RecipeInterface, builder?: OverrideableBuilder ) => RecipeInterface; - apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -65,12 +64,9 @@ export type TypeNormalisedInput = { originalImplementation: RecipeInterface, builder?: OverrideableBuilder ) => RecipeInterface; - apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; -export type APIInterface = {}; - export type RecipeInterface = { getRecipeUserIdsForPrimaryUserIds: (input: { primaryUserIds: string[]; @@ -186,7 +182,7 @@ export type RecipeInterface = { }>; }; -type RecipeLevelUser = { +export type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; id: string; // can be recipeUserId or primaryUserId timeJoined: number; From df027fe73ae85aebee3143a8b4bf95c8617863bc Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Thu, 29 Dec 2022 11:57:52 +0530 Subject: [PATCH 06/82] Update lib/ts/recipe/accountlinking/types.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 2bd747855..568cc4df7 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -72,7 +72,7 @@ export type RecipeInterface = { primaryUserIds: string[]; userContext: any; }) => Promise<{ - [primaryUserId: string]: string[]; // recipeUserIds + [primaryUserId: string]: string[]; // recipeUserIds. If input primary user ID doesn't exists, those ids will not be part of the output set. }>; getPrimaryUserIdsforRecipeUserIds: (input: { recipeUserIds: string[]; From 61d605022f50e6f5d9d3865767faa9076966a74e Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Thu, 29 Dec 2022 11:58:02 +0530 Subject: [PATCH 07/82] Update lib/ts/recipe/accountlinking/types.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 568cc4df7..7dc1f0bd3 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -78,7 +78,7 @@ export type RecipeInterface = { recipeUserIds: string[]; userContext: any; }) => Promise<{ - [recipeUserId: string]: string | null; + [recipeUserId: string]: string | null; // if recipeUserId doesn't have a primaryUserId, then it will be mapped to `null`. If the input recipeUserId doesn't exist, then it won't be a part of the map }>; addNewRecipeUserIdWithoutPrimaryUserId: (input: { recipeUserId: string; From da4a11bb6f505b5c9d9be8ac9784a29eb93c5284 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Thu, 29 Dec 2022 11:58:09 +0530 Subject: [PATCH 08/82] Update lib/ts/recipe/accountlinking/types.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/types.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 7dc1f0bd3..018f16eef 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -85,7 +85,12 @@ export type RecipeInterface = { recipeId: string; timeJoined: number; userContext: any; - }) => Promise; + }) => Promise<{ + status: "OK", + createdNewEntry: boolean + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + }>; getUsers: (input: { timeJoinedOrder: "ASC" | "DESC"; limit?: number; From e8fb6df08e47e0eef88a0a6c1f8e889cedb9d42b Mon Sep 17 00:00:00 2001 From: Bhumil Date: Thu, 29 Dec 2022 12:06:48 +0530 Subject: [PATCH 09/82] return type update --- lib/build/recipe/accountlinking/recipe.d.ts | 7 ++- lib/build/recipe/accountlinking/recipe.js | 48 ++++++++++++++++--- lib/ts/recipe/accountlinking/recipe.ts | 52 +++++++++++++++++---- 3 files changed, 91 insertions(+), 16 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 8610afb11..2e87af32e 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -96,7 +96,12 @@ export default class Recipe extends RecipeModule { createRecipeUser: false; } & { accountsLinked: false; - reason: string; + reason: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" + | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; }) >; } diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index b2fb46d8f..fdd75692c 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -200,7 +200,11 @@ class Recipe extends recipeModule_1.default { userContext ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - throw Error("Acount linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + }; } let recipeId = user.linkedRecipes[0].recipeId; let querier = querier_1.Querier.getNewInstanceOrThrowError(recipeId); @@ -214,11 +218,29 @@ class Recipe extends recipeModule_1.default { userContext ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - throw Error("Acount linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + }; } if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - throw Error("Account link failure"); + if (recipeId === "emailpassword" || recipeId === "thirdparty") { + let querier2 = querier_1.Querier.getNewInstanceOrThrowError("emailverification"); + let response = yield querier2.sendGetRequest( + new normalisedURLPath_1.default("/recipe/user/email/verify"), + { + userId: recipeUser.user.id, + email: recipeUser.user.email, + } + ); + if (!response.isVerified) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; + } } } let canCreatePrimaryUser = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ @@ -226,14 +248,22 @@ class Recipe extends recipeModule_1.default { userContext, }); if (canCreatePrimaryUser.status !== "OK") { - throw canCreatePrimaryUser; + return { + createRecipeUser: false, + accountsLinked: false, + reason: canCreatePrimaryUser.status, + }; } let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: user.id, userContext, }); if (createPrimaryUserResult.status !== "OK") { - throw createPrimaryUserResult; + return { + createRecipeUser: false, + accountsLinked: false, + reason: createPrimaryUserResult.status, + }; } user = createPrimaryUserResult.user; } @@ -244,7 +274,11 @@ class Recipe extends recipeModule_1.default { userContext ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - throw Error("account linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + }; } let recipeInfo; if (info.recipeId === "emailpassword" && info.email !== undefined) { diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 2513d4bb7..734b750f1 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -320,7 +320,12 @@ export default class Recipe extends RecipeModule { } | { accountsLinked: false; - reason: string; // TODO + reason: + | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; } )) > => { @@ -339,7 +344,11 @@ export default class Recipe extends RecipeModule { userContext ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - throw Error("Acount linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + }; } let recipeId = user.linkedRecipes[0].recipeId; @@ -355,11 +364,26 @@ export default class Recipe extends RecipeModule { userContext ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - throw Error("Acount linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + }; } if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - throw Error("Account link failure"); + if (recipeId === "emailpassword" || recipeId === "thirdparty") { + let querier2 = Querier.getNewInstanceOrThrowError("emailverification"); + let response = await querier2.sendGetRequest(new NormalisedURLPath("/recipe/user/email/verify"), { + userId: recipeUser.user.id, + email: recipeUser.user.email, + }); + if (!response.isVerified) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; + } } } let canCreatePrimaryUser = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ @@ -367,14 +391,22 @@ export default class Recipe extends RecipeModule { userContext, }); if (canCreatePrimaryUser.status !== "OK") { - throw canCreatePrimaryUser; + return { + createRecipeUser: false, + accountsLinked: false, + reason: canCreatePrimaryUser.status, + }; } let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: user.id, userContext, }); if (createPrimaryUserResult.status !== "OK") { - throw createPrimaryUserResult; + return { + createRecipeUser: false, + accountsLinked: false, + reason: createPrimaryUserResult.status, + }; } user = createPrimaryUserResult.user; } @@ -385,7 +417,11 @@ export default class Recipe extends RecipeModule { userContext ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - throw Error("account linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + }; } let recipeInfo: AccountInfoWithRecipeId; if (info.recipeId === "emailpassword" && info.email !== undefined) { From dce3429dc0dc78bb2c9fdc7b16eb029bd4025a38 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Thu, 29 Dec 2022 12:28:24 +0530 Subject: [PATCH 10/82] index file updated --- lib/build/recipe/accountlinking/index.d.ts | 124 +++++++++++++++++++ lib/build/recipe/accountlinking/index.js | 131 ++++++++++++++++++++- lib/build/recipe/accountlinking/recipe.js | 13 +- lib/ts/recipe/accountlinking/index.ts | 89 +++++++++++++- lib/ts/recipe/accountlinking/recipe.ts | 13 +- 5 files changed, 359 insertions(+), 11 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 86168f84a..e0bbdfd51 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,5 +1,129 @@ // @ts-nocheck import Recipe from "./recipe"; +import { RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; + static getRecipeUserIdsForPrimaryUserIds( + primaryUserIds: string[], + userContext: any + ): Promise<{ + [primaryUserId: string]: string[]; + }>; + static getPrimaryUserIdsforRecipeUserIds( + recipeUserIds: string[], + userContext: any + ): Promise<{ + [recipeUserId: string]: string | null; + }>; + static addNewRecipeUserIdWithoutPrimaryUserId( + recipeUserId: string, + recipeId: string, + timeJoined: number, + userContext: any + ): Promise; + static getUsers( + timeJoinedOrder: "ASC" | "DESC", + limit: number | undefined, + paginationToken: string | undefined, + includeRecipeIds: string[] | undefined, + userContext: any + ): Promise<{ + users: import("../../types").User[]; + nextPaginationToken?: string | undefined; + }>; + static canCreatePrimaryUserId( + recipeUserId: string, + userContext: any + ): Promise< + | { + status: "OK"; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static createPrimaryUser( + recipeUserId: string, + userContext: any + ): Promise< + | { + status: "OK"; + user: import("../../types").User; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static canLinkAccounts( + recipeUserId: string, + primaryUserId: string, + userContext: any + ): Promise< + | { + status: "OK"; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } + | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static linkAccounts( + recipeUserId: string, + primaryUserId: string, + userContext: any + ): Promise< + | { + status: "OK"; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static unlinkAccounts( + recipeUserId: string, + userContext: any + ): Promise<{ + status: "OK"; + wasRecipeUserDeleted: boolean; + }>; } +export declare const init: typeof Recipe.init; +export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; +export declare const getPrimaryUserIdsforRecipeUserIds: typeof Wrapper.getPrimaryUserIdsforRecipeUserIds; +export declare const addNewRecipeUserIdWithoutPrimaryUserId: typeof Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; +export declare const getUsers: typeof Wrapper.getUsers; +export declare const canCreatePrimaryUserId: typeof Wrapper.canCreatePrimaryUserId; +export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; +export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; +export declare const linkAccounts: typeof Wrapper.linkAccounts; +export declare const unlinkAccounts: typeof Wrapper.unlinkAccounts; +export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 5e235c4f1..7652cb1b2 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -13,10 +13,135 @@ * License for the specific language governing permissions and limitations * under the License. */ +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipe_1 = require("./recipe"); -// import { RecipeInterface } from "./types"; -// import { User } from "../../types"; -class Wrapper {} +class Wrapper { + static getRecipeUserIdsForPrimaryUserIds(primaryUserIds, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getRecipeUserIdsForPrimaryUserIds({ + primaryUserIds, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static getPrimaryUserIdsforRecipeUserIds(recipeUserIds, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ + recipeUserIds, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static addNewRecipeUserIdWithoutPrimaryUserId(recipeUserId, recipeId, timeJoined, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.addNewRecipeUserIdWithoutPrimaryUserId({ + recipeUserId, + recipeId, + timeJoined, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static getUsers(timeJoinedOrder, limit, paginationToken, includeRecipeIds, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsers({ + timeJoinedOrder, + limit, + paginationToken, + includeRecipeIds, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static canCreatePrimaryUserId(recipeUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static createPrimaryUser(recipeUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createPrimaryUser({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static canLinkAccounts(recipeUserId, primaryUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.canLinkAccounts({ + recipeUserId, + primaryUserId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static linkAccounts(recipeUserId, primaryUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ + recipeUserId, + primaryUserId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static unlinkAccounts(recipeUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.unlinkAccounts({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } +} exports.default = Wrapper; Wrapper.init = recipe_1.default.init; +exports.init = Wrapper.init; +exports.getRecipeUserIdsForPrimaryUserIds = Wrapper.getRecipeUserIdsForPrimaryUserIds; +exports.getPrimaryUserIdsforRecipeUserIds = Wrapper.getPrimaryUserIdsforRecipeUserIds; +exports.addNewRecipeUserIdWithoutPrimaryUserId = Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; +exports.getUsers = Wrapper.getUsers; +exports.canCreatePrimaryUserId = Wrapper.canCreatePrimaryUserId; +exports.createPrimaryUser = Wrapper.createPrimaryUser; +exports.canLinkAccounts = Wrapper.canLinkAccounts; +exports.linkAccounts = Wrapper.linkAccounts; +exports.unlinkAccounts = Wrapper.unlinkAccounts; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index fdd75692c..6c7d2b29c 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -182,7 +182,6 @@ class Recipe extends recipeModule_1.default { }); return primaryUser.id; }); - // TODO: account linking failures needs to be improved this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => __awaiter(this, void 0, void 0, function* () { let userId = session.getUserId(); @@ -339,7 +338,11 @@ class Recipe extends recipeModule_1.default { let doesPrimaryUserIdAlreadyExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; if (doesPrimaryUserIdAlreadyExists) { - throw Error("account linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + }; } } if (!infoVerified) { @@ -395,7 +398,11 @@ class Recipe extends recipeModule_1.default { } else { if (shouldDoAccountLinking.shouldRequireVerification) { if (!infoVerified) { - throw Error("account link failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; } } } diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index fabee246a..cfcac39b1 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -14,9 +14,94 @@ */ import Recipe from "./recipe"; -// import { RecipeInterface } from "./types"; -// import { User } from "../../types"; +import { RecipeInterface } from "./types"; export default class Wrapper { static init = Recipe.init; + + static async getRecipeUserIdsForPrimaryUserIds(primaryUserIds: string[], userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getRecipeUserIdsForPrimaryUserIds({ + primaryUserIds, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async getPrimaryUserIdsforRecipeUserIds(recipeUserIds: string[], userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ + recipeUserIds, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async addNewRecipeUserIdWithoutPrimaryUserId( + recipeUserId: string, + recipeId: string, + timeJoined: number, + userContext: any + ) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.addNewRecipeUserIdWithoutPrimaryUserId({ + recipeUserId, + recipeId, + timeJoined, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async getUsers( + timeJoinedOrder: "ASC" | "DESC", + limit: number | undefined, + paginationToken: string | undefined, + includeRecipeIds: string[] | undefined, + userContext: any + ) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUsers({ + timeJoinedOrder, + limit, + paginationToken, + includeRecipeIds, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async canCreatePrimaryUserId(recipeUserId: string, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async createPrimaryUser(recipeUserId: string, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.createPrimaryUser({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async canLinkAccounts(recipeUserId: string, primaryUserId: string, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.canLinkAccounts({ + recipeUserId, + primaryUserId, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async linkAccounts(recipeUserId: string, primaryUserId: string, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ + recipeUserId, + primaryUserId, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async unlinkAccounts(recipeUserId: string, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.unlinkAccounts({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + } } + +export const init = Wrapper.init; +export const getRecipeUserIdsForPrimaryUserIds = Wrapper.getRecipeUserIdsForPrimaryUserIds; +export const getPrimaryUserIdsforRecipeUserIds = Wrapper.getPrimaryUserIdsforRecipeUserIds; +export const addNewRecipeUserIdWithoutPrimaryUserId = Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; +export const getUsers = Wrapper.getUsers; +export const canCreatePrimaryUserId = Wrapper.canCreatePrimaryUserId; +export const createPrimaryUser = Wrapper.createPrimaryUser; +export const canLinkAccounts = Wrapper.canLinkAccounts; +export const linkAccounts = Wrapper.linkAccounts; +export const unlinkAccounts = Wrapper.unlinkAccounts; + +export type { RecipeInterface }; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 734b750f1..04c65ffcf 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -295,7 +295,6 @@ export default class Recipe extends RecipeModule { return primaryUser.id; }; - // TODO: account linking failures needs to be improved accountLinkPostSignInViaSession = async ({ session, info, @@ -483,7 +482,11 @@ export default class Recipe extends RecipeModule { let doesPrimaryUserIdAlreadyExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; if (doesPrimaryUserIdAlreadyExists) { - throw Error("account linking failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + }; } } if (!infoVerified) { @@ -540,7 +543,11 @@ export default class Recipe extends RecipeModule { } else { if (shouldDoAccountLinking.shouldRequireVerification) { if (!infoVerified) { - throw Error("account link failure"); + return { + createRecipeUser: false, + accountsLinked: false, + reason: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; } } } From 8f08c86090d387335ee83bd1e23accd0cdd269e3 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Thu, 29 Dec 2022 12:31:56 +0530 Subject: [PATCH 11/82] merge with account-linking interface --- lib/build/recipe/accountlinking/index.d.ts | 10 +++++++++- lib/build/recipe/accountlinking/types.d.ts | 10 +++++++++- .../recipe/accountlinking/recipeImplementation.ts | 10 +++++++++- lib/ts/recipe/accountlinking/types.ts | 15 +++++++++------ 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index e0bbdfd51..1bbf0ad87 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -20,7 +20,15 @@ export default class Wrapper { recipeId: string, timeJoined: number, userContext: any - ): Promise; + ): Promise< + | { + status: "OK"; + createdNewEntry: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + } + >; static getUsers( timeJoinedOrder: "ASC" | "DESC", limit: number | undefined, diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 4b436e359..904687fc3 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -68,7 +68,15 @@ export declare type RecipeInterface = { recipeId: string; timeJoined: number; userContext: any; - }) => Promise; + }) => Promise< + | { + status: "OK"; + createdNewEntry: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + } + >; getUsers: (input: { timeJoinedOrder: "ASC" | "DESC"; limit?: number; diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index f8957b47f..bb6371778 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -53,7 +53,15 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo recipeUserId: string; recipeId: string; timeJoined: number; - }): Promise { + }): Promise< + | { + status: "OK"; + createdNewEntry: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + } + > { return querier.sendPutRequest(new NormalisedURLPath("/recipe/accountlinking/user"), { recipeUserId, recipeId, diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 018f16eef..c7c31319b 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -85,12 +85,15 @@ export type RecipeInterface = { recipeId: string; timeJoined: number; userContext: any; - }) => Promise<{ - status: "OK", - createdNewEntry: boolean - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - }>; + }) => Promise< + | { + status: "OK"; + createdNewEntry: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + } + >; getUsers: (input: { timeJoinedOrder: "ASC" | "DESC"; limit?: number; From 7e4d64f4b79b18931e5555d002b58f0c2ad708de Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Sat, 31 Dec 2022 13:11:18 +0530 Subject: [PATCH 12/82] Update lib/ts/recipe/accountlinking/recipeImplementation.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipeImplementation.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index bb6371778..bdf14437f 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -84,11 +84,6 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }> { let querier = Querier.getNewInstanceOrThrowError(undefined); let apiVersion = await querier.getAPIVersion(); - if (maxVersion(apiVersion, "2.7") === "2.7") { - throw new Error( - "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUsersOldestFirst() or .getUsersNewestFirst() instead (for example, EmailPassword.getUsersOldestFirst())" - ); - } let includeRecipeIdsStr = undefined; if (includeRecipeIds !== undefined) { includeRecipeIdsStr = includeRecipeIds.join(","); From e1af59229ae229245ea4535c106e8341c4d791b2 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Tue, 3 Jan 2023 14:51:36 +0530 Subject: [PATCH 13/82] code review changes --- lib/build/index.d.ts | 8 +- lib/build/index.js | 12 - lib/build/recipe/accountlinking/index.d.ts | 29 +- lib/build/recipe/accountlinking/index.js | 37 +++ lib/build/recipe/accountlinking/recipe.js | 16 +- .../accountlinking/recipeImplementation.js | 273 +++++++++++---- lib/build/recipe/accountlinking/types.d.ts | 44 ++- lib/build/recipe/accountlinking/utils.d.ts | 15 +- lib/build/recipe/accountlinking/utils.js | 101 +++++- lib/build/supertokens.d.ts | 5 +- lib/build/supertokens.js | 54 --- lib/build/types.d.ts | 25 -- lib/ts/index.ts | 20 +- lib/ts/recipe/accountlinking/index.ts | 31 +- lib/ts/recipe/accountlinking/recipe.ts | 30 +- .../accountlinking/recipeImplementation.ts | 310 ++++++++++++++---- lib/ts/recipe/accountlinking/types.ts | 50 ++- lib/ts/recipe/accountlinking/utils.ts | 150 ++++++++- lib/ts/supertokens.ts | 56 +--- lib/ts/types.ts | 28 +- 20 files changed, 919 insertions(+), 375 deletions(-) diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index 499c7827e..0d491ed91 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -1,7 +1,7 @@ // @ts-nocheck import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; -import { AccountInfo, AccountInfoWithRecipeId, User } from "./types"; +import { User } from "./types"; export default class SuperTokensWrapper { static init: typeof SuperTokens.init; static Error: typeof SuperTokensError; @@ -73,9 +73,6 @@ export default class SuperTokensWrapper { }): Promise<{ status: "OK" | "UNKNOWN_MAPPING_ERROR"; }>; - static getUser(input: { userId: string }): Promise; - static listUsersByAccountInfo(input: { info: AccountInfo }): Promise; - static getUserByAccountInfoAndRecipeId(input: { info: AccountInfoWithRecipeId }): Promise; } export declare let init: typeof SuperTokens.init; export declare let getAllCORSHeaders: typeof SuperTokensWrapper.getAllCORSHeaders; @@ -87,7 +84,4 @@ export declare let createUserIdMapping: typeof SuperTokensWrapper.createUserIdMa export declare let getUserIdMapping: typeof SuperTokensWrapper.getUserIdMapping; export declare let deleteUserIdMapping: typeof SuperTokensWrapper.deleteUserIdMapping; export declare let updateOrDeleteUserIdMappingInfo: typeof SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; -export declare let getUser: typeof SuperTokensWrapper.getUser; -export declare let listUsersByAccountInfo: typeof SuperTokensWrapper.listUsersByAccountInfo; -export declare let getUserByAccountInfoAndRecipeId: typeof SuperTokensWrapper.getUserByAccountInfoAndRecipeId; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/index.js b/lib/build/index.js index a51f91065..9ef8498de 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -52,15 +52,6 @@ class SuperTokensWrapper { static updateOrDeleteUserIdMappingInfo(input) { return supertokens_1.default.getInstanceOrThrowError().updateOrDeleteUserIdMappingInfo(input); } - static getUser(input) { - return supertokens_1.default.getInstanceOrThrowError().getUser(input); - } - static listUsersByAccountInfo(input) { - return supertokens_1.default.getInstanceOrThrowError().listUsersByAccountInfo(input); - } - static getUserByAccountInfoAndRecipeId(input) { - return supertokens_1.default.getInstanceOrThrowError().getUserByAccountInfoAndRecipeId(input); - } } exports.default = SuperTokensWrapper; SuperTokensWrapper.init = supertokens_1.default.init; @@ -75,7 +66,4 @@ exports.createUserIdMapping = SuperTokensWrapper.createUserIdMapping; exports.getUserIdMapping = SuperTokensWrapper.getUserIdMapping; exports.deleteUserIdMapping = SuperTokensWrapper.deleteUserIdMapping; exports.updateOrDeleteUserIdMappingInfo = SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; -exports.getUser = SuperTokensWrapper.getUser; -exports.listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; -exports.getUserByAccountInfoAndRecipeId = SuperTokensWrapper.getUserByAccountInfoAndRecipeId; exports.Error = SuperTokensWrapper.Error; diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 1bbf0ad87..9411d32ea 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,6 +1,6 @@ // @ts-nocheck import Recipe from "./recipe"; -import { RecipeInterface } from "./types"; +import type { AccountInfo, AccountInfoWithRecipeId, RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static getRecipeUserIdsForPrimaryUserIds( @@ -119,9 +119,30 @@ export default class Wrapper { static unlinkAccounts( recipeUserId: string, userContext: any + ): Promise< + | { + status: "OK"; + wasRecipeUserDeleted: boolean; + } + | { + status: "NO_PRIMARY_USER_FOUND"; + } + >; + static getUser(userId: string, userContext: any): Promise; + static listUsersByAccountInfo( + info: AccountInfo, + userContext: any + ): Promise; + static getUserByAccountInfo( + info: AccountInfoWithRecipeId, + userContext: any + ): Promise; + static deleteUser( + userId: string, + removeAllLinkedAccounts: boolean, + userContext: any ): Promise<{ status: "OK"; - wasRecipeUserDeleted: boolean; }>; } export declare const init: typeof Recipe.init; @@ -134,4 +155,8 @@ export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; export declare const linkAccounts: typeof Wrapper.linkAccounts; export declare const unlinkAccounts: typeof Wrapper.unlinkAccounts; +export declare const getUser: typeof Wrapper.getUser; +export declare const listUsersByAccountInfo: typeof Wrapper.listUsersByAccountInfo; +export declare const getUserByAccountInfo: typeof Wrapper.getUserByAccountInfo; +export declare const deleteUser: typeof Wrapper.deleteUser; export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 7652cb1b2..6934e2f53 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -132,6 +132,39 @@ class Wrapper { }); }); } + static getUser(userId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ + userId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static listUsersByAccountInfo(info, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static getUserByAccountInfo(info, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static deleteUser(userId, removeAllLinkedAccounts, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ + userId, + removeAllLinkedAccounts, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } } exports.default = Wrapper; Wrapper.init = recipe_1.default.init; @@ -145,3 +178,7 @@ exports.createPrimaryUser = Wrapper.createPrimaryUser; exports.canLinkAccounts = Wrapper.canLinkAccounts; exports.linkAccounts = Wrapper.linkAccounts; exports.unlinkAccounts = Wrapper.unlinkAccounts; +exports.getUser = Wrapper.getUser; +exports.listUsersByAccountInfo = Wrapper.listUsersByAccountInfo; +exports.getUserByAccountInfo = Wrapper.getUserByAccountInfo; +exports.deleteUser = Wrapper.deleteUser; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 6c7d2b29c..91058cbc3 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -46,7 +46,6 @@ var __awaiter = }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); -const __1 = require("../.."); const supertokens_1 = require("../../supertokens"); const utils_1 = require("./utils"); const supertokens_js_override_1 = require("supertokens-js-override"); @@ -80,8 +79,9 @@ class Recipe extends recipeModule_1.default { } else { throw Error("this error should never be thrown"); } - let users = yield __1.default.listUsersByAccountInfo({ + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ info: identifier, + userContext, }); if (users === undefined || users.length === 0) { return true; @@ -156,8 +156,9 @@ class Recipe extends recipeModule_1.default { } else { throw Error("this error should never be thrown"); } - let users = yield __1.default.listUsersByAccountInfo({ + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ info: identifier, + userContext, }); if (users === undefined || users.length === 0) { throw Error("this error should never be thrown"); @@ -185,8 +186,9 @@ class Recipe extends recipeModule_1.default { this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => __awaiter(this, void 0, void 0, function* () { let userId = session.getUserId(); - let user = yield __1.getUser({ + let user = yield this.recipeInterfaceImpl.getUser({ userId, + userContext, }); if (user === undefined) { throw Error("this should not be thrown"); @@ -304,8 +306,9 @@ class Recipe extends recipeModule_1.default { } else { throw Error("this error should never be thrown"); } - let recipeUser = yield __1.getUserByAccountInfoAndRecipeId({ + let recipeUser = yield this.recipeInterfaceImpl.getUserByAccountInfo({ info: recipeInfo, + userContext, }); if (recipeUser === undefined) { let identitiesForPrimaryUser = yield this.getIdentitiesForPrimaryUserId(user.id); @@ -331,8 +334,9 @@ class Recipe extends recipeModule_1.default { }; } } - let existingRecipeUserForInputInfo = yield __1.listUsersByAccountInfo({ + let existingRecipeUserForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ info: recipeInfo, + userContext, }); if (existingRecipeUserForInputInfo !== undefined) { let doesPrimaryUserIdAlreadyExists = diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 057964a2b..e38200586 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -45,11 +45,9 @@ var __awaiter = }); }; Object.defineProperty(exports, "__esModule", { value: true }); -const querier_1 = require("../../querier"); const normalisedURLPath_1 = require("../../normalisedURLPath"); -const utils_1 = require("../../utils"); -const __1 = require("../../"); const session_1 = require("../session"); +const utils_1 = require("./utils"); function getRecipeImplementation(querier, config) { return { getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { @@ -77,13 +75,6 @@ function getRecipeImplementation(querier, config) { }, getUsers: function ({ timeJoinedOrder, limit, paginationToken, includeRecipeIds }) { return __awaiter(this, void 0, void 0, function* () { - let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); - let apiVersion = yield querier.getAPIVersion(); - if (utils_1.maxVersion(apiVersion, "2.7") === "2.7") { - throw new Error( - "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUsersOldestFirst() or .getUsersNewestFirst() instead (for example, EmailPassword.getUsersOldestFirst())" - ); - } let includeRecipeIdsStr = undefined; if (includeRecipeIds !== undefined) { includeRecipeIdsStr = includeRecipeIds.join(","); @@ -100,11 +91,20 @@ function getRecipeImplementation(querier, config) { }; }); }, - canCreatePrimaryUserId: function ({ recipeUserId }) { + canCreatePrimaryUserId: function ({ recipeUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { + /** + * getting map of recipeUserIds to primaryUserIds + * This is to know if the existing recipeUserId + * is already associated with a primaryUserId + */ let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds: [recipeUserId], + userContext, }); + /** + * checking if primaryUserId exists for the recipeUserId + */ if ( recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== undefined && recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== null @@ -115,49 +115,62 @@ function getRecipeImplementation(querier, config) { description: "Recipe user is already linked with another primary user id", }; } - let user = yield __1.getUser({ + /** + * if the code reaches this point, it means + * the recipeuserId is definitely not associated + * with any primaryUserId. So the getUser function + * here will return an user object which would + * definitely be a recipeUser only. + */ + let user = yield this.getUser({ userId: recipeUserId, + userContext, }); + /** + * precautionary check + */ if (user === undefined) { - // QUESTION: should we throw an error here instead? - return { - status: "OK", - }; + throw Error("this error should not be thrown"); } + /** + * for all the identifying info associated with the recipeUser, + * we get all the accounts with those identifying infos. + * From those users, we'll try to find if there already exists + * a primaryUser which is associated with the identifying info + */ let usersForAccountInfo = []; - let promises = []; for (let i = 0; i < user.emails.length; i++) { - promises.push( - __1.listUsersByAccountInfo({ + usersForAccountInfo.push( + ...(yield this.listUsersByAccountInfo({ info: { email: user.emails[i], }, - }) + userContext, + })) ); } for (let i = 0; i < user.thirdpartyInfo.length; i++) { - promises.push( - __1.listUsersByAccountInfo({ + usersForAccountInfo.push( + ...(yield this.listUsersByAccountInfo({ info: Object.assign({}, user.thirdpartyInfo[i]), - }) + userContext, + })) ); } for (let i = 0; i < user.phoneNumbers.length; i++) { - promises.push( - __1.listUsersByAccountInfo({ + usersForAccountInfo.push( + ...(yield this.listUsersByAccountInfo({ info: { phoneNumber: user.phoneNumbers[i], }, - }) + userContext, + })) ); } - for (let i = 0; i < promises.length; i++) { - let result = yield promises[i]; - if (result !== undefined) { - usersForAccountInfo.push(...result); - } - } let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); + /** + * checking if primaryUserId exists for the account identifying info + */ if (primaryUser !== undefined) { return { status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", @@ -166,15 +179,20 @@ function getRecipeImplementation(querier, config) { "Account info related to recipe user is already linked with another primary user id", }; } + /** + * no primaryUser found for either recipeUserId or + * the identiyfing info asscociated with the recipeUser + */ return { status: "OK", }; }); }, - createPrimaryUser: function ({ recipeUserId }) { + createPrimaryUser: function ({ recipeUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ recipeUserId, + userContext, }); if (canCreatePrimaryUser.status !== "OK") { return canCreatePrimaryUser; @@ -188,22 +206,46 @@ function getRecipeImplementation(querier, config) { return primaryUser; }); }, - canLinkAccounts: function ({ recipeUserId, primaryUserId }) { + canLinkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let primaryUser = yield __1.getUser({ + let primaryUser = yield this.getUser({ userId: primaryUserId, + userContext, }); if (primaryUser === undefined) { throw Error("primary user not found"); } - let recipeUser = yield __1.getUser({ + /** + * getUser function returns a primaryUser even if + * recipeUserId is passed, if the recipeUserId has + * an associated primaryUserId. Here, after calling + * getUser for the recipeUser, we will check if there + * is already a primaryUser associated with it. If + * there is, we'll check if there exists if it's the + * input primaryUserId or some different primaryUserId + */ + let recipeUser = yield this.getUser({ userId: recipeUserId, }); if (recipeUser === undefined) { throw Error("recipe user not found"); } + if (recipeUser.isPrimaryUser) { + if (recipeUser.id === primaryUserId) { + return { + status: "ACCOUNTS_ALREADY_LINKED_ERROR", + description: "accounts are already linked", + }; + } + return { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + description: "recipeUserId already associated with another primaryUserId", + primaryUserId: recipeUser.id, + }; + } let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ recipeUserId, + userContext, }); if ( canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" @@ -240,6 +282,7 @@ function getRecipeImplementation(querier, config) { let canLinkAccountsResult = yield this.canLinkAccounts({ recipeUserId, primaryUserId, + userContext, }); if (canLinkAccountsResult.status !== "OK") { return canLinkAccountsResult; @@ -253,22 +296,25 @@ function getRecipeImplementation(querier, config) { ); if (accountsLinkingResult.status === "OK") { yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); - let user = yield __1.getUser({ + let user = yield this.getUser({ userId: primaryUserId, + userContext, }); if (user === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); - if (recipeUser === undefined) { + let recipeUserObj = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); + if (recipeUserObj === undefined) { throw Error("this error should never be thrown"); } - let recipeUserInfo = yield querier_1.Querier.getNewInstanceOrThrowError( - recipeUser.recipeId - ).sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { - userId: recipeUserId, - }); - yield config.onAccountLinked(user, recipeUserInfo.user, userContext); + let recipeUser = yield utils_1.getUserForRecipeId( + recipeUserObj.recipeUserId, + recipeUserObj.recipeId + ); + if (recipeUser.user === undefined) { + throw Error("this error should never be thrown"); + } + yield config.onAccountLinked(user, recipeUser.user, userContext); } return accountsLinkingResult; }); @@ -277,38 +323,24 @@ function getRecipeImplementation(querier, config) { return __awaiter(this, void 0, void 0, function* () { let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds: [recipeUserId], + userContext, }); if ( recipeUserIdToPrimaryUserIdMapping[recipeUserId] === undefined || recipeUserIdToPrimaryUserIdMapping[recipeUserId] === null ) { return { - status: "OK", - wasRecipeUserDeleted: false, + status: "NO_PRIMARY_USER_FOUND", }; } let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - let user = yield __1.getUser({ - userId: primaryUserId, - }); - if (user === undefined) { - throw Error("this error should never be thrown"); - } - let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); - if (recipeUser === undefined) { - throw Error("this error should never be thrown"); - } - let recipeUserInfo = yield querier_1.Querier.getNewInstanceOrThrowError( - recipeUser.recipeId - ).sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { - userId: recipeUserId, - }); /** * primaryUserId === recipeUserId */ if (primaryUserId === recipeUserId) { - let user = yield __1.getUser({ + let user = yield this.getUser({ userId: primaryUserId, + userContext, }); if (user === undefined) { return { @@ -317,7 +349,11 @@ function getRecipeImplementation(querier, config) { }; } if (user.linkedRecipes.length > 1) { - yield __1.deleteUser(recipeUserId, false); + yield this.deleteUser({ + userId: recipeUserId, + removeAllLinkedAccounts: false, + userContext, + }); return { status: "OK", wasRecipeUserDeleted: true, @@ -334,13 +370,120 @@ function getRecipeImplementation(querier, config) { if (accountsUnlinkingResult.status === "OK") { yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); } - yield config.onAccountUnlinked(user, recipeUserInfo.user, userContext); return { status: "OK", wasRecipeUserDeleted: false, }; }); }, + getUser: function ({ userId }) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { + userId, + }); + if (result.status === "OK") { + return result.user; + } + return undefined; + }); + }, + listUsersByAccountInfo: function ({ info }) { + return __awaiter(this, void 0, void 0, function* () { + /** + * if input is only email: + * let emailPasswordUser = emailpassword.getUserByEmail(email); + * + * let thirdpartyUsers = thirdparty.getUsersByEmail(email); + * + * let passwordlessUser = passwordless.getUserByEmail(email); + * + * let recipeUsers = []; + * + * if (emailPasswordUser !== undefined) { + * recipeUsers.push(emailPasswordUser); + * } + * + * recipeUsers.push(...thirdpartyUsers); + * + * if (passwordlessUser !== undefined) { + * recipeUsers.push(passwordlessUser); + * } + * + * let recipeUserIds = recipeUsers.map(r => r.id); + * + * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); + * + * let result: {id: User | User[]} = {}; + * + * for (let i = 0; i < recipeUsers.length; i++) { + * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { + * result[recipeUsers[i].id] = recipeUsers[i]; + * } else { + * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; + * if (result[pUserId] === undefined) { + * result[pUserId] = []; + * } + * result[pUserId].push(recipeUsers[i]); + * } + * } + * + * + */ + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/users"), + Object.assign({}, info) + ); + if (result.status === "OK") { + return result.user; + } + return undefined; + }); + }, + getUserByAccountInfo: function ({ info }) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/user"), + Object.assign({}, info) + ); + if (result.status === "OK") { + return result.user; + } + return undefined; + }); + }, + deleteUser: function ({ userId, removeAllLinkedAccounts, userContext }) { + return __awaiter(this, void 0, void 0, function* () { + let user = yield this.getUser({ userId, userContext }); + if (user === undefined) { + return { + status: "OK", + }; + } + let recipeUsersToRemove = []; + /** + * if true, the user should be treated as primaryUser + */ + if (removeAllLinkedAccounts) { + recipeUsersToRemove = user.linkedRecipes; + } else { + recipeUsersToRemove = user.linkedRecipes.filter((u) => u.recipeUserId === userId); + } + for (let i = 0; i < recipeUsersToRemove.length; i++) { + /** + * - the core will also remove any primary userId association, if exists + * - while removing the primary userId association, if there exists no + * other recipe user associated with the primary user, the core will + * also remove all data linked to the primary user in other non-auth tables + */ + yield querier.sendPostRequest(new normalisedURLPath_1.default("/user/remove"), { + userId: recipeUsersToRemove[i].recipeUserId, + }); + } + return { + status: "OK", + }; + }); + }, }; } exports.default = getRecipeImplementation; diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 904687fc3..23e053e9b 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -4,7 +4,6 @@ import type { User } from "../../types"; import { SessionContainer } from "../session"; export declare type TypeInput = { onAccountLinked?: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - onAccountUnlinked?: (user: User, unlinkedAccount: RecipeLevelUser, userContext: any) => Promise; shouldDoAutomaticAccountLinking?: ( newAccountInfo: AccountInfoAndEmailWithRecipeId, user: User | undefined, @@ -28,7 +27,6 @@ export declare type TypeInput = { }; export declare type TypeNormalisedInput = { onAccountLinked: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - onAccountUnlinked: (user: User, unlinkedAccount: RecipeLevelUser, userContext: any) => Promise; shouldDoAutomaticAccountLinking: ( newAccountInfo: AccountInfoAndEmailWithRecipeId, user: User | undefined, @@ -167,9 +165,24 @@ export declare type RecipeInterface = { unlinkAccounts: (input: { recipeUserId: string; userContext: any; + }) => Promise< + | { + status: "OK"; + wasRecipeUserDeleted: boolean; + } + | { + status: "NO_PRIMARY_USER_FOUND"; + } + >; + getUser: (input: { userId: string; userContext: any }) => Promise; + listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; + getUserByAccountInfo: (input: { info: AccountInfoWithRecipeId; userContext: any }) => Promise; + deleteUser: (input: { + userId: string; + removeAllLinkedAccounts: boolean; + userContext: any; }) => Promise<{ status: "OK"; - wasRecipeUserDeleted: boolean; }>; }; export declare type RecipeLevelUser = { @@ -193,3 +206,28 @@ export declare type AccountInfoAndEmailWithRecipeId = { userId: string; }; }; +export declare type AccountInfo = + | { + email: string; + } + | { + thirdpartyId: string; + thirdpartyUserId: string; + } + | { + phoneNumber: string; + }; +export declare type AccountInfoWithRecipeId = + | { + recipeId: "emailpassword" | "passwordless"; + email: string; + } + | { + recipeId: "thirdparty"; + thirdpartyId: string; + thirdpartyUserId: string; + } + | { + recipeId: "passwordless"; + phoneNumber: string; + }; diff --git a/lib/build/recipe/accountlinking/utils.d.ts b/lib/build/recipe/accountlinking/utils.d.ts index 687c0db39..45b3bce43 100644 --- a/lib/build/recipe/accountlinking/utils.d.ts +++ b/lib/build/recipe/accountlinking/utils.d.ts @@ -1,4 +1,17 @@ // @ts-nocheck import type { NormalisedAppinfo } from "../../types"; -import type { TypeInput, TypeNormalisedInput } from "./types"; +import type { TypeInput, RecipeLevelUser, TypeNormalisedInput } from "./types"; export declare function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; +export declare function getUserForRecipeId( + userId: string, + recipeId: string +): Promise<{ + user: RecipeLevelUser | undefined; + recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; +}>; diff --git a/lib/build/recipe/accountlinking/utils.js b/lib/build/recipe/accountlinking/utils.js index 79d6256ba..4fe8d6c3b 100644 --- a/lib/build/recipe/accountlinking/utils.js +++ b/lib/build/recipe/accountlinking/utils.js @@ -45,12 +45,17 @@ var __awaiter = }); }; Object.defineProperty(exports, "__esModule", { value: true }); +const recipe_1 = require("../emailpassword/recipe"); +const recipe_2 = require("../thirdparty/recipe"); +const recipe_3 = require("../passwordless/recipe"); +const emailpassword_1 = require("../emailpassword"); +const thirdparty_1 = require("../thirdparty"); +const passwordless_1 = require("../passwordless"); +const thirdpartyemailpassword_1 = require("../thirdpartyemailpassword"); +const thirdpartypasswordless_1 = require("../thirdpartypasswordless"); function defaultOnAccountLinked(_user, _newAccountInfo, _userContext) { return __awaiter(this, void 0, void 0, function* () {}); } -function defaultOnAccountUnlinked(_user, _unlinkedAccount, _userContext) { - return __awaiter(this, void 0, void 0, function* () {}); -} function defaultShouldDoAutomaticAccountLinking(_newAccountInfo, _user, _session, _userContext) { return __awaiter(this, void 0, void 0, function* () { return { @@ -60,15 +65,101 @@ function defaultShouldDoAutomaticAccountLinking(_newAccountInfo, _user, _session } function validateAndNormaliseUserInput(_, config) { let onAccountLinked = config.onAccountLinked || defaultOnAccountLinked; - let onAccountUnlinked = config.onAccountUnlinked || defaultOnAccountUnlinked; let shouldDoAutomaticAccountLinking = config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; let override = Object.assign({ functions: (originalImplementation) => originalImplementation }, config.override); return { override, onAccountLinked, - onAccountUnlinked, shouldDoAutomaticAccountLinking, }; } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; +function getUserForRecipeId(userId, recipeId) { + return __awaiter(this, void 0, void 0, function* () { + let user; + let recipe; + if (recipeId === recipe_1.default.RECIPE_ID) { + try { + const userResponse = yield emailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); + recipe = "emailpassword"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === recipe_2.default.RECIPE_ID) { + try { + const userResponse = yield thirdparty_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdparty"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + if (user === undefined) { + try { + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === recipe_3.default.RECIPE_ID) { + try { + const userResponse = yield passwordless_1.default.getUserById({ + userId, + }); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); + recipe = "passwordless"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } + return { + user, + recipe, + }; + }); +} +exports.getUserForRecipeId = getUserForRecipeId; diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 0d87b1bd5..915fcab44 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -4,7 +4,7 @@ import RecipeModule from "./recipeModule"; import NormalisedURLPath from "./normalisedURLPath"; import { BaseRequest, BaseResponse } from "./framework"; import { TypeFramework } from "./framework/types"; -import { AccountInfo, AccountInfoWithRecipeId, User } from "./types"; +import { User } from "./types"; export default class SuperTokens { private static instance; framework: TypeFramework; @@ -88,7 +88,4 @@ export default class SuperTokens { }>; middleware: (request: BaseRequest, response: BaseResponse) => Promise; errorHandler: (err: any, request: BaseRequest, response: BaseResponse) => Promise; - getUser: (_input: { userId: string }) => Promise; - listUsersByAccountInfo: (_input: { info: AccountInfo }) => Promise; - getUserByAccountInfoAndRecipeId: (_input: { info: AccountInfoWithRecipeId }) => Promise; } diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index ab3dff692..a1d14584e 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -334,60 +334,6 @@ class SuperTokens { } throw err; }); - this.getUser = (_input) => - __awaiter(this, void 0, void 0, function* () { - // TODO - return; - }); - this.listUsersByAccountInfo = (_input) => - __awaiter(this, void 0, void 0, function* () { - /** - * if input is only email: - * let emailPasswordUser = emailpassword.getUserByEmail(email); - * - * let thirdpartyUsers = thirdparty.getUsersByEmail(email); - * - * let passwordlessUser = passwordless.getUserByEmail(email); - * - * let recipeUsers = []; - * - * if (emailPasswordUser !== undefined) { - * recipeUsers.push(emailPasswordUser); - * } - * - * recipeUsers.push(...thirdpartyUsers); - * - * if (passwordlessUser !== undefined) { - * recipeUsers.push(passwordlessUser); - * } - * - * let recipeUserIds = recipeUsers.map(r => r.id); - * - * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); - * - * let result: {id: User | User[]} = {}; - * - * for (let i = 0; i < recipeUsers.length; i++) { - * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { - * result[recipeUsers[i].id] = recipeUsers[i]; - * } else { - * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; - * if (result[pUserId] === undefined) { - * result[pUserId] = []; - * } - * result[pUserId].push(recipeUsers[i]); - * } - * } - * - * - */ - return; - }); - this.getUserByAccountInfoAndRecipeId = (_input) => - __awaiter(this, void 0, void 0, function* () { - // TODO - return; - }); logger_1.logDebugMessage("Started SuperTokens with debug logging (supertokens.init called)"); logger_1.logDebugMessage("appInfo: " + JSON.stringify(config.appInfo)); this.framework = config.framework !== undefined ? config.framework : "express"; diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index af8501195..8b1453fd9 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -49,31 +49,6 @@ export declare type GeneralErrorResponse = { status: "GENERAL_ERROR"; message: string; }; -export declare type AccountInfo = - | { - email: string; - } - | { - thirdpartyId: string; - thirdpartyUserId: string; - } - | { - phoneNumber: string; - }; -export declare type AccountInfoWithRecipeId = - | { - recipeId: "emailpassword" | "passwordless"; - email: string; - } - | { - recipeId: "thirdparty"; - thirdpartyId: string; - thirdpartyUserId: string; - } - | { - recipeId: "passwordless"; - phoneNumber: string; - }; export declare type User = { id: string; isPrimaryUser: boolean; diff --git a/lib/ts/index.ts b/lib/ts/index.ts index a09c272a8..a0a229742 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -15,7 +15,7 @@ import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; -import { AccountInfo, AccountInfoWithRecipeId, User } from "./types"; +import { User } from "./types"; // For Express export default class SuperTokensWrapper { @@ -94,18 +94,6 @@ export default class SuperTokensWrapper { }) { return SuperTokens.getInstanceOrThrowError().updateOrDeleteUserIdMappingInfo(input); } - - static getUser(input: { userId: string }) { - return SuperTokens.getInstanceOrThrowError().getUser(input); - } - - static listUsersByAccountInfo(input: { info: AccountInfo }) { - return SuperTokens.getInstanceOrThrowError().listUsersByAccountInfo(input); - } - - static getUserByAccountInfoAndRecipeId(input: { info: AccountInfoWithRecipeId }) { - return SuperTokens.getInstanceOrThrowError().getUserByAccountInfoAndRecipeId(input); - } } export let init = SuperTokensWrapper.init; @@ -128,10 +116,4 @@ export let deleteUserIdMapping = SuperTokensWrapper.deleteUserIdMapping; export let updateOrDeleteUserIdMappingInfo = SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; -export let getUser = SuperTokensWrapper.getUser; - -export let listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; - -export let getUserByAccountInfoAndRecipeId = SuperTokensWrapper.getUserByAccountInfoAndRecipeId; - export let Error = SuperTokensWrapper.Error; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index cfcac39b1..6477ad8c5 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -14,7 +14,7 @@ */ import Recipe from "./recipe"; -import { RecipeInterface } from "./types"; +import type { AccountInfo, AccountInfoWithRecipeId, RecipeInterface } from "./types"; export default class Wrapper { static init = Recipe.init; @@ -91,6 +91,31 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } + static async getUser(userId: string, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ + userId, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async listUsersByAccountInfo(info: AccountInfo, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async getUserByAccountInfo(info: AccountInfoWithRecipeId, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async deleteUser(userId: string, removeAllLinkedAccounts: boolean, userContext: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ + userId, + removeAllLinkedAccounts, + userContext: userContext === undefined ? {} : userContext, + }); + } } export const init = Wrapper.init; @@ -103,5 +128,9 @@ export const createPrimaryUser = Wrapper.createPrimaryUser; export const canLinkAccounts = Wrapper.canLinkAccounts; export const linkAccounts = Wrapper.linkAccounts; export const unlinkAccounts = Wrapper.unlinkAccounts; +export const getUser = Wrapper.getUser; +export const listUsersByAccountInfo = Wrapper.listUsersByAccountInfo; +export const getUserByAccountInfo = Wrapper.getUserByAccountInfo; +export const deleteUser = Wrapper.deleteUser; export type { RecipeInterface }; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 04c65ffcf..fa6e114e2 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -17,17 +17,16 @@ import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; -import SuperTokens, { getUser, getUserByAccountInfoAndRecipeId, listUsersByAccountInfo } from "../.."; import SuperTokensModule from "../../supertokens"; +import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction } from "../../types"; +import { SessionContainer } from "../session"; import type { + TypeNormalisedInput, + RecipeInterface, + TypeInput, + AccountInfoAndEmailWithRecipeId, AccountInfoWithRecipeId, - APIHandled, - HTTPMethod, - NormalisedAppinfo, - RecipeListFunction, -} from "../../types"; -import { SessionContainer } from "../session"; -import type { TypeNormalisedInput, RecipeInterface, TypeInput, AccountInfoAndEmailWithRecipeId } from "./types"; +} from "./types"; import { validateAndNormaliseUserInput } from "./utils"; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; @@ -178,8 +177,9 @@ export default class Recipe extends RecipeModule { } else { throw Error("this error should never be thrown"); } - let users = await SuperTokens.listUsersByAccountInfo({ + let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ info: identifier, + userContext, }); if (users === undefined || users.length === 0) { return true; @@ -268,8 +268,9 @@ export default class Recipe extends RecipeModule { } else { throw Error("this error should never be thrown"); } - let users = await SuperTokens.listUsersByAccountInfo({ + let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ info: identifier, + userContext, }); if (users === undefined || users.length === 0) { throw Error("this error should never be thrown"); @@ -329,8 +330,9 @@ export default class Recipe extends RecipeModule { )) > => { let userId = session.getUserId(); - let user = await getUser({ + let user = await this.recipeInterfaceImpl.getUser({ userId, + userContext, }); if (user === undefined) { throw Error("this should not be thrown"); @@ -447,8 +449,9 @@ export default class Recipe extends RecipeModule { } else { throw Error("this error should never be thrown"); } - let recipeUser = await getUserByAccountInfoAndRecipeId({ + let recipeUser = await this.recipeInterfaceImpl.getUserByAccountInfo({ info: recipeInfo, + userContext, }); if (recipeUser === undefined) { let identitiesForPrimaryUser = await this.getIdentitiesForPrimaryUserId(user.id); @@ -475,8 +478,9 @@ export default class Recipe extends RecipeModule { } } - let existingRecipeUserForInputInfo = await listUsersByAccountInfo({ + let existingRecipeUserForInputInfo = await this.recipeInterfaceImpl.listUsersByAccountInfo({ info: recipeInfo, + userContext, }); if (existingRecipeUserForInputInfo !== undefined) { let doesPrimaryUserIdAlreadyExists = diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index bdf14437f..3d6908d8a 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -13,13 +13,12 @@ * under the License. */ -import { RecipeInterface, TypeNormalisedInput } from "./types"; +import { AccountInfo, AccountInfoWithRecipeId, RecipeInterface, TypeNormalisedInput } from "./types"; import { Querier } from "../../querier"; import type { User } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; -import { maxVersion } from "../../utils"; -import { getUser, listUsersByAccountInfo, deleteUser } from "../../"; import Session from "../session"; +import { getUserForRecipeId } from "./utils"; export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface { return { @@ -82,8 +81,6 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo users: User[]; nextPaginationToken?: string; }> { - let querier = Querier.getNewInstanceOrThrowError(undefined); - let apiVersion = await querier.getAPIVersion(); let includeRecipeIdsStr = undefined; if (includeRecipeIds !== undefined) { includeRecipeIdsStr = includeRecipeIds.join(","); @@ -101,8 +98,10 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }, canCreatePrimaryUserId: async function ({ recipeUserId, + userContext, }: { recipeUserId: string; + userContext: any; }): Promise< | { status: "OK"; @@ -115,10 +114,19 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } > { + /** + * getting map of recipeUserIds to primaryUserIds + * This is to know if the existing recipeUserId + * is already associated with a primaryUserId + */ let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds: [recipeUserId], + userContext, }); + /** + * checking if primaryUserId exists for the recipeUserId + */ if ( recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== undefined && recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== null @@ -130,60 +138,71 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }; } - let user = await getUser({ + /** + * if the code reaches this point, it means + * the recipeuserId is definitely not associated + * with any primaryUserId. So the getUser function + * here will return an user object which would + * definitely be a recipeUser only. + */ + let user = await this.getUser({ userId: recipeUserId, + userContext, }); + /** + * precautionary check + */ if (user === undefined) { - // QUESTION: should we throw an error here instead? - return { - status: "OK", - }; + throw Error("this error should not be thrown"); } + /** + * for all the identifying info associated with the recipeUser, + * we get all the accounts with those identifying infos. + * From those users, we'll try to find if there already exists + * a primaryUser which is associated with the identifying info + */ let usersForAccountInfo = []; - let promises = []; - for (let i = 0; i < user.emails.length; i++) { - promises.push( - listUsersByAccountInfo({ + usersForAccountInfo.push( + ...(await this.listUsersByAccountInfo({ info: { email: user.emails[i], }, - }) + userContext, + })) ); } for (let i = 0; i < user.thirdpartyInfo.length; i++) { - promises.push( - listUsersByAccountInfo({ + usersForAccountInfo.push( + ...(await this.listUsersByAccountInfo({ info: { ...user.thirdpartyInfo[i], }, - }) + userContext, + })) ); } for (let i = 0; i < user.phoneNumbers.length; i++) { - promises.push( - listUsersByAccountInfo({ + usersForAccountInfo.push( + ...(await this.listUsersByAccountInfo({ info: { phoneNumber: user.phoneNumbers[i], }, - }) + userContext, + })) ); } - for (let i = 0; i < promises.length; i++) { - let result = await promises[i]; - if (result !== undefined) { - usersForAccountInfo.push(...result); - } - } - let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); + /** + * checking if primaryUserId exists for the account identifying info + */ if (primaryUser !== undefined) { return { status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", @@ -192,14 +211,20 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }; } + /** + * no primaryUser found for either recipeUserId or + * the identiyfing info asscociated with the recipeUser + */ return { status: "OK", }; }, createPrimaryUser: async function ({ recipeUserId, + userContext, }: { recipeUserId: string; + userContext: any; }): Promise< | { status: "OK"; @@ -225,6 +250,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } = await this.canCreatePrimaryUserId({ recipeUserId, + userContext, }); if (canCreatePrimaryUser.status !== "OK") { return canCreatePrimaryUser; @@ -242,9 +268,11 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo canLinkAccounts: async function ({ recipeUserId, primaryUserId, + userContext, }: { recipeUserId: string; primaryUserId: string; + userContext: any; }): Promise< | { status: "OK"; @@ -264,18 +292,41 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } > { - let primaryUser = await getUser({ + let primaryUser: User | undefined = await this.getUser({ userId: primaryUserId, + userContext, }); if (primaryUser === undefined) { throw Error("primary user not found"); } - let recipeUser = await getUser({ + /** + * getUser function returns a primaryUser even if + * recipeUserId is passed, if the recipeUserId has + * an associated primaryUserId. Here, after calling + * getUser for the recipeUser, we will check if there + * is already a primaryUser associated with it. If + * there is, we'll check if there exists if it's the + * input primaryUserId or some different primaryUserId + */ + let recipeUser: User | undefined = await this.getUser({ userId: recipeUserId, }); if (recipeUser === undefined) { throw Error("recipe user not found"); } + if (recipeUser.isPrimaryUser) { + if (recipeUser.id === primaryUserId) { + return { + status: "ACCOUNTS_ALREADY_LINKED_ERROR", + description: "accounts are already linked", + }; + } + return { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + description: "recipeUserId already associated with another primaryUserId", + primaryUserId: recipeUser.id, + }; + } let canCreatePrimaryUser: | { status: "OK"; @@ -288,6 +339,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } = await this.canCreatePrimaryUserId({ recipeUserId, + userContext, }); if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { if (canCreatePrimaryUser.primaryUserId === primaryUserId) { @@ -343,9 +395,27 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } > { - let canLinkAccountsResult = await this.canLinkAccounts({ + let canLinkAccountsResult: + | { + status: "OK"; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } + | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } = await this.canLinkAccounts({ recipeUserId, primaryUserId, + userContext, }); if (canLinkAccountsResult.status !== "OK") { return canLinkAccountsResult; @@ -359,23 +429,22 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo ); if (accountsLinkingResult.status === "OK") { await Session.revokeAllSessionsForUser(recipeUserId, userContext); - let user = await getUser({ + let user: User | undefined = await this.getUser({ userId: primaryUserId, + userContext, }); if (user === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); - if (recipeUser === undefined) { + let recipeUserObj = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); + if (recipeUserObj === undefined) { throw Error("this error should never be thrown"); } - let recipeUserInfo = await Querier.getNewInstanceOrThrowError(recipeUser.recipeId).sendGetRequest( - new NormalisedURLPath("/recipe/user"), - { - userId: recipeUserId, - } - ); - await config.onAccountLinked(user, recipeUserInfo.user, userContext); + let recipeUser = await getUserForRecipeId(recipeUserObj.recipeUserId, recipeUserObj.recipeId); + if (recipeUser.user === undefined) { + throw Error("this error should never be thrown"); + } + await config.onAccountLinked(user, recipeUser.user, userContext); } return accountsLinkingResult; }, @@ -385,45 +454,35 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }: { recipeUserId: string; userContext: any; - }): Promise<{ - status: "OK"; - wasRecipeUserDeleted: boolean; - }> { + }): Promise< + | { + status: "OK"; + wasRecipeUserDeleted: boolean; + } + | { + status: "NO_PRIMARY_USER_FOUND"; + } + > { let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds: [recipeUserId], + userContext, }); if ( recipeUserIdToPrimaryUserIdMapping[recipeUserId] === undefined || recipeUserIdToPrimaryUserIdMapping[recipeUserId] === null ) { return { - status: "OK", - wasRecipeUserDeleted: false, + status: "NO_PRIMARY_USER_FOUND", }; } let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - let user = await getUser({ - userId: primaryUserId, - }); - if (user === undefined) { - throw Error("this error should never be thrown"); - } - let recipeUser = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); - if (recipeUser === undefined) { - throw Error("this error should never be thrown"); - } - let recipeUserInfo = await Querier.getNewInstanceOrThrowError(recipeUser.recipeId).sendGetRequest( - new NormalisedURLPath("/recipe/user"), - { - userId: recipeUserId, - } - ); /** * primaryUserId === recipeUserId */ if (primaryUserId === recipeUserId) { - let user = await getUser({ + let user = await this.getUser({ userId: primaryUserId, + userContext, }); if (user === undefined) { @@ -433,7 +492,12 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }; } if (user.linkedRecipes.length > 1) { - await deleteUser(recipeUserId, false); + await this.deleteUser({ + userId: recipeUserId, + removeAllLinkedAccounts: false, + userContext, + }); + return { status: "OK", wasRecipeUserDeleted: true, @@ -451,11 +515,125 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo await Session.revokeAllSessionsForUser(recipeUserId, userContext); } - await config.onAccountUnlinked(user, recipeUserInfo.user, userContext); return { status: "OK", wasRecipeUserDeleted: false, }; }, + getUser: async function ({ userId }: { userId: string }): Promise { + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { + userId, + }); + if (result.status === "OK") { + return result.user; + } + return undefined; + }, + listUsersByAccountInfo: async function ({ info }: { info: AccountInfo }): Promise { + /** + * if input is only email: + * let emailPasswordUser = emailpassword.getUserByEmail(email); + * + * let thirdpartyUsers = thirdparty.getUsersByEmail(email); + * + * let passwordlessUser = passwordless.getUserByEmail(email); + * + * let recipeUsers = []; + * + * if (emailPasswordUser !== undefined) { + * recipeUsers.push(emailPasswordUser); + * } + * + * recipeUsers.push(...thirdpartyUsers); + * + * if (passwordlessUser !== undefined) { + * recipeUsers.push(passwordlessUser); + * } + * + * let recipeUserIds = recipeUsers.map(r => r.id); + * + * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); + * + * let result: {id: User | User[]} = {}; + * + * for (let i = 0; i < recipeUsers.length; i++) { + * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { + * result[recipeUsers[i].id] = recipeUsers[i]; + * } else { + * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; + * if (result[pUserId] === undefined) { + * result[pUserId] = []; + * } + * result[pUserId].push(recipeUsers[i]); + * } + * } + * + * + */ + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/users"), { + ...info, + }); + if (result.status === "OK") { + return result.user; + } + return undefined; + }, + getUserByAccountInfo: async function ({ info }: { info: AccountInfoWithRecipeId }): Promise { + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { + ...info, + }); + if (result.status === "OK") { + return result.user; + } + return undefined; + }, + deleteUser: async function ({ + userId, + removeAllLinkedAccounts, + userContext, + }: { + userId: string; + removeAllLinkedAccounts: boolean; + userContext: any; + }): Promise<{ + status: "OK"; + }> { + let user: User | undefined = await this.getUser({ userId, userContext }); + + if (user === undefined) { + return { + status: "OK", + }; + } + + let recipeUsersToRemove: { + recipeId: string; + recipeUserId: string; + }[] = []; + + /** + * if true, the user should be treated as primaryUser + */ + if (removeAllLinkedAccounts) { + recipeUsersToRemove = user.linkedRecipes; + } else { + recipeUsersToRemove = user.linkedRecipes.filter((u) => u.recipeUserId === userId); + } + + for (let i = 0; i < recipeUsersToRemove.length; i++) { + /** + * - the core will also remove any primary userId association, if exists + * - while removing the primary userId association, if there exists no + * other recipe user associated with the primary user, the core will + * also remove all data linked to the primary user in other non-auth tables + */ + await querier.sendPostRequest(new NormalisedURLPath("/user/remove"), { + userId: recipeUsersToRemove[i].recipeUserId, + }); + } + return { + status: "OK", + }; + }, }; } diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index c7c31319b..3488453cf 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -19,7 +19,6 @@ import { SessionContainer } from "../session"; export type TypeInput = { onAccountLinked?: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - onAccountUnlinked?: (user: User, unlinkedAccount: RecipeLevelUser, userContext: any) => Promise; shouldDoAutomaticAccountLinking?: ( newAccountInfo: AccountInfoAndEmailWithRecipeId, user: User | undefined, @@ -44,7 +43,6 @@ export type TypeInput = { export type TypeNormalisedInput = { onAccountLinked: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - onAccountUnlinked: (user: User, unlinkedAccount: RecipeLevelUser, userContext: any) => Promise; shouldDoAutomaticAccountLinking: ( newAccountInfo: AccountInfoAndEmailWithRecipeId, user: User | undefined, @@ -184,10 +182,23 @@ export type RecipeInterface = { unlinkAccounts: (input: { recipeUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - wasRecipeUserDeleted: boolean; - }>; + }) => Promise< + | { + status: "OK"; + wasRecipeUserDeleted: boolean; + } + | { + status: "NO_PRIMARY_USER_FOUND"; + } + >; + getUser: (input: { userId: string; userContext: any }) => Promise; + listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; + getUserByAccountInfo: (input: { info: AccountInfoWithRecipeId; userContext: any }) => Promise; + deleteUser: (input: { + userId: string; + removeAllLinkedAccounts: boolean; + userContext: any; + }) => Promise<{ status: "OK" }>; }; export type RecipeLevelUser = { @@ -212,3 +223,30 @@ export type AccountInfoAndEmailWithRecipeId = { userId: string; }; }; + +export type AccountInfo = + | { + email: string; + } + | { + thirdpartyId: string; + thirdpartyUserId: string; + } + | { + phoneNumber: string; + }; + +export type AccountInfoWithRecipeId = + | { + recipeId: "emailpassword" | "passwordless"; + email: string; + } + | { + recipeId: "thirdparty"; + thirdpartyId: string; + thirdpartyUserId: string; + } + | { + recipeId: "passwordless"; + phoneNumber: string; + }; diff --git a/lib/ts/recipe/accountlinking/utils.ts b/lib/ts/recipe/accountlinking/utils.ts index 45969c41f..bf228391b 100644 --- a/lib/ts/recipe/accountlinking/utils.ts +++ b/lib/ts/recipe/accountlinking/utils.ts @@ -22,11 +22,17 @@ import type { TypeNormalisedInput, AccountInfoAndEmailWithRecipeId, } from "./types"; +import EmailPasswordRecipe from "../emailpassword/recipe"; +import ThirdPartyRecipe from "../thirdparty/recipe"; +import PasswordlessRecipe from "../passwordless/recipe"; +import EmailPassword from "../emailpassword"; +import ThirdParty from "../thirdparty"; +import Passwordless from "../passwordless"; +import ThirdPartyEmailPassword from "../thirdpartyemailpassword"; +import ThirdPartyPasswordless from "../thirdpartypasswordless"; async function defaultOnAccountLinked(_user: User, _newAccountInfo: RecipeLevelUser, _userContext: any) {} -async function defaultOnAccountUnlinked(_user: User, _unlinkedAccount: RecipeLevelUser, _userContext: any) {} - async function defaultShouldDoAutomaticAccountLinking( _newAccountInfo: AccountInfoAndEmailWithRecipeId, _user: User | undefined, @@ -42,7 +48,6 @@ async function defaultShouldDoAutomaticAccountLinking( export function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput { let onAccountLinked = config.onAccountLinked || defaultOnAccountLinked; - let onAccountUnlinked = config.onAccountUnlinked || defaultOnAccountUnlinked; let shouldDoAutomaticAccountLinking = config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; @@ -54,7 +59,144 @@ export function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: Type return { override, onAccountLinked, - onAccountUnlinked, shouldDoAutomaticAccountLinking, }; } + +export async function getUserForRecipeId( + userId: string, + recipeId: string +): Promise<{ + user: RecipeLevelUser | undefined; + recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; +}> { + let user: RecipeLevelUser | undefined; + let recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; + + if (recipeId === EmailPasswordRecipe.RECIPE_ID) { + try { + const userResponse = await EmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "emailpassword", + }; + recipe = "emailpassword"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyEmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "emailpassword", + }; + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === ThirdPartyRecipe.RECIPE_ID) { + try { + const userResponse = await ThirdParty.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdparty"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyEmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyPasswordless.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === PasswordlessRecipe.RECIPE_ID) { + try { + const userResponse = await Passwordless.getUserById({ + userId, + }); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "passwordless", + }; + recipe = "passwordless"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyPasswordless.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "passwordless", + }; + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } + + return { + user, + recipe, + }; +} diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index aae817f7a..89e72ae0e 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -31,7 +31,7 @@ import { TypeFramework } from "./framework/types"; import STError from "./error"; import { logDebugMessage } from "./logger"; import { PostSuperTokensInitCallbacks } from "./postSuperTokensInitCallbacks"; -import { AccountInfo, AccountInfoWithRecipeId, User } from "./types"; +import { User } from "./types"; export default class SuperTokens { private static instance: SuperTokens | undefined; @@ -440,58 +440,4 @@ export default class SuperTokens { } throw err; }; - - getUser = async (_input: { userId: string }): Promise => { - // TODO - return; - }; - - listUsersByAccountInfo = async (_input: { info: AccountInfo }): Promise => { - /** - * if input is only email: - * let emailPasswordUser = emailpassword.getUserByEmail(email); - * - * let thirdpartyUsers = thirdparty.getUsersByEmail(email); - * - * let passwordlessUser = passwordless.getUserByEmail(email); - * - * let recipeUsers = []; - * - * if (emailPasswordUser !== undefined) { - * recipeUsers.push(emailPasswordUser); - * } - * - * recipeUsers.push(...thirdpartyUsers); - * - * if (passwordlessUser !== undefined) { - * recipeUsers.push(passwordlessUser); - * } - * - * let recipeUserIds = recipeUsers.map(r => r.id); - * - * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); - * - * let result: {id: User | User[]} = {}; - * - * for (let i = 0; i < recipeUsers.length; i++) { - * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { - * result[recipeUsers[i].id] = recipeUsers[i]; - * } else { - * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; - * if (result[pUserId] === undefined) { - * result[pUserId] = []; - * } - * result[pUserId].push(recipeUsers[i]); - * } - * } - * - * - */ - return; - }; - - getUserByAccountInfoAndRecipeId = async (_input: { info: AccountInfoWithRecipeId }): Promise => { - // TODO - return; - }; } diff --git a/lib/ts/types.ts b/lib/ts/types.ts index 9f1ec146c..d6c532d19 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -72,33 +72,6 @@ export type GeneralErrorResponse = { message: string; }; -export type AccountInfo = - | { - email: string; - } - | { - thirdpartyId: string; - thirdpartyUserId: string; - } - | { - phoneNumber: string; - }; - -export type AccountInfoWithRecipeId = - | { - recipeId: "emailpassword" | "passwordless"; - email: string; - } - | { - recipeId: "thirdparty"; - thirdpartyId: string; - thirdpartyUserId: string; - } - | { - recipeId: "passwordless"; - phoneNumber: string; - }; - export type User = { id: string; isPrimaryUser: boolean; @@ -109,6 +82,7 @@ export type User = { thirdpartyUserId: string; }[]; linkedRecipes: { + // this will always have one item in the array regardless of whether it's a primaryUser or a recipeUser recipeId: string; recipeUserId: string; }[]; From 91f51a5adc3da493c25fa8d4d8e530a46ef8daf4 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Wed, 4 Jan 2023 15:57:09 +0530 Subject: [PATCH 14/82] Update lib/ts/recipe/accountlinking/recipeImplementation.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipeImplementation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 3d6908d8a..52810f8b5 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -324,7 +324,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo return { status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", description: "recipeUserId already associated with another primaryUserId", - primaryUserId: recipeUser.id, + primaryUserId: recipeUser.id, // this is actually the primary user ID cause isPrimaryUser is true }; } let canCreatePrimaryUser: From 983a16bce6741b92502f07a3c6d73ea92c8a9807 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Wed, 4 Jan 2023 17:13:20 +0530 Subject: [PATCH 15/82] Update lib/ts/recipe/accountlinking/recipe.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipe.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index fa6e114e2..6cbffa413 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -246,7 +246,7 @@ export default class Recipe extends RecipeModule { userContext, }); if (user.status !== "OK") { - throw Error(user.status); + throw Error("should never come here. Error from createPrimaryUser: " + user.status); } return user.user.id; } From ce31b94ff825f9fbb14ab5c419b1d7727ecee4e1 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Wed, 4 Jan 2023 17:19:46 +0530 Subject: [PATCH 16/82] Update lib/ts/recipe/accountlinking/recipe.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipe.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 6cbffa413..ffae8877a 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -214,7 +214,7 @@ export default class Recipe extends RecipeModule { } throw Error("it should never reach here"); }; - createPrimaryUserIdOrLinkAccountPostSignUp = async ({ + doPostSignUpAccountLinkingOperations = async ({ info, infoVerified, recipeUserId, From 680ff1f02bb08abc68b6afc292904ab977a2d9ea Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 16 Jan 2023 13:38:19 +0530 Subject: [PATCH 17/82] code review changes --- lib/build/index.d.ts | 20 +- lib/build/index.js | 74 +++- lib/build/recipe/accountlinking/index.d.ts | 53 +-- lib/build/recipe/accountlinking/index.js | 37 -- lib/build/recipe/accountlinking/recipe.d.ts | 24 +- lib/build/recipe/accountlinking/recipe.js | 151 ++++++-- .../accountlinking/recipeImplementation.js | 164 ++++---- lib/build/recipe/accountlinking/types.d.ts | 13 +- lib/build/recipe/dashboard/api/usersGet.d.ts | 19 +- lib/build/recipe/dashboard/utils.js | 93 +---- lib/build/supertokens.d.ts | 6 - lib/build/supertokens.js | 16 - lib/build/types.d.ts | 15 +- lib/ts/index.ts | 41 +- lib/ts/recipe/accountlinking/index.ts | 49 +-- lib/ts/recipe/accountlinking/recipe.ts | 189 ++++++--- .../accountlinking/recipeImplementation.ts | 365 +++++++++--------- lib/ts/recipe/accountlinking/types.ts | 13 +- lib/ts/recipe/dashboard/api/usersGet.ts | 39 +- lib/ts/recipe/dashboard/utils.ts | 144 +------ lib/ts/supertokens.ts | 17 - lib/ts/types.ts | 19 +- 22 files changed, 721 insertions(+), 840 deletions(-) diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index 0d491ed91..9bb313ba5 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -2,6 +2,7 @@ import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; import { User } from "./types"; +import { AccountInfo, AccountInfoWithRecipeId } from "./recipe/accountlinking/types"; export default class SuperTokensWrapper { static init: typeof SuperTokens.init; static Error: typeof SuperTokensError; @@ -23,12 +24,6 @@ export default class SuperTokensWrapper { users: User[]; nextPaginationToken?: string; }>; - static deleteUser( - userId: string, - removeAllLinkedAccounts?: boolean - ): Promise<{ - status: "OK"; - }>; static createUserIdMapping(input: { superTokensUserId: string; externalUserId: string; @@ -73,6 +68,16 @@ export default class SuperTokensWrapper { }): Promise<{ status: "OK" | "UNKNOWN_MAPPING_ERROR"; }>; + static getUser(userId: string, userContext?: any): Promise; + static listUsersByAccountInfo(info: AccountInfo, userContext?: any): Promise; + static getUserByAccountInfo(info: AccountInfoWithRecipeId, userContext?: any): Promise; + static deleteUser( + userId: string, + removeAllLinkedAccounts?: boolean, + userContext?: any + ): Promise<{ + status: "OK"; + }>; } export declare let init: typeof SuperTokens.init; export declare let getAllCORSHeaders: typeof SuperTokensWrapper.getAllCORSHeaders; @@ -84,4 +89,7 @@ export declare let createUserIdMapping: typeof SuperTokensWrapper.createUserIdMa export declare let getUserIdMapping: typeof SuperTokensWrapper.getUserIdMapping; export declare let deleteUserIdMapping: typeof SuperTokensWrapper.deleteUserIdMapping; export declare let updateOrDeleteUserIdMappingInfo: typeof SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; +export declare let getUser: typeof SuperTokensWrapper.getUser; +export declare let listUsersByAccountInfo: typeof SuperTokensWrapper.listUsersByAccountInfo; +export declare let getUserByAccountInfo: typeof SuperTokensWrapper.getUserByAccountInfo; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/index.js b/lib/build/index.js index 9ef8498de..43536c30d 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -13,9 +13,41 @@ * License for the specific language governing permissions and limitations * under the License. */ +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_1 = require("./supertokens"); const error_1 = require("./error"); +const recipe_1 = require("./recipe/accountlinking/recipe"); // For Express class SuperTokensWrapper { static getAllCORSHeaders() { @@ -34,12 +66,6 @@ class SuperTokensWrapper { .getInstanceOrThrowError() .getUsers(Object.assign({ timeJoinedOrder: "DESC" }, input)); } - static deleteUser(userId, removeAllLinkedAccounts = true) { - return supertokens_1.default.getInstanceOrThrowError().deleteUser({ - userId, - removeAllLinkedAccounts, - }); - } static createUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().createUserIdMapping(input); } @@ -52,6 +78,39 @@ class SuperTokensWrapper { static updateOrDeleteUserIdMappingInfo(input) { return supertokens_1.default.getInstanceOrThrowError().updateOrDeleteUserIdMappingInfo(input); } + static getUser(userId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ + userId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static listUsersByAccountInfo(info, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static getUserByAccountInfo(info, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static deleteUser(userId, removeAllLinkedAccounts = false, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ + userId, + removeAllLinkedAccounts, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } } exports.default = SuperTokensWrapper; SuperTokensWrapper.init = supertokens_1.default.init; @@ -66,4 +125,7 @@ exports.createUserIdMapping = SuperTokensWrapper.createUserIdMapping; exports.getUserIdMapping = SuperTokensWrapper.getUserIdMapping; exports.deleteUserIdMapping = SuperTokensWrapper.deleteUserIdMapping; exports.updateOrDeleteUserIdMappingInfo = SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; +exports.getUser = SuperTokensWrapper.getUser; +exports.listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; +exports.getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; exports.Error = SuperTokensWrapper.Error; diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 9411d32ea..092367e09 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,17 +1,17 @@ // @ts-nocheck import Recipe from "./recipe"; -import type { AccountInfo, AccountInfoWithRecipeId, RecipeInterface } from "./types"; +import type { RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static getRecipeUserIdsForPrimaryUserIds( primaryUserIds: string[], - userContext: any + userContext?: any ): Promise<{ [primaryUserId: string]: string[]; }>; static getPrimaryUserIdsforRecipeUserIds( recipeUserIds: string[], - userContext: any + userContext?: any ): Promise<{ [recipeUserId: string]: string | null; }>; @@ -19,29 +19,24 @@ export default class Wrapper { recipeUserId: string, recipeId: string, timeJoined: number, - userContext: any - ): Promise< - | { - status: "OK"; - createdNewEntry: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - } - >; + userContext?: any + ): Promise<{ + status: "OK"; + createdNewEntry: boolean; + }>; static getUsers( timeJoinedOrder: "ASC" | "DESC", limit: number | undefined, paginationToken: string | undefined, includeRecipeIds: string[] | undefined, - userContext: any + userContext?: any ): Promise<{ users: import("../../types").User[]; nextPaginationToken?: string | undefined; }>; static canCreatePrimaryUserId( recipeUserId: string, - userContext: any + userContext?: any ): Promise< | { status: "OK"; @@ -56,7 +51,7 @@ export default class Wrapper { >; static createPrimaryUser( recipeUserId: string, - userContext: any + userContext?: any ): Promise< | { status: "OK"; @@ -73,7 +68,7 @@ export default class Wrapper { static canLinkAccounts( recipeUserId: string, primaryUserId: string, - userContext: any + userContext?: any ): Promise< | { status: "OK"; @@ -96,7 +91,7 @@ export default class Wrapper { static linkAccounts( recipeUserId: string, primaryUserId: string, - userContext: any + userContext?: any ): Promise< | { status: "OK"; @@ -118,7 +113,7 @@ export default class Wrapper { >; static unlinkAccounts( recipeUserId: string, - userContext: any + userContext?: any ): Promise< | { status: "OK"; @@ -128,22 +123,6 @@ export default class Wrapper { status: "NO_PRIMARY_USER_FOUND"; } >; - static getUser(userId: string, userContext: any): Promise; - static listUsersByAccountInfo( - info: AccountInfo, - userContext: any - ): Promise; - static getUserByAccountInfo( - info: AccountInfoWithRecipeId, - userContext: any - ): Promise; - static deleteUser( - userId: string, - removeAllLinkedAccounts: boolean, - userContext: any - ): Promise<{ - status: "OK"; - }>; } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; @@ -155,8 +134,4 @@ export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; export declare const linkAccounts: typeof Wrapper.linkAccounts; export declare const unlinkAccounts: typeof Wrapper.unlinkAccounts; -export declare const getUser: typeof Wrapper.getUser; -export declare const listUsersByAccountInfo: typeof Wrapper.listUsersByAccountInfo; -export declare const getUserByAccountInfo: typeof Wrapper.getUserByAccountInfo; -export declare const deleteUser: typeof Wrapper.deleteUser; export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 6934e2f53..7652cb1b2 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -132,39 +132,6 @@ class Wrapper { }); }); } - static getUser(userId, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ - userId, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } - static listUsersByAccountInfo(info, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ - info, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } - static getUserByAccountInfo(info, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ - info, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } - static deleteUser(userId, removeAllLinkedAccounts, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ - userId, - removeAllLinkedAccounts, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } } exports.default = Wrapper; Wrapper.init = recipe_1.default.init; @@ -178,7 +145,3 @@ exports.createPrimaryUser = Wrapper.createPrimaryUser; exports.canLinkAccounts = Wrapper.canLinkAccounts; exports.linkAccounts = Wrapper.linkAccounts; exports.unlinkAccounts = Wrapper.unlinkAccounts; -exports.getUser = Wrapper.getUser; -exports.listUsersByAccountInfo = Wrapper.listUsersByAccountInfo; -exports.getUserByAccountInfo = Wrapper.getUserByAccountInfo; -exports.deleteUser = Wrapper.deleteUser; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 2e87af32e..f19b148d4 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -3,7 +3,7 @@ import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; -import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction } from "../../types"; +import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction, User } from "../../types"; import { SessionContainer } from "../session"; import type { TypeNormalisedInput, RecipeInterface, TypeInput, AccountInfoAndEmailWithRecipeId } from "./types"; export default class Recipe extends RecipeModule { @@ -11,15 +11,7 @@ export default class Recipe extends RecipeModule { static RECIPE_ID: string; config: TypeNormalisedInput; recipeInterfaceImpl: RecipeInterface; - isInServerlessEnv: boolean; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - _recipes: {}, - _ingredients: {} - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, config: TypeInput, _recipes: {}, _ingredients: {}); static init(config: TypeInput): RecipeListFunction; static getInstanceOrThrowError(): Recipe; getAPIsHandled(): APIHandled[]; @@ -33,23 +25,23 @@ export default class Recipe extends RecipeModule { handleError(error: error, _request: BaseRequest, _response: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; - getIdentitiesForPrimaryUserId: ( - primaryUserId: string + getIdentitiesForUser: ( + user: User ) => Promise<{ verified: { emails: string[]; phoneNumbers: string[]; thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + id: string; + userId: string; }[]; }; unverified: { emails: string[]; phoneNumbers: string[]; thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + id: string; + userId: string; }[]; }; }>; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 91058cbc3..6bb729416 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -52,18 +52,48 @@ const supertokens_js_override_1 = require("supertokens-js-override"); const recipeImplementation_1 = require("./recipeImplementation"); const querier_1 = require("../../querier"); const error_1 = require("../../error"); -const normalisedURLPath_1 = require("../../normalisedURLPath"); class Recipe extends recipeModule_1.default { - constructor(recipeId, appInfo, isInServerlessEnv, config, _recipes, _ingredients) { + constructor(recipeId, appInfo, config, _recipes, _ingredients) { super(recipeId, appInfo); - this.getIdentitiesForPrimaryUserId = (primaryUserId) => + this.getIdentitiesForUser = (user) => __awaiter(this, void 0, void 0, function* () { - return yield querier_1.Querier.getNewInstanceOrThrowError(this.getRecipeId()).sendGetRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/identities"), - { - primaryUserId, + let identities = { + verified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + unverified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + }; + for (let i = 0; i < user.loginMethods.length; i++) { + let loginMethod = user.loginMethods[i]; + if (loginMethod.email !== undefined) { + if (loginMethod.verified) { + identities.verified.emails.push(loginMethod.email); + } else { + identities.unverified.emails.push(loginMethod.email); + } } - ); + if (loginMethod.phoneNumber !== undefined) { + if (loginMethod.verified) { + identities.verified.phoneNumbers.push(loginMethod.phoneNumber); + } else { + identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); + } + } + if (loginMethod.thirdParty !== undefined) { + if (loginMethod.verified) { + identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); + } else { + identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); + } + } + } + return identities; }); this.isSignUpAllowed = ({ info, userContext }) => __awaiter(this, void 0, void 0, function* () { @@ -102,10 +132,7 @@ class Recipe extends recipeModule_1.default { if (!shouldRequireVerification) { return true; } - /** - * DISCUSS: new API in core which returns all the verified identities for primaryUserId - */ - let identitiesForPrimaryUser = yield this.getIdentitiesForPrimaryUserId(primaryUser.id); + let identitiesForPrimaryUser = yield this.getIdentitiesForUser(primaryUser); if (info.email !== undefined) { return identitiesForPrimaryUser.verified.emails.includes(info.email); } @@ -176,11 +203,14 @@ class Recipe extends recipeModule_1.default { if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return recipeUserId; } - yield this.recipeInterfaceImpl.linkAccounts({ + let result = yield this.recipeInterfaceImpl.linkAccounts({ recipeUserId, primaryUserId: primaryUser.id, userContext, }); + if (result.status !== "OK") { + throw Error("this error status shouldn't not be thrown. Error" + result.status); + } return primaryUser.id; }); this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => @@ -193,6 +223,10 @@ class Recipe extends recipeModule_1.default { if (user === undefined) { throw Error("this should not be thrown"); } + /** + * checking if the user with existing session + * is a primary user or not + */ if (!user.isPrimaryUser) { let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( info, @@ -207,11 +241,13 @@ class Recipe extends recipeModule_1.default { reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", }; } - let recipeId = user.linkedRecipes[0].recipeId; - let querier = querier_1.Querier.getNewInstanceOrThrowError(recipeId); - let recipeUser = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { - userId: user.id, - }); + let recipeId = user.loginMethods[0].recipeId; + let recipeUser = yield utils_1.getUserForRecipeId(user.id, recipeId); + if (recipeUser.user === undefined) { + throw Error( + "This error should never be thrown. Check for bug in `getUserForRecipeId` function" + ); + } shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( recipeUser.user, undefined, @@ -226,24 +262,17 @@ class Recipe extends recipeModule_1.default { }; } if (shouldDoAccountLinking.shouldRequireVerification) { - if (recipeId === "emailpassword" || recipeId === "thirdparty") { - let querier2 = querier_1.Querier.getNewInstanceOrThrowError("emailverification"); - let response = yield querier2.sendGetRequest( - new normalisedURLPath_1.default("/recipe/user/email/verify"), - { - userId: recipeUser.user.id, - email: recipeUser.user.email, - } - ); - if (!response.isVerified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } + if (!user.loginMethods[0].verified) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; } } + /** + * checking if primary user can be created for the existing recipe user + */ let canCreatePrimaryUser = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ recipeUserId: user.id, userContext, @@ -255,6 +284,9 @@ class Recipe extends recipeModule_1.default { reason: canCreatePrimaryUser.status, }; } + /** + * creating primary user for the recipe user + */ let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: user.id, userContext, @@ -268,6 +300,10 @@ class Recipe extends recipeModule_1.default { } user = createPrimaryUserResult.user; } + /** + * checking if account linking is allowed for given primary user + * and new login info + */ let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( info, user, @@ -281,6 +317,10 @@ class Recipe extends recipeModule_1.default { reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", }; } + /** + * checking if a recipe user already exists for the given + * login info + */ let recipeInfo; if (info.recipeId === "emailpassword" && info.email !== undefined) { recipeInfo = { @@ -311,7 +351,17 @@ class Recipe extends recipeModule_1.default { userContext, }); if (recipeUser === undefined) { - let identitiesForPrimaryUser = yield this.getIdentitiesForPrimaryUserId(user.id); + /** + * if recipe user doesn't exists, we check if + * any of the identifying info associated with + * the primary user equals to the identifying info + * of the given input. If so, return createRecipeUser + * as true to let the recipe know that a recipe user needs + * to be created and set updateVerificationClaim to false + * so the recipe will call back this function when the + * recipe user is created + */ + let identitiesForPrimaryUser = yield this.getIdentitiesForUser(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -334,6 +384,11 @@ class Recipe extends recipeModule_1.default { }; } } + /** + * checking if there already exists any other primary + * user which is associated with the identifying info + * for the given input + */ let existingRecipeUserForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ info: recipeInfo, userContext, @@ -349,6 +404,19 @@ class Recipe extends recipeModule_1.default { }; } } + /** + * if the existing info is not verified, we do want + * to create a recipe user but don't want recipe + * to again callback this function for any further + * linking part. Instead, we want the recipe to + * update the session claim so it can be known that + * the new account needs to be verified. so, return + * createRecipeUser as true to let the recipe know + * that a recipe user needs to be created and set + * updateVerificationClaim to true so the recipe will + * not call back this function and update the session + * claim instead + */ if (!infoVerified) { if (shouldDoAccountLinking.shouldRequireVerification) { return { @@ -362,6 +430,11 @@ class Recipe extends recipeModule_1.default { updateVerificationClaim: false, }; } + /** + * checking if th primary user (associated with session) + * and recipe user (associated with login info) can be + * linked + */ let canLinkAccounts = yield this.recipeInterfaceImpl.canLinkAccounts({ recipeUserId: recipeUser.id, primaryUserId: user.id, @@ -381,7 +454,7 @@ class Recipe extends recipeModule_1.default { reason: canLinkAccounts.status, }; } - let identitiesForPrimaryUser = yield this.getIdentitiesForPrimaryUserId(user.id); + let identitiesForPrimaryUser = yield this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = @@ -422,7 +495,6 @@ class Recipe extends recipeModule_1.default { }; }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); - this.isInServerlessEnv = isInServerlessEnv; { let builder = new supertokens_js_override_1.default( recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config) @@ -431,12 +503,11 @@ class Recipe extends recipeModule_1.default { } } static init(config) { - return (appInfo, isInServerlessEnv) => { - if (Recipe.instance === undefined) { + return (appInfo) => { + if (Recipe.instance !== undefined) { Recipe.instance = new Recipe( Recipe.RECIPE_ID, appInfo, - isInServerlessEnv, config, {}, { diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index e38200586..bb70e0da3 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -52,16 +52,24 @@ function getRecipeImplementation(querier, config) { return { getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { return __awaiter(this, void 0, void 0, function* () { - return querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { - primaryUserIds: primaryUserIds.join(","), - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/users"), + { + primaryUserIds: primaryUserIds.join(","), + } + ); + return result.userIdMapping; }); }, getPrimaryUserIdsforRecipeUserIds: function ({ recipeUserIds }) { return __awaiter(this, void 0, void 0, function* () { - return querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { - recipeUserIds: recipeUserIds.join(","), - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/users"), + { + recipeUserIds: recipeUserIds.join(","), + } + ); + return result.userIdMapping; }); }, addNewRecipeUserIdWithoutPrimaryUserId: function ({ recipeUserId, recipeId, timeJoined }) { @@ -105,13 +113,11 @@ function getRecipeImplementation(querier, config) { /** * checking if primaryUserId exists for the recipeUserId */ - if ( - recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== undefined && - recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== null - ) { + let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; + if (primaryUserId !== undefined && primaryUserId !== null) { return { status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: recipeUserIdToPrimaryUserIdMapping[recipeUserId], + primaryUserId, description: "Recipe user is already linked with another primary user id", }; } @@ -139,33 +145,34 @@ function getRecipeImplementation(querier, config) { * a primaryUser which is associated with the identifying info */ let usersForAccountInfo = []; - for (let i = 0; i < user.emails.length; i++) { - usersForAccountInfo.push( - ...(yield this.listUsersByAccountInfo({ - info: { - email: user.emails[i], - }, - userContext, - })) - ); - } - for (let i = 0; i < user.thirdpartyInfo.length; i++) { - usersForAccountInfo.push( - ...(yield this.listUsersByAccountInfo({ - info: Object.assign({}, user.thirdpartyInfo[i]), - userContext, - })) - ); - } - for (let i = 0; i < user.phoneNumbers.length; i++) { - usersForAccountInfo.push( - ...(yield this.listUsersByAccountInfo({ - info: { - phoneNumber: user.phoneNumbers[i], - }, + for (let i = 0; i < user.loginMethods.length; i++) { + let loginMethod = user.loginMethods[i]; + let info = undefined; + if (loginMethod.email !== undefined) { + info = { + email: loginMethod.email, + }; + } + if (loginMethod.phoneNumber !== undefined) { + info = { + phoneNumber: loginMethod.phoneNumber, + }; + } + if (loginMethod.thirdParty !== undefined) { + info = { + thirdpartyId: loginMethod.thirdParty.id, + thirdpartyUserId: loginMethod.thirdParty.userId, + }; + } + if (info !== undefined) { + let usersList = yield this.listUsersByAccountInfo({ + info, userContext, - })) - ); + }); + if (usersList !== undefined) { + usersForAccountInfo.push(...usersList); + } + } } let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); /** @@ -226,6 +233,7 @@ function getRecipeImplementation(querier, config) { */ let recipeUser = yield this.getUser({ userId: recipeUserId, + userContext, }); if (recipeUser === undefined) { throw Error("recipe user not found"); @@ -303,13 +311,13 @@ function getRecipeImplementation(querier, config) { if (user === undefined) { throw Error("this error should never be thrown"); } - let recipeUserObj = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); - if (recipeUserObj === undefined) { + let loginMethodInfo = user.loginMethods.find((u) => u.recipeUserId === recipeUserId); + if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } let recipeUser = yield utils_1.getUserForRecipeId( - recipeUserObj.recipeUserId, - recipeUserObj.recipeId + loginMethodInfo.recipeUserId, + loginMethodInfo.recipeId ); if (recipeUser.user === undefined) { throw Error("this error should never be thrown"); @@ -325,15 +333,10 @@ function getRecipeImplementation(querier, config) { recipeUserIds: [recipeUserId], userContext, }); - if ( - recipeUserIdToPrimaryUserIdMapping[recipeUserId] === undefined || - recipeUserIdToPrimaryUserIdMapping[recipeUserId] === null - ) { - return { - status: "NO_PRIMARY_USER_FOUND", - }; - } let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; + if (primaryUserId === undefined || primaryUserId === null) { + throw Error("recipeUserId is not associated with any primaryUserId"); + } /** * primaryUserId === recipeUserId */ @@ -348,7 +351,7 @@ function getRecipeImplementation(querier, config) { wasRecipeUserDeleted: false, }; } - if (user.linkedRecipes.length > 1) { + if (user.loginMethods.length > 1) { yield this.deleteUser({ userId: recipeUserId, removeAllLinkedAccounts: false, @@ -378,9 +381,12 @@ function getRecipeImplementation(querier, config) { }, getUser: function ({ userId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { - userId, - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user"), + { + userId, + } + ); if (result.status === "OK") { return result.user; } @@ -389,52 +395,12 @@ function getRecipeImplementation(querier, config) { }, listUsersByAccountInfo: function ({ info }) { return __awaiter(this, void 0, void 0, function* () { - /** - * if input is only email: - * let emailPasswordUser = emailpassword.getUserByEmail(email); - * - * let thirdpartyUsers = thirdparty.getUsersByEmail(email); - * - * let passwordlessUser = passwordless.getUserByEmail(email); - * - * let recipeUsers = []; - * - * if (emailPasswordUser !== undefined) { - * recipeUsers.push(emailPasswordUser); - * } - * - * recipeUsers.push(...thirdpartyUsers); - * - * if (passwordlessUser !== undefined) { - * recipeUsers.push(passwordlessUser); - * } - * - * let recipeUserIds = recipeUsers.map(r => r.id); - * - * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); - * - * let result: {id: User | User[]} = {}; - * - * for (let i = 0; i < recipeUsers.length; i++) { - * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { - * result[recipeUsers[i].id] = recipeUsers[i]; - * } else { - * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; - * if (result[pUserId] === undefined) { - * result[pUserId] = []; - * } - * result[pUserId].push(recipeUsers[i]); - * } - * } - * - * - */ let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/users"), + new normalisedURLPath_1.default("/users"), Object.assign({}, info) ); if (result.status === "OK") { - return result.user; + return result.users; } return undefined; }); @@ -442,11 +408,11 @@ function getRecipeImplementation(querier, config) { getUserByAccountInfo: function ({ info }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/user"), + new normalisedURLPath_1.default("/users"), Object.assign({}, info) ); if (result.status === "OK") { - return result.user; + return result.users[0]; } return undefined; }); @@ -464,9 +430,9 @@ function getRecipeImplementation(querier, config) { * if true, the user should be treated as primaryUser */ if (removeAllLinkedAccounts) { - recipeUsersToRemove = user.linkedRecipes; + recipeUsersToRemove = user.loginMethods; } else { - recipeUsersToRemove = user.linkedRecipes.filter((u) => u.recipeUserId === userId); + recipeUsersToRemove = user.loginMethods.filter((u) => u.recipeUserId === userId); } for (let i = 0; i < recipeUsersToRemove.length; i++) { /** diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 23e053e9b..f9f4851e1 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -66,15 +66,10 @@ export declare type RecipeInterface = { recipeId: string; timeJoined: number; userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewEntry: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - } - >; + }) => Promise<{ + status: "OK"; + createdNewEntry: boolean; + }>; getUsers: (input: { timeJoinedOrder: "ASC" | "DESC"; limit?: number; diff --git a/lib/build/recipe/dashboard/api/usersGet.d.ts b/lib/build/recipe/dashboard/api/usersGet.d.ts index b1a06465c..baa83fa49 100644 --- a/lib/build/recipe/dashboard/api/usersGet.d.ts +++ b/lib/build/recipe/dashboard/api/usersGet.d.ts @@ -2,18 +2,23 @@ import { APIInterface, APIOptions } from "../types"; declare type User = { id: string; + timeJoined: number; isPrimaryUser: boolean; - firstName?: string; - lastName?: string; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; - }[]; - linkedRecipes: { + firstName?: string; + lastName?: string; + loginMethods: { recipeId: string; recipeUserId: string; + timeJoined: number; + verified: boolean; + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; }[]; }; export declare type Response = { diff --git a/lib/build/recipe/dashboard/utils.js b/lib/build/recipe/dashboard/utils.js index 8fef0e64e..75e6b67be 100644 --- a/lib/build/recipe/dashboard/utils.js +++ b/lib/build/recipe/dashboard/utils.js @@ -48,14 +48,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); const utils_1 = require("../../utils"); const constants_1 = require("./constants"); -const recipe_1 = require("../emailpassword/recipe"); -const recipe_2 = require("../thirdparty/recipe"); -const recipe_3 = require("../passwordless/recipe"); -const emailpassword_1 = require("../emailpassword"); -const thirdparty_1 = require("../thirdparty"); -const passwordless_1 = require("../passwordless"); -const thirdpartyemailpassword_1 = require("../thirdpartyemailpassword"); -const thirdpartypasswordless_1 = require("../thirdpartypasswordless"); +const utils_2 = require("../accountlinking/utils"); function validateAndNormaliseUserInput(config) { if (config.apiKey.trim().length === 0) { throw new Error("apiKey provided to Dashboard recipe cannot be empty"); @@ -142,88 +135,14 @@ function isValidRecipeId(recipeId) { exports.isValidRecipeId = isValidRecipeId; function getUserForRecipeId(userId, recipeId) { return __awaiter(this, void 0, void 0, function* () { - let user; - let recipe; - if (recipeId === recipe_1.default.RECIPE_ID) { - try { - const userResponse = yield emailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { firstName: "", lastName: "" }); - recipe = "emailpassword"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { firstName: "", lastName: "" }); - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === recipe_2.default.RECIPE_ID) { - try { - const userResponse = yield thirdparty_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { firstName: "", lastName: "" }); - recipe = "thirdparty"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { firstName: "", lastName: "" }); - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { firstName: "", lastName: "" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === recipe_3.default.RECIPE_ID) { - try { - const userResponse = yield passwordless_1.default.getUserById({ - userId, - }); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { firstName: "", lastName: "" }); - recipe = "passwordless"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { firstName: "", lastName: "" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } + let userResponse = yield utils_2.getUserForRecipeId(userId, recipeId); + let user = undefined; + if (userResponse.user !== undefined) { + user = Object.assign(Object.assign({}, userResponse.user), { firstName: "", lastName: "" }); } return { user, - recipe, + recipe: userResponse.recipe, }; }); } diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 915fcab44..98b18b20a 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -36,12 +36,6 @@ export default class SuperTokens { users: User[]; nextPaginationToken?: string | undefined; }>; - deleteUser: (input: { - userId: string; - removeAllLinkedAccounts: boolean; - }) => Promise<{ - status: "OK"; - }>; createUserIdMapping: (input: { superTokensUserId: string; externalUserId: string; diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index a1d14584e..a57d37f7d 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -138,22 +138,6 @@ class SuperTokens { nextPaginationToken: response.nextPaginationToken, }; }); - this.deleteUser = (input) => - __awaiter(this, void 0, void 0, function* () { - let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); - let cdiVersion = yield querier.getAPIVersion(); - if (utils_1.maxVersion("2.10", cdiVersion) === cdiVersion) { - // delete user is only available >= CDI 2.10 - yield querier.sendPostRequest(new normalisedURLPath_1.default("/user/remove"), { - userId: input.userId, - }); - return { - status: "OK", - }; - } else { - throw new global.Error("Please upgrade the SuperTokens core to >= 3.7.0"); - } - }); this.createUserIdMapping = function (input) { return __awaiter(this, void 0, void 0, function* () { let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index 8b1453fd9..1b775c9d0 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -51,15 +51,20 @@ export declare type GeneralErrorResponse = { }; export declare type User = { id: string; + timeJoined: number; isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; - }[]; - linkedRecipes: { + loginMethods: { recipeId: string; recipeUserId: string; + timeJoined: number; + verified: boolean; + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; }[]; }; diff --git a/lib/ts/index.ts b/lib/ts/index.ts index a0a229742..4b611397f 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -16,6 +16,8 @@ import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; import { User } from "./types"; +import AccountLinking from "./recipe/accountlinking/recipe"; +import { AccountInfo, AccountInfoWithRecipeId } from "./recipe/accountlinking/types"; // For Express export default class SuperTokensWrapper { @@ -59,13 +61,6 @@ export default class SuperTokensWrapper { }); } - static deleteUser(userId: string, removeAllLinkedAccounts: boolean = true) { - return SuperTokens.getInstanceOrThrowError().deleteUser({ - userId, - removeAllLinkedAccounts, - }); - } - static createUserIdMapping(input: { superTokensUserId: string; externalUserId: string; @@ -94,6 +89,32 @@ export default class SuperTokensWrapper { }) { return SuperTokens.getInstanceOrThrowError().updateOrDeleteUserIdMappingInfo(input); } + + static async getUser(userId: string, userContext?: any) { + return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ + userId, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async listUsersByAccountInfo(info: AccountInfo, userContext?: any) { + return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async getUserByAccountInfo(info: AccountInfoWithRecipeId, userContext?: any) { + return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ + info, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async deleteUser(userId: string, removeAllLinkedAccounts: boolean = false, userContext?: any) { + return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ + userId, + removeAllLinkedAccounts, + userContext: userContext === undefined ? {} : userContext, + }); + } } export let init = SuperTokensWrapper.init; @@ -116,4 +137,10 @@ export let deleteUserIdMapping = SuperTokensWrapper.deleteUserIdMapping; export let updateOrDeleteUserIdMappingInfo = SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; +export let getUser = SuperTokensWrapper.getUser; + +export let listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; + +export let getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; + export let Error = SuperTokensWrapper.Error; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index 6477ad8c5..b518a21be 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -14,18 +14,18 @@ */ import Recipe from "./recipe"; -import type { AccountInfo, AccountInfoWithRecipeId, RecipeInterface } from "./types"; +import type { RecipeInterface } from "./types"; export default class Wrapper { static init = Recipe.init; - static async getRecipeUserIdsForPrimaryUserIds(primaryUserIds: string[], userContext: any) { + static async getRecipeUserIdsForPrimaryUserIds(primaryUserIds: string[], userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getRecipeUserIdsForPrimaryUserIds({ primaryUserIds, userContext: userContext === undefined ? {} : userContext, }); } - static async getPrimaryUserIdsforRecipeUserIds(recipeUserIds: string[], userContext: any) { + static async getPrimaryUserIdsforRecipeUserIds(recipeUserIds: string[], userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds, userContext: userContext === undefined ? {} : userContext, @@ -35,7 +35,7 @@ export default class Wrapper { recipeUserId: string, recipeId: string, timeJoined: number, - userContext: any + userContext?: any ) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.addNewRecipeUserIdWithoutPrimaryUserId({ recipeUserId, @@ -49,7 +49,7 @@ export default class Wrapper { limit: number | undefined, paginationToken: string | undefined, includeRecipeIds: string[] | undefined, - userContext: any + userContext?: any ) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUsers({ timeJoinedOrder, @@ -59,63 +59,38 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } - static async canCreatePrimaryUserId(recipeUserId: string, userContext: any) { + static async canCreatePrimaryUserId(recipeUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.canCreatePrimaryUserId({ recipeUserId, userContext: userContext === undefined ? {} : userContext, }); } - static async createPrimaryUser(recipeUserId: string, userContext: any) { + static async createPrimaryUser(recipeUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.createPrimaryUser({ recipeUserId, userContext: userContext === undefined ? {} : userContext, }); } - static async canLinkAccounts(recipeUserId: string, primaryUserId: string, userContext: any) { + static async canLinkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.canLinkAccounts({ recipeUserId, primaryUserId, userContext: userContext === undefined ? {} : userContext, }); } - static async linkAccounts(recipeUserId: string, primaryUserId: string, userContext: any) { + static async linkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ recipeUserId, primaryUserId, userContext: userContext === undefined ? {} : userContext, }); } - static async unlinkAccounts(recipeUserId: string, userContext: any) { + static async unlinkAccounts(recipeUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.unlinkAccounts({ recipeUserId, userContext: userContext === undefined ? {} : userContext, }); } - static async getUser(userId: string, userContext: any) { - return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ - userId, - userContext: userContext === undefined ? {} : userContext, - }); - } - static async listUsersByAccountInfo(info: AccountInfo, userContext: any) { - return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ - info, - userContext: userContext === undefined ? {} : userContext, - }); - } - static async getUserByAccountInfo(info: AccountInfoWithRecipeId, userContext: any) { - return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ - info, - userContext: userContext === undefined ? {} : userContext, - }); - } - static async deleteUser(userId: string, removeAllLinkedAccounts: boolean, userContext: any) { - return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ - userId, - removeAllLinkedAccounts, - userContext: userContext === undefined ? {} : userContext, - }); - } } export const init = Wrapper.init; @@ -128,9 +103,5 @@ export const createPrimaryUser = Wrapper.createPrimaryUser; export const canLinkAccounts = Wrapper.canLinkAccounts; export const linkAccounts = Wrapper.linkAccounts; export const unlinkAccounts = Wrapper.unlinkAccounts; -export const getUser = Wrapper.getUser; -export const listUsersByAccountInfo = Wrapper.listUsersByAccountInfo; -export const getUserByAccountInfo = Wrapper.getUserByAccountInfo; -export const deleteUser = Wrapper.deleteUser; export type { RecipeInterface }; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index fa6e114e2..7160a169d 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -18,7 +18,7 @@ import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; import SuperTokensModule from "../../supertokens"; -import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction } from "../../types"; +import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction, User } from "../../types"; import { SessionContainer } from "../session"; import type { TypeNormalisedInput, @@ -27,12 +27,11 @@ import type { AccountInfoAndEmailWithRecipeId, AccountInfoWithRecipeId, } from "./types"; -import { validateAndNormaliseUserInput } from "./utils"; +import { getUserForRecipeId, validateAndNormaliseUserInput } from "./utils"; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; import SuperTokensError from "../../error"; -import NormalisedURLPath from "../../normalisedURLPath"; export default class Recipe extends RecipeModule { private static instance: Recipe | undefined = undefined; @@ -43,19 +42,9 @@ export default class Recipe extends RecipeModule { recipeInterfaceImpl: RecipeInterface; - isInServerlessEnv: boolean; - - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - _recipes: {}, - _ingredients: {} - ) { + constructor(recipeId: string, appInfo: NormalisedAppinfo, config: TypeInput, _recipes: {}, _ingredients: {}) { super(recipeId, appInfo); this.config = validateAndNormaliseUserInput(appInfo, config); - this.isInServerlessEnv = isInServerlessEnv; { let builder = new OverrideableBuilder( @@ -66,12 +55,11 @@ export default class Recipe extends RecipeModule { } static init(config: TypeInput): RecipeListFunction { - return (appInfo, isInServerlessEnv) => { - if (Recipe.instance === undefined) { + return (appInfo) => { + if (Recipe.instance !== undefined) { Recipe.instance = new Recipe( Recipe.RECIPE_ID, appInfo, - isInServerlessEnv, config, {}, { @@ -124,32 +112,80 @@ export default class Recipe extends RecipeModule { return SuperTokensError.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; } - getIdentitiesForPrimaryUserId = async ( - primaryUserId: string + getIdentitiesForUser = async ( + user: User ): Promise<{ verified: { emails: string[]; phoneNumbers: string[]; thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + id: string; + userId: string; }[]; }; unverified: { emails: string[]; phoneNumbers: string[]; thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + id: string; + userId: string; }[]; }; }> => { - return await Querier.getNewInstanceOrThrowError(this.getRecipeId()).sendGetRequest( - new NormalisedURLPath("/recipe/accountlinking/user/identities"), - { - primaryUserId, + let identities: { + verified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + id: string; + userId: string; + }[]; + }; + unverified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + id: string; + userId: string; + }[]; + }; + } = { + verified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + unverified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + }; + for (let i = 0; i < user.loginMethods.length; i++) { + let loginMethod = user.loginMethods[i]; + if (loginMethod.email !== undefined) { + if (loginMethod.verified) { + identities.verified.emails.push(loginMethod.email); + } else { + identities.unverified.emails.push(loginMethod.email); + } } - ); + if (loginMethod.phoneNumber !== undefined) { + if (loginMethod.verified) { + identities.verified.phoneNumbers.push(loginMethod.phoneNumber); + } else { + identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); + } + } + if (loginMethod.thirdParty !== undefined) { + if (loginMethod.verified) { + identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); + } else { + identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); + } + } + } + return identities; }; isSignUpAllowed = async ({ @@ -201,10 +237,7 @@ export default class Recipe extends RecipeModule { return true; } - /** - * DISCUSS: new API in core which returns all the verified identities for primaryUserId - */ - let identitiesForPrimaryUser = await this.getIdentitiesForPrimaryUserId(primaryUser.id); + let identitiesForPrimaryUser = await this.getIdentitiesForUser(primaryUser); if (info.email !== undefined) { return identitiesForPrimaryUser.verified.emails.includes(info.email); @@ -288,11 +321,14 @@ export default class Recipe extends RecipeModule { if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return recipeUserId; } - await this.recipeInterfaceImpl.linkAccounts({ + let result = await this.recipeInterfaceImpl.linkAccounts({ recipeUserId, primaryUserId: primaryUser.id, userContext, }); + if (result.status !== "OK") { + throw Error("this error status shouldn't not be thrown. Error" + result.status); + } return primaryUser.id; }; @@ -337,6 +373,10 @@ export default class Recipe extends RecipeModule { if (user === undefined) { throw Error("this should not be thrown"); } + /** + * checking if the user with existing session + * is a primary user or not + */ if (!user.isPrimaryUser) { let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( info, @@ -352,11 +392,12 @@ export default class Recipe extends RecipeModule { }; } - let recipeId = user.linkedRecipes[0].recipeId; - let querier = Querier.getNewInstanceOrThrowError(recipeId); - let recipeUser = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { - userId: user.id, - }); + let recipeId = user.loginMethods[0].recipeId; + let recipeUser = await getUserForRecipeId(user.id, recipeId); + + if (recipeUser.user === undefined) { + throw Error("This error should never be thrown. Check for bug in `getUserForRecipeId` function"); + } shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( recipeUser.user, @@ -372,21 +413,18 @@ export default class Recipe extends RecipeModule { }; } if (shouldDoAccountLinking.shouldRequireVerification) { - if (recipeId === "emailpassword" || recipeId === "thirdparty") { - let querier2 = Querier.getNewInstanceOrThrowError("emailverification"); - let response = await querier2.sendGetRequest(new NormalisedURLPath("/recipe/user/email/verify"), { - userId: recipeUser.user.id, - email: recipeUser.user.email, - }); - if (!response.isVerified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } + if (!user.loginMethods[0].verified) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; } } + + /** + * checking if primary user can be created for the existing recipe user + */ let canCreatePrimaryUser = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ recipeUserId: user.id, userContext, @@ -398,6 +436,9 @@ export default class Recipe extends RecipeModule { reason: canCreatePrimaryUser.status, }; } + /** + * creating primary user for the recipe user + */ let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: user.id, userContext, @@ -411,6 +452,10 @@ export default class Recipe extends RecipeModule { } user = createPrimaryUserResult.user; } + /** + * checking if account linking is allowed for given primary user + * and new login info + */ let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( info, user, @@ -424,6 +469,11 @@ export default class Recipe extends RecipeModule { reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", }; } + + /** + * checking if a recipe user already exists for the given + * login info + */ let recipeInfo: AccountInfoWithRecipeId; if (info.recipeId === "emailpassword" && info.email !== undefined) { recipeInfo = { @@ -454,7 +504,17 @@ export default class Recipe extends RecipeModule { userContext, }); if (recipeUser === undefined) { - let identitiesForPrimaryUser = await this.getIdentitiesForPrimaryUserId(user.id); + /** + * if recipe user doesn't exists, we check if + * any of the identifying info associated with + * the primary user equals to the identifying info + * of the given input. If so, return createRecipeUser + * as true to let the recipe know that a recipe user needs + * to be created and set updateVerificationClaim to false + * so the recipe will call back this function when the + * recipe user is created + */ + let identitiesForPrimaryUser = await this.getIdentitiesForUser(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -478,6 +538,11 @@ export default class Recipe extends RecipeModule { } } + /** + * checking if there already exists any other primary + * user which is associated with the identifying info + * for the given input + */ let existingRecipeUserForInputInfo = await this.recipeInterfaceImpl.listUsersByAccountInfo({ info: recipeInfo, userContext, @@ -493,6 +558,19 @@ export default class Recipe extends RecipeModule { }; } } + /** + * if the existing info is not verified, we do want + * to create a recipe user but don't want recipe + * to again callback this function for any further + * linking part. Instead, we want the recipe to + * update the session claim so it can be known that + * the new account needs to be verified. so, return + * createRecipeUser as true to let the recipe know + * that a recipe user needs to be created and set + * updateVerificationClaim to true so the recipe will + * not call back this function and update the session + * claim instead + */ if (!infoVerified) { if (shouldDoAccountLinking.shouldRequireVerification) { return { @@ -506,6 +584,11 @@ export default class Recipe extends RecipeModule { updateVerificationClaim: false, }; } + /** + * checking if th primary user (associated with session) + * and recipe user (associated with login info) can be + * linked + */ let canLinkAccounts = await this.recipeInterfaceImpl.canLinkAccounts({ recipeUserId: recipeUser.id, primaryUserId: user.id, @@ -526,7 +609,7 @@ export default class Recipe extends RecipeModule { }; } - let identitiesForPrimaryUser = await this.getIdentitiesForPrimaryUserId(user.id); + let identitiesForPrimaryUser = await this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 3d6908d8a..9f793825b 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -22,62 +22,71 @@ import { getUserForRecipeId } from "./utils"; export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface { return { - getRecipeUserIdsForPrimaryUserIds: async function ({ - primaryUserIds, - }: { - primaryUserIds: string[]; - }): Promise<{ + getRecipeUserIdsForPrimaryUserIds: async function ( + this: RecipeInterface, + { + primaryUserIds, + }: { + primaryUserIds: string[]; + } + ): Promise<{ [primaryUserId: string]: string[]; }> { - return querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/users"), { + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/users"), { primaryUserIds: primaryUserIds.join(","), }); + return result.userIdMapping; }, - getPrimaryUserIdsforRecipeUserIds: async function ({ - recipeUserIds, - }: { - recipeUserIds: string[]; - }): Promise<{ + getPrimaryUserIdsforRecipeUserIds: async function ( + this: RecipeInterface, + { + recipeUserIds, + }: { + recipeUserIds: string[]; + } + ): Promise<{ [recipeUserId: string]: string | null; }> { - return querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/users"), { + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/users"), { recipeUserIds: recipeUserIds.join(","), }); + return result.userIdMapping; }, - addNewRecipeUserIdWithoutPrimaryUserId: async function ({ - recipeUserId, - recipeId, - timeJoined, - }: { - recipeUserId: string; - recipeId: string; - timeJoined: number; - }): Promise< - | { - status: "OK"; - createdNewEntry: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - } - > { + addNewRecipeUserIdWithoutPrimaryUserId: async function ( + this: RecipeInterface, + { + recipeUserId, + recipeId, + timeJoined, + }: { + recipeUserId: string; + recipeId: string; + timeJoined: number; + } + ): Promise<{ + status: "OK"; + createdNewEntry: boolean; + }> { return querier.sendPutRequest(new NormalisedURLPath("/recipe/accountlinking/user"), { recipeUserId, recipeId, timeJoined, }); }, - getUsers: async function ({ - timeJoinedOrder, - limit, - paginationToken, - includeRecipeIds, - }: { - timeJoinedOrder: "ASC" | "DESC"; - limit?: number; - paginationToken?: string; - includeRecipeIds?: string[]; - }): Promise<{ + getUsers: async function ( + this: RecipeInterface, + { + timeJoinedOrder, + limit, + paginationToken, + includeRecipeIds, + }: { + timeJoinedOrder: "ASC" | "DESC"; + limit?: number; + paginationToken?: string; + includeRecipeIds?: string[]; + } + ): Promise<{ users: User[]; nextPaginationToken?: string; }> { @@ -96,13 +105,16 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo nextPaginationToken: response.nextPaginationToken, }; }, - canCreatePrimaryUserId: async function ({ - recipeUserId, - userContext, - }: { - recipeUserId: string; - userContext: any; - }): Promise< + canCreatePrimaryUserId: async function ( + this: RecipeInterface, + { + recipeUserId, + userContext, + }: { + recipeUserId: string; + userContext: any; + } + ): Promise< | { status: "OK"; } @@ -127,13 +139,11 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo /** * checking if primaryUserId exists for the recipeUserId */ - if ( - recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== undefined && - recipeUserIdToPrimaryUserIdMapping[recipeUserId] !== null - ) { + let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; + if (primaryUserId !== undefined && primaryUserId !== null) { return { status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: recipeUserIdToPrimaryUserIdMapping[recipeUserId], + primaryUserId, description: "Recipe user is already linked with another primary user id", }; } @@ -165,37 +175,34 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo */ let usersForAccountInfo = []; - for (let i = 0; i < user.emails.length; i++) { - usersForAccountInfo.push( - ...(await this.listUsersByAccountInfo({ - info: { - email: user.emails[i], - }, - userContext, - })) - ); - } - - for (let i = 0; i < user.thirdpartyInfo.length; i++) { - usersForAccountInfo.push( - ...(await this.listUsersByAccountInfo({ - info: { - ...user.thirdpartyInfo[i], - }, - userContext, - })) - ); - } - - for (let i = 0; i < user.phoneNumbers.length; i++) { - usersForAccountInfo.push( - ...(await this.listUsersByAccountInfo({ - info: { - phoneNumber: user.phoneNumbers[i], - }, + for (let i = 0; i < user.loginMethods.length; i++) { + let loginMethod = user.loginMethods[i]; + let info: AccountInfo | undefined = undefined; + if (loginMethod.email !== undefined) { + info = { + email: loginMethod.email, + }; + } + if (loginMethod.phoneNumber !== undefined) { + info = { + phoneNumber: loginMethod.phoneNumber, + }; + } + if (loginMethod.thirdParty !== undefined) { + info = { + thirdpartyId: loginMethod.thirdParty.id, + thirdpartyUserId: loginMethod.thirdParty.userId, + }; + } + if (info !== undefined) { + let usersList = await this.listUsersByAccountInfo({ + info, userContext, - })) - ); + }); + if (usersList !== undefined) { + usersForAccountInfo.push(...usersList); + } + } } let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); @@ -219,13 +226,16 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo status: "OK", }; }, - createPrimaryUser: async function ({ - recipeUserId, - userContext, - }: { - recipeUserId: string; - userContext: any; - }): Promise< + createPrimaryUser: async function ( + this: RecipeInterface, + { + recipeUserId, + userContext, + }: { + recipeUserId: string; + userContext: any; + } + ): Promise< | { status: "OK"; user: User; @@ -265,15 +275,18 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo return primaryUser; }, - canLinkAccounts: async function ({ - recipeUserId, - primaryUserId, - userContext, - }: { - recipeUserId: string; - primaryUserId: string; - userContext: any; - }): Promise< + canLinkAccounts: async function ( + this: RecipeInterface, + { + recipeUserId, + primaryUserId, + userContext, + }: { + recipeUserId: string; + primaryUserId: string; + userContext: any; + } + ): Promise< | { status: "OK"; } @@ -310,6 +323,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo */ let recipeUser: User | undefined = await this.getUser({ userId: recipeUserId, + userContext, }); if (recipeUser === undefined) { throw Error("recipe user not found"); @@ -368,15 +382,18 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo status: "OK", }; }, - linkAccounts: async function ({ - recipeUserId, - primaryUserId, - userContext, - }: { - recipeUserId: string; - primaryUserId: string; - userContext: any; - }): Promise< + linkAccounts: async function ( + this: RecipeInterface, + { + recipeUserId, + primaryUserId, + userContext, + }: { + recipeUserId: string; + primaryUserId: string; + userContext: any; + } + ): Promise< | { status: "OK"; } @@ -436,11 +453,11 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo if (user === undefined) { throw Error("this error should never be thrown"); } - let recipeUserObj = user.linkedRecipes.find((u) => u.recipeUserId === recipeUserId); - if (recipeUserObj === undefined) { + let loginMethodInfo = user.loginMethods.find((u) => u.recipeUserId === recipeUserId); + if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = await getUserForRecipeId(recipeUserObj.recipeUserId, recipeUserObj.recipeId); + let recipeUser = await getUserForRecipeId(loginMethodInfo.recipeUserId, loginMethodInfo.recipeId); if (recipeUser.user === undefined) { throw Error("this error should never be thrown"); } @@ -448,34 +465,27 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } return accountsLinkingResult; }, - unlinkAccounts: async function ({ - recipeUserId, - userContext, - }: { - recipeUserId: string; - userContext: any; - }): Promise< - | { - status: "OK"; - wasRecipeUserDeleted: boolean; - } - | { - status: "NO_PRIMARY_USER_FOUND"; - } - > { + unlinkAccounts: async function ( + this: RecipeInterface, + { + recipeUserId, + userContext, + }: { + recipeUserId: string; + userContext: any; + } + ): Promise<{ + status: "OK"; + wasRecipeUserDeleted: boolean; + }> { let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds: [recipeUserId], userContext, }); - if ( - recipeUserIdToPrimaryUserIdMapping[recipeUserId] === undefined || - recipeUserIdToPrimaryUserIdMapping[recipeUserId] === null - ) { - return { - status: "NO_PRIMARY_USER_FOUND", - }; - } let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; + if (primaryUserId === undefined || primaryUserId === null) { + throw Error("recipeUserId is not associated with any primaryUserId"); + } /** * primaryUserId === recipeUserId */ @@ -491,7 +501,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo wasRecipeUserDeleted: false, }; } - if (user.linkedRecipes.length > 1) { + if (user.loginMethods.length > 1) { await this.deleteUser({ userId: recipeUserId, removeAllLinkedAccounts: false, @@ -520,8 +530,8 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo wasRecipeUserDeleted: false, }; }, - getUser: async function ({ userId }: { userId: string }): Promise { - let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { + getUser: async function (this: RecipeInterface, { userId }: { userId: string }): Promise { + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user"), { userId, }); if (result.status === "OK") { @@ -529,73 +539,42 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } return undefined; }, - listUsersByAccountInfo: async function ({ info }: { info: AccountInfo }): Promise { - /** - * if input is only email: - * let emailPasswordUser = emailpassword.getUserByEmail(email); - * - * let thirdpartyUsers = thirdparty.getUsersByEmail(email); - * - * let passwordlessUser = passwordless.getUserByEmail(email); - * - * let recipeUsers = []; - * - * if (emailPasswordUser !== undefined) { - * recipeUsers.push(emailPasswordUser); - * } - * - * recipeUsers.push(...thirdpartyUsers); - * - * if (passwordlessUser !== undefined) { - * recipeUsers.push(passwordlessUser); - * } - * - * let recipeUserIds = recipeUsers.map(r => r.id); - * - * let primaryUserIdMapping: {recipeUserId: primaryUserId} = getPrimaryUserIdsforRecipeUserIds(recipeUserIds); - * - * let result: {id: User | User[]} = {}; - * - * for (let i = 0; i < recipeUsers.length; i++) { - * if (primaryUserIdMapping[recipeUsers[i].id] === undefined) { - * result[recipeUsers[i].id] = recipeUsers[i]; - * } else { - * let pUserId = primaryUserIdMapping[recipeUsers[i].id]; - * if (result[pUserId] === undefined) { - * result[pUserId] = []; - * } - * result[pUserId].push(recipeUsers[i]); - * } - * } - * - * - */ - let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/users"), { + listUsersByAccountInfo: async function ( + this: RecipeInterface, + { info }: { info: AccountInfo } + ): Promise { + let result = await querier.sendGetRequest(new NormalisedURLPath("/users"), { ...info, }); if (result.status === "OK") { - return result.user; + return result.users; } return undefined; }, - getUserByAccountInfo: async function ({ info }: { info: AccountInfoWithRecipeId }): Promise { - let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { + getUserByAccountInfo: async function ( + this: RecipeInterface, + { info }: { info: AccountInfoWithRecipeId } + ): Promise { + let result = await querier.sendGetRequest(new NormalisedURLPath("/users"), { ...info, }); if (result.status === "OK") { - return result.user; + return result.users[0]; } return undefined; }, - deleteUser: async function ({ - userId, - removeAllLinkedAccounts, - userContext, - }: { - userId: string; - removeAllLinkedAccounts: boolean; - userContext: any; - }): Promise<{ + deleteUser: async function ( + this: RecipeInterface, + { + userId, + removeAllLinkedAccounts, + userContext, + }: { + userId: string; + removeAllLinkedAccounts: boolean; + userContext: any; + } + ): Promise<{ status: "OK"; }> { let user: User | undefined = await this.getUser({ userId, userContext }); @@ -615,9 +594,9 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo * if true, the user should be treated as primaryUser */ if (removeAllLinkedAccounts) { - recipeUsersToRemove = user.linkedRecipes; + recipeUsersToRemove = user.loginMethods; } else { - recipeUsersToRemove = user.linkedRecipes.filter((u) => u.recipeUserId === userId); + recipeUsersToRemove = user.loginMethods.filter((u) => u.recipeUserId === userId); } for (let i = 0; i < recipeUsersToRemove.length; i++) { diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 3488453cf..3952e95bb 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -83,15 +83,10 @@ export type RecipeInterface = { recipeId: string; timeJoined: number; userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewEntry: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - } - >; + }) => Promise<{ + status: "OK"; + createdNewEntry: boolean; + }>; getUsers: (input: { timeJoinedOrder: "ASC" | "DESC"; limit?: number; diff --git a/lib/ts/recipe/dashboard/api/usersGet.ts b/lib/ts/recipe/dashboard/api/usersGet.ts index b30eed18f..1714856b9 100644 --- a/lib/ts/recipe/dashboard/api/usersGet.ts +++ b/lib/ts/recipe/dashboard/api/usersGet.ts @@ -18,20 +18,43 @@ import SuperTokens from "../../../supertokens"; import UserMetaDataRecipe from "../../usermetadata/recipe"; import UserMetaData from "../../usermetadata"; +// Old format. Commented and kept for review purposes +// type User = { +// id: string; +// isPrimaryUser: boolean; +// firstName?: string; +// lastName?: string; +// emails: string[]; +// phoneNumbers: string[]; +// thirdpartyInfo: { +// thirdpartyId: string; +// thirdpartyUserId: string; +// }[]; +// linkedRecipes: { +// recipeId: string; +// recipeUserId: string; +// }[]; +// }; + type User = { - id: string; + id: string; // primaryUserId or recipeUserId + timeJoined: number; // minimum timeJoined value from linkedRecipes isPrimaryUser: boolean; - firstName?: string; - lastName?: string; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; - }[]; - linkedRecipes: { + firstName?: string; + lastName?: string; + loginMethods: { recipeId: string; recipeUserId: string; + timeJoined: number; + verified: boolean; + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; }[]; }; diff --git a/lib/ts/recipe/dashboard/utils.ts b/lib/ts/recipe/dashboard/utils.ts index 44a985d30..a5ba99d91 100644 --- a/lib/ts/recipe/dashboard/utils.ts +++ b/lib/ts/recipe/dashboard/utils.ts @@ -39,14 +39,7 @@ import { TypeInput, TypeNormalisedInput, } from "./types"; -import EmailPasswordRecipe from "../emailpassword/recipe"; -import ThirdPartyRecipe from "../thirdparty/recipe"; -import PasswordlessRecipe from "../passwordless/recipe"; -import EmailPassword from "../emailpassword"; -import ThirdParty from "../thirdparty"; -import Passwordless from "../passwordless"; -import ThirdPartyEmailPassword from "../thirdpartyemailpassword"; -import ThirdPartyPasswordless from "../thirdpartypasswordless"; +import { getUserForRecipeId as getUserForRecipeIdAccountLinking } from "../accountlinking/utils"; export function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput { if (config.apiKey.trim().length === 0) { @@ -157,134 +150,17 @@ export async function getUserForRecipeId( | "thirdpartypasswordless" | undefined; }> { - let user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined; - let recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; - - if (recipeId === EmailPasswordRecipe.RECIPE_ID) { - try { - const userResponse = await EmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - firstName: "", - lastName: "", - }; - recipe = "emailpassword"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - firstName: "", - lastName: "", - }; - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === ThirdPartyRecipe.RECIPE_ID) { - try { - const userResponse = await ThirdParty.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - firstName: "", - lastName: "", - }; - recipe = "thirdparty"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - firstName: "", - lastName: "", - }; - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyPasswordless.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - firstName: "", - lastName: "", - }; - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === PasswordlessRecipe.RECIPE_ID) { - try { - const userResponse = await Passwordless.getUserById({ - userId, - }); - - if (userResponse !== undefined) { - user = { - ...userResponse, - firstName: "", - lastName: "", - }; - recipe = "passwordless"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyPasswordless.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - firstName: "", - lastName: "", - }; - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } + let userResponse = await getUserForRecipeIdAccountLinking(userId, recipeId); + let user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined = undefined; + if (userResponse.user !== undefined) { + user = { + ...userResponse.user, + firstName: "", + lastName: "", + }; } - return { user, - recipe, + recipe: userResponse.recipe, }; } diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index 89e72ae0e..2d3ee0e66 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -217,23 +217,6 @@ export default class SuperTokens { }; }; - deleteUser = async (input: { userId: string; removeAllLinkedAccounts: boolean }): Promise<{ status: "OK" }> => { - let querier = Querier.getNewInstanceOrThrowError(undefined); - let cdiVersion = await querier.getAPIVersion(); - if (maxVersion("2.10", cdiVersion) === cdiVersion) { - // delete user is only available >= CDI 2.10 - await querier.sendPostRequest(new NormalisedURLPath("/user/remove"), { - userId: input.userId, - }); - - return { - status: "OK", - }; - } else { - throw new global.Error("Please upgrade the SuperTokens core to >= 3.7.0"); - } - }; - createUserIdMapping = async function (input: { superTokensUserId: string; externalUserId: string; diff --git a/lib/ts/types.ts b/lib/ts/types.ts index d6c532d19..719b67b9f 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -73,17 +73,22 @@ export type GeneralErrorResponse = { }; export type User = { - id: string; + id: string; // primaryUserId or recipeUserId + timeJoined: number; // minimum timeJoined value from linkedRecipes isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; - }[]; - linkedRecipes: { - // this will always have one item in the array regardless of whether it's a primaryUser or a recipeUser + + loginMethods: { recipeId: string; recipeUserId: string; + timeJoined: number; + verified: boolean; + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; }[]; }; From c56aae39f57043ca2f1dd72190a0a708c4be5e9a Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 16 Jan 2023 13:49:00 +0530 Subject: [PATCH 18/82] code review changes --- lib/build/index.js | 12 +++++--- lib/build/recipe/accountlinking/index.d.ts | 11 ------- lib/build/recipe/accountlinking/index.js | 12 -------- lib/build/recipe/accountlinking/recipe.d.ts | 2 +- lib/build/recipe/accountlinking/recipe.js | 4 +-- lib/build/recipe/dashboard/api/usersGet.js | 17 +++++++---- lib/build/supertokens.d.ts | 10 ------- lib/build/supertokens.js | 24 --------------- lib/ts/index.ts | 6 ++-- lib/ts/recipe/accountlinking/index.ts | 16 ---------- lib/ts/recipe/dashboard/api/usersGet.ts | 17 +++++++---- lib/ts/supertokens.ts | 33 --------------------- 12 files changed, 37 insertions(+), 127 deletions(-) diff --git a/lib/build/index.js b/lib/build/index.js index 43536c30d..1852ca7bb 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -57,14 +57,18 @@ class SuperTokensWrapper { return supertokens_1.default.getInstanceOrThrowError().getUserCount(includeRecipeIds); } static getUsersOldestFirst(input) { - return supertokens_1.default + return recipe_1.default .getInstanceOrThrowError() - .getUsers(Object.assign({ timeJoinedOrder: "ASC" }, input)); + .recipeInterfaceImpl.getUsers( + Object.assign(Object.assign({ timeJoinedOrder: "ASC" }, input), { userContext: undefined }) + ); } static getUsersNewestFirst(input) { - return supertokens_1.default + return recipe_1.default .getInstanceOrThrowError() - .getUsers(Object.assign({ timeJoinedOrder: "DESC" }, input)); + .recipeInterfaceImpl.getUsers( + Object.assign(Object.assign({ timeJoinedOrder: "DESC" }, input), { userContext: undefined }) + ); } static createUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().createUserIdMapping(input); diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 092367e09..06f395ee2 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -24,16 +24,6 @@ export default class Wrapper { status: "OK"; createdNewEntry: boolean; }>; - static getUsers( - timeJoinedOrder: "ASC" | "DESC", - limit: number | undefined, - paginationToken: string | undefined, - includeRecipeIds: string[] | undefined, - userContext?: any - ): Promise<{ - users: import("../../types").User[]; - nextPaginationToken?: string | undefined; - }>; static canCreatePrimaryUserId( recipeUserId: string, userContext?: any @@ -128,7 +118,6 @@ export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; export declare const getPrimaryUserIdsforRecipeUserIds: typeof Wrapper.getPrimaryUserIdsforRecipeUserIds; export declare const addNewRecipeUserIdWithoutPrimaryUserId: typeof Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; -export declare const getUsers: typeof Wrapper.getUsers; export declare const canCreatePrimaryUserId: typeof Wrapper.canCreatePrimaryUserId; export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 7652cb1b2..71f480c45 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -79,17 +79,6 @@ class Wrapper { }); }); } - static getUsers(timeJoinedOrder, limit, paginationToken, includeRecipeIds, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsers({ - timeJoinedOrder, - limit, - paginationToken, - includeRecipeIds, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } static canCreatePrimaryUserId(recipeUserId, userContext) { return __awaiter(this, void 0, void 0, function* () { return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.canCreatePrimaryUserId({ @@ -139,7 +128,6 @@ exports.init = Wrapper.init; exports.getRecipeUserIdsForPrimaryUserIds = Wrapper.getRecipeUserIdsForPrimaryUserIds; exports.getPrimaryUserIdsforRecipeUserIds = Wrapper.getPrimaryUserIdsforRecipeUserIds; exports.addNewRecipeUserIdWithoutPrimaryUserId = Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; -exports.getUsers = Wrapper.getUsers; exports.canCreatePrimaryUserId = Wrapper.canCreatePrimaryUserId; exports.createPrimaryUser = Wrapper.createPrimaryUser; exports.canLinkAccounts = Wrapper.canLinkAccounts; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index f19b148d4..7327c716e 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -52,7 +52,7 @@ export default class Recipe extends RecipeModule { info: AccountInfoAndEmailWithRecipeId; userContext: any; }) => Promise; - createPrimaryUserIdOrLinkAccountPostSignUp: ({ + doPostSignUpAccountLinkingOperations: ({ info, infoVerified, recipeUserId, diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 6bb729416..8e0c30b88 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -141,7 +141,7 @@ class Recipe extends recipeModule_1.default { } throw Error("it should never reach here"); }); - this.createPrimaryUserIdOrLinkAccountPostSignUp = ({ info, infoVerified, recipeUserId, userContext }) => + this.doPostSignUpAccountLinkingOperations = ({ info, infoVerified, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( info, @@ -167,7 +167,7 @@ class Recipe extends recipeModule_1.default { userContext, }); if (user.status !== "OK") { - throw Error(user.status); + throw Error("should never come here. Error from createPrimaryUser: " + user.status); } return user.user.id; } diff --git a/lib/build/recipe/dashboard/api/usersGet.js b/lib/build/recipe/dashboard/api/usersGet.js index aab9dc97e..cbc3a9044 100644 --- a/lib/build/recipe/dashboard/api/usersGet.js +++ b/lib/build/recipe/dashboard/api/usersGet.js @@ -32,7 +32,7 @@ var __awaiter = }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../../../error"); -const supertokens_1 = require("../../../supertokens"); +const __1 = require("../../.."); const recipe_1 = require("../../usermetadata/recipe"); const usermetadata_1 = require("../../usermetadata"); function usersGet(_, options) { @@ -56,11 +56,16 @@ function usersGet(_, options) { }); } let paginationToken = options.req.getKeyValueFromQuery("paginationToken"); - let usersResponse = yield supertokens_1.default.getInstanceOrThrowError().getUsers({ - timeJoinedOrder: timeJoinedOrder, - limit: parseInt(limit), - paginationToken, - }); + let usersResponse = + timeJoinedOrder === "DESC" + ? yield __1.getUsersNewestFirst({ + limit: parseInt(limit), + paginationToken, + }) + : yield __1.getUsersOldestFirst({ + limit: parseInt(limit), + paginationToken, + }); // If the UserMetaData recipe has been initialised, fetch first and last name try { recipe_1.default.getInstanceOrThrowError(); diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 98b18b20a..3e85b0460 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -4,7 +4,6 @@ import RecipeModule from "./recipeModule"; import NormalisedURLPath from "./normalisedURLPath"; import { BaseRequest, BaseResponse } from "./framework"; import { TypeFramework } from "./framework/types"; -import { User } from "./types"; export default class SuperTokens { private static instance; framework: TypeFramework; @@ -27,15 +26,6 @@ export default class SuperTokens { ) => Promise; getAllCORSHeaders: () => string[]; getUserCount: (includeRecipeIds?: string[] | undefined) => Promise; - getUsers: (input: { - timeJoinedOrder: "ASC" | "DESC"; - limit?: number | undefined; - paginationToken?: string | undefined; - includeRecipeIds?: string[] | undefined; - }) => Promise<{ - users: User[]; - nextPaginationToken?: string | undefined; - }>; createUserIdMapping: (input: { superTokensUserId: string; externalUserId: string; diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index a57d37f7d..af462eb42 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -114,30 +114,6 @@ class SuperTokens { }); return Number(response.count); }); - this.getUsers = (input) => - __awaiter(this, void 0, void 0, function* () { - let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); - let apiVersion = yield querier.getAPIVersion(); - if (utils_1.maxVersion(apiVersion, "2.7") === "2.7") { - throw new Error( - "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUsersOldestFirst() or .getUsersNewestFirst() instead (for example, EmailPassword.getUsersOldestFirst())" - ); - } - let includeRecipeIdsStr = undefined; - if (input.includeRecipeIds !== undefined) { - includeRecipeIdsStr = input.includeRecipeIds.join(","); - } - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users"), { - includeRecipeIds: includeRecipeIdsStr, - timeJoinedOrder: input.timeJoinedOrder, - limit: input.limit, - paginationToken: input.paginationToken, - }); - return { - users: response.users, - nextPaginationToken: response.nextPaginationToken, - }; - }); this.createUserIdMapping = function (input) { return __awaiter(this, void 0, void 0, function* () { let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); diff --git a/lib/ts/index.ts b/lib/ts/index.ts index 4b611397f..45eb6894f 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -41,9 +41,10 @@ export default class SuperTokensWrapper { users: User[]; nextPaginationToken?: string; }> { - return SuperTokens.getInstanceOrThrowError().getUsers({ + return AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.getUsers({ timeJoinedOrder: "ASC", ...input, + userContext: undefined, }); } @@ -55,9 +56,10 @@ export default class SuperTokensWrapper { users: User[]; nextPaginationToken?: string; }> { - return SuperTokens.getInstanceOrThrowError().getUsers({ + return AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.getUsers({ timeJoinedOrder: "DESC", ...input, + userContext: undefined, }); } diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index b518a21be..a7fd3604c 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -44,21 +44,6 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } - static async getUsers( - timeJoinedOrder: "ASC" | "DESC", - limit: number | undefined, - paginationToken: string | undefined, - includeRecipeIds: string[] | undefined, - userContext?: any - ) { - return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUsers({ - timeJoinedOrder, - limit, - paginationToken, - includeRecipeIds, - userContext: userContext === undefined ? {} : userContext, - }); - } static async canCreatePrimaryUserId(recipeUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.canCreatePrimaryUserId({ recipeUserId, @@ -97,7 +82,6 @@ export const init = Wrapper.init; export const getRecipeUserIdsForPrimaryUserIds = Wrapper.getRecipeUserIdsForPrimaryUserIds; export const getPrimaryUserIdsforRecipeUserIds = Wrapper.getPrimaryUserIdsforRecipeUserIds; export const addNewRecipeUserIdWithoutPrimaryUserId = Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; -export const getUsers = Wrapper.getUsers; export const canCreatePrimaryUserId = Wrapper.canCreatePrimaryUserId; export const createPrimaryUser = Wrapper.createPrimaryUser; export const canLinkAccounts = Wrapper.canLinkAccounts; diff --git a/lib/ts/recipe/dashboard/api/usersGet.ts b/lib/ts/recipe/dashboard/api/usersGet.ts index 1714856b9..51cd05933 100644 --- a/lib/ts/recipe/dashboard/api/usersGet.ts +++ b/lib/ts/recipe/dashboard/api/usersGet.ts @@ -14,7 +14,7 @@ */ import { APIInterface, APIOptions } from "../types"; import STError from "../../../error"; -import SuperTokens from "../../../supertokens"; +import { getUsersNewestFirst, getUsersOldestFirst } from "../../.."; import UserMetaDataRecipe from "../../usermetadata/recipe"; import UserMetaData from "../../usermetadata"; @@ -90,11 +90,16 @@ export default async function usersGet(_: APIInterface, options: APIOptions): Pr let paginationToken = options.req.getKeyValueFromQuery("paginationToken"); - let usersResponse = await SuperTokens.getInstanceOrThrowError().getUsers({ - timeJoinedOrder: timeJoinedOrder, - limit: parseInt(limit), - paginationToken, - }); + let usersResponse = + timeJoinedOrder === "DESC" + ? await getUsersNewestFirst({ + limit: parseInt(limit), + paginationToken, + }) + : await getUsersOldestFirst({ + limit: parseInt(limit), + paginationToken, + }); // If the UserMetaData recipe has been initialised, fetch first and last name try { diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index 2d3ee0e66..448338558 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -31,7 +31,6 @@ import { TypeFramework } from "./framework/types"; import STError from "./error"; import { logDebugMessage } from "./logger"; import { PostSuperTokensInitCallbacks } from "./postSuperTokensInitCallbacks"; -import { User } from "./types"; export default class SuperTokens { private static instance: SuperTokens | undefined; @@ -185,38 +184,6 @@ export default class SuperTokens { return Number(response.count); }; - getUsers = async (input: { - timeJoinedOrder: "ASC" | "DESC"; - limit?: number; - paginationToken?: string; - includeRecipeIds?: string[]; - }): Promise<{ - users: User[]; - nextPaginationToken?: string; - }> => { - let querier = Querier.getNewInstanceOrThrowError(undefined); - let apiVersion = await querier.getAPIVersion(); - if (maxVersion(apiVersion, "2.7") === "2.7") { - throw new Error( - "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUsersOldestFirst() or .getUsersNewestFirst() instead (for example, EmailPassword.getUsersOldestFirst())" - ); - } - let includeRecipeIdsStr = undefined; - if (input.includeRecipeIds !== undefined) { - includeRecipeIdsStr = input.includeRecipeIds.join(","); - } - let response = await querier.sendGetRequest(new NormalisedURLPath("/users"), { - includeRecipeIds: includeRecipeIdsStr, - timeJoinedOrder: input.timeJoinedOrder, - limit: input.limit, - paginationToken: input.paginationToken, - }); - return { - users: response.users, - nextPaginationToken: response.nextPaginationToken, - }; - }; - createUserIdMapping = async function (input: { superTokensUserId: string; externalUserId: string; From bb44a895c35f99a268fc5a8cc32a3c04a0f91e41 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 16 Jan 2023 13:55:25 +0530 Subject: [PATCH 19/82] code review changes --- lib/build/recipe/accountlinking/recipe.js | 2 +- lib/build/supertokens.js | 7 +++++++ lib/ts/recipe/accountlinking/recipe.ts | 2 +- lib/ts/supertokens.ts | 5 +++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 8e0c30b88..db17de147 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -504,7 +504,7 @@ class Recipe extends recipeModule_1.default { } static init(config) { return (appInfo) => { - if (Recipe.instance !== undefined) { + if (Recipe.instance === undefined) { Recipe.instance = new Recipe( Recipe.RECIPE_ID, appInfo, diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index af462eb42..9b8461071 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -54,6 +54,7 @@ const normalisedURLPath_1 = require("./normalisedURLPath"); const error_1 = require("./error"); const logger_1 = require("./logger"); const postSuperTokensInitCallbacks_1 = require("./postSuperTokensInitCallbacks"); +const recipe_1 = require("./recipe/accountlinking/recipe"); class SuperTokens { constructor(config) { var _a, _b; @@ -326,6 +327,12 @@ class SuperTokens { this.recipeModules = config.recipeList.map((func) => { return func(this.appInfo, this.isInServerlessEnv); }); + let isAccountLinkingInitialised = this.recipeModules.find( + (r) => r.getRecipeId() === recipe_1.default.RECIPE_ID + ); + if (!isAccountLinkingInitialised) { + this.recipeModules.push(recipe_1.default.init({})(this.appInfo, this.isInServerlessEnv)); + } let telemetry = config.telemetry === undefined ? process.env.TEST_MODE !== "testing" : config.telemetry; if (telemetry) { if (this.isInServerlessEnv) { diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 7266b98a9..6870859eb 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -56,7 +56,7 @@ export default class Recipe extends RecipeModule { static init(config: TypeInput): RecipeListFunction { return (appInfo) => { - if (Recipe.instance !== undefined) { + if (Recipe.instance === undefined) { Recipe.instance = new Recipe( Recipe.RECIPE_ID, appInfo, diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index 448338558..f4b4a03bd 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -31,6 +31,7 @@ import { TypeFramework } from "./framework/types"; import STError from "./error"; import { logDebugMessage } from "./logger"; import { PostSuperTokensInitCallbacks } from "./postSuperTokensInitCallbacks"; +import AccountLinking from "./recipe/accountlinking/recipe"; export default class SuperTokens { private static instance: SuperTokens | undefined; @@ -82,6 +83,10 @@ export default class SuperTokens { return func(this.appInfo, this.isInServerlessEnv); }); + let isAccountLinkingInitialised = this.recipeModules.find((r) => r.getRecipeId() === AccountLinking.RECIPE_ID); + if (!isAccountLinkingInitialised) { + this.recipeModules.push(AccountLinking.init({})(this.appInfo, this.isInServerlessEnv)); + } let telemetry = config.telemetry === undefined ? process.env.TEST_MODE !== "testing" : config.telemetry; if (telemetry) { From 9c0c76690ebd99e617f2e74bcf4c45c4761168f8 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Thu, 19 Jan 2023 02:52:08 +0530 Subject: [PATCH 20/82] code review changes --- CHANGELOG.md | 11 ++ lib/build/index.d.ts | 14 ++ lib/build/index.js | 6 +- lib/build/recipe/accountlinking/index.d.ts | 41 ++++- lib/build/recipe/accountlinking/index.js | 31 ++++ lib/build/recipe/accountlinking/recipe.js | 10 +- .../accountlinking/recipeImplementation.js | 21 +-- lib/build/recipe/accountlinking/utils.d.ts | 15 +- lib/build/recipe/accountlinking/utils.js | 96 ------------ lib/build/recipe/dashboard/api/usersGet.d.ts | 18 +-- lib/build/recipe/dashboard/utils.js | 4 +- lib/build/supertokens.d.ts | 14 ++ lib/build/supertokens.js | 94 +++++++++++ lib/build/types.d.ts | 18 +-- lib/ts/index.ts | 8 +- lib/ts/recipe/accountlinking/index.ts | 48 +++++- lib/ts/recipe/accountlinking/recipe.ts | 11 +- .../accountlinking/recipeImplementation.ts | 19 +-- lib/ts/recipe/accountlinking/utils.ts | 146 ----------------- lib/ts/recipe/dashboard/api/usersGet.ts | 36 +---- lib/ts/recipe/dashboard/utils.ts | 4 +- lib/ts/supertokens.ts | 147 ++++++++++++++++++ lib/ts/types.ts | 19 +-- 23 files changed, 469 insertions(+), 362 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4873226ea..c017736f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [unreleased] +### Added: + +- Account-Linking Recipe added +- Functions `getUserForRecipeId`, `getUserByAccountInfo`, `listUsersByAccountInfo` and `getUser` added + +### Changed: + +- Type of `User` object returned by get users function +- Functions `deleteuser`, `getUsersNewestFirst` and `getUsersOldestFirst` are now based on account linking recipe +- Function `deleteuser` takes a new parameter `removeAllLinkedAccounts` which will be `true` by default + ## [12.1.0] - 2022-11-17 ### Added: diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index 9bb313ba5..2868b27a1 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -39,6 +39,19 @@ export default class SuperTokensWrapper { doesExternalUserIdExist: boolean; } >; + static getUserForRecipeId( + userId: string, + recipeId: string + ): Promise<{ + user: import("./recipe/accountlinking/types").RecipeLevelUser | undefined; + recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; + }>; static getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; @@ -92,4 +105,5 @@ export declare let updateOrDeleteUserIdMappingInfo: typeof SuperTokensWrapper.up export declare let getUser: typeof SuperTokensWrapper.getUser; export declare let listUsersByAccountInfo: typeof SuperTokensWrapper.listUsersByAccountInfo; export declare let getUserByAccountInfo: typeof SuperTokensWrapper.getUserByAccountInfo; +export declare let getUserForRecipeId: typeof SuperTokensWrapper.getUserForRecipeId; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/index.js b/lib/build/index.js index 1852ca7bb..f7a35dd5c 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -73,6 +73,9 @@ class SuperTokensWrapper { static createUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().createUserIdMapping(input); } + static getUserForRecipeId(userId, recipeId) { + return supertokens_1.default.getInstanceOrThrowError().getUserForRecipeId(userId, recipeId); + } static getUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().getUserIdMapping(input); } @@ -106,7 +109,7 @@ class SuperTokensWrapper { }); }); } - static deleteUser(userId, removeAllLinkedAccounts = false, userContext) { + static deleteUser(userId, removeAllLinkedAccounts = true, userContext) { return __awaiter(this, void 0, void 0, function* () { return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ userId, @@ -132,4 +135,5 @@ exports.updateOrDeleteUserIdMappingInfo = SuperTokensWrapper.updateOrDeleteUserI exports.getUser = SuperTokensWrapper.getUser; exports.listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; exports.getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; +exports.getUserForRecipeId = SuperTokensWrapper.getUserForRecipeId; exports.Error = SuperTokensWrapper.Error; diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 06f395ee2..b34b0e0e8 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,6 +1,7 @@ // @ts-nocheck +import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { RecipeInterface } from "./types"; +import type { AccountInfoAndEmailWithRecipeId, RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static getRecipeUserIdsForPrimaryUserIds( @@ -113,6 +114,41 @@ export default class Wrapper { status: "NO_PRIMARY_USER_FOUND"; } >; + static isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any): Promise; + static doPostSignUpAccountLinkingOperations( + info: AccountInfoAndEmailWithRecipeId, + infoVerified: boolean, + recipeUserId: string, + userContext: any + ): Promise; + static accountLinkPostSignInViaSession( + session: SessionContainer, + info: AccountInfoAndEmailWithRecipeId, + infoVerified: boolean, + userContext: any + ): Promise< + | { + createRecipeUser: true; + updateVerificationClaim: boolean; + } + | ({ + createRecipeUser: false; + } & { + accountsLinked: true; + updateVerificationClaim: boolean; + }) + | ({ + createRecipeUser: false; + } & { + accountsLinked: false; + reason: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" + | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + }) + >; } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; @@ -123,4 +159,7 @@ export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; export declare const linkAccounts: typeof Wrapper.linkAccounts; export declare const unlinkAccounts: typeof Wrapper.unlinkAccounts; +export declare const isSignUpAllowed: typeof Wrapper.isSignUpAllowed; +export declare const doPostSignUpAccountLinkingOperations: typeof Wrapper.doPostSignUpAccountLinkingOperations; +export declare const accountLinkPostSignInViaSession: typeof Wrapper.accountLinkPostSignInViaSession; export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 71f480c45..798b2ed2b 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -121,6 +121,34 @@ class Wrapper { }); }); } + static isSignUpAllowed(info, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().isSignUpAllowed({ + info, + userContext, + }); + }); + } + static doPostSignUpAccountLinkingOperations(info, infoVerified, recipeUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations({ + info, + infoVerified, + recipeUserId, + userContext, + }); + }); + } + static accountLinkPostSignInViaSession(session, info, infoVerified, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + session, + info, + infoVerified, + userContext, + }); + }); + } } exports.default = Wrapper; Wrapper.init = recipe_1.default.init; @@ -133,3 +161,6 @@ exports.createPrimaryUser = Wrapper.createPrimaryUser; exports.canLinkAccounts = Wrapper.canLinkAccounts; exports.linkAccounts = Wrapper.linkAccounts; exports.unlinkAccounts = Wrapper.unlinkAccounts; +exports.isSignUpAllowed = Wrapper.isSignUpAllowed; +exports.doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; +exports.accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index db17de147..3799c3009 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -46,8 +46,8 @@ var __awaiter = }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); -const supertokens_1 = require("../../supertokens"); const utils_1 = require("./utils"); +const __1 = require("../.."); const supertokens_js_override_1 = require("supertokens-js-override"); const recipeImplementation_1 = require("./recipeImplementation"); const querier_1 = require("../../querier"); @@ -242,7 +242,7 @@ class Recipe extends recipeModule_1.default { }; } let recipeId = user.loginMethods[0].recipeId; - let recipeUser = yield utils_1.getUserForRecipeId(user.id, recipeId); + let recipeUser = yield __1.getUserForRecipeId(user.id, recipeId); if (recipeUser.user === undefined) { throw Error( "This error should never be thrown. Check for bug in `getUserForRecipeId` function" @@ -521,12 +521,6 @@ class Recipe extends recipeModule_1.default { }; } static getInstanceOrThrowError() { - if (Recipe.instance === undefined) { - Recipe.init({})( - supertokens_1.default.getInstanceOrThrowError().appInfo, - supertokens_1.default.getInstanceOrThrowError().isInServerlessEnv - ); - } if (Recipe.instance !== undefined) { return Recipe.instance; } diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index bb70e0da3..26cca2d21 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -47,7 +47,7 @@ var __awaiter = Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); const session_1 = require("../session"); -const utils_1 = require("./utils"); +const __1 = require("../.."); function getRecipeImplementation(querier, config) { return { getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { @@ -147,24 +147,25 @@ function getRecipeImplementation(querier, config) { let usersForAccountInfo = []; for (let i = 0; i < user.loginMethods.length; i++) { let loginMethod = user.loginMethods[i]; - let info = undefined; + let infos = []; if (loginMethod.email !== undefined) { - info = { + infos.push({ email: loginMethod.email, - }; + }); } if (loginMethod.phoneNumber !== undefined) { - info = { + infos.push({ phoneNumber: loginMethod.phoneNumber, - }; + }); } if (loginMethod.thirdParty !== undefined) { - info = { + infos.push({ thirdpartyId: loginMethod.thirdParty.id, thirdpartyUserId: loginMethod.thirdParty.userId, - }; + }); } - if (info !== undefined) { + for (let j = 0; j < infos.length; j++) { + let info = infos[j]; let usersList = yield this.listUsersByAccountInfo({ info, userContext, @@ -315,7 +316,7 @@ function getRecipeImplementation(querier, config) { if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = yield utils_1.getUserForRecipeId( + let recipeUser = yield __1.getUserForRecipeId( loginMethodInfo.recipeUserId, loginMethodInfo.recipeId ); diff --git a/lib/build/recipe/accountlinking/utils.d.ts b/lib/build/recipe/accountlinking/utils.d.ts index 45b3bce43..687c0db39 100644 --- a/lib/build/recipe/accountlinking/utils.d.ts +++ b/lib/build/recipe/accountlinking/utils.d.ts @@ -1,17 +1,4 @@ // @ts-nocheck import type { NormalisedAppinfo } from "../../types"; -import type { TypeInput, RecipeLevelUser, TypeNormalisedInput } from "./types"; +import type { TypeInput, TypeNormalisedInput } from "./types"; export declare function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; -export declare function getUserForRecipeId( - userId: string, - recipeId: string -): Promise<{ - user: RecipeLevelUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; -}>; diff --git a/lib/build/recipe/accountlinking/utils.js b/lib/build/recipe/accountlinking/utils.js index 4fe8d6c3b..632652d47 100644 --- a/lib/build/recipe/accountlinking/utils.js +++ b/lib/build/recipe/accountlinking/utils.js @@ -45,14 +45,6 @@ var __awaiter = }); }; Object.defineProperty(exports, "__esModule", { value: true }); -const recipe_1 = require("../emailpassword/recipe"); -const recipe_2 = require("../thirdparty/recipe"); -const recipe_3 = require("../passwordless/recipe"); -const emailpassword_1 = require("../emailpassword"); -const thirdparty_1 = require("../thirdparty"); -const passwordless_1 = require("../passwordless"); -const thirdpartyemailpassword_1 = require("../thirdpartyemailpassword"); -const thirdpartypasswordless_1 = require("../thirdpartypasswordless"); function defaultOnAccountLinked(_user, _newAccountInfo, _userContext) { return __awaiter(this, void 0, void 0, function* () {}); } @@ -75,91 +67,3 @@ function validateAndNormaliseUserInput(_, config) { }; } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; -function getUserForRecipeId(userId, recipeId) { - return __awaiter(this, void 0, void 0, function* () { - let user; - let recipe; - if (recipeId === recipe_1.default.RECIPE_ID) { - try { - const userResponse = yield emailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); - recipe = "emailpassword"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === recipe_2.default.RECIPE_ID) { - try { - const userResponse = yield thirdparty_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdparty"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === recipe_3.default.RECIPE_ID) { - try { - const userResponse = yield passwordless_1.default.getUserById({ - userId, - }); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); - recipe = "passwordless"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } - return { - user, - recipe, - }; - }); -} -exports.getUserForRecipeId = getUserForRecipeId; diff --git a/lib/build/recipe/dashboard/api/usersGet.d.ts b/lib/build/recipe/dashboard/api/usersGet.d.ts index baa83fa49..ec90a7275 100644 --- a/lib/build/recipe/dashboard/api/usersGet.d.ts +++ b/lib/build/recipe/dashboard/api/usersGet.d.ts @@ -1,25 +1,21 @@ // @ts-nocheck import { APIInterface, APIOptions } from "../types"; +import { RecipeLevelUser } from "../../accountlinking/types"; declare type User = { id: string; timeJoined: number; isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; + }[]; firstName?: string; lastName?: string; - loginMethods: { - recipeId: string; - recipeUserId: string; - timeJoined: number; + loginMethods: (RecipeLevelUser & { verified: boolean; - email?: string; - phoneNumber?: string; - thirdParty?: { - id: string; - userId: string; - }; - }[]; + })[]; }; export declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/utils.js b/lib/build/recipe/dashboard/utils.js index 75e6b67be..7020add55 100644 --- a/lib/build/recipe/dashboard/utils.js +++ b/lib/build/recipe/dashboard/utils.js @@ -48,7 +48,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); const utils_1 = require("../../utils"); const constants_1 = require("./constants"); -const utils_2 = require("../accountlinking/utils"); +const __1 = require("../.."); function validateAndNormaliseUserInput(config) { if (config.apiKey.trim().length === 0) { throw new Error("apiKey provided to Dashboard recipe cannot be empty"); @@ -135,7 +135,7 @@ function isValidRecipeId(recipeId) { exports.isValidRecipeId = isValidRecipeId; function getUserForRecipeId(userId, recipeId) { return __awaiter(this, void 0, void 0, function* () { - let userResponse = yield utils_2.getUserForRecipeId(userId, recipeId); + let userResponse = yield __1.default.getUserForRecipeId(userId, recipeId); let user = undefined; if (userResponse.user !== undefined) { user = Object.assign(Object.assign({}, userResponse.user), { firstName: "", lastName: "" }); diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 3e85b0460..158fca09b 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -4,6 +4,7 @@ import RecipeModule from "./recipeModule"; import NormalisedURLPath from "./normalisedURLPath"; import { BaseRequest, BaseResponse } from "./framework"; import { TypeFramework } from "./framework/types"; +import { RecipeLevelUser } from "./recipe/accountlinking/types"; export default class SuperTokens { private static instance; framework: TypeFramework; @@ -72,4 +73,17 @@ export default class SuperTokens { }>; middleware: (request: BaseRequest, response: BaseResponse) => Promise; errorHandler: (err: any, request: BaseRequest, response: BaseResponse) => Promise; + getUserForRecipeId: ( + userId: string, + recipeId: string + ) => Promise<{ + user: RecipeLevelUser | undefined; + recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; + }>; } diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index 9b8461071..b80eeae29 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -55,6 +55,14 @@ const error_1 = require("./error"); const logger_1 = require("./logger"); const postSuperTokensInitCallbacks_1 = require("./postSuperTokensInitCallbacks"); const recipe_1 = require("./recipe/accountlinking/recipe"); +const recipe_2 = require("./recipe/emailpassword/recipe"); +const recipe_3 = require("./recipe/thirdparty/recipe"); +const recipe_4 = require("./recipe/passwordless/recipe"); +const emailpassword_1 = require("./recipe/emailpassword"); +const thirdparty_1 = require("./recipe/thirdparty"); +const passwordless_1 = require("./recipe/passwordless"); +const thirdpartyemailpassword_1 = require("./recipe/thirdpartyemailpassword"); +const thirdpartypasswordless_1 = require("./recipe/thirdpartypasswordless"); class SuperTokens { constructor(config) { var _a, _b; @@ -295,6 +303,92 @@ class SuperTokens { } throw err; }); + this.getUserForRecipeId = (userId, recipeId) => + __awaiter(this, void 0, void 0, function* () { + let user; + let recipe; + if (recipeId === recipe_2.default.RECIPE_ID) { + try { + const userResponse = yield emailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); + recipe = "emailpassword"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === recipe_3.default.RECIPE_ID) { + try { + const userResponse = yield thirdparty_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdparty"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + if (user === undefined) { + try { + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === recipe_4.default.RECIPE_ID) { + try { + const userResponse = yield passwordless_1.default.getUserById({ + userId, + }); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); + recipe = "passwordless"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } + return { + user, + recipe, + }; + }); logger_1.logDebugMessage("Started SuperTokens with debug logging (supertokens.init called)"); logger_1.logDebugMessage("appInfo: " + JSON.stringify(config.appInfo)); this.framework = config.framework !== undefined ? config.framework : "express"; diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index 1b775c9d0..593ed2a96 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -3,6 +3,7 @@ import RecipeModule from "./recipeModule"; import NormalisedURLDomain from "./normalisedURLDomain"; import NormalisedURLPath from "./normalisedURLPath"; import { TypeFramework } from "./framework/types"; +import { RecipeLevelUser } from "./recipe/accountlinking/types"; export declare type AppInfo = { appName: string; websiteDomain: string; @@ -55,16 +56,11 @@ export declare type User = { isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - loginMethods: { - recipeId: string; - recipeUserId: string; - timeJoined: number; - verified: boolean; - email?: string; - phoneNumber?: string; - thirdParty?: { - id: string; - userId: string; - }; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; }[]; + loginMethods: (RecipeLevelUser & { + verified: boolean; + })[]; }; diff --git a/lib/ts/index.ts b/lib/ts/index.ts index 45eb6894f..098f8b330 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -72,6 +72,10 @@ export default class SuperTokensWrapper { return SuperTokens.getInstanceOrThrowError().createUserIdMapping(input); } + static getUserForRecipeId(userId: string, recipeId: string) { + return SuperTokens.getInstanceOrThrowError().getUserForRecipeId(userId, recipeId); + } + static getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }) { return SuperTokens.getInstanceOrThrowError().getUserIdMapping(input); } @@ -110,7 +114,7 @@ export default class SuperTokensWrapper { userContext: userContext === undefined ? {} : userContext, }); } - static async deleteUser(userId: string, removeAllLinkedAccounts: boolean = false, userContext?: any) { + static async deleteUser(userId: string, removeAllLinkedAccounts: boolean = true, userContext?: any) { return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ userId, removeAllLinkedAccounts, @@ -145,4 +149,6 @@ export let listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; export let getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; +export let getUserForRecipeId = SuperTokensWrapper.getUserForRecipeId; + export let Error = SuperTokensWrapper.Error; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index a7fd3604c..3be040ab7 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -13,8 +13,9 @@ * under the License. */ +import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { RecipeInterface } from "./types"; +import type { AccountInfoAndEmailWithRecipeId, RecipeInterface } from "./types"; export default class Wrapper { static init = Recipe.init; @@ -25,12 +26,14 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } + static async getPrimaryUserIdsforRecipeUserIds(recipeUserIds: string[], userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds, userContext: userContext === undefined ? {} : userContext, }); } + static async addNewRecipeUserIdWithoutPrimaryUserId( recipeUserId: string, recipeId: string, @@ -44,18 +47,21 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } + static async canCreatePrimaryUserId(recipeUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.canCreatePrimaryUserId({ recipeUserId, userContext: userContext === undefined ? {} : userContext, }); } + static async createPrimaryUser(recipeUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.createPrimaryUser({ recipeUserId, userContext: userContext === undefined ? {} : userContext, }); } + static async canLinkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.canLinkAccounts({ recipeUserId, @@ -63,6 +69,7 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } + static async linkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ recipeUserId, @@ -70,12 +77,48 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } + static async unlinkAccounts(recipeUserId: string, userContext?: any) { return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.unlinkAccounts({ recipeUserId, userContext: userContext === undefined ? {} : userContext, }); } + + static async isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any) { + return await Recipe.getInstanceOrThrowError().isSignUpAllowed({ + info, + userContext, + }); + } + + static async doPostSignUpAccountLinkingOperations( + info: AccountInfoAndEmailWithRecipeId, + infoVerified: boolean, + recipeUserId: string, + userContext: any + ) { + return await Recipe.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations({ + info, + infoVerified, + recipeUserId, + userContext, + }); + } + + static async accountLinkPostSignInViaSession( + session: SessionContainer, + info: AccountInfoAndEmailWithRecipeId, + infoVerified: boolean, + userContext: any + ) { + return await Recipe.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + session, + info, + infoVerified, + userContext, + }); + } } export const init = Wrapper.init; @@ -87,5 +130,8 @@ export const createPrimaryUser = Wrapper.createPrimaryUser; export const canLinkAccounts = Wrapper.canLinkAccounts; export const linkAccounts = Wrapper.linkAccounts; export const unlinkAccounts = Wrapper.unlinkAccounts; +export const isSignUpAllowed = Wrapper.isSignUpAllowed; +export const doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; +export const accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; export type { RecipeInterface }; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 6870859eb..e82f51d1d 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -17,7 +17,6 @@ import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; -import SuperTokensModule from "../../supertokens"; import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction, User } from "../../types"; import { SessionContainer } from "../session"; import type { @@ -27,7 +26,8 @@ import type { AccountInfoAndEmailWithRecipeId, AccountInfoWithRecipeId, } from "./types"; -import { getUserForRecipeId, validateAndNormaliseUserInput } from "./utils"; +import { validateAndNormaliseUserInput } from "./utils"; +import { getUserForRecipeId } from "../.."; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; @@ -74,12 +74,6 @@ export default class Recipe extends RecipeModule { } static getInstanceOrThrowError(): Recipe { - if (Recipe.instance === undefined) { - Recipe.init({})( - SuperTokensModule.getInstanceOrThrowError().appInfo, - SuperTokensModule.getInstanceOrThrowError().isInServerlessEnv - ); - } if (Recipe.instance !== undefined) { return Recipe.instance; } @@ -247,6 +241,7 @@ export default class Recipe extends RecipeModule { } throw Error("it should never reach here"); }; + doPostSignUpAccountLinkingOperations = async ({ info, infoVerified, diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index f8b8f7efe..1aea5e777 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -18,7 +18,7 @@ import { Querier } from "../../querier"; import type { User } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; import Session from "../session"; -import { getUserForRecipeId } from "./utils"; +import { getUserForRecipeId } from "../.."; export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface { return { @@ -177,24 +177,25 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo for (let i = 0; i < user.loginMethods.length; i++) { let loginMethod = user.loginMethods[i]; - let info: AccountInfo | undefined = undefined; + let infos: AccountInfo[] = []; if (loginMethod.email !== undefined) { - info = { + infos.push({ email: loginMethod.email, - }; + }); } if (loginMethod.phoneNumber !== undefined) { - info = { + infos.push({ phoneNumber: loginMethod.phoneNumber, - }; + }); } if (loginMethod.thirdParty !== undefined) { - info = { + infos.push({ thirdpartyId: loginMethod.thirdParty.id, thirdpartyUserId: loginMethod.thirdParty.userId, - }; + }); } - if (info !== undefined) { + for (let j = 0; j < infos.length; j++) { + let info = infos[j]; let usersList = await this.listUsersByAccountInfo({ info, userContext, diff --git a/lib/ts/recipe/accountlinking/utils.ts b/lib/ts/recipe/accountlinking/utils.ts index bf228391b..ad89f631f 100644 --- a/lib/ts/recipe/accountlinking/utils.ts +++ b/lib/ts/recipe/accountlinking/utils.ts @@ -22,14 +22,6 @@ import type { TypeNormalisedInput, AccountInfoAndEmailWithRecipeId, } from "./types"; -import EmailPasswordRecipe from "../emailpassword/recipe"; -import ThirdPartyRecipe from "../thirdparty/recipe"; -import PasswordlessRecipe from "../passwordless/recipe"; -import EmailPassword from "../emailpassword"; -import ThirdParty from "../thirdparty"; -import Passwordless from "../passwordless"; -import ThirdPartyEmailPassword from "../thirdpartyemailpassword"; -import ThirdPartyPasswordless from "../thirdpartypasswordless"; async function defaultOnAccountLinked(_user: User, _newAccountInfo: RecipeLevelUser, _userContext: any) {} @@ -62,141 +54,3 @@ export function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: Type shouldDoAutomaticAccountLinking, }; } - -export async function getUserForRecipeId( - userId: string, - recipeId: string -): Promise<{ - user: RecipeLevelUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; -}> { - let user: RecipeLevelUser | undefined; - let recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; - - if (recipeId === EmailPasswordRecipe.RECIPE_ID) { - try { - const userResponse = await EmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "emailpassword", - }; - recipe = "emailpassword"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "emailpassword", - }; - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === ThirdPartyRecipe.RECIPE_ID) { - try { - const userResponse = await ThirdParty.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "thirdparty", - }; - recipe = "thirdparty"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "thirdparty", - }; - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyPasswordless.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "thirdparty", - }; - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === PasswordlessRecipe.RECIPE_ID) { - try { - const userResponse = await Passwordless.getUserById({ - userId, - }); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "passwordless", - }; - recipe = "passwordless"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyPasswordless.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "passwordless", - }; - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } - - return { - user, - recipe, - }; -} diff --git a/lib/ts/recipe/dashboard/api/usersGet.ts b/lib/ts/recipe/dashboard/api/usersGet.ts index 51cd05933..8c36dab68 100644 --- a/lib/ts/recipe/dashboard/api/usersGet.ts +++ b/lib/ts/recipe/dashboard/api/usersGet.ts @@ -17,24 +17,7 @@ import STError from "../../../error"; import { getUsersNewestFirst, getUsersOldestFirst } from "../../.."; import UserMetaDataRecipe from "../../usermetadata/recipe"; import UserMetaData from "../../usermetadata"; - -// Old format. Commented and kept for review purposes -// type User = { -// id: string; -// isPrimaryUser: boolean; -// firstName?: string; -// lastName?: string; -// emails: string[]; -// phoneNumbers: string[]; -// thirdpartyInfo: { -// thirdpartyId: string; -// thirdpartyUserId: string; -// }[]; -// linkedRecipes: { -// recipeId: string; -// recipeUserId: string; -// }[]; -// }; +import { RecipeLevelUser } from "../../accountlinking/types"; type User = { id: string; // primaryUserId or recipeUserId @@ -42,20 +25,15 @@ type User = { isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; + }[]; firstName?: string; lastName?: string; - loginMethods: { - recipeId: string; - recipeUserId: string; - timeJoined: number; + loginMethods: (RecipeLevelUser & { verified: boolean; - email?: string; - phoneNumber?: string; - thirdParty?: { - id: string; - userId: string; - }; - }[]; + })[]; }; export type Response = { diff --git a/lib/ts/recipe/dashboard/utils.ts b/lib/ts/recipe/dashboard/utils.ts index a5ba99d91..9b392e7c1 100644 --- a/lib/ts/recipe/dashboard/utils.ts +++ b/lib/ts/recipe/dashboard/utils.ts @@ -39,7 +39,7 @@ import { TypeInput, TypeNormalisedInput, } from "./types"; -import { getUserForRecipeId as getUserForRecipeIdAccountLinking } from "../accountlinking/utils"; +import Supertokens from "../.."; export function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput { if (config.apiKey.trim().length === 0) { @@ -150,7 +150,7 @@ export async function getUserForRecipeId( | "thirdpartypasswordless" | undefined; }> { - let userResponse = await getUserForRecipeIdAccountLinking(userId, recipeId); + let userResponse = await Supertokens.getUserForRecipeId(userId, recipeId); let user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined = undefined; if (userResponse.user !== undefined) { user = { diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index f4b4a03bd..752046342 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -32,6 +32,15 @@ import STError from "./error"; import { logDebugMessage } from "./logger"; import { PostSuperTokensInitCallbacks } from "./postSuperTokensInitCallbacks"; import AccountLinking from "./recipe/accountlinking/recipe"; +import { RecipeLevelUser } from "./recipe/accountlinking/types"; +import EmailPasswordRecipe from "./recipe/emailpassword/recipe"; +import ThirdPartyRecipe from "./recipe/thirdparty/recipe"; +import PasswordlessRecipe from "./recipe/passwordless/recipe"; +import EmailPassword from "./recipe/emailpassword"; +import ThirdParty from "./recipe/thirdparty"; +import Passwordless from "./recipe/passwordless"; +import ThirdPartyEmailPassword from "./recipe/thirdpartyemailpassword"; +import ThirdPartyPasswordless from "./recipe/thirdpartypasswordless"; export default class SuperTokens { private static instance: SuperTokens | undefined; @@ -395,4 +404,142 @@ export default class SuperTokens { } throw err; }; + + getUserForRecipeId = async ( + userId: string, + recipeId: string + ): Promise<{ + user: RecipeLevelUser | undefined; + recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; + }> => { + let user: RecipeLevelUser | undefined; + let recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; + + if (recipeId === EmailPasswordRecipe.RECIPE_ID) { + try { + const userResponse = await EmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "emailpassword", + }; + recipe = "emailpassword"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyEmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "emailpassword", + }; + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === ThirdPartyRecipe.RECIPE_ID) { + try { + const userResponse = await ThirdParty.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdparty"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyEmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdpartyemailpassword"; + } + } catch (e) { + // No - op + } + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyPasswordless.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === PasswordlessRecipe.RECIPE_ID) { + try { + const userResponse = await Passwordless.getUserById({ + userId, + }); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "passwordless", + }; + recipe = "passwordless"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyPasswordless.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "passwordless", + }; + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } + + return { + user, + recipe, + }; + }; } diff --git a/lib/ts/types.ts b/lib/ts/types.ts index 719b67b9f..2a1c82499 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -17,6 +17,7 @@ import RecipeModule from "./recipeModule"; import NormalisedURLDomain from "./normalisedURLDomain"; import NormalisedURLPath from "./normalisedURLPath"; import { TypeFramework } from "./framework/types"; +import { RecipeLevelUser } from "./recipe/accountlinking/types"; export type AppInfo = { appName: string; @@ -78,17 +79,11 @@ export type User = { isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - - loginMethods: { - recipeId: string; - recipeUserId: string; - timeJoined: number; - verified: boolean; - email?: string; - phoneNumber?: string; - thirdParty?: { - id: string; - userId: string; - }; + thirdpartyInfo: { + thirdpartyId: string; + thirdpartyUserId: string; }[]; + loginMethods: (RecipeLevelUser & { + verified: boolean; + })[]; }; From c4302d072d3002f13a67b63b8df1c5188ff152cb Mon Sep 17 00:00:00 2001 From: Bhumil Date: Sun, 22 Jan 2023 22:30:09 +0530 Subject: [PATCH 21/82] review changes --- .../accountlinking/recipeImplementation.js | 11 +++++++-- .../accountlinking/recipeImplementation.ts | 23 ++++++++++++------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 26cca2d21..102267e8f 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -211,6 +211,9 @@ function getRecipeImplementation(querier, config) { recipeUserId, } ); + if (!primaryUser.user.isPrimaryUser) { + throw Error("creating primaryUser for recipeUser failed in core"); + } return primaryUser; }); }, @@ -324,6 +327,8 @@ function getRecipeImplementation(querier, config) { throw Error("this error should never be thrown"); } yield config.onAccountLinked(user, recipeUser.user, userContext); + } else { + throw Error(`error thrown from core while linking accounts: ${accountsLinkingResult.status}`); } return accountsLinkingResult; }); @@ -373,6 +378,8 @@ function getRecipeImplementation(querier, config) { ); if (accountsUnlinkingResult.status === "OK") { yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); + } else { + throw Error(`error thrown from core while unlinking accounts: ${accountsUnlinkingResult.status}`); } return { status: "OK", @@ -397,7 +404,7 @@ function getRecipeImplementation(querier, config) { listUsersByAccountInfo: function ({ info }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/users"), + new normalisedURLPath_1.default("/users/accountinfo"), Object.assign({}, info) ); if (result.status === "OK") { @@ -409,7 +416,7 @@ function getRecipeImplementation(querier, config) { getUserByAccountInfo: function ({ info }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/users"), + new normalisedURLPath_1.default("/users/accountinfo"), Object.assign({}, info) ); if (result.status === "OK") { diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 1aea5e777..6a8341b8e 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -267,13 +267,16 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo return canCreatePrimaryUser; } - let primaryUser = await querier.sendPostRequest( - new NormalisedURLPath("/recipe/accountlinking/user/primary"), - { - recipeUserId, - } - ); + let primaryUser: { + status: "OK"; + user: User; + } = await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/primary"), { + recipeUserId, + }); + if (!primaryUser.user.isPrimaryUser) { + throw Error("creating primaryUser for recipeUser failed in core"); + } return primaryUser; }, canLinkAccounts: async function ( @@ -463,6 +466,8 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo throw Error("this error should never be thrown"); } await config.onAccountLinked(user, recipeUser.user, userContext); + } else { + throw Error(`error thrown from core while linking accounts: ${accountsLinkingResult.status}`); } return accountsLinkingResult; }, @@ -524,6 +529,8 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo ); if (accountsUnlinkingResult.status === "OK") { await Session.revokeAllSessionsForUser(recipeUserId, userContext); + } else { + throw Error(`error thrown from core while unlinking accounts: ${accountsUnlinkingResult.status}`); } return { @@ -544,7 +551,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo this: RecipeInterface, { info }: { info: AccountInfo } ): Promise { - let result = await querier.sendGetRequest(new NormalisedURLPath("/users"), { + let result = await querier.sendGetRequest(new NormalisedURLPath("/users/accountinfo"), { ...info, }); if (result.status === "OK") { @@ -556,7 +563,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo this: RecipeInterface, { info }: { info: AccountInfoWithRecipeId } ): Promise { - let result = await querier.sendGetRequest(new NormalisedURLPath("/users"), { + let result = await querier.sendGetRequest(new NormalisedURLPath("/users/accountinfo"), { ...info, }); if (result.status === "OK") { From 8613c6c408617da9f2187c0fd6b8371f701a26e0 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 30 Jan 2023 01:49:05 +0530 Subject: [PATCH 22/82] sign-up post login updated --- CHANGELOG.md | 5 + lib/build/recipe/accountlinking/index.d.ts | 24 +- lib/build/recipe/accountlinking/index.js | 21 + lib/build/recipe/accountlinking/recipe.d.ts | 26 +- lib/build/recipe/accountlinking/recipe.js | 146 ++++--- .../accountlinking/recipeImplementation.js | 11 + lib/build/recipe/accountlinking/types.d.ts | 4 + .../emailpassword/api/implementation.js | 361 +++++++++++++++++- .../services/backwardCompatibility/index.d.ts | 15 +- .../services/backwardCompatibility/index.js | 41 +- lib/build/recipe/emailpassword/index.d.ts | 2 +- .../emailpassword/passwordResetFunctions.d.ts | 11 +- .../emailpassword/recipeImplementation.js | 43 ++- lib/build/recipe/emailpassword/types.d.ts | 11 +- lib/build/recipe/emailpassword/utils.js | 12 +- .../services/backwardCompatibility/index.d.ts | 11 +- .../services/backwardCompatibility/index.js | 5 +- .../recipe/thirdpartyemailpassword/index.d.ts | 2 +- .../recipe/thirdpartyemailpassword/recipe.js | 1 - .../recipe/thirdpartyemailpassword/types.d.ts | 5 +- .../recipe/thirdpartyemailpassword/utils.js | 9 +- lib/ts/recipe/accountlinking/index.ts | 24 ++ lib/ts/recipe/accountlinking/recipe.ts | 104 ++++- .../accountlinking/recipeImplementation.ts | 16 + lib/ts/recipe/accountlinking/types.ts | 4 + .../emailpassword/api/implementation.ts | 358 ++++++++++++++++- .../services/backwardCompatibility/index.ts | 69 ++-- .../emailpassword/passwordResetFunctions.ts | 11 +- .../emailpassword/recipeImplementation.ts | 48 ++- lib/ts/recipe/emailpassword/types.ts | 12 +- lib/ts/recipe/emailpassword/utils.ts | 12 +- .../services/backwardCompatibility/index.ts | 14 +- .../recipe/thirdpartyemailpassword/recipe.ts | 1 - .../emailPasswordRecipeImplementation.ts | 4 +- .../recipeImplementation/index.ts | 2 +- .../recipe/thirdpartyemailpassword/types.ts | 5 +- .../recipe/thirdpartyemailpassword/utils.ts | 10 +- 37 files changed, 1216 insertions(+), 244 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c017736f1..bb639cc10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Type of `User` object returned by get users function - Functions `deleteuser`, `getUsersNewestFirst` and `getUsersOldestFirst` are now based on account linking recipe - Function `deleteuser` takes a new parameter `removeAllLinkedAccounts` which will be `true` by default +- Generate Password Reset Token API logic updated + +### Removed: + +- For EmailPassword recipe input, resetPasswordUsingTokenFeature user input removed ## [12.1.0] - 2022-11-17 diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index b34b0e0e8..36a400a2a 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -114,6 +114,10 @@ export default class Wrapper { status: "NO_PRIMARY_USER_FOUND"; } >; + static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId( + recipeUserId: string, + userContext?: any + ): Promise; static isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any): Promise; static doPostSignUpAccountLinkingOperations( info: AccountInfoAndEmailWithRecipeId, @@ -142,13 +146,25 @@ export default class Wrapper { } & { accountsLinked: false; reason: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; }) + | ({ + createRecipeUser: false; + } & { + accountsLinked: false; + reason: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + }) >; + static createPrimaryUserIdOrLinkAccounts( + recipeUserId: string, + session: SessionContainer | undefined, + userContext?: any + ): Promise; } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; @@ -159,7 +175,9 @@ export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; export declare const linkAccounts: typeof Wrapper.linkAccounts; export declare const unlinkAccounts: typeof Wrapper.unlinkAccounts; +export declare const getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId: typeof Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; export declare const isSignUpAllowed: typeof Wrapper.isSignUpAllowed; export declare const doPostSignUpAccountLinkingOperations: typeof Wrapper.doPostSignUpAccountLinkingOperations; export declare const accountLinkPostSignInViaSession: typeof Wrapper.accountLinkPostSignInViaSession; +export declare const createPrimaryUserIdOrLinkAccounts: typeof Wrapper.createPrimaryUserIdOrLinkAccounts; export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 798b2ed2b..0ae668663 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -121,6 +121,16 @@ class Wrapper { }); }); } + static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId(recipeUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } static isSignUpAllowed(info, userContext) { return __awaiter(this, void 0, void 0, function* () { return yield recipe_1.default.getInstanceOrThrowError().isSignUpAllowed({ @@ -149,6 +159,15 @@ class Wrapper { }); }); } + static createPrimaryUserIdOrLinkAccounts(recipeUserId, session, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + recipeUserId, + session, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } } exports.default = Wrapper; Wrapper.init = recipe_1.default.init; @@ -161,6 +180,8 @@ exports.createPrimaryUser = Wrapper.createPrimaryUser; exports.canLinkAccounts = Wrapper.canLinkAccounts; exports.linkAccounts = Wrapper.linkAccounts; exports.unlinkAccounts = Wrapper.unlinkAccounts; +exports.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; exports.isSignUpAllowed = Wrapper.isSignUpAllowed; exports.doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; exports.accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; +exports.createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 7327c716e..893bdc0c0 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -27,7 +27,7 @@ export default class Recipe extends RecipeModule { isErrorFromThisRecipe(err: any): err is error; getIdentitiesForUser: ( user: User - ) => Promise<{ + ) => { verified: { emails: string[]; phoneNumbers: string[]; @@ -44,7 +44,7 @@ export default class Recipe extends RecipeModule { userId: string; }[]; }; - }>; + }; isSignUpAllowed: ({ info, userContext, @@ -89,11 +89,27 @@ export default class Recipe extends RecipeModule { } & { accountsLinked: false; reason: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; }) + | ({ + createRecipeUser: false; + } & { + accountsLinked: false; + reason: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + }) >; + createPrimaryUserIdOrLinkAccounts: ({ + recipeUserId, + session, + userContext, + }: { + recipeUserId: string; + session: SessionContainer | undefined; + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 3799c3009..c02a53e19 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -55,46 +55,45 @@ const error_1 = require("../../error"); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, config, _recipes, _ingredients) { super(recipeId, appInfo); - this.getIdentitiesForUser = (user) => - __awaiter(this, void 0, void 0, function* () { - let identities = { - verified: { - emails: [], - phoneNumbers: [], - thirdpartyInfo: [], - }, - unverified: { - emails: [], - phoneNumbers: [], - thirdpartyInfo: [], - }, - }; - for (let i = 0; i < user.loginMethods.length; i++) { - let loginMethod = user.loginMethods[i]; - if (loginMethod.email !== undefined) { - if (loginMethod.verified) { - identities.verified.emails.push(loginMethod.email); - } else { - identities.unverified.emails.push(loginMethod.email); - } + this.getIdentitiesForUser = (user) => { + let identities = { + verified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + unverified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + }; + for (let i = 0; i < user.loginMethods.length; i++) { + let loginMethod = user.loginMethods[i]; + if (loginMethod.email !== undefined) { + if (loginMethod.verified) { + identities.verified.emails.push(loginMethod.email); + } else { + identities.unverified.emails.push(loginMethod.email); } - if (loginMethod.phoneNumber !== undefined) { - if (loginMethod.verified) { - identities.verified.phoneNumbers.push(loginMethod.phoneNumber); - } else { - identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); - } + } + if (loginMethod.phoneNumber !== undefined) { + if (loginMethod.verified) { + identities.verified.phoneNumbers.push(loginMethod.phoneNumber); + } else { + identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); } - if (loginMethod.thirdParty !== undefined) { - if (loginMethod.verified) { - identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); - } else { - identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); - } + } + if (loginMethod.thirdParty !== undefined) { + if (loginMethod.verified) { + identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); + } else { + identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); } } - return identities; - }); + } + return identities; + }; this.isSignUpAllowed = ({ info, userContext }) => __awaiter(this, void 0, void 0, function* () { let identifier; @@ -132,7 +131,7 @@ class Recipe extends recipeModule_1.default { if (!shouldRequireVerification) { return true; } - let identitiesForPrimaryUser = yield this.getIdentitiesForUser(primaryUser); + let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); if (info.email !== undefined) { return identitiesForPrimaryUser.verified.emails.includes(info.email); } @@ -238,7 +237,7 @@ class Recipe extends recipeModule_1.default { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } let recipeId = user.loginMethods[0].recipeId; @@ -258,7 +257,7 @@ class Recipe extends recipeModule_1.default { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } if (shouldDoAccountLinking.shouldRequireVerification) { @@ -282,6 +281,7 @@ class Recipe extends recipeModule_1.default { createRecipeUser: false, accountsLinked: false, reason: canCreatePrimaryUser.status, + primaryUserId: canCreatePrimaryUser.primaryUserId, }; } /** @@ -296,6 +296,7 @@ class Recipe extends recipeModule_1.default { createRecipeUser: false, accountsLinked: false, reason: createPrimaryUserResult.status, + primaryUserId: createPrimaryUserResult.primaryUserId, }; } user = createPrimaryUserResult.user; @@ -314,7 +315,7 @@ class Recipe extends recipeModule_1.default { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } /** @@ -361,7 +362,7 @@ class Recipe extends recipeModule_1.default { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = yield this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -394,13 +395,13 @@ class Recipe extends recipeModule_1.default { userContext, }); if (existingRecipeUserForInputInfo !== undefined) { - let doesPrimaryUserIdAlreadyExists = - existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; - if (doesPrimaryUserIdAlreadyExists) { + let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); + if (primaryUserIfExists !== undefined) { return { createRecipeUser: false, accountsLinked: false, reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUserIfExists.id, }; } } @@ -452,9 +453,10 @@ class Recipe extends recipeModule_1.default { createRecipeUser: false, accountsLinked: false, reason: canLinkAccounts.status, + primaryUserId: canLinkAccounts.primaryUserId, }; } - let identitiesForPrimaryUser = yield this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = @@ -494,6 +496,60 @@ class Recipe extends recipeModule_1.default { updateVerificationClaim: true, }; }); + this.createPrimaryUserIdOrLinkAccounts = ({ recipeUserId, session, userContext }) => + __awaiter(this, void 0, void 0, function* () { + let primaryUser = yield this.recipeInterfaceImpl.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext, + }); + if (primaryUser === undefined) { + let user = yield __1.getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + Object.assign({}, user.loginMethods[0]), + undefined, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: recipeUserId, + userContext, + }); + // TODO: remove session claim + } + } else { + /** + * recipeUser already linked with primaryUser + */ + let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); + if (recipeUser === undefined) { + let user = yield __1.getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + Object.assign({}, user.loginMethods[0]), + primaryUser, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + let linkAccountsResult = yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUserId, + primaryUserId: primaryUser.id, + userContext, + }); + if (linkAccountsResult.status === "OK") { + // TODO: remove session claim if session claim exists + // else create a new session + } + } + } + } + }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); { let builder = new supertokens_js_override_1.default( diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 102267e8f..1c766233d 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -458,6 +458,17 @@ function getRecipeImplementation(querier, config) { }; }); }, + getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId: function ({ recipeUserId }) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/linked_or_linkable"), + { + recipeUserId, + } + ); + return result.user; + }); + }, }; } exports.default = getRecipeImplementation; diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index f9f4851e1..89fbba47e 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -179,6 +179,10 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; + getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId: (input: { + recipeUserId: string; + userContext: any; + }) => Promise; }; export declare type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index dd82895e8..c8aa3b12f 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -33,14 +33,119 @@ var __awaiter = Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const session_1 = require("../../session"); +const __1 = require("../../../"); +const recipe_1 = require("../../accountlinking/recipe"); +const recipe_2 = require("../../emailverification/recipe"); function getAPIImplementation() { return { - linkAccountToExistingAccountPOST: function (_input) { + linkAccountToExistingAccountPOST: function ({ formFields, session, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { + let email = formFields.filter((f) => f.id === "email")[0].value; + let result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + session, + info: { + email, + recipeId: "emailpassword", + }, + infoVerified: false, + userContext, + }); + let createdNewRecipeUser = false; + if (result.createRecipeUser) { + let password = formFields.filter((f) => f.id === "password")[0].value; + let response = yield options.recipeImplementation.signUp({ email, password, userContext }); + if (response.status !== "OK") { + throw Error( + `this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}` + ); + } + createdNewRecipeUser = true; + if (result.updateVerificationClaim) { + // TODO: update session verification claim + return { + status: "ACCOUNT_NOT_VERIFIED_ERROR", + isNotVerifiedAccountFromInputSession: false, + description: "", + }; + } else { + result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + session, + info: { + email, + recipeId: "emailpassword", + }, + infoVerified: false, + userContext, + }); + } + } + if (result.createRecipeUser) { + throw Error( + `this error should never be thrown after creating a new user during accountLinkPostSignInViaSession flow` + ); + } + if (!result.accountsLinked) { + if (result.reason === "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + return { + status: "ACCOUNT_NOT_VERIFIED_ERROR", + isNotVerifiedAccountFromInputSession: true, + description: "", + }; + } + if (result.reason === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + return { + status: "ACCOUNT_NOT_VERIFIED_ERROR", + isNotVerifiedAccountFromInputSession: false, + description: "", + }; + } + if ( + result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + return { + status: result.reason, + description: "", + primaryUserId: result.primaryUserId, + }; + } + return { + status: result.reason, + description: "", + }; + } + let wereAccountsAlreadyLinked = false; + if (result.updateVerificationClaim) { + // TODO: remove session claim + } else { + wereAccountsAlreadyLinked = true; + } + let user = yield __1.getUser(session.getUserId()); + if (user === undefined) { + throw Error( + "this error should never be thrown. Can't find primary user with userId: " + session.getUserId() + ); + } + let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + if (recipeUser === undefined) { + throw Error( + "this error should never be thrown. Can't find emailPassword recipeUser with email: " + + email + + " and primary userId: " + + session.getUserId() + ); + } return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: false, - description: "", + status: "OK", + user: { + id: user.id, + recipeUserId: recipeUser.id, + timeJoined: recipeUser.timeJoined, + email, + }, + createdNewRecipeUser, + wereAccountsAlreadyLinked, + session, }; }); }, @@ -56,19 +161,172 @@ function getAPIImplementation() { generatePasswordResetTokenPOST: function ({ formFields, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; - let user = yield options.recipeImplementation.getUserByEmail({ email, userContext }); - if (user === undefined) { + let userIdForPasswordReset = undefined; + let recipeUserId = undefined; + /** + * check if primaryUserId is linked with this email + */ + let users = yield __1.listUsersByAccountInfo({ + email, + }); + if (users !== undefined) { + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser !== undefined) { + /** + * checking if emailpassword user exists for the input email and associated with the primaryUserId + */ + let epUser = primaryUser.loginMethods.find((l) => l.recipeId === "emailpassword"); + if (epUser === undefined) { + /** + * this means no emailpassword user is associated with the primaryUserId which + * has the input email as identifying info + * now checking if emailpassword user exists for the input email + */ + let epRecipeUser = users.find( + (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + ); + if (epRecipeUser === undefined) { + /** + * this means that there is no emailpassword recipe user for the input email + * so we check is account linking is enabled for the given email and primaryUserId + */ + let shouldDoAccountLinking = yield recipe_1.default + .getInstanceOrThrowError() + .config.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + /** + * here, reset password token generation is not allowed + * and we have decided to return "OK" status + */ + return { + status: "OK", + }; + } + let identitiesForPrimaryUser = recipe_1.default + .getInstanceOrThrowError() + .getIdentitiesForUser(primaryUser); + /** + * if input email doens't belong to the verified indentity for the primaryUser, + * we need to check shouldRequireVerification boolean + */ + if (!identitiesForPrimaryUser.verified.emails.includes(email)) { + if (shouldDoAccountLinking.shouldRequireVerification) { + /** + * here, reset password token generation is not allowed + * an + */ + return { + status: "OK", + }; + } + } + userIdForPasswordReset = primaryUser.id; + } else { + /** + * this means emailpassword user associated with the input email exists but it + * is currently not associated with the primaryUserId we found in the + * previous step. We simply generate password reset token for such user + */ + userIdForPasswordReset = epRecipeUser.id; + recipeUserId = epRecipeUser.id; + } + } else { + /** + * the primaryUserId associated with the email has a linked + * emailpassword recipe user with same email + */ + recipeUserId = epUser.recipeUserId; + /** + * checking for shouldDoAccountLinking + */ + let shouldDoAccountLinking = yield recipe_1.default + .getInstanceOrThrowError() + .config.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); + let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink + ? shouldDoAccountLinking.shouldRequireVerification + : false; + if (shouldRequireVerification) { + /** + * if verification is required, we check if this is EP user is + * the only user associated with the primaryUserId. + */ + if (primaryUser.loginMethods.length > 1) { + /** + * checking if the email belongs to the verified identities for the + * primary user + */ + let identitiesForPrimaryUser = recipe_1.default + .getInstanceOrThrowError() + .getIdentitiesForUser(primaryUser); + if (!identitiesForPrimaryUser.verified.emails.includes(email)) { + /** + * the email is not verified for any account linked to the primary user. + * so we check if there exists any account linked with the primary user + * which doesn't have this email as identifying info + */ + let differentIdentityUser = primaryUser.loginMethods.find( + (u) => u.email !== email + ); + if (differentIdentityUser !== undefined) { + /** + * if any such user found, we return status to contact support + */ + return { + status: "GENERAL_ERROR", + message: "Password Reset Not Allowed. Please contact support.", + }; + } + } + } + } + userIdForPasswordReset = primaryUser.id; + } + } else { + /** + * no primaryUser exists for the given email. So we just find the + * associated emailpasword user, if exists + */ + let epRecipeUser = users.find( + (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + ); + if (epRecipeUser === undefined) { + return { + status: "OK", + }; + } + userIdForPasswordReset = epRecipeUser.id; + recipeUserId = epRecipeUser.id; + } + } else { return { status: "OK", }; } let response = yield options.recipeImplementation.createResetPasswordToken({ - userId: user.recipeUserId, - email: user.email, + userId: userIdForPasswordReset, + email, userContext, }); if (response.status === "UNKNOWN_USER_ID_ERROR") { - logger_1.logDebugMessage(`Password reset email not sent, unknown user id: ${user.id}`); + logger_1.logDebugMessage( + `Password reset email not sent, unknown user id: ${userIdForPasswordReset}` + ); return { status: "OK", }; @@ -83,7 +341,11 @@ function getAPIImplementation() { logger_1.logDebugMessage(`Sending password reset email to ${email}`); yield options.emailDelivery.ingredientInterfaceImpl.sendEmail({ type: "PASSWORD_RESET", - user, + user: { + id: userIdForPasswordReset, + recipeUserId, + email, + }, passwordResetLink, userContext, }); @@ -100,6 +362,85 @@ function getAPIImplementation() { newPassword, userContext, }); + if (response.status === "OK") { + let userId = response.userId; + let email = response.email; + function verifyUser(rUserId) { + return __awaiter(this, void 0, void 0, function* () { + const emailVerificationInstance = recipe_2.default.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: rUserId, + email, + userContext, + } + ); + if (tokenResponse.status === "OK") { + yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext, + }); + } + } + }); + } + let user = yield __1.getUser(userId); + if (user === undefined) { + throw Error("this error should never be thrown"); + } + /** + * check if the user is a primaryUser + */ + if (user.isPrimaryUser) { + /** + * check if there exists an emailpassword recipe user + * associated with the primary user with the same email + * which is returned by core in the response + */ + let epUser = user.loginMethods.find((u) => u.email === email && u.recipeId === "emailpassword"); + if (epUser === undefined) { + /** + * create a new emailpassword recipe user + */ + let response = yield options.recipeImplementation.signUp({ + email, + password: newPassword, + userContext, + }); + if (response.status !== "OK") { + throw Error("this error should not be thrown. EP user already for email: " + email); + } + let recipeUser = response.user; + yield verifyUser(response.user.id); + yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); + } else if (!epUser.verified) { + yield verifyUser(epUser.id); + } + } else { + /** + * it's a recipe user + */ + if (!user.loginMethods[0].verified) { + yield verifyUser(user.loginMethods[0].id); + } + const session = yield session_1.default.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [], sessionRequired: false }, + userContext + ); + yield recipe_1.default.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + recipeUserId: user.id, + session, + userContext, + }); + } + } return response; }); }, diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 31b3d1fd8..a60d08b49 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,5 +1,5 @@ // @ts-nocheck -import { TypeEmailPasswordEmailDeliveryInput, User, RecipeInterface } from "../../../types"; +import { TypeEmailPasswordEmailDeliveryInput, RecipeInterface } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; export default class BackwardCompatibilityService @@ -8,18 +8,7 @@ export default class BackwardCompatibilityService private isInServerlessEnv; private appInfo; private resetPasswordUsingTokenFeature; - constructor( - recipeInterfaceImpl: RecipeInterface, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - resetPasswordUsingTokenFeature?: { - createAndSendCustomEmail?: ( - user: User, - passwordResetURLWithToken: string, - userContext: any - ) => Promise; - } - ); + constructor(recipeInterfaceImpl: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean); sendEmail: ( input: import("../../../types").TypeEmailPasswordPasswordResetEmailDeliveryInput & { userContext: any; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js index 69a1f3f81..5d9358c97 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -32,14 +32,30 @@ var __awaiter = }; Object.defineProperty(exports, "__esModule", { value: true }); const passwordResetFunctions_1 = require("../../../passwordResetFunctions"); +const __1 = require("../../../../.."); class BackwardCompatibilityService { - constructor(recipeInterfaceImpl, appInfo, isInServerlessEnv, resetPasswordUsingTokenFeature) { + constructor(recipeInterfaceImpl, appInfo, isInServerlessEnv) { this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - let user = yield this.recipeInterfaceImpl.getUserById({ - userId: input.user.recipeUserId, - userContext: input.userContext, - }); + let user = + input.user.recipeUserId !== undefined + ? yield this.recipeInterfaceImpl.getUserById({ + userId: input.user.recipeUserId, + userContext: input.userContext, + }) + : undefined; + if (input.user.recipeUserId === undefined) { + let primaryUser = yield __1.getUser(input.user.id); + if (primaryUser === undefined) { + throw Error("this should never come here"); + } + user = { + id: primaryUser.id, + recipeUserId: undefined, + timeJoined: primaryUser.timeJoined, + email: input.user.email, + }; + } if (user === undefined) { throw Error("this should never come here"); } @@ -62,18 +78,9 @@ class BackwardCompatibilityService { this.isInServerlessEnv = isInServerlessEnv; this.appInfo = appInfo; { - let inputCreateAndSendCustomEmail = - resetPasswordUsingTokenFeature === null || resetPasswordUsingTokenFeature === void 0 - ? void 0 - : resetPasswordUsingTokenFeature.createAndSendCustomEmail; - this.resetPasswordUsingTokenFeature = - inputCreateAndSendCustomEmail !== undefined - ? { - createAndSendCustomEmail: inputCreateAndSendCustomEmail, - } - : { - createAndSendCustomEmail: passwordResetFunctions_1.createAndSendCustomEmail(this.appInfo), - }; + this.resetPasswordUsingTokenFeature = { + createAndSendCustomEmail: passwordResetFunctions_1.createAndSendCustomEmail(this.appInfo), + }; } } } diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index b56deadee..b71bb9f94 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -77,7 +77,7 @@ export default class Wrapper { password?: string; userContext?: any; }): Promise<{ - status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; + status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; }>; static sendEmail( input: TypeEmailPasswordEmailDeliveryInput & { diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index 56b10c948..2226432b8 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -1,6 +1,13 @@ // @ts-nocheck -import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; export declare function createAndSendCustomEmail( appInfo: NormalisedAppinfo -): (user: User, passwordResetURLWithToken: string) => Promise; +): ( + user: { + id: string; + recipeUserId?: string | undefined; + email: string; + timeJoined: number; + }, + passwordResetURLWithToken: string +) => Promise; diff --git a/lib/build/recipe/emailpassword/recipeImplementation.js b/lib/build/recipe/emailpassword/recipeImplementation.js index 307ac1e64..8f3d69840 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -32,6 +32,8 @@ var __awaiter = }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); +const __1 = require("../.."); +const recipe_1 = require("../emailverification/recipe"); function getRecipeInterface(querier) { return { signUp: function ({ email, password }) { @@ -88,12 +90,13 @@ function getRecipeInterface(querier) { } }); }, - createResetPasswordToken: function ({ userId }) { + createResetPasswordToken: function ({ userId, email }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest( new normalisedURLPath_1.default("/recipe/user/password/reset/token"), { userId, + email, } ); if (response.status === "OK") { @@ -123,12 +126,50 @@ function getRecipeInterface(querier) { }, updateEmailOrPassword: function (input) { return __awaiter(this, void 0, void 0, function* () { + let markEmailAsVerified = false; + if (input.email !== undefined) { + let userForUserId = yield __1.getUser(input.userId); + if (userForUserId !== undefined && userForUserId.isPrimaryUser) { + let usersForEmail = yield __1.listUsersByAccountInfo({ + email: input.email, + }); + if (usersForEmail !== undefined) { + let primaryUserFromEmailUsers = usersForEmail.find((u) => u.isPrimaryUser); + if (primaryUserFromEmailUsers !== undefined) { + if (primaryUserFromEmailUsers.id !== userForUserId.id) { + return { + status: "EMAIL_CHANGE_NOT_ALLOWED", + }; + } + markEmailAsVerified = true; + } + } + } + } let response = yield querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/user"), { userId: input.userId, email: input.email, password: input.password, }); if (response.status === "OK") { + if (markEmailAsVerified && input.email !== undefined) { + const emailVerificationInstance = recipe_1.default.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: input.userId, + email: input.email, + userContext: undefined, + } + ); + if (tokenResponse.status === "OK") { + yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext: undefined, + }); + } + } + } return { status: "OK", }; diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index f4c3d4ef5..7f9386b86 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -47,12 +47,6 @@ export declare type TypeNormalisedInputSignUp = { export declare type TypeNormalisedInputSignIn = { formFields: NormalisedFormField[]; }; -export declare type TypeInputResetPasswordUsingTokenFeature = { - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: (user: User, passwordResetURLWithToken: string, userContext: any) => Promise; -}; export declare type TypeNormalisedInputResetPasswordUsingTokenFeature = { formFieldsForGenerateTokenForm: NormalisedFormField[]; formFieldsForPasswordResetForm: NormalisedFormField[]; @@ -66,7 +60,6 @@ export declare type User = { export declare type TypeInput = { signUpFeature?: TypeInputSignUp; emailDelivery?: EmailDeliveryTypeInput; - resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override?: { functions?: ( originalImplementation: RecipeInterface, @@ -148,7 +141,7 @@ export declare type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; }>; }; export declare type APIOptions = { @@ -304,7 +297,7 @@ export declare type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; user: { id: string; - recipeUserId: string; + recipeUserId?: string; email: string; }; passwordResetLink: string; diff --git a/lib/build/recipe/emailpassword/utils.js b/lib/build/recipe/emailpassword/utils.js index 880c657c4..65cb972c5 100644 --- a/lib/build/recipe/emailpassword/utils.js +++ b/lib/build/recipe/emailpassword/utils.js @@ -69,19 +69,11 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { ? void 0 : _a.service; /** - * following code is for backward compatibility. - * if user has not passed emailDelivery config, we - * use the createAndSendCustomEmail config. If the user - * has not passed even that config, we use the default + * If the user has not passed even that config, we use the default * createAndSendCustomEmail implementation which calls our supertokens API */ if (emailService === undefined) { - emailService = new backwardCompatibility_1.default( - recipeImpl, - appInfo, - isInServerlessEnv, - config === null || config === void 0 ? void 0 : config.resetPasswordUsingTokenFeature - ); + emailService = new backwardCompatibility_1.default(recipeImpl, appInfo, isInServerlessEnv); } return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 83eec483b..fedf54fc4 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,5 +1,5 @@ // @ts-nocheck -import { TypeThirdPartyEmailPasswordEmailDeliveryInput, User } from "../../../types"; +import { TypeThirdPartyEmailPasswordEmailDeliveryInput } from "../../../types"; import { RecipeInterface as EmailPasswordRecipeInterface } from "../../../../emailpassword"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; @@ -9,14 +9,7 @@ export default class BackwardCompatibilityService constructor( emailPasswordRecipeInterfaceImpl: EmailPasswordRecipeInterface, appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - resetPasswordUsingTokenFeature?: { - createAndSendCustomEmail?: ( - user: User, - passwordResetURLWithToken: string, - userContext: any - ) => Promise; - } + isInServerlessEnv: boolean ); sendEmail: ( input: import("../../../../emailpassword/types").TypeEmailPasswordPasswordResetEmailDeliveryInput & { diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js index 823bd0411..0f15f3e29 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -33,7 +33,7 @@ var __awaiter = Object.defineProperty(exports, "__esModule", { value: true }); const backwardCompatibility_1 = require("../../../../emailpassword/emaildelivery/services/backwardCompatibility"); class BackwardCompatibilityService { - constructor(emailPasswordRecipeInterfaceImpl, appInfo, isInServerlessEnv, resetPasswordUsingTokenFeature) { + constructor(emailPasswordRecipeInterfaceImpl, appInfo, isInServerlessEnv) { this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { yield this.emailPasswordBackwardCompatibilityService.sendEmail(input); @@ -42,8 +42,7 @@ class BackwardCompatibilityService { this.emailPasswordBackwardCompatibilityService = new backwardCompatibility_1.default( emailPasswordRecipeInterfaceImpl, appInfo, - isInServerlessEnv, - resetPasswordUsingTokenFeature + isInServerlessEnv ); } } diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index 020257c41..717ffc5a0 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -83,7 +83,7 @@ export default class Wrapper { password?: string; userContext?: any; }): Promise<{ - status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; + status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; }>; static Google: typeof import("../thirdparty/providers/google").default; static Github: typeof import("../thirdparty/providers/github").default; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.js b/lib/build/recipe/thirdpartyemailpassword/recipe.js index d1bf60332..d9d4d162d 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.js @@ -158,7 +158,6 @@ class Recipe extends recipeModule_1.default { signUpFeature: { formFields: this.config.signUpFeature.formFields, }, - resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, }, { emailDelivery: this.emailDelivery, diff --git a/lib/build/recipe/thirdpartyemailpassword/types.d.ts b/lib/build/recipe/thirdpartyemailpassword/types.d.ts index 2abd1a64d..22543227f 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -4,7 +4,6 @@ import { NormalisedFormField, TypeFormField, TypeInputFormField, - TypeInputResetPasswordUsingTokenFeature, APIOptions as EmailPasswordAPIOptionsOriginal, TypeEmailPasswordEmailDeliveryInput, RecipeInterface as EPRecipeInterface, @@ -47,7 +46,6 @@ export declare type TypeInput = { signUpFeature?: TypeInputSignUp; providers?: TypeProvider[]; emailDelivery?: EmailDeliveryTypeInput; - resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override?: { functions?: ( originalImplementation: RecipeInterface, @@ -63,7 +61,6 @@ export declare type TypeNormalisedInput = { emailPasswordRecipeImpl: EPRecipeInterface, isInServerlessEnv: boolean ) => EmailDeliveryTypeInputWithService; - resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override: { functions: ( originalImplementation: RecipeInterface, @@ -149,7 +146,7 @@ export declare type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; }>; }; export declare type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; diff --git a/lib/build/recipe/thirdpartyemailpassword/utils.js b/lib/build/recipe/thirdpartyemailpassword/utils.js index 7ef3b2d23..5e162c8cd 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.js +++ b/lib/build/recipe/thirdpartyemailpassword/utils.js @@ -22,7 +22,6 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { appInfo, config === undefined ? undefined : config.signUpFeature ); - let resetPasswordUsingTokenFeature = config === undefined ? undefined : config.resetPasswordUsingTokenFeature; let providers = config === undefined || config.providers === undefined ? [] : config.providers; let override = Object.assign( { @@ -45,12 +44,7 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { * createAndSendCustomEmail implementation */ if (emailService === undefined) { - emailService = new backwardCompatibility_1.default( - emailPasswordRecipeImpl, - appInfo, - isInServerlessEnv, - config === null || config === void 0 ? void 0 : config.resetPasswordUsingTokenFeature - ); + emailService = new backwardCompatibility_1.default(emailPasswordRecipeImpl, appInfo, isInServerlessEnv); } return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** @@ -72,7 +66,6 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { getEmailDeliveryConfig, signUpFeature, providers, - resetPasswordUsingTokenFeature, }; } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index 3be040ab7..8e2bef4db 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -85,6 +85,15 @@ export default class Wrapper { }); } + static async getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId(recipeUserId: string, userContext?: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId( + { + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + } + ); + } + static async isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any) { return await Recipe.getInstanceOrThrowError().isSignUpAllowed({ info, @@ -119,6 +128,18 @@ export default class Wrapper { userContext, }); } + + static async createPrimaryUserIdOrLinkAccounts( + recipeUserId: string, + session: SessionContainer | undefined, + userContext?: any + ) { + return await Recipe.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + recipeUserId, + session, + userContext: userContext === undefined ? {} : userContext, + }); + } } export const init = Wrapper.init; @@ -130,8 +151,11 @@ export const createPrimaryUser = Wrapper.createPrimaryUser; export const canLinkAccounts = Wrapper.canLinkAccounts; export const linkAccounts = Wrapper.linkAccounts; export const unlinkAccounts = Wrapper.unlinkAccounts; +export const getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = + Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; export const isSignUpAllowed = Wrapper.isSignUpAllowed; export const doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; export const accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; +export const createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; export type { RecipeInterface }; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index e82f51d1d..64049c338 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -27,7 +27,7 @@ import type { AccountInfoWithRecipeId, } from "./types"; import { validateAndNormaliseUserInput } from "./utils"; -import { getUserForRecipeId } from "../.."; +import { getUser, getUserForRecipeId } from "../.."; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; @@ -106,9 +106,9 @@ export default class Recipe extends RecipeModule { return SuperTokensError.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; } - getIdentitiesForUser = async ( + getIdentitiesForUser = ( user: User - ): Promise<{ + ): { verified: { emails: string[]; phoneNumbers: string[]; @@ -125,7 +125,7 @@ export default class Recipe extends RecipeModule { userId: string; }[]; }; - }> => { + } => { let identities: { verified: { emails: string[]; @@ -231,7 +231,7 @@ export default class Recipe extends RecipeModule { return true; } - let identitiesForPrimaryUser = await this.getIdentitiesForUser(primaryUser); + let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); if (info.email !== undefined) { return identitiesForPrimaryUser.verified.emails.includes(info.email); @@ -352,11 +352,16 @@ export default class Recipe extends RecipeModule { | { accountsLinked: false; reason: - | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" + | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + } + | { + accountsLinked: false; + reason: | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; } )) > => { @@ -383,7 +388,7 @@ export default class Recipe extends RecipeModule { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } @@ -404,7 +409,7 @@ export default class Recipe extends RecipeModule { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } if (shouldDoAccountLinking.shouldRequireVerification) { @@ -429,6 +434,7 @@ export default class Recipe extends RecipeModule { createRecipeUser: false, accountsLinked: false, reason: canCreatePrimaryUser.status, + primaryUserId: canCreatePrimaryUser.primaryUserId, }; } /** @@ -443,6 +449,7 @@ export default class Recipe extends RecipeModule { createRecipeUser: false, accountsLinked: false, reason: createPrimaryUserResult.status, + primaryUserId: createPrimaryUserResult.primaryUserId, }; } user = createPrimaryUserResult.user; @@ -461,7 +468,7 @@ export default class Recipe extends RecipeModule { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } @@ -509,7 +516,7 @@ export default class Recipe extends RecipeModule { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = await this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -543,13 +550,13 @@ export default class Recipe extends RecipeModule { userContext, }); if (existingRecipeUserForInputInfo !== undefined) { - let doesPrimaryUserIdAlreadyExists = - existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; - if (doesPrimaryUserIdAlreadyExists) { + let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); + if (primaryUserIfExists !== undefined) { return { createRecipeUser: false, accountsLinked: false, reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUserIfExists.id, }; } } @@ -601,10 +608,11 @@ export default class Recipe extends RecipeModule { createRecipeUser: false, accountsLinked: false, reason: canLinkAccounts.status, + primaryUserId: canLinkAccounts.primaryUserId, }; } - let identitiesForPrimaryUser = await this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = @@ -644,4 +652,70 @@ export default class Recipe extends RecipeModule { updateVerificationClaim: true, }; }; + + createPrimaryUserIdOrLinkAccounts = async ({ + recipeUserId, + session, + userContext, + }: { + recipeUserId: string; + session: SessionContainer | undefined; + userContext: any; + }) => { + let primaryUser = await this.recipeInterfaceImpl.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext, + }); + if (primaryUser === undefined) { + let user = await getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + { + ...user.loginMethods[0], + }, + undefined, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + await this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: recipeUserId, + userContext, + }); + // TODO: remove session claim + } + } else { + /** + * recipeUser already linked with primaryUser + */ + let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); + if (recipeUser === undefined) { + let user = await getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + { + ...user.loginMethods[0], + }, + primaryUser, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + let linkAccountsResult = await this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUserId, + primaryUserId: primaryUser.id, + userContext, + }); + if (linkAccountsResult.status === "OK") { + // TODO: remove session claim if session claim exists + // else create a new session + } + } + } + } + }; } diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 6a8341b8e..46137be9e 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -622,5 +622,21 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo status: "OK", }; }, + getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId: async function ( + this: RecipeInterface, + { + recipeUserId, + }: { + recipeUserId: string; + } + ): Promise { + let result = await querier.sendGetRequest( + new NormalisedURLPath("/recipe/accountlinking/user/linked_or_linkable"), + { + recipeUserId, + } + ); + return result.user; + }, }; } diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 3952e95bb..2f5bfb602 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -194,6 +194,10 @@ export type RecipeInterface = { removeAllLinkedAccounts: boolean; userContext: any; }) => Promise<{ status: "OK" }>; + getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId: (input: { + recipeUserId: string; + userContext: any; + }) => Promise; }; export type RecipeLevelUser = { diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 4d5f36020..22b9cecbe 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -3,10 +3,18 @@ import { logDebugMessage } from "../../../logger"; import Session from "../../session"; import { SessionContainerInterface } from "../../session/types"; import { GeneralErrorResponse } from "../../../types"; +import { listUsersByAccountInfo, getUser } from "../../../"; +import AccountLinkingRecipe from "../../accountlinking/recipe"; +import EmailVerification from "../../emailverification/recipe"; export default function getAPIImplementation(): APIInterface { return { - linkAccountToExistingAccountPOST: async function (_input: { + linkAccountToExistingAccountPOST: async function ({ + formFields, + session, + options, + userContext, + }: { formFields: { id: string; value: string; @@ -43,10 +51,113 @@ export default function getAPIImplementation(): APIInterface { } | GeneralErrorResponse > { + let email = formFields.filter((f) => f.id === "email")[0].value; + let result = await AccountLinkingRecipe.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + session, + info: { + email, + recipeId: "emailpassword", + }, + infoVerified: false, + userContext, + }); + let createdNewRecipeUser = false; + if (result.createRecipeUser) { + let password = formFields.filter((f) => f.id === "password")[0].value; + + let response = await options.recipeImplementation.signUp({ email, password, userContext }); + if (response.status !== "OK") { + throw Error( + `this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}` + ); + } + createdNewRecipeUser = true; + if (result.updateVerificationClaim) { + // TODO: update session verification claim + return { + status: "ACCOUNT_NOT_VERIFIED_ERROR", + isNotVerifiedAccountFromInputSession: false, + description: "", + }; + } else { + result = await AccountLinkingRecipe.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + session, + info: { + email, + recipeId: "emailpassword", + }, + infoVerified: false, + userContext, + }); + } + } + if (result.createRecipeUser) { + throw Error( + `this error should never be thrown after creating a new user during accountLinkPostSignInViaSession flow` + ); + } + if (!result.accountsLinked) { + if (result.reason === "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + return { + status: "ACCOUNT_NOT_VERIFIED_ERROR", + isNotVerifiedAccountFromInputSession: true, + description: "", + }; + } + if (result.reason === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + return { + status: "ACCOUNT_NOT_VERIFIED_ERROR", + isNotVerifiedAccountFromInputSession: false, + description: "", + }; + } + if ( + result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + return { + status: result.reason, + description: "", + primaryUserId: result.primaryUserId, + }; + } + return { + status: result.reason, + description: "", + }; + } + let wereAccountsAlreadyLinked = false; + if (result.updateVerificationClaim) { + // TODO: remove session claim + } else { + wereAccountsAlreadyLinked = true; + } + let user = await getUser(session.getUserId()); + if (user === undefined) { + throw Error( + "this error should never be thrown. Can't find primary user with userId: " + session.getUserId() + ); + } + let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + if (recipeUser === undefined) { + throw Error( + "this error should never be thrown. Can't find emailPassword recipeUser with email: " + + email + + " and primary userId: " + + session.getUserId() + ); + } return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: false, - description: "", + status: "OK", + user: { + id: user.id, + recipeUserId: recipeUser.id, + timeJoined: recipeUser.timeJoined, + email, + }, + createdNewRecipeUser, + wereAccountsAlreadyLinked, + session, }; }, emailExistsGET: async function ({ @@ -90,21 +201,166 @@ export default function getAPIImplementation(): APIInterface { | GeneralErrorResponse > { let email = formFields.filter((f) => f.id === "email")[0].value; + let userIdForPasswordReset: string | undefined = undefined; + let recipeUserId: string | undefined = undefined; - let user = await options.recipeImplementation.getUserByEmail({ email, userContext }); - if (user === undefined) { + /** + * check if primaryUserId is linked with this email + */ + let users = await listUsersByAccountInfo({ + email, + }); + if (users !== undefined) { + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser !== undefined) { + /** + * checking if emailpassword user exists for the input email and associated with the primaryUserId + */ + let epUser = primaryUser.loginMethods.find((l) => l.recipeId === "emailpassword"); + if (epUser === undefined) { + /** + * this means no emailpassword user is associated with the primaryUserId which + * has the input email as identifying info + * now checking if emailpassword user exists for the input email + */ + let epRecipeUser = users.find( + (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + ); + if (epRecipeUser === undefined) { + /** + * this means that there is no emailpassword recipe user for the input email + * so we check is account linking is enabled for the given email and primaryUserId + */ + let shouldDoAccountLinking = await AccountLinkingRecipe.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + /** + * here, reset password token generation is not allowed + * and we have decided to return "OK" status + */ + return { + status: "OK", + }; + } + let identitiesForPrimaryUser = AccountLinkingRecipe.getInstanceOrThrowError().getIdentitiesForUser( + primaryUser + ); + /** + * if input email doens't belong to the verified indentity for the primaryUser, + * we need to check shouldRequireVerification boolean + */ + if (!identitiesForPrimaryUser.verified.emails.includes(email)) { + if (shouldDoAccountLinking.shouldRequireVerification) { + /** + * here, reset password token generation is not allowed + * an + */ + return { + status: "OK", + }; + } + } + userIdForPasswordReset = primaryUser.id; + } else { + /** + * this means emailpassword user associated with the input email exists but it + * is currently not associated with the primaryUserId we found in the + * previous step. We simply generate password reset token for such user + */ + userIdForPasswordReset = epRecipeUser.id; + recipeUserId = epRecipeUser.id; + } + } else { + /** + * the primaryUserId associated with the email has a linked + * emailpassword recipe user with same email + */ + recipeUserId = epUser.recipeUserId; + /** + * checking for shouldDoAccountLinking + */ + let shouldDoAccountLinking = await AccountLinkingRecipe.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); + let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink + ? shouldDoAccountLinking.shouldRequireVerification + : false; + if (shouldRequireVerification) { + /** + * if verification is required, we check if this is EP user is + * the only user associated with the primaryUserId. + */ + if (primaryUser.loginMethods.length > 1) { + /** + * checking if the email belongs to the verified identities for the + * primary user + */ + let identitiesForPrimaryUser = AccountLinkingRecipe.getInstanceOrThrowError().getIdentitiesForUser( + primaryUser + ); + if (!identitiesForPrimaryUser.verified.emails.includes(email)) { + /** + * the email is not verified for any account linked to the primary user. + * so we check if there exists any account linked with the primary user + * which doesn't have this email as identifying info + */ + let differentIdentityUser = primaryUser.loginMethods.find((u) => u.email !== email); + if (differentIdentityUser !== undefined) { + /** + * if any such user found, we return status to contact support + */ + return { + status: "GENERAL_ERROR", + message: "Password Reset Not Allowed. Please contact support.", + }; + } + } + } + } + userIdForPasswordReset = primaryUser.id; + } + } else { + /** + * no primaryUser exists for the given email. So we just find the + * associated emailpasword user, if exists + */ + let epRecipeUser = users.find( + (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + ); + if (epRecipeUser === undefined) { + return { + status: "OK", + }; + } + userIdForPasswordReset = epRecipeUser.id; + recipeUserId = epRecipeUser.id; + } + } else { return { status: "OK", }; } let response = await options.recipeImplementation.createResetPasswordToken({ - userId: user.recipeUserId, - email: user.email, + userId: userIdForPasswordReset, + email, userContext, }); if (response.status === "UNKNOWN_USER_ID_ERROR") { - logDebugMessage(`Password reset email not sent, unknown user id: ${user.id}`); + logDebugMessage(`Password reset email not sent, unknown user id: ${userIdForPasswordReset}`); return { status: "OK", }; @@ -121,7 +377,11 @@ export default function getAPIImplementation(): APIInterface { logDebugMessage(`Sending password reset email to ${email}`); await options.emailDelivery.ingredientInterfaceImpl.sendEmail({ type: "PASSWORD_RESET", - user, + user: { + id: userIdForPasswordReset, + recipeUserId, + email, + }, passwordResetLink, userContext, }); @@ -160,6 +420,84 @@ export default function getAPIImplementation(): APIInterface { userContext, }); + if (response.status === "OK") { + let userId = response.userId; + let email = response.email; + async function verifyUser(rUserId: string) { + const emailVerificationInstance = EmailVerification.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: rUserId, + email, + userContext, + } + ); + + if (tokenResponse.status === "OK") { + await emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext, + }); + } + } + } + let user = await getUser(userId); + if (user === undefined) { + throw Error("this error should never be thrown"); + } + /** + * check if the user is a primaryUser + */ + if (user.isPrimaryUser) { + /** + * check if there exists an emailpassword recipe user + * associated with the primary user with the same email + * which is returned by core in the response + */ + let epUser = user.loginMethods.find((u) => u.email === email && u.recipeId === "emailpassword"); + if (epUser === undefined) { + /** + * create a new emailpassword recipe user + */ + let response = await options.recipeImplementation.signUp({ + email, + password: newPassword, + userContext, + }); + if (response.status !== "OK") { + throw Error("this error should not be thrown. EP user already for email: " + email); + } + let recipeUser = response.user; + await verifyUser(response.user.id); + await AccountLinkingRecipe.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); + } else if (!epUser.verified) { + await verifyUser(epUser.id); + } + } else { + /** + * it's a recipe user + */ + if (!user.loginMethods[0].verified) { + await verifyUser(user.loginMethods[0].id); + } + const session = await Session.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [], sessionRequired: false }, + userContext + ); + await AccountLinkingRecipe.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + recipeUserId: user.id, + session, + userContext, + }); + } + } return response; }, signInPOST: async function ({ diff --git a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts index 7928535eb..acc8e5348 100644 --- a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts +++ b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts @@ -12,10 +12,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -import { TypeEmailPasswordEmailDeliveryInput, User, RecipeInterface } from "../../../types"; +import { TypeEmailPasswordEmailDeliveryInput, RecipeInterface } from "../../../types"; import { createAndSendCustomEmail as defaultCreateAndSendCustomEmail } from "../../../passwordResetFunctions"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; +import { getUser } from "../../../../.."; export default class BackwardCompatibilityService implements EmailDeliveryInterface { @@ -23,42 +24,56 @@ export default class BackwardCompatibilityService private isInServerlessEnv: boolean; private appInfo: NormalisedAppinfo; private resetPasswordUsingTokenFeature: { - createAndSendCustomEmail: (user: User, passwordResetURLWithToken: string, userContext: any) => Promise; + createAndSendCustomEmail: ( + user: { + id: string; + recipeUserId?: string; + email: string; + timeJoined: number; + }, + passwordResetURLWithToken: string, + userContext: any + ) => Promise; }; - constructor( - recipeInterfaceImpl: RecipeInterface, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - resetPasswordUsingTokenFeature?: { - createAndSendCustomEmail?: ( - user: User, - passwordResetURLWithToken: string, - userContext: any - ) => Promise; - } - ) { + constructor(recipeInterfaceImpl: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean) { this.recipeInterfaceImpl = recipeInterfaceImpl; this.isInServerlessEnv = isInServerlessEnv; this.appInfo = appInfo; { - let inputCreateAndSendCustomEmail = resetPasswordUsingTokenFeature?.createAndSendCustomEmail; - this.resetPasswordUsingTokenFeature = - inputCreateAndSendCustomEmail !== undefined - ? { - createAndSendCustomEmail: inputCreateAndSendCustomEmail, - } - : { - createAndSendCustomEmail: defaultCreateAndSendCustomEmail(this.appInfo), - }; + this.resetPasswordUsingTokenFeature = { + createAndSendCustomEmail: defaultCreateAndSendCustomEmail(this.appInfo), + }; } } sendEmail = async (input: TypeEmailPasswordEmailDeliveryInput & { userContext: any }) => { - let user = await this.recipeInterfaceImpl.getUserById({ - userId: input.user.recipeUserId, - userContext: input.userContext, - }); + let user: + | { + id: string; + recipeUserId?: string; + email: string; + timeJoined: number; + } + | undefined = + input.user.recipeUserId !== undefined + ? await this.recipeInterfaceImpl.getUserById({ + userId: input.user.recipeUserId, + userContext: input.userContext, + }) + : undefined; + if (input.user.recipeUserId === undefined) { + let primaryUser = await getUser(input.user.id); + if (primaryUser === undefined) { + throw Error("this should never come here"); + } + user = { + id: primaryUser.id, + recipeUserId: undefined, + timeJoined: primaryUser.timeJoined, + email: input.user.email, + }; + } if (user === undefined) { throw Error("this should never come here"); } diff --git a/lib/ts/recipe/emailpassword/passwordResetFunctions.ts b/lib/ts/recipe/emailpassword/passwordResetFunctions.ts index d5671a545..c620afea5 100644 --- a/lib/ts/recipe/emailpassword/passwordResetFunctions.ts +++ b/lib/ts/recipe/emailpassword/passwordResetFunctions.ts @@ -13,13 +13,20 @@ * under the License. */ -import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; import axios, { AxiosError } from "axios"; import { logDebugMessage } from "../../logger"; export function createAndSendCustomEmail(appInfo: NormalisedAppinfo) { - return async (user: User, passwordResetURLWithToken: string) => { + return async ( + user: { + id: string; + recipeUserId?: string; + email: string; + timeJoined: number; + }, + passwordResetURLWithToken: string + ) => { // related issue: https://github.com/supertokens/supertokens-node/issues/38 if (process.env.TEST_MODE === "testing") { return; diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index 7ee518b0e..793e2465b 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -1,6 +1,8 @@ import { RecipeInterface, User } from "./types"; import { Querier } from "../../querier"; import NormalisedURLPath from "../../normalisedURLPath"; +import { getUser, listUsersByAccountInfo } from "../.."; +import EmailVerification from "../emailverification/recipe"; export default function getRecipeInterface(querier: Querier): RecipeInterface { return { @@ -72,11 +74,14 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { createResetPasswordToken: async function ({ userId, + email, }: { userId: string; + email: string; }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }> { let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/user/password/reset/token"), { userId, + email, }); if (response.status === "OK") { return { @@ -116,13 +121,54 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { userId: string; email?: string; password?: string; - }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise<{ + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + }> { + let markEmailAsVerified = false; + if (input.email !== undefined) { + let userForUserId = await getUser(input.userId); + if (userForUserId !== undefined && userForUserId.isPrimaryUser) { + let usersForEmail = await listUsersByAccountInfo({ + email: input.email, + }); + if (usersForEmail !== undefined) { + let primaryUserFromEmailUsers = usersForEmail.find((u) => u.isPrimaryUser); + if (primaryUserFromEmailUsers !== undefined) { + if (primaryUserFromEmailUsers.id !== userForUserId.id) { + return { + status: "EMAIL_CHANGE_NOT_ALLOWED", + }; + } + markEmailAsVerified = true; + } + } + } + } let response = await querier.sendPutRequest(new NormalisedURLPath("/recipe/user"), { userId: input.userId, email: input.email, password: input.password, }); if (response.status === "OK") { + if (markEmailAsVerified && input.email !== undefined) { + const emailVerificationInstance = EmailVerification.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: input.userId, + email: input.email, + userContext: undefined, + } + ); + + if (tokenResponse.status === "OK") { + await emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext: undefined, + }); + } + } + } return { status: "OK", }; diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index 3a77e8507..d04182647 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -66,13 +66,6 @@ export type TypeNormalisedInputSignIn = { formFields: NormalisedFormField[]; }; -export type TypeInputResetPasswordUsingTokenFeature = { - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: (user: User, passwordResetURLWithToken: string, userContext: any) => Promise; -}; - export type TypeNormalisedInputResetPasswordUsingTokenFeature = { formFieldsForGenerateTokenForm: NormalisedFormField[]; formFieldsForPasswordResetForm: NormalisedFormField[]; @@ -88,7 +81,6 @@ export type User = { export type TypeInput = { signUpFeature?: TypeInputSignUp; emailDelivery?: EmailDeliveryTypeInput; - resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override?: { functions?: ( originalImplementation: RecipeInterface, @@ -151,7 +143,7 @@ export type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; }>; }; @@ -315,7 +307,7 @@ export type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; user: { id: string; - recipeUserId: string; + recipeUserId?: string; email: string; }; passwordResetLink: string; diff --git a/lib/ts/recipe/emailpassword/utils.ts b/lib/ts/recipe/emailpassword/utils.ts index 27cade323..9cd12c4a0 100644 --- a/lib/ts/recipe/emailpassword/utils.ts +++ b/lib/ts/recipe/emailpassword/utils.ts @@ -53,19 +53,11 @@ export function validateAndNormaliseUserInput( function getEmailDeliveryConfig(recipeImpl: RecipeInterface, isInServerlessEnv: boolean) { let emailService = config?.emailDelivery?.service; /** - * following code is for backward compatibility. - * if user has not passed emailDelivery config, we - * use the createAndSendCustomEmail config. If the user - * has not passed even that config, we use the default + * If the user has not passed even that config, we use the default * createAndSendCustomEmail implementation which calls our supertokens API */ if (emailService === undefined) { - emailService = new BackwardCompatibilityService( - recipeImpl, - appInfo, - isInServerlessEnv, - config?.resetPasswordUsingTokenFeature - ); + emailService = new BackwardCompatibilityService(recipeImpl, appInfo, isInServerlessEnv); } return { ...config?.emailDelivery, diff --git a/lib/ts/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.ts b/lib/ts/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.ts index e6c6f07b1..c585bcb58 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.ts @@ -12,7 +12,7 @@ * License for the specific language governing permissions and limitations * under the License. */ -import { TypeThirdPartyEmailPasswordEmailDeliveryInput, User } from "../../../types"; +import { TypeThirdPartyEmailPasswordEmailDeliveryInput } from "../../../types"; import { RecipeInterface as EmailPasswordRecipeInterface } from "../../../../emailpassword"; import { NormalisedAppinfo } from "../../../../../types"; import EmailPasswordBackwardCompatibilityService from "../../../../emailpassword/emaildelivery/services/backwardCompatibility"; @@ -25,21 +25,13 @@ export default class BackwardCompatibilityService constructor( emailPasswordRecipeInterfaceImpl: EmailPasswordRecipeInterface, appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - resetPasswordUsingTokenFeature?: { - createAndSendCustomEmail?: ( - user: User, - passwordResetURLWithToken: string, - userContext: any - ) => Promise; - } + isInServerlessEnv: boolean ) { { this.emailPasswordBackwardCompatibilityService = new EmailPasswordBackwardCompatibilityService( emailPasswordRecipeInterfaceImpl, appInfo, - isInServerlessEnv, - resetPasswordUsingTokenFeature + isInServerlessEnv ); } } diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipe.ts b/lib/ts/recipe/thirdpartyemailpassword/recipe.ts index d796181de..38779aa7a 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipe.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipe.ts @@ -118,7 +118,6 @@ export default class Recipe extends RecipeModule { signUpFeature: { formFields: this.config.signUpFeature.formFields, }, - resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, }, { emailDelivery: this.emailDelivery, diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts index fa68edf9b..e8d3e8319 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts @@ -55,7 +55,9 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw email?: string; password?: string; userContext: any; - }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise<{ + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + }> { return recipeInterface.updateEmailOrPassword(input); }, }; diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts index d61f91a64..dbcac64b9 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts @@ -109,7 +109,7 @@ export default function getRecipeInterface( userContext: any; } ): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; }> { let user = await this.getUserById({ userId: input.userId, userContext: input.userContext }); if (user === undefined) { diff --git a/lib/ts/recipe/thirdpartyemailpassword/types.ts b/lib/ts/recipe/thirdpartyemailpassword/types.ts index fee2260fa..7db5d7097 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/types.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/types.ts @@ -17,7 +17,6 @@ import { NormalisedFormField, TypeFormField, TypeInputFormField, - TypeInputResetPasswordUsingTokenFeature, APIOptions as EmailPasswordAPIOptionsOriginal, TypeEmailPasswordEmailDeliveryInput, RecipeInterface as EPRecipeInterface, @@ -67,7 +66,6 @@ export type TypeInput = { signUpFeature?: TypeInputSignUp; providers?: TypeProvider[]; emailDelivery?: EmailDeliveryTypeInput; - resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override?: { functions?: ( originalImplementation: RecipeInterface, @@ -84,7 +82,6 @@ export type TypeNormalisedInput = { emailPasswordRecipeImpl: EPRecipeInterface, isInServerlessEnv: boolean ) => EmailDeliveryTypeInputWithService; - resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override: { functions: ( originalImplementation: RecipeInterface, @@ -149,7 +146,7 @@ export type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; }>; }; diff --git a/lib/ts/recipe/thirdpartyemailpassword/utils.ts b/lib/ts/recipe/thirdpartyemailpassword/utils.ts index 2c1577768..b27c6239d 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/utils.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/utils.ts @@ -33,8 +33,6 @@ export function validateAndNormaliseUserInput( config === undefined ? undefined : config.signUpFeature ); - let resetPasswordUsingTokenFeature = config === undefined ? undefined : config.resetPasswordUsingTokenFeature; - let providers = config === undefined || config.providers === undefined ? [] : config.providers; let override = { @@ -53,12 +51,7 @@ export function validateAndNormaliseUserInput( * createAndSendCustomEmail implementation */ if (emailService === undefined) { - emailService = new BackwardCompatibilityService( - emailPasswordRecipeImpl, - appInfo, - isInServerlessEnv, - config?.resetPasswordUsingTokenFeature - ); + emailService = new BackwardCompatibilityService(emailPasswordRecipeImpl, appInfo, isInServerlessEnv); } return { ...config?.emailDelivery, @@ -82,7 +75,6 @@ export function validateAndNormaliseUserInput( getEmailDeliveryConfig, signUpFeature, providers, - resetPasswordUsingTokenFeature, }; } From da1c640a9574b7c16ad8fcc6425f8595c84c1fc0 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 30 Jan 2023 01:56:46 +0530 Subject: [PATCH 23/82] sign-up post login updated --- .../api/linkAccountToExistingAccount.d.ts | 6 ++ .../api/linkAccountToExistingAccount.js | 99 +++++++++++++++++++ lib/build/recipe/emailpassword/constants.d.ts | 1 + lib/build/recipe/emailpassword/constants.js | 1 + lib/build/recipe/emailpassword/recipe.js | 8 ++ .../api/linkAccountToExistingAccount.ts | 75 ++++++++++++++ lib/ts/recipe/emailpassword/constants.ts | 2 + lib/ts/recipe/emailpassword/recipe.ts | 7 ++ 8 files changed, 199 insertions(+) create mode 100644 lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts create mode 100644 lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js create mode 100644 lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts diff --git a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts new file mode 100644 index 000000000..5588e7dd1 --- /dev/null +++ b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts @@ -0,0 +1,6 @@ +// @ts-nocheck +import { APIInterface, APIOptions } from ".."; +export default function linkAccountToExistingAccountAPI( + apiImplementation: APIInterface, + options: APIOptions +): Promise; diff --git a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js new file mode 100644 index 000000000..627d05fb0 --- /dev/null +++ b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js @@ -0,0 +1,99 @@ +"use strict"; +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("../../../utils"); +const utils_2 = require("./utils"); +const error_1 = require("../error"); +const utils_3 = require("../../../utils"); +const session_1 = require("../../session"); +function linkAccountToExistingAccountAPI(apiImplementation, options) { + return __awaiter(this, void 0, void 0, function* () { + // Logic as per https://github.com/supertokens/supertokens-node/issues/21#issuecomment-710423536 + if (apiImplementation.linkAccountToExistingAccountPOST === undefined) { + return false; + } + // step 1 + let formFields = yield utils_2.validateFormFieldsOrThrowError( + options.config.signUpFeature.formFields, + (yield options.req.getJSONBody()).formFields + ); + let userContext = utils_3.makeDefaultUserContextFromAPI(options.req); + const session = yield session_1.default.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [] }, + userContext + ); + let result = yield apiImplementation.linkAccountToExistingAccountPOST({ + formFields, + session: session, + options, + userContext, + }); + if (result.status === "OK") { + utils_1.send200Response(options.res, { + status: "OK", + user: result.user, + }); + } else if (result.status === "GENERAL_ERROR") { + utils_1.send200Response(options.res, result); + } else { + throw new error_1.default({ + type: error_1.default.FIELD_ERROR, + payload: [ + { + id: "email", + error: "This email already exists. Please sign in instead.", + }, + ], + message: "Error in input formFields", + }); + } + return true; + }); +} +exports.default = linkAccountToExistingAccountAPI; diff --git a/lib/build/recipe/emailpassword/constants.d.ts b/lib/build/recipe/emailpassword/constants.d.ts index 9b58b697a..04d93fceb 100644 --- a/lib/build/recipe/emailpassword/constants.d.ts +++ b/lib/build/recipe/emailpassword/constants.d.ts @@ -6,3 +6,4 @@ export declare const SIGN_IN_API = "/signin"; export declare const GENERATE_PASSWORD_RESET_TOKEN_API = "/user/password/reset/token"; export declare const PASSWORD_RESET_API = "/user/password/reset"; export declare const SIGNUP_EMAIL_EXISTS_API = "/signup/email/exists"; +export declare const LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/link-account/signup"; diff --git a/lib/build/recipe/emailpassword/constants.js b/lib/build/recipe/emailpassword/constants.js index 5a9dad752..dd75468bd 100644 --- a/lib/build/recipe/emailpassword/constants.js +++ b/lib/build/recipe/emailpassword/constants.js @@ -21,3 +21,4 @@ exports.SIGN_IN_API = "/signin"; exports.GENERATE_PASSWORD_RESET_TOKEN_API = "/user/password/reset/token"; exports.PASSWORD_RESET_API = "/user/password/reset"; exports.SIGNUP_EMAIL_EXISTS_API = "/signup/email/exists"; +exports.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/link-account/signup"; diff --git a/lib/build/recipe/emailpassword/recipe.js b/lib/build/recipe/emailpassword/recipe.js index 9dc18f245..6c95f82e5 100644 --- a/lib/build/recipe/emailpassword/recipe.js +++ b/lib/build/recipe/emailpassword/recipe.js @@ -101,6 +101,14 @@ class Recipe extends recipeModule_1.default { id: constants_1.SIGNUP_EMAIL_EXISTS_API, disabled: this.apiImpl.emailExistsGET === undefined, }, + { + method: "post", + pathWithoutApiBasePath: new normalisedURLPath_1.default( + constants_1.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API + ), + id: constants_1.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API, + disabled: this.apiImpl.linkAccountToExistingAccountPOST === undefined, + }, ]; }; this.handleAPIRequest = (id, req, res, _path, _method) => diff --git a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts new file mode 100644 index 000000000..43b20ac31 --- /dev/null +++ b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts @@ -0,0 +1,75 @@ +/* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +import { send200Response } from "../../../utils"; +import { validateFormFieldsOrThrowError } from "./utils"; +import { APIInterface, APIOptions } from ".."; +import STError from "../error"; +import { makeDefaultUserContextFromAPI } from "../../../utils"; +import Session from "../../session"; + +export default async function linkAccountToExistingAccountAPI( + apiImplementation: APIInterface, + options: APIOptions +): Promise { + // Logic as per https://github.com/supertokens/supertokens-node/issues/21#issuecomment-710423536 + + if (apiImplementation.linkAccountToExistingAccountPOST === undefined) { + return false; + } + + // step 1 + let formFields: { + id: string; + value: string; + }[] = await validateFormFieldsOrThrowError( + options.config.signUpFeature.formFields, + (await options.req.getJSONBody()).formFields + ); + + let userContext = makeDefaultUserContextFromAPI(options.req); + const session = await Session.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [] }, + userContext + ); + let result = await apiImplementation.linkAccountToExistingAccountPOST({ + formFields, + session: session, + options, + userContext, + }); + if (result.status === "OK") { + send200Response(options.res, { + status: "OK", + user: result.user, + }); + } else if (result.status === "GENERAL_ERROR") { + send200Response(options.res, result); + } else { + throw new STError({ + type: STError.FIELD_ERROR, + payload: [ + { + id: "email", + error: "This email already exists. Please sign in instead.", + }, + ], + message: "Error in input formFields", + }); + } + return true; +} diff --git a/lib/ts/recipe/emailpassword/constants.ts b/lib/ts/recipe/emailpassword/constants.ts index 730d815c7..a152f0da8 100644 --- a/lib/ts/recipe/emailpassword/constants.ts +++ b/lib/ts/recipe/emailpassword/constants.ts @@ -26,3 +26,5 @@ export const GENERATE_PASSWORD_RESET_TOKEN_API = "/user/password/reset/token"; export const PASSWORD_RESET_API = "/user/password/reset"; export const SIGNUP_EMAIL_EXISTS_API = "/signup/email/exists"; + +export const LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/link-account/signup"; diff --git a/lib/ts/recipe/emailpassword/recipe.ts b/lib/ts/recipe/emailpassword/recipe.ts index 094ad0e4c..5b8626318 100644 --- a/lib/ts/recipe/emailpassword/recipe.ts +++ b/lib/ts/recipe/emailpassword/recipe.ts @@ -25,6 +25,7 @@ import { GENERATE_PASSWORD_RESET_TOKEN_API, PASSWORD_RESET_API, SIGNUP_EMAIL_EXISTS_API, + LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API, } from "./constants"; import signUpAPI from "./api/signup"; import signInAPI from "./api/signin"; @@ -158,6 +159,12 @@ export default class Recipe extends RecipeModule { id: SIGNUP_EMAIL_EXISTS_API, disabled: this.apiImpl.emailExistsGET === undefined, }, + { + method: "post", + pathWithoutApiBasePath: new NormalisedURLPath(LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API), + id: LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API, + disabled: this.apiImpl.linkAccountToExistingAccountPOST === undefined, + }, ]; }; From 9cddbba93575d141a44fcd52acc35d6380f8c276 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 30 Jan 2023 11:19:28 +0530 Subject: [PATCH 24/82] sign-up API implementation update --- .../emailpassword/api/implementation.js | 28 ++++++++++++- .../emailpassword/api/implementation.ts | 39 +++++++++++++++++-- 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index c8aa3b12f..0d6bd5236 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -472,14 +472,38 @@ function getAPIImplementation() { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; + let isSignUpAllowed = yield recipe_1.default.getInstanceOrThrowError().isSignUpAllowed({ + info: { + recipeId: "emailpassword", + email, + }, + userContext, + }); + if (!isSignUpAllowed) { + return { + status: "SIGNUP_NOT_ALLOWED", + reason: "the sign-up info is already associated with another account where it is not verified", + }; + } let response = yield options.recipeImplementation.signUp({ email, password, userContext }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; } let user = response.user; + let userIdForSession = yield recipe_1.default + .getInstanceOrThrowError() + .doPostSignUpAccountLinkingOperations({ + info: { + email, + recipeId: "emailpassword", + }, + recipeUserId: user.id, + userContext, + infoVerified: false, + }); let session = yield session_1.default.createNewSession( options.res, - user.id, + userIdForSession, user.recipeUserId, {}, {}, @@ -489,7 +513,7 @@ function getAPIImplementation() { status: "OK", session, user, - createdNewUser: true, + createdNewUser: userIdForSession === user.recipeUserId, createdNewRecipeUser: true, }; }); diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 22b9cecbe..6bf7f8011 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -569,19 +569,52 @@ export default function getAPIImplementation(): APIInterface { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; + let isSignUpAllowed = await AccountLinkingRecipe.getInstanceOrThrowError().isSignUpAllowed({ + info: { + recipeId: "emailpassword", + email, + }, + userContext, + }); + + if (!isSignUpAllowed) { + return { + status: "SIGNUP_NOT_ALLOWED", + reason: "the sign-up info is already associated with another account where it is not verified", + }; + } let response = await options.recipeImplementation.signUp({ email, password, userContext }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; } let user = response.user; - let session = await Session.createNewSession(options.res, user.id, user.recipeUserId, {}, {}, userContext); + let userIdForSession = await AccountLinkingRecipe.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations( + { + info: { + email, + recipeId: "emailpassword", + }, + recipeUserId: user.id, + userContext, + infoVerified: false, + } + ); + + let session = await Session.createNewSession( + options.res, + userIdForSession, + user.recipeUserId, + {}, + {}, + userContext + ); return { status: "OK", session, user, - createdNewUser: true, // TODO - createdNewRecipeUser: true, // TODO + createdNewUser: userIdForSession === user.recipeUserId, // TODO + createdNewRecipeUser: true, }; }, }; From ed042271cf841f58227cb01c4b810bf78248005f Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 30 Jan 2023 18:16:29 +0530 Subject: [PATCH 25/82] import update --- .../emailpassword/api/implementation.js | 27 +++++++++---------- .../emailpassword/api/implementation.ts | 27 +++++++++---------- 2 files changed, 24 insertions(+), 30 deletions(-) diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index 0d6bd5236..c0dc779e0 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -34,6 +34,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const session_1 = require("../../session"); const __1 = require("../../../"); +const accountlinking_1 = require("../../accountlinking"); const recipe_1 = require("../../accountlinking/recipe"); const recipe_2 = require("../../emailverification/recipe"); function getAPIImplementation() { @@ -41,15 +42,15 @@ function getAPIImplementation() { linkAccountToExistingAccountPOST: function ({ formFields, session, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; - let result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + let result = yield accountlinking_1.default.accountLinkPostSignInViaSession( session, - info: { + { email, recipeId: "emailpassword", }, - infoVerified: false, - userContext, - }); + false, + userContext + ); let createdNewRecipeUser = false; if (result.createRecipeUser) { let password = formFields.filter((f) => f.id === "password")[0].value; @@ -68,15 +69,15 @@ function getAPIImplementation() { description: "", }; } else { - result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + result = yield accountlinking_1.default.accountLinkPostSignInViaSession( session, - info: { + { email, recipeId: "emailpassword", }, - infoVerified: false, - userContext, - }); + false, + userContext + ); } } if (result.createRecipeUser) { @@ -413,11 +414,7 @@ function getAPIImplementation() { } let recipeUser = response.user; yield verifyUser(response.user.id); - yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, - userContext, - }); + yield accountlinking_1.default.linkAccounts(recipeUser.id, user.id, userContext); } else if (!epUser.verified) { yield verifyUser(epUser.id); } diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 6bf7f8011..948e0ef95 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -4,6 +4,7 @@ import Session from "../../session"; import { SessionContainerInterface } from "../../session/types"; import { GeneralErrorResponse } from "../../../types"; import { listUsersByAccountInfo, getUser } from "../../../"; +import AccountLinking from "../../accountlinking"; import AccountLinkingRecipe from "../../accountlinking/recipe"; import EmailVerification from "../../emailverification/recipe"; @@ -52,15 +53,15 @@ export default function getAPIImplementation(): APIInterface { | GeneralErrorResponse > { let email = formFields.filter((f) => f.id === "email")[0].value; - let result = await AccountLinkingRecipe.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + let result = await AccountLinking.accountLinkPostSignInViaSession( session, - info: { + { email, recipeId: "emailpassword", }, - infoVerified: false, - userContext, - }); + false, + userContext + ); let createdNewRecipeUser = false; if (result.createRecipeUser) { let password = formFields.filter((f) => f.id === "password")[0].value; @@ -80,15 +81,15 @@ export default function getAPIImplementation(): APIInterface { description: "", }; } else { - result = await AccountLinkingRecipe.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + result = await AccountLinking.accountLinkPostSignInViaSession( session, - info: { + { email, recipeId: "emailpassword", }, - infoVerified: false, - userContext, - }); + false, + userContext + ); } } if (result.createRecipeUser) { @@ -470,11 +471,7 @@ export default function getAPIImplementation(): APIInterface { } let recipeUser = response.user; await verifyUser(response.user.id); - await AccountLinkingRecipe.getInstanceOrThrowError().recipeInterfaceImpl.linkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, - userContext, - }); + await AccountLinking.linkAccounts(recipeUser.id, user.id, userContext); } else if (!epUser.verified) { await verifyUser(epUser.id); } From fb5fb4370886ed101263901aefe758a42d39f08c Mon Sep 17 00:00:00 2001 From: Bhumil Date: Wed, 1 Feb 2023 18:50:40 +0530 Subject: [PATCH 26/82] function import update --- .../emailpassword/api/implementation.js | 28 +++++++++---------- .../emailpassword/api/implementation.ts | 24 ++++++++-------- 2 files changed, 24 insertions(+), 28 deletions(-) diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index c0dc779e0..16513471d 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -469,13 +469,13 @@ function getAPIImplementation() { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; - let isSignUpAllowed = yield recipe_1.default.getInstanceOrThrowError().isSignUpAllowed({ - info: { + let isSignUpAllowed = yield accountlinking_1.default.isSignUpAllowed( + { recipeId: "emailpassword", email, }, - userContext, - }); + userContext + ); if (!isSignUpAllowed) { return { status: "SIGNUP_NOT_ALLOWED", @@ -487,17 +487,15 @@ function getAPIImplementation() { return response; } let user = response.user; - let userIdForSession = yield recipe_1.default - .getInstanceOrThrowError() - .doPostSignUpAccountLinkingOperations({ - info: { - email, - recipeId: "emailpassword", - }, - recipeUserId: user.id, - userContext, - infoVerified: false, - }); + let userIdForSession = yield accountlinking_1.default.doPostSignUpAccountLinkingOperations( + { + email, + recipeId: "emailpassword", + }, + false, + user.id, + userContext + ); let session = yield session_1.default.createNewSession( options.res, userIdForSession, diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 948e0ef95..06075ca7f 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -566,13 +566,13 @@ export default function getAPIImplementation(): APIInterface { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; - let isSignUpAllowed = await AccountLinkingRecipe.getInstanceOrThrowError().isSignUpAllowed({ - info: { + let isSignUpAllowed = await AccountLinking.isSignUpAllowed( + { recipeId: "emailpassword", email, }, - userContext, - }); + userContext + ); if (!isSignUpAllowed) { return { @@ -586,16 +586,14 @@ export default function getAPIImplementation(): APIInterface { } let user = response.user; - let userIdForSession = await AccountLinkingRecipe.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations( + let userIdForSession = await AccountLinking.doPostSignUpAccountLinkingOperations( { - info: { - email, - recipeId: "emailpassword", - }, - recipeUserId: user.id, - userContext, - infoVerified: false, - } + email, + recipeId: "emailpassword", + }, + false, + user.id, + userContext ); let session = await Session.createNewSession( From c0fd1be1ff3c45ce3c8206f4dd88ba26dabbb487 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Thu, 2 Feb 2023 16:18:24 +0530 Subject: [PATCH 27/82] changes in signup recipeimplementation --- lib/build/recipe/accountlinking/index.d.ts | 45 ++++++++- lib/build/recipe/accountlinking/index.js | 22 +++++ .../emailpassword/api/implementation.js | 91 +++++++++---------- lib/build/recipe/emailpassword/index.d.ts | 1 + lib/build/recipe/emailpassword/index.js | 3 +- .../emailpassword/recipeImplementation.js | 15 ++- lib/build/recipe/emailpassword/types.d.ts | 1 + .../recipe/thirdpartyemailpassword/index.d.ts | 1 + .../recipe/thirdpartyemailpassword/index.js | 3 +- .../recipe/thirdpartyemailpassword/types.d.ts | 1 + lib/ts/recipe/accountlinking/index.ts | 31 ++++++- .../emailpassword/api/implementation.ts | 55 ++++------- lib/ts/recipe/emailpassword/index.ts | 3 +- .../emailpassword/recipeImplementation.ts | 17 ++++ lib/ts/recipe/emailpassword/types.ts | 1 + .../recipe/thirdpartyemailpassword/index.ts | 8 +- .../emailPasswordRecipeImplementation.ts | 1 + .../recipeImplementation/index.ts | 1 + .../recipe/thirdpartyemailpassword/types.ts | 1 + 19 files changed, 207 insertions(+), 94 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 36a400a2a..9169315c4 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,7 +1,8 @@ // @ts-nocheck import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { AccountInfoAndEmailWithRecipeId, RecipeInterface } from "./types"; +import type { AccountInfoAndEmailWithRecipeId, RecipeInterface, RecipeLevelUser } from "./types"; +import type { User } from "../../types"; export default class Wrapper { static init: typeof Recipe.init; static getRecipeUserIdsForPrimaryUserIds( @@ -46,7 +47,7 @@ export default class Wrapper { ): Promise< | { status: "OK"; - user: import("../../types").User; + user: User; } | { status: @@ -117,7 +118,7 @@ export default class Wrapper { static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId( recipeUserId: string, userContext?: any - ): Promise; + ): Promise; static isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any): Promise; static doPostSignUpAccountLinkingOperations( info: AccountInfoAndEmailWithRecipeId, @@ -165,6 +166,41 @@ export default class Wrapper { session: SessionContainer | undefined, userContext?: any ): Promise; + static onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any): Promise; + static shouldDoAutomaticAccountLinking( + newAccountInfo: AccountInfoAndEmailWithRecipeId, + user: User | undefined, + session: SessionContainer | undefined, + userContext?: any + ): Promise< + | { + shouldAutomaticallyLink: false; + } + | { + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + } + >; + static getIdentitiesForUser( + user: User + ): { + verified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + id: string; + userId: string; + }[]; + }; + unverified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + id: string; + userId: string; + }[]; + }; + }; } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; @@ -180,4 +216,7 @@ export declare const isSignUpAllowed: typeof Wrapper.isSignUpAllowed; export declare const doPostSignUpAccountLinkingOperations: typeof Wrapper.doPostSignUpAccountLinkingOperations; export declare const accountLinkPostSignInViaSession: typeof Wrapper.accountLinkPostSignInViaSession; export declare const createPrimaryUserIdOrLinkAccounts: typeof Wrapper.createPrimaryUserIdOrLinkAccounts; +export declare const onAccountLinked: typeof Wrapper.onAccountLinked; +export declare const shouldDoAutomaticAccountLinking: typeof Wrapper.shouldDoAutomaticAccountLinking; +export declare const getIdentitiesForUser: typeof Wrapper.getIdentitiesForUser; export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 0ae668663..96bdf43d3 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -168,6 +168,25 @@ class Wrapper { }); }); } + static onAccountLinked(user, newAccountInfo, userContext) { + return __awaiter(this, void 0, void 0, function* () { + userContext = userContext === undefined ? {} : userContext; + return yield recipe_1.default + .getInstanceOrThrowError() + .config.onAccountLinked(user, newAccountInfo, userContext); + }); + } + static shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext) { + return __awaiter(this, void 0, void 0, function* () { + userContext = userContext === undefined ? {} : userContext; + return yield recipe_1.default + .getInstanceOrThrowError() + .config.shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext); + }); + } + static getIdentitiesForUser(user) { + return recipe_1.default.getInstanceOrThrowError().getIdentitiesForUser(user); + } } exports.default = Wrapper; Wrapper.init = recipe_1.default.init; @@ -185,3 +204,6 @@ exports.isSignUpAllowed = Wrapper.isSignUpAllowed; exports.doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; exports.accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; exports.createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; +exports.onAccountLinked = Wrapper.onAccountLinked; +exports.shouldDoAutomaticAccountLinking = Wrapper.shouldDoAutomaticAccountLinking; +exports.getIdentitiesForUser = Wrapper.getIdentitiesForUser; diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index 16513471d..f2a1b4341 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -35,8 +35,7 @@ const logger_1 = require("../../../logger"); const session_1 = require("../../session"); const __1 = require("../../../"); const accountlinking_1 = require("../../accountlinking"); -const recipe_1 = require("../../accountlinking/recipe"); -const recipe_2 = require("../../emailverification/recipe"); +const recipe_1 = require("../../emailverification/recipe"); function getAPIImplementation() { return { linkAccountToExistingAccountPOST: function ({ formFields, session, options, userContext }) { @@ -54,7 +53,12 @@ function getAPIImplementation() { let createdNewRecipeUser = false; if (result.createRecipeUser) { let password = formFields.filter((f) => f.id === "password")[0].value; - let response = yield options.recipeImplementation.signUp({ email, password, userContext }); + let response = yield options.recipeImplementation.signUp({ + email, + password, + doAutomaticAccountLinking: false, + userContext, + }); if (response.status !== "OK") { throw Error( `this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}` @@ -191,17 +195,15 @@ function getAPIImplementation() { * this means that there is no emailpassword recipe user for the input email * so we check is account linking is enabled for the given email and primaryUserId */ - let shouldDoAccountLinking = yield recipe_1.default - .getInstanceOrThrowError() - .config.shouldDoAutomaticAccountLinking( - { - email, - recipeId: "emailpassword", - }, - primaryUser, - undefined, - userContext - ); + let shouldDoAccountLinking = yield accountlinking_1.default.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { /** * here, reset password token generation is not allowed @@ -211,9 +213,9 @@ function getAPIImplementation() { status: "OK", }; } - let identitiesForPrimaryUser = recipe_1.default - .getInstanceOrThrowError() - .getIdentitiesForUser(primaryUser); + let identitiesForPrimaryUser = accountlinking_1.default.getIdentitiesForUser( + primaryUser + ); /** * if input email doens't belong to the verified indentity for the primaryUser, * we need to check shouldRequireVerification boolean @@ -248,17 +250,15 @@ function getAPIImplementation() { /** * checking for shouldDoAccountLinking */ - let shouldDoAccountLinking = yield recipe_1.default - .getInstanceOrThrowError() - .config.shouldDoAutomaticAccountLinking( - { - email, - recipeId: "emailpassword", - }, - primaryUser, - undefined, - userContext - ); + let shouldDoAccountLinking = yield accountlinking_1.default.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink ? shouldDoAccountLinking.shouldRequireVerification : false; @@ -272,9 +272,9 @@ function getAPIImplementation() { * checking if the email belongs to the verified identities for the * primary user */ - let identitiesForPrimaryUser = recipe_1.default - .getInstanceOrThrowError() - .getIdentitiesForUser(primaryUser); + let identitiesForPrimaryUser = accountlinking_1.default.getIdentitiesForUser( + primaryUser + ); if (!identitiesForPrimaryUser.verified.emails.includes(email)) { /** * the email is not verified for any account linked to the primary user. @@ -368,7 +368,7 @@ function getAPIImplementation() { let email = response.email; function verifyUser(rUserId) { return __awaiter(this, void 0, void 0, function* () { - const emailVerificationInstance = recipe_2.default.getInstance(); + const emailVerificationInstance = recipe_1.default.getInstance(); if (emailVerificationInstance) { const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( { @@ -408,6 +408,7 @@ function getAPIImplementation() { email, password: newPassword, userContext, + doAutomaticAccountLinking: false, }); if (response.status !== "OK") { throw Error("this error should not be thrown. EP user already for email: " + email); @@ -431,11 +432,7 @@ function getAPIImplementation() { { overrideGlobalClaimValidators: () => [], sessionRequired: false }, userContext ); - yield recipe_1.default.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ - recipeUserId: user.id, - session, - userContext, - }); + yield accountlinking_1.default.createPrimaryUserIdOrLinkAccounts(user.id, session, userContext); } } return response; @@ -482,23 +479,19 @@ function getAPIImplementation() { reason: "the sign-up info is already associated with another account where it is not verified", }; } - let response = yield options.recipeImplementation.signUp({ email, password, userContext }); + let response = yield options.recipeImplementation.signUp({ + email, + password, + doAutomaticAccountLinking: true, + userContext, + }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; } let user = response.user; - let userIdForSession = yield accountlinking_1.default.doPostSignUpAccountLinkingOperations( - { - email, - recipeId: "emailpassword", - }, - false, - user.id, - userContext - ); let session = yield session_1.default.createNewSession( options.res, - userIdForSession, + user.id, user.recipeUserId, {}, {}, @@ -508,7 +501,7 @@ function getAPIImplementation() { status: "OK", session, user, - createdNewUser: userIdForSession === user.recipeUserId, + createdNewUser: user.id === user.recipeUserId, createdNewRecipeUser: true, }; }); diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index b71bb9f94..805a0cde5 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -8,6 +8,7 @@ export default class Wrapper { static signUp( email: string, password: string, + doAutomaticAccountLinking?: boolean, userContext?: any ): Promise< | { diff --git a/lib/build/recipe/emailpassword/index.js b/lib/build/recipe/emailpassword/index.js index c430e0567..e71a7d8ee 100644 --- a/lib/build/recipe/emailpassword/index.js +++ b/lib/build/recipe/emailpassword/index.js @@ -48,10 +48,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); const recipe_1 = require("./recipe"); const error_1 = require("./error"); class Wrapper { - static signUp(email, password, userContext) { + static signUp(email, password, doAutomaticAccountLinking = false, userContext) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.signUp({ email, password, + doAutomaticAccountLinking, userContext: userContext === undefined ? {} : userContext, }); } diff --git a/lib/build/recipe/emailpassword/recipeImplementation.js b/lib/build/recipe/emailpassword/recipeImplementation.js index 8f3d69840..2f6146792 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -31,18 +31,31 @@ var __awaiter = }); }; Object.defineProperty(exports, "__esModule", { value: true }); +const accountlinking_1 = require("../accountlinking"); const normalisedURLPath_1 = require("../../normalisedURLPath"); const __1 = require("../.."); const recipe_1 = require("../emailverification/recipe"); function getRecipeInterface(querier) { return { - signUp: function ({ email, password }) { + signUp: function ({ email, password, doAutomaticAccountLinking, userContext }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signup"), { email, password, }); if (response.status === "OK") { + if (doAutomaticAccountLinking) { + let primaryUserId = yield accountlinking_1.default.doPostSignUpAccountLinkingOperations( + { + email, + recipeId: "emailpassword", + }, + false, + response.user.id, + userContext + ); + response.user.id = primaryUserId; + } return response; } else { return { diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index 7f9386b86..84d7aad19 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -72,6 +72,7 @@ export declare type RecipeInterface = { signUp(input: { email: string; password: string; + doAutomaticAccountLinking: boolean; userContext: any; }): Promise< | { diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index 717ffc5a0..17e1f3771 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -25,6 +25,7 @@ export default class Wrapper { static emailPasswordSignUp( email: string, password: string, + doAutomaticAccountLinking?: boolean, userContext?: any ): Promise< | { diff --git a/lib/build/recipe/thirdpartyemailpassword/index.js b/lib/build/recipe/thirdpartyemailpassword/index.js index 90b6c5a35..fb3a05b3d 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/index.js @@ -64,10 +64,11 @@ class Wrapper { userContext, }); } - static emailPasswordSignUp(email, password, userContext = {}) { + static emailPasswordSignUp(email, password, doAutomaticAccountLinking = false, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.emailPasswordSignUp({ email, password, + doAutomaticAccountLinking, userContext, }); } diff --git a/lib/build/recipe/thirdpartyemailpassword/types.d.ts b/lib/build/recipe/thirdpartyemailpassword/types.d.ts index 22543227f..d2e909adf 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -90,6 +90,7 @@ export declare type RecipeInterface = { emailPasswordSignUp(input: { email: string; password: string; + doAutomaticAccountLinking: boolean; userContext: any; }): Promise< | { diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index 8e2bef4db..c93775441 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -15,8 +15,8 @@ import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { AccountInfoAndEmailWithRecipeId, RecipeInterface } from "./types"; - +import type { AccountInfoAndEmailWithRecipeId, RecipeInterface, RecipeLevelUser } from "./types"; +import type { User } from "../../types"; export default class Wrapper { static init = Recipe.init; @@ -140,6 +140,30 @@ export default class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } + + static async onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any) { + userContext = userContext === undefined ? {} : userContext; + return await Recipe.getInstanceOrThrowError().config.onAccountLinked(user, newAccountInfo, userContext); + } + + static async shouldDoAutomaticAccountLinking( + newAccountInfo: AccountInfoAndEmailWithRecipeId, + user: User | undefined, + session: SessionContainer | undefined, + userContext?: any + ) { + userContext = userContext === undefined ? {} : userContext; + return await Recipe.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( + newAccountInfo, + user, + session, + userContext + ); + } + + static getIdentitiesForUser(user: User) { + return Recipe.getInstanceOrThrowError().getIdentitiesForUser(user); + } } export const init = Wrapper.init; @@ -157,5 +181,8 @@ export const isSignUpAllowed = Wrapper.isSignUpAllowed; export const doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; export const accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; export const createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; +export const onAccountLinked = Wrapper.onAccountLinked; +export const shouldDoAutomaticAccountLinking = Wrapper.shouldDoAutomaticAccountLinking; +export const getIdentitiesForUser = Wrapper.getIdentitiesForUser; export type { RecipeInterface }; diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 06075ca7f..ca5ea6f09 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -5,7 +5,6 @@ import { SessionContainerInterface } from "../../session/types"; import { GeneralErrorResponse } from "../../../types"; import { listUsersByAccountInfo, getUser } from "../../../"; import AccountLinking from "../../accountlinking"; -import AccountLinkingRecipe from "../../accountlinking/recipe"; import EmailVerification from "../../emailverification/recipe"; export default function getAPIImplementation(): APIInterface { @@ -66,7 +65,12 @@ export default function getAPIImplementation(): APIInterface { if (result.createRecipeUser) { let password = formFields.filter((f) => f.id === "password")[0].value; - let response = await options.recipeImplementation.signUp({ email, password, userContext }); + let response = await options.recipeImplementation.signUp({ + email, + password, + doAutomaticAccountLinking: false, + userContext, + }); if (response.status !== "OK") { throw Error( `this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}` @@ -232,7 +236,7 @@ export default function getAPIImplementation(): APIInterface { * this means that there is no emailpassword recipe user for the input email * so we check is account linking is enabled for the given email and primaryUserId */ - let shouldDoAccountLinking = await AccountLinkingRecipe.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( + let shouldDoAccountLinking = await AccountLinking.shouldDoAutomaticAccountLinking( { email, recipeId: "emailpassword", @@ -250,9 +254,7 @@ export default function getAPIImplementation(): APIInterface { status: "OK", }; } - let identitiesForPrimaryUser = AccountLinkingRecipe.getInstanceOrThrowError().getIdentitiesForUser( - primaryUser - ); + let identitiesForPrimaryUser = AccountLinking.getIdentitiesForUser(primaryUser); /** * if input email doens't belong to the verified indentity for the primaryUser, * we need to check shouldRequireVerification boolean @@ -287,7 +289,7 @@ export default function getAPIImplementation(): APIInterface { /** * checking for shouldDoAccountLinking */ - let shouldDoAccountLinking = await AccountLinkingRecipe.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( + let shouldDoAccountLinking = await AccountLinking.shouldDoAutomaticAccountLinking( { email, recipeId: "emailpassword", @@ -309,9 +311,7 @@ export default function getAPIImplementation(): APIInterface { * checking if the email belongs to the verified identities for the * primary user */ - let identitiesForPrimaryUser = AccountLinkingRecipe.getInstanceOrThrowError().getIdentitiesForUser( - primaryUser - ); + let identitiesForPrimaryUser = AccountLinking.getIdentitiesForUser(primaryUser); if (!identitiesForPrimaryUser.verified.emails.includes(email)) { /** * the email is not verified for any account linked to the primary user. @@ -465,6 +465,7 @@ export default function getAPIImplementation(): APIInterface { email, password: newPassword, userContext, + doAutomaticAccountLinking: false, }); if (response.status !== "OK") { throw Error("this error should not be thrown. EP user already for email: " + email); @@ -488,11 +489,7 @@ export default function getAPIImplementation(): APIInterface { { overrideGlobalClaimValidators: () => [], sessionRequired: false }, userContext ); - await AccountLinkingRecipe.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ - recipeUserId: user.id, - session, - userContext, - }); + await AccountLinking.createPrimaryUserIdOrLinkAccounts(user.id, session, userContext); } } return response; @@ -580,35 +577,23 @@ export default function getAPIImplementation(): APIInterface { reason: "the sign-up info is already associated with another account where it is not verified", }; } - let response = await options.recipeImplementation.signUp({ email, password, userContext }); + let response = await options.recipeImplementation.signUp({ + email, + password, + doAutomaticAccountLinking: true, + userContext, + }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; } let user = response.user; - let userIdForSession = await AccountLinking.doPostSignUpAccountLinkingOperations( - { - email, - recipeId: "emailpassword", - }, - false, - user.id, - userContext - ); - - let session = await Session.createNewSession( - options.res, - userIdForSession, - user.recipeUserId, - {}, - {}, - userContext - ); + let session = await Session.createNewSession(options.res, user.id, user.recipeUserId, {}, {}, userContext); return { status: "OK", session, user, - createdNewUser: userIdForSession === user.recipeUserId, // TODO + createdNewUser: user.id === user.recipeUserId, createdNewRecipeUser: true, }; }, diff --git a/lib/ts/recipe/emailpassword/index.ts b/lib/ts/recipe/emailpassword/index.ts index 42276add4..8d59dac76 100644 --- a/lib/ts/recipe/emailpassword/index.ts +++ b/lib/ts/recipe/emailpassword/index.ts @@ -22,10 +22,11 @@ export default class Wrapper { static Error = SuperTokensError; - static signUp(email: string, password: string, userContext?: any) { + static signUp(email: string, password: string, doAutomaticAccountLinking = false, userContext?: any) { return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.signUp({ email, password, + doAutomaticAccountLinking, userContext: userContext === undefined ? {} : userContext, }); } diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index 793e2465b..90df09cda 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -1,4 +1,5 @@ import { RecipeInterface, User } from "./types"; +import AccountLinking from "../accountlinking"; import { Querier } from "../../querier"; import NormalisedURLPath from "../../normalisedURLPath"; import { getUser, listUsersByAccountInfo } from "../.."; @@ -9,15 +10,31 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { signUp: async function ({ email, password, + doAutomaticAccountLinking, + userContext, }: { email: string; password: string; + doAutomaticAccountLinking: boolean; + userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { email, password, }); if (response.status === "OK") { + if (doAutomaticAccountLinking) { + let primaryUserId = await AccountLinking.doPostSignUpAccountLinkingOperations( + { + email, + recipeId: "emailpassword", + }, + false, + response.user.id, + userContext + ); + response.user.id = primaryUserId; + } return response; } else { return { diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index d04182647..e2c636e4b 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -94,6 +94,7 @@ export type RecipeInterface = { signUp(input: { email: string; password: string; + doAutomaticAccountLinking: boolean; userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; diff --git a/lib/ts/recipe/thirdpartyemailpassword/index.ts b/lib/ts/recipe/thirdpartyemailpassword/index.ts index 17cc46039..e736fc568 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/index.ts @@ -42,10 +42,16 @@ export default class Wrapper { }); } - static emailPasswordSignUp(email: string, password: string, userContext: any = {}) { + static emailPasswordSignUp( + email: string, + password: string, + doAutomaticAccountLinking = false, + userContext: any = {} + ) { return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.emailPasswordSignUp({ email, password, + doAutomaticAccountLinking, userContext, }); } diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts index e8d3e8319..c9b8a8f3b 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts @@ -6,6 +6,7 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw signUp: async function (input: { email: string; password: string; + doAutomaticAccountLinking: boolean; userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { return await recipeInterface.emailPasswordSignUp(input); diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts index dbcac64b9..26168277d 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts @@ -21,6 +21,7 @@ export default function getRecipeInterface( emailPasswordSignUp: async function (input: { email: string; password: string; + doAutomaticAccountLinking: boolean; userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { return await originalEmailPasswordImplementation.signUp.bind(DerivedEP(this))(input); diff --git a/lib/ts/recipe/thirdpartyemailpassword/types.ts b/lib/ts/recipe/thirdpartyemailpassword/types.ts index 7db5d7097..42db41c13 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/types.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/types.ts @@ -112,6 +112,7 @@ export type RecipeInterface = { emailPasswordSignUp(input: { email: string; password: string; + doAutomaticAccountLinking: boolean; userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; From 9c6d33a4f343d5bd483e618cad75d48977fbb62c Mon Sep 17 00:00:00 2001 From: Bhumil Date: Thu, 9 Feb 2023 01:32:29 +0530 Subject: [PATCH 28/82] recipeImplementation types update --- lib/build/recipe/accountlinking/index.d.ts | 77 +++++++- lib/build/recipe/accountlinking/index.js | 59 ++++++ lib/build/recipe/accountlinking/recipe.d.ts | 33 +++- lib/build/recipe/accountlinking/recipe.js | 181 +++++++++++++----- .../accountlinking/recipeImplementation.js | 23 +++ lib/build/recipe/accountlinking/types.d.ts | 8 + lib/ts/recipe/accountlinking/index.ts | 72 ++++++- lib/ts/recipe/accountlinking/recipe.ts | 151 +++++++++++++-- .../accountlinking/recipeImplementation.ts | 23 +++ lib/ts/recipe/accountlinking/types.ts | 6 + 10 files changed, 561 insertions(+), 72 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index b34b0e0e8..9dc6815df 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,7 +1,8 @@ // @ts-nocheck import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { AccountInfoAndEmailWithRecipeId, RecipeInterface } from "./types"; +import type { AccountInfoAndEmailWithRecipeId, RecipeInterface, RecipeLevelUser } from "./types"; +import type { User } from "../../types"; export default class Wrapper { static init: typeof Recipe.init; static getRecipeUserIdsForPrimaryUserIds( @@ -46,7 +47,7 @@ export default class Wrapper { ): Promise< | { status: "OK"; - user: import("../../types").User; + user: User; } | { status: @@ -114,6 +115,10 @@ export default class Wrapper { status: "NO_PRIMARY_USER_FOUND"; } >; + static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId( + recipeUserId: string, + userContext?: any + ): Promise; static isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any): Promise; static doPostSignUpAccountLinkingOperations( info: AccountInfoAndEmailWithRecipeId, @@ -142,13 +147,68 @@ export default class Wrapper { } & { accountsLinked: false; reason: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; }) + | ({ + createRecipeUser: false; + } & { + accountsLinked: false; + reason: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + }) >; + static createPrimaryUserIdOrLinkAccounts( + recipeUserId: string, + session: SessionContainer | undefined, + userContext?: any + ): Promise; + static onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any): Promise; + static shouldDoAutomaticAccountLinking( + newAccountInfo: AccountInfoAndEmailWithRecipeId, + user: User | undefined, + session: SessionContainer | undefined, + userContext?: any + ): Promise< + | { + shouldAutomaticallyLink: false; + } + | { + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + } + >; + static getIdentitiesForUser( + user: User + ): { + verified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + id: string; + userId: string; + }[]; + }; + unverified: { + emails: string[]; + phoneNumbers: string[]; + thirdpartyInfo: { + id: string; + userId: string; + }[]; + }; + }; + static fetchFromAccountToLinkTable(recipeUserId: string, userContext?: any): Promise; + static storeIntoAccountToLinkTable( + recipeUserId: string, + primaryUserId: string, + userContext?: any + ): Promise<{ + status: "OK"; + }>; } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; @@ -159,7 +219,14 @@ export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; export declare const linkAccounts: typeof Wrapper.linkAccounts; export declare const unlinkAccounts: typeof Wrapper.unlinkAccounts; +export declare const getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId: typeof Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; export declare const isSignUpAllowed: typeof Wrapper.isSignUpAllowed; export declare const doPostSignUpAccountLinkingOperations: typeof Wrapper.doPostSignUpAccountLinkingOperations; export declare const accountLinkPostSignInViaSession: typeof Wrapper.accountLinkPostSignInViaSession; +export declare const createPrimaryUserIdOrLinkAccounts: typeof Wrapper.createPrimaryUserIdOrLinkAccounts; +export declare const onAccountLinked: typeof Wrapper.onAccountLinked; +export declare const shouldDoAutomaticAccountLinking: typeof Wrapper.shouldDoAutomaticAccountLinking; +export declare const getIdentitiesForUser: typeof Wrapper.getIdentitiesForUser; +export declare const fetchFromAccountToLinkTable: typeof Wrapper.fetchFromAccountToLinkTable; +export declare const storeIntoAccountToLinkTable: typeof Wrapper.storeIntoAccountToLinkTable; export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 798b2ed2b..a46dc88d6 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -121,6 +121,14 @@ class Wrapper { }); }); } + static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId(recipeUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } static isSignUpAllowed(info, userContext) { return __awaiter(this, void 0, void 0, function* () { return yield recipe_1.default.getInstanceOrThrowError().isSignUpAllowed({ @@ -149,6 +157,50 @@ class Wrapper { }); }); } + static createPrimaryUserIdOrLinkAccounts(recipeUserId, session, userContext) { + return __awaiter(this, void 0, void 0, function* () { + return yield recipe_1.default.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + recipeUserId, + session, + userContext: userContext === undefined ? {} : userContext, + }); + }); + } + static onAccountLinked(user, newAccountInfo, userContext) { + return __awaiter(this, void 0, void 0, function* () { + userContext = userContext === undefined ? {} : userContext; + return yield recipe_1.default + .getInstanceOrThrowError() + .config.onAccountLinked(user, newAccountInfo, userContext); + }); + } + static shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext) { + return __awaiter(this, void 0, void 0, function* () { + userContext = userContext === undefined ? {} : userContext; + return yield recipe_1.default + .getInstanceOrThrowError() + .config.shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext); + }); + } + static getIdentitiesForUser(user) { + return recipe_1.default.getInstanceOrThrowError().getIdentitiesForUser(user); + } + static fetchFromAccountToLinkTable(recipeUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + userContext = userContext === undefined ? {} : userContext; + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); + }); + } + static storeIntoAccountToLinkTable(recipeUserId, primaryUserId, userContext) { + return __awaiter(this, void 0, void 0, function* () { + userContext = userContext === undefined ? {} : userContext; + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.storeIntoAccountToLinkTable({ recipeUserId, primaryUserId, userContext }); + }); + } } exports.default = Wrapper; Wrapper.init = recipe_1.default.init; @@ -161,6 +213,13 @@ exports.createPrimaryUser = Wrapper.createPrimaryUser; exports.canLinkAccounts = Wrapper.canLinkAccounts; exports.linkAccounts = Wrapper.linkAccounts; exports.unlinkAccounts = Wrapper.unlinkAccounts; +exports.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; exports.isSignUpAllowed = Wrapper.isSignUpAllowed; exports.doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; exports.accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; +exports.createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; +exports.onAccountLinked = Wrapper.onAccountLinked; +exports.shouldDoAutomaticAccountLinking = Wrapper.shouldDoAutomaticAccountLinking; +exports.getIdentitiesForUser = Wrapper.getIdentitiesForUser; +exports.fetchFromAccountToLinkTable = Wrapper.fetchFromAccountToLinkTable; +exports.storeIntoAccountToLinkTable = Wrapper.storeIntoAccountToLinkTable; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 7327c716e..94357d75f 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -27,7 +27,7 @@ export default class Recipe extends RecipeModule { isErrorFromThisRecipe(err: any): err is error; getIdentitiesForUser: ( user: User - ) => Promise<{ + ) => { verified: { emails: string[]; phoneNumbers: string[]; @@ -44,7 +44,7 @@ export default class Recipe extends RecipeModule { userId: string; }[]; }; - }>; + }; isSignUpAllowed: ({ info, userContext, @@ -89,11 +89,34 @@ export default class Recipe extends RecipeModule { } & { accountsLinked: false; reason: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; }) + | ({ + createRecipeUser: false; + } & { + accountsLinked: false; + reason: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + }) >; + getPrimaryUserIdThatCanBeLinkedToRecipeUserId: ({ + recipeUserId, + userContext, + }: { + recipeUserId: string; + userContext: any; + }) => Promise; + createPrimaryUserIdOrLinkAccounts: ({ + recipeUserId, + session, + userContext, + }: { + recipeUserId: string; + session: SessionContainer | undefined; + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 3799c3009..d7a7515e1 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -55,46 +55,45 @@ const error_1 = require("../../error"); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, config, _recipes, _ingredients) { super(recipeId, appInfo); - this.getIdentitiesForUser = (user) => - __awaiter(this, void 0, void 0, function* () { - let identities = { - verified: { - emails: [], - phoneNumbers: [], - thirdpartyInfo: [], - }, - unverified: { - emails: [], - phoneNumbers: [], - thirdpartyInfo: [], - }, - }; - for (let i = 0; i < user.loginMethods.length; i++) { - let loginMethod = user.loginMethods[i]; - if (loginMethod.email !== undefined) { - if (loginMethod.verified) { - identities.verified.emails.push(loginMethod.email); - } else { - identities.unverified.emails.push(loginMethod.email); - } + this.getIdentitiesForUser = (user) => { + let identities = { + verified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + unverified: { + emails: [], + phoneNumbers: [], + thirdpartyInfo: [], + }, + }; + for (let i = 0; i < user.loginMethods.length; i++) { + let loginMethod = user.loginMethods[i]; + if (loginMethod.email !== undefined) { + if (loginMethod.verified) { + identities.verified.emails.push(loginMethod.email); + } else { + identities.unverified.emails.push(loginMethod.email); } - if (loginMethod.phoneNumber !== undefined) { - if (loginMethod.verified) { - identities.verified.phoneNumbers.push(loginMethod.phoneNumber); - } else { - identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); - } + } + if (loginMethod.phoneNumber !== undefined) { + if (loginMethod.verified) { + identities.verified.phoneNumbers.push(loginMethod.phoneNumber); + } else { + identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); } - if (loginMethod.thirdParty !== undefined) { - if (loginMethod.verified) { - identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); - } else { - identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); - } + } + if (loginMethod.thirdParty !== undefined) { + if (loginMethod.verified) { + identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); + } else { + identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); } } - return identities; - }); + } + return identities; + }; this.isSignUpAllowed = ({ info, userContext }) => __awaiter(this, void 0, void 0, function* () { let identifier; @@ -132,7 +131,7 @@ class Recipe extends recipeModule_1.default { if (!shouldRequireVerification) { return true; } - let identitiesForPrimaryUser = yield this.getIdentitiesForUser(primaryUser); + let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); if (info.email !== undefined) { return identitiesForPrimaryUser.verified.emails.includes(info.email); } @@ -238,7 +237,7 @@ class Recipe extends recipeModule_1.default { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } let recipeId = user.loginMethods[0].recipeId; @@ -258,7 +257,7 @@ class Recipe extends recipeModule_1.default { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } if (shouldDoAccountLinking.shouldRequireVerification) { @@ -282,6 +281,7 @@ class Recipe extends recipeModule_1.default { createRecipeUser: false, accountsLinked: false, reason: canCreatePrimaryUser.status, + primaryUserId: canCreatePrimaryUser.primaryUserId, }; } /** @@ -296,6 +296,7 @@ class Recipe extends recipeModule_1.default { createRecipeUser: false, accountsLinked: false, reason: createPrimaryUserResult.status, + primaryUserId: createPrimaryUserResult.primaryUserId, }; } user = createPrimaryUserResult.user; @@ -314,7 +315,7 @@ class Recipe extends recipeModule_1.default { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } /** @@ -361,7 +362,7 @@ class Recipe extends recipeModule_1.default { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = yield this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -394,13 +395,13 @@ class Recipe extends recipeModule_1.default { userContext, }); if (existingRecipeUserForInputInfo !== undefined) { - let doesPrimaryUserIdAlreadyExists = - existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; - if (doesPrimaryUserIdAlreadyExists) { + let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); + if (primaryUserIfExists !== undefined) { return { createRecipeUser: false, accountsLinked: false, reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUserIfExists.id, }; } } @@ -452,9 +453,10 @@ class Recipe extends recipeModule_1.default { createRecipeUser: false, accountsLinked: false, reason: canLinkAccounts.status, + primaryUserId: canLinkAccounts.primaryUserId, }; } - let identitiesForPrimaryUser = yield this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = @@ -494,6 +496,95 @@ class Recipe extends recipeModule_1.default { updateVerificationClaim: true, }; }); + this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId = ({ recipeUserId, userContext }) => + __awaiter(this, void 0, void 0, function* () { + let user = yield __1.getUser(recipeUserId, userContext); + if (user === undefined) { + return undefined; + } + if (user.isPrimaryUser) { + return user; + } + let pUser = yield this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); + if (pUser !== undefined && pUser.isPrimaryUser) { + return pUser; + } + let identifier; + let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array + if (loginMethodInfo.email !== undefined) { + identifier = { + email: loginMethodInfo.email, + }; + } else if (loginMethodInfo.phoneNumber !== undefined) { + identifier = { + phoneNumber: loginMethodInfo.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: identifier, + userContext, + }); + if (users === undefined || users.length === 0) { + return undefined; + } + return users.find((u) => u.isPrimaryUser); + }); + this.createPrimaryUserIdOrLinkAccounts = ({ recipeUserId, session, userContext }) => + __awaiter(this, void 0, void 0, function* () { + let primaryUser = yield this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext, + }); + if (primaryUser === undefined) { + let user = yield __1.getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + Object.assign({}, user.loginMethods[0]), + undefined, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: recipeUserId, + userContext, + }); + // TODO: remove session claim + } + } else { + /** + * recipeUser already linked with primaryUser + */ + let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); + if (recipeUser === undefined) { + let user = yield __1.getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + Object.assign({}, user.loginMethods[0]), + primaryUser, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + let linkAccountsResult = yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUserId, + primaryUserId: primaryUser.id, + userContext, + }); + if (linkAccountsResult.status === "OK") { + // TODO: remove session claim if session claim exists + // else create a new session + } + } + } + } + }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); { let builder = new supertokens_js_override_1.default( diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 102267e8f..8c9036891 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -458,6 +458,29 @@ function getRecipeImplementation(querier, config) { }; }); }, + fetchFromAccountToLinkTable: function ({ recipeUserId }) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), + { + recipeUserId, + } + ); + return result.user; + }); + }, + storeIntoAccountToLinkTable: function ({ recipeUserId, primaryUserId }) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), + { + recipeUserId, + primaryUserId, + } + ); + return result; + }); + }, }; } exports.default = getRecipeImplementation; diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index f9f4851e1..1553c6a05 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -179,6 +179,14 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; + fetchFromAccountToLinkTable: (input: { recipeUserId: string; userContext: any }) => Promise; + storeIntoAccountToLinkTable: (input: { + recipeUserId: string; + primaryUserId: string; + userContext: any; + }) => Promise<{ + status: "OK"; + }>; }; export declare type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index 3be040ab7..0e6d4c993 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -15,8 +15,8 @@ import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { AccountInfoAndEmailWithRecipeId, RecipeInterface } from "./types"; - +import type { AccountInfoAndEmailWithRecipeId, RecipeInterface, RecipeLevelUser } from "./types"; +import type { User } from "../../types"; export default class Wrapper { static init = Recipe.init; @@ -85,6 +85,13 @@ export default class Wrapper { }); } + static async getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId(recipeUserId: string, userContext?: any) { + return await Recipe.getInstanceOrThrowError().getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext: userContext === undefined ? {} : userContext, + }); + } + static async isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any) { return await Recipe.getInstanceOrThrowError().isSignUpAllowed({ info, @@ -119,6 +126,59 @@ export default class Wrapper { userContext, }); } + + static async createPrimaryUserIdOrLinkAccounts( + recipeUserId: string, + session: SessionContainer | undefined, + userContext?: any + ) { + return await Recipe.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + recipeUserId, + session, + userContext: userContext === undefined ? {} : userContext, + }); + } + + static async onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any) { + userContext = userContext === undefined ? {} : userContext; + return await Recipe.getInstanceOrThrowError().config.onAccountLinked(user, newAccountInfo, userContext); + } + + static async shouldDoAutomaticAccountLinking( + newAccountInfo: AccountInfoAndEmailWithRecipeId, + user: User | undefined, + session: SessionContainer | undefined, + userContext?: any + ) { + userContext = userContext === undefined ? {} : userContext; + return await Recipe.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( + newAccountInfo, + user, + session, + userContext + ); + } + + static getIdentitiesForUser(user: User) { + return Recipe.getInstanceOrThrowError().getIdentitiesForUser(user); + } + + static async fetchFromAccountToLinkTable(recipeUserId: string, userContext?: any) { + userContext = userContext === undefined ? {} : userContext; + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.fetchFromAccountToLinkTable({ + recipeUserId, + userContext, + }); + } + + static async storeIntoAccountToLinkTable(recipeUserId: string, primaryUserId: string, userContext?: any) { + userContext = userContext === undefined ? {} : userContext; + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.storeIntoAccountToLinkTable({ + recipeUserId, + primaryUserId, + userContext, + }); + } } export const init = Wrapper.init; @@ -130,8 +190,16 @@ export const createPrimaryUser = Wrapper.createPrimaryUser; export const canLinkAccounts = Wrapper.canLinkAccounts; export const linkAccounts = Wrapper.linkAccounts; export const unlinkAccounts = Wrapper.unlinkAccounts; +export const getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = + Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; export const isSignUpAllowed = Wrapper.isSignUpAllowed; export const doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; export const accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; +export const createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; +export const onAccountLinked = Wrapper.onAccountLinked; +export const shouldDoAutomaticAccountLinking = Wrapper.shouldDoAutomaticAccountLinking; +export const getIdentitiesForUser = Wrapper.getIdentitiesForUser; +export const fetchFromAccountToLinkTable = Wrapper.fetchFromAccountToLinkTable; +export const storeIntoAccountToLinkTable = Wrapper.storeIntoAccountToLinkTable; export type { RecipeInterface }; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index e82f51d1d..1def947e2 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -27,7 +27,7 @@ import type { AccountInfoWithRecipeId, } from "./types"; import { validateAndNormaliseUserInput } from "./utils"; -import { getUserForRecipeId } from "../.."; +import { getUser, getUserForRecipeId } from "../.."; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; @@ -106,9 +106,9 @@ export default class Recipe extends RecipeModule { return SuperTokensError.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; } - getIdentitiesForUser = async ( + getIdentitiesForUser = ( user: User - ): Promise<{ + ): { verified: { emails: string[]; phoneNumbers: string[]; @@ -125,7 +125,7 @@ export default class Recipe extends RecipeModule { userId: string; }[]; }; - }> => { + } => { let identities: { verified: { emails: string[]; @@ -231,7 +231,7 @@ export default class Recipe extends RecipeModule { return true; } - let identitiesForPrimaryUser = await this.getIdentitiesForUser(primaryUser); + let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); if (info.email !== undefined) { return identitiesForPrimaryUser.verified.emails.includes(info.email); @@ -352,11 +352,16 @@ export default class Recipe extends RecipeModule { | { accountsLinked: false; reason: - | "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR" + | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" + | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + } + | { + accountsLinked: false; + reason: | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; } )) > => { @@ -383,7 +388,7 @@ export default class Recipe extends RecipeModule { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } @@ -404,7 +409,7 @@ export default class Recipe extends RecipeModule { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } if (shouldDoAccountLinking.shouldRequireVerification) { @@ -429,6 +434,7 @@ export default class Recipe extends RecipeModule { createRecipeUser: false, accountsLinked: false, reason: canCreatePrimaryUser.status, + primaryUserId: canCreatePrimaryUser.primaryUserId, }; } /** @@ -443,6 +449,7 @@ export default class Recipe extends RecipeModule { createRecipeUser: false, accountsLinked: false, reason: createPrimaryUserResult.status, + primaryUserId: createPrimaryUserResult.primaryUserId, }; } user = createPrimaryUserResult.user; @@ -461,7 +468,7 @@ export default class Recipe extends RecipeModule { return { createRecipeUser: false, accountsLinked: false, - reason: "ACCOUNT_LINKING_IS_NOT_ALLOWED_ERROR", + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } @@ -509,7 +516,7 @@ export default class Recipe extends RecipeModule { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = await this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -543,13 +550,13 @@ export default class Recipe extends RecipeModule { userContext, }); if (existingRecipeUserForInputInfo !== undefined) { - let doesPrimaryUserIdAlreadyExists = - existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser) !== undefined; - if (doesPrimaryUserIdAlreadyExists) { + let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); + if (primaryUserIfExists !== undefined) { return { createRecipeUser: false, accountsLinked: false, reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUserIfExists.id, }; } } @@ -601,10 +608,11 @@ export default class Recipe extends RecipeModule { createRecipeUser: false, accountsLinked: false, reason: canLinkAccounts.status, + primaryUserId: canLinkAccounts.primaryUserId, }; } - let identitiesForPrimaryUser = await this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = @@ -644,4 +652,117 @@ export default class Recipe extends RecipeModule { updateVerificationClaim: true, }; }; + + getPrimaryUserIdThatCanBeLinkedToRecipeUserId = async ({ + recipeUserId, + userContext, + }: { + recipeUserId: string; + userContext: any; + }): Promise => { + let user = await getUser(recipeUserId, userContext); + if (user === undefined) { + return undefined; + } + if (user.isPrimaryUser) { + return user; + } + let pUser = await this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); + if (pUser !== undefined && pUser.isPrimaryUser) { + return pUser; + } + let identifier: + | { + email: string; + } + | { + phoneNumber: string; + }; + let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array + if (loginMethodInfo.email !== undefined) { + identifier = { + email: loginMethodInfo.email, + }; + } else if (loginMethodInfo.phoneNumber !== undefined) { + identifier = { + phoneNumber: loginMethodInfo.phoneNumber, + }; + } else { + throw Error("this error should never be thrown"); + } + let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: identifier, + userContext, + }); + if (users === undefined || users.length === 0) { + return undefined; + } + return users.find((u) => u.isPrimaryUser); + }; + + createPrimaryUserIdOrLinkAccounts = async ({ + recipeUserId, + session, + userContext, + }: { + recipeUserId: string; + session: SessionContainer | undefined; + userContext: any; + }) => { + let primaryUser = await this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext, + }); + if (primaryUser === undefined) { + let user = await getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + { + ...user.loginMethods[0], + }, + undefined, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + await this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: recipeUserId, + userContext, + }); + // TODO: remove session claim + } + } else { + /** + * recipeUser already linked with primaryUser + */ + let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); + if (recipeUser === undefined) { + let user = await getUser(recipeUserId, userContext); + if (user === undefined || user.isPrimaryUser) { + throw Error("this error should never be thrown"); + } + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + { + ...user.loginMethods[0], + }, + primaryUser, + session, + userContext + ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + let linkAccountsResult = await this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUserId, + primaryUserId: primaryUser.id, + userContext, + }); + if (linkAccountsResult.status === "OK") { + // TODO: remove session claim if session claim exists + // else create a new session + } + } + } + } + }; } diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 6a8341b8e..ed156d1f1 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -622,5 +622,28 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo status: "OK", }; }, + fetchFromAccountToLinkTable: async function ({ + recipeUserId, + }: { + recipeUserId: string; + }): Promise { + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user/link"), { + recipeUserId, + }); + return result.user; + }, + storeIntoAccountToLinkTable: async function ({ + recipeUserId, + primaryUserId, + }: { + recipeUserId: string; + primaryUserId: string; + }): Promise<{ status: "OK" }> { + let result = await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/link"), { + recipeUserId, + primaryUserId, + }); + return result; + }, }; } diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 3952e95bb..7def9756b 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -194,6 +194,12 @@ export type RecipeInterface = { removeAllLinkedAccounts: boolean; userContext: any; }) => Promise<{ status: "OK" }>; + fetchFromAccountToLinkTable: (input: { recipeUserId: string; userContext: any }) => Promise; + storeIntoAccountToLinkTable: (input: { + recipeUserId: string; + primaryUserId: string; + userContext: any; + }) => Promise<{ status: "OK" }>; }; export type RecipeLevelUser = { From 69bd6909c0f71321663ebc27fbf23ec7678320cc Mon Sep 17 00:00:00 2001 From: Bhumil Date: Sun, 12 Feb 2023 03:00:01 +0530 Subject: [PATCH 29/82] merge with 13.0 --- .circleci/setupAndTestWithAuthReact.sh | 4 +- .circleci/setupAndTestWithFrontend.sh | 2 +- .gitignore | 1 + CHANGELOG.md | 76 + README.md | 1 + docs/assets/highlight.css | 8 +- docs/assets/main.js | 4 +- docs/assets/search.js | 2 +- docs/assets/style.css | 5 +- docs/classes/framework.BaseRequest.html | 2 +- docs/classes/framework.BaseResponse.html | 2 +- docs/classes/index.default.html | 2 +- .../ingredients_emaildelivery.default.html | 2 +- .../ingredients_smsdelivery.default.html | 2 +- docs/classes/recipe_dashboard.default.html | 2 +- .../classes/recipe_emailpassword.default.html | 2 +- .../recipe_emailverification.default.html | 2 +- docs/classes/recipe_jwt.default.html | 2 +- docs/classes/recipe_openid.default.html | 2 +- docs/classes/recipe_passwordless.default.html | 2 +- docs/classes/recipe_session.default.html | 2 +- docs/classes/recipe_thirdparty.default.html | 2 +- ...ecipe_thirdpartyemailpassword.default.html | 2 +- ...recipe_thirdpartypasswordless.default.html | 2 +- docs/classes/recipe_usermetadata.default.html | 2 +- docs/classes/recipe_userroles.default.html | 2 +- docs/index.html | 3 +- .../framework_awsLambda.SessionEvent.html | 2 +- .../framework_awsLambda.SessionEventV2.html | 2 +- .../framework_express.SessionRequest.html | 112 +- .../framework_fastify.SessionRequest.html | 4 +- .../framework_hapi.SessionRequest.html | 28 +- .../framework_koa.SessionContext.html | 20 +- .../framework_loopback.SessionContext.html | 84 +- .../recipe_session.SessionContainer.html | 4 +- .../recipe_session.VerifySessionOptions.html | 2 +- .../recipe_usermetadata.JSONObject.html | 2 +- docs/modules.html | 2 +- docs/modules/framework.html | 2 +- docs/modules/framework_awsLambda.html | 2 +- docs/modules/framework_express.html | 2 +- docs/modules/framework_fastify.html | 2 +- docs/modules/framework_hapi.html | 2 +- docs/modules/framework_koa.html | 2 +- docs/modules/framework_loopback.html | 2 +- docs/modules/index.html | 2 +- docs/modules/ingredients_emaildelivery.html | 2 +- docs/modules/ingredients_smsdelivery.html | 2 +- docs/modules/recipe_dashboard.html | 2 +- docs/modules/recipe_emailpassword.html | 2 +- docs/modules/recipe_emailverification.html | 2 +- docs/modules/recipe_jwt.html | 2 +- docs/modules/recipe_openid.html | 2 +- docs/modules/recipe_passwordless.html | 2 +- docs/modules/recipe_session.html | 10 +- docs/modules/recipe_thirdparty.html | 2 +- .../recipe_thirdpartyemailpassword.html | 2 +- .../recipe_thirdpartypasswordless.html | 2 +- docs/modules/recipe_usermetadata.html | 4 +- docs/modules/recipe_userroles.html | 2 +- frontendDriverInterfaceSupported.json | 2 +- lib/build/constants.d.ts | 1 - lib/build/constants.js | 1 + lib/build/error.d.ts | 23 +- lib/build/framework/awsLambda/framework.d.ts | 27 +- lib/build/framework/awsLambda/framework.js | 202 +-- lib/build/framework/awsLambda/index.d.ts | 5 +- lib/build/framework/awsLambda/index.js | 1 + lib/build/framework/constants.d.ts | 1 - lib/build/framework/constants.js | 1 + lib/build/framework/express/framework.d.ts | 13 +- lib/build/framework/express/framework.js | 154 +- lib/build/framework/express/index.d.ts | 15 +- lib/build/framework/express/index.js | 1 + lib/build/framework/fastify/framework.d.ts | 30 +- lib/build/framework/fastify/framework.js | 117 +- lib/build/framework/fastify/index.d.ts | 17 +- lib/build/framework/fastify/index.js | 1 + lib/build/framework/hapi/framework.d.ts | 15 +- lib/build/framework/hapi/framework.js | 150 +- lib/build/framework/hapi/index.d.ts | 1 - lib/build/framework/hapi/index.js | 1 + lib/build/framework/index.d.ts | 1 - lib/build/framework/index.js | 5 +- lib/build/framework/koa/framework.d.ts | 13 +- lib/build/framework/koa/framework.js | 108 +- lib/build/framework/koa/index.d.ts | 2 +- lib/build/framework/koa/index.js | 1 + lib/build/framework/loopback/framework.d.ts | 13 +- lib/build/framework/loopback/framework.js | 115 +- lib/build/framework/loopback/index.d.ts | 1 - lib/build/framework/loopback/index.js | 1 + lib/build/framework/request.d.ts | 1 - lib/build/framework/request.js | 1 + lib/build/framework/response.d.ts | 13 +- lib/build/framework/response.js | 1 + lib/build/framework/types.d.ts | 1 - lib/build/framework/types.js | 1 + lib/build/framework/utils.d.ts | 54 +- lib/build/framework/utils.js | 88 +- lib/build/index.d.ts | 56 +- lib/build/index.js | 53 +- .../ingredients/emaildelivery/index.d.ts | 1 - .../emaildelivery/services/smtp.d.ts | 9 +- .../ingredients/emaildelivery/types.d.ts | 19 +- lib/build/ingredients/smsdelivery/index.d.ts | 1 - .../smsdelivery/services/supertokens.d.ts | 1 - .../smsdelivery/services/supertokens.js | 1 + .../smsdelivery/services/twilio.d.ts | 46 +- .../smsdelivery/services/twilio.js | 10 +- lib/build/ingredients/smsdelivery/types.d.ts | 19 +- lib/build/logger.d.ts | 1 - lib/build/logger.js | 7 +- lib/build/nextjs.d.ts | 7 +- lib/build/nextjs.js | 82 +- lib/build/normalisedURLDomain.d.ts | 1 - lib/build/normalisedURLDomain.js | 18 +- lib/build/normalisedURLPath.d.ts | 1 - lib/build/normalisedURLPath.js | 18 +- lib/build/postSuperTokensInitCallbacks.d.ts | 1 - lib/build/postSuperTokensInitCallbacks.js | 1 + lib/build/processState.d.ts | 3 +- lib/build/processState.js | 87 +- lib/build/querier.d.ts | 12 +- lib/build/querier.js | 375 ++--- lib/build/recipe/accountlinking/index.d.ts | 255 +-- lib/build/recipe/accountlinking/index.js | 98 +- lib/build/recipe/accountlinking/recipe.d.ts | 89 +- lib/build/recipe/accountlinking/recipe.js | 886 +++++------ .../accountlinking/recipeImplementation.d.ts | 1 - .../accountlinking/recipeImplementation.js | 175 +-- lib/build/recipe/accountlinking/types.d.ts | 236 ++- lib/build/recipe/accountlinking/utils.d.ts | 1 - lib/build/recipe/accountlinking/utils.js | 46 +- .../recipe/dashboard/api/apiKeyProtector.d.ts | 7 +- .../recipe/dashboard/api/apiKeyProtector.js | 40 +- lib/build/recipe/dashboard/api/dashboard.d.ts | 1 - lib/build/recipe/dashboard/api/dashboard.js | 40 +- .../recipe/dashboard/api/implementation.d.ts | 1 - .../recipe/dashboard/api/implementation.js | 47 +- .../dashboard/api/userdetails/userDelete.d.ts | 1 - .../dashboard/api/userdetails/userDelete.js | 80 +- .../api/userdetails/userEmailVerifyGet.d.ts | 1 - .../api/userdetails/userEmailVerifyGet.js | 84 +- .../api/userdetails/userEmailVerifyPut.d.ts | 1 - .../api/userdetails/userEmailVerifyPut.js | 110 +- .../userdetails/userEmailVerifyTokenPost.d.ts | 1 - .../userdetails/userEmailVerifyTokenPost.js | 107 +- .../dashboard/api/userdetails/userGet.d.ts | 1 - .../dashboard/api/userdetails/userGet.js | 135 +- .../api/userdetails/userMetadataGet.d.ts | 1 - .../api/userdetails/userMetadataGet.js | 82 +- .../api/userdetails/userMetadataPut.d.ts | 1 - .../api/userdetails/userMetadataPut.js | 144 +- .../api/userdetails/userPasswordPut.d.ts | 20 +- .../api/userdetails/userPasswordPut.js | 167 +- .../dashboard/api/userdetails/userPut.d.ts | 32 +- .../dashboard/api/userdetails/userPut.js | 590 ++++--- .../api/userdetails/userSessionsGet.d.ts | 1 - .../api/userdetails/userSessionsGet.js | 106 +- .../api/userdetails/userSessionsPost.d.ts | 1 - .../api/userdetails/userSessionsPost.js | 71 +- .../recipe/dashboard/api/usersCountGet.d.ts | 1 - .../recipe/dashboard/api/usersCountGet.js | 40 +- lib/build/recipe/dashboard/api/usersGet.d.ts | 1 - lib/build/recipe/dashboard/api/usersGet.js | 93 +- .../recipe/dashboard/api/validateKey.d.ts | 1 - lib/build/recipe/dashboard/api/validateKey.js | 43 +- lib/build/recipe/dashboard/constants.d.ts | 1 - lib/build/recipe/dashboard/constants.js | 1 + lib/build/recipe/dashboard/index.d.ts | 1 - lib/build/recipe/dashboard/index.js | 4 +- lib/build/recipe/dashboard/recipe.d.ts | 9 +- lib/build/recipe/dashboard/recipe.js | 188 +-- .../dashboard/recipeImplementation.d.ts | 1 - .../recipe/dashboard/recipeImplementation.js | 45 +- lib/build/recipe/dashboard/types.d.ts | 26 +- lib/build/recipe/dashboard/utils.d.ts | 24 +- lib/build/recipe/dashboard/utils.js | 112 +- .../recipe/emailpassword/api/emailExists.d.ts | 1 - .../recipe/emailpassword/api/emailExists.js | 40 +- .../api/generatePasswordResetToken.d.ts | 6 +- .../api/generatePasswordResetToken.js | 45 +- .../emailpassword/api/implementation.d.ts | 1 - .../emailpassword/api/implementation.js | 73 +- .../emailpassword/api/passwordReset.d.ts | 1 - .../recipe/emailpassword/api/passwordReset.js | 58 +- .../recipe/emailpassword/api/signin.d.ts | 1 - lib/build/recipe/emailpassword/api/signin.js | 48 +- .../recipe/emailpassword/api/signup.d.ts | 1 - lib/build/recipe/emailpassword/api/signup.js | 51 +- lib/build/recipe/emailpassword/api/utils.d.ts | 14 +- lib/build/recipe/emailpassword/api/utils.js | 44 +- lib/build/recipe/emailpassword/constants.d.ts | 1 - lib/build/recipe/emailpassword/constants.js | 1 + .../services/backwardCompatibility/index.d.ts | 27 +- .../services/backwardCompatibility/index.js | 100 +- .../emaildelivery/services/index.d.ts | 1 - .../emaildelivery/services/index.js | 1 + .../emaildelivery/services/smtp/index.d.ts | 9 +- .../emaildelivery/services/smtp/index.js | 55 +- .../services/smtp/passwordReset.d.ts | 5 +- .../services/smtp/passwordReset.js | 8 +- .../smtp/serviceImplementation/index.d.ts | 12 +- .../smtp/serviceImplementation/index.js | 44 +- lib/build/recipe/emailpassword/error.d.ts | 27 +- lib/build/recipe/emailpassword/index.d.ts | 87 +- lib/build/recipe/emailpassword/index.js | 49 +- .../emailpassword/passwordResetFunctions.d.ts | 5 +- .../emailpassword/passwordResetFunctions.js | 127 +- lib/build/recipe/emailpassword/recipe.d.ts | 21 +- lib/build/recipe/emailpassword/recipe.js | 154 +- .../emailpassword/recipeImplementation.d.ts | 1 - .../emailpassword/recipeImplementation.js | 91 +- lib/build/recipe/emailpassword/types.d.ts | 328 ++-- lib/build/recipe/emailpassword/utils.d.ts | 22 +- lib/build/recipe/emailpassword/utils.js | 127 +- .../emailverification/api/emailVerify.d.ts | 1 - .../emailverification/api/emailVerify.js | 60 +- .../api/generateEmailVerifyToken.d.ts | 6 +- .../api/generateEmailVerifyToken.js | 47 +- .../emailverification/api/implementation.d.ts | 1 - .../emailverification/api/implementation.js | 85 +- .../recipe/emailverification/constants.d.ts | 1 - .../recipe/emailverification/constants.js | 1 + .../emailVerificationClaim.d.ts | 1 - .../emailVerificationClaim.js | 76 +- .../emailVerificationFunctions.d.ts | 5 +- .../emailVerificationFunctions.js | 125 +- .../services/backwardCompatibility/index.d.ts | 22 +- .../services/backwardCompatibility/index.js | 67 +- .../emaildelivery/services/index.d.ts | 1 - .../emaildelivery/services/index.js | 1 + .../services/smtp/emailVerify.d.ts | 1 - .../services/smtp/emailVerify.js | 8 +- .../emaildelivery/services/smtp/index.d.ts | 9 +- .../emaildelivery/services/smtp/index.js | 55 +- .../services/smtp/serviceImplementation.d.ts | 12 +- .../services/smtp/serviceImplementation.js | 44 +- lib/build/recipe/emailverification/error.d.ts | 6 +- lib/build/recipe/emailverification/index.d.ts | 58 +- lib/build/recipe/emailverification/index.js | 71 +- .../recipe/emailverification/recipe.d.ts | 21 +- lib/build/recipe/emailverification/recipe.js | 139 +- .../recipeImplementation.d.ts | 1 - .../emailverification/recipeImplementation.js | 94 +- lib/build/recipe/emailverification/types.d.ts | 178 +-- lib/build/recipe/emailverification/utils.d.ts | 7 +- lib/build/recipe/emailverification/utils.js | 26 +- lib/build/recipe/jwt/api/getJWKS.d.ts | 1 - lib/build/recipe/jwt/api/getJWKS.js | 43 +- lib/build/recipe/jwt/api/implementation.d.ts | 1 - lib/build/recipe/jwt/api/implementation.js | 42 +- lib/build/recipe/jwt/constants.d.ts | 1 - lib/build/recipe/jwt/constants.js | 1 + lib/build/recipe/jwt/index.d.ts | 24 +- lib/build/recipe/jwt/index.js | 41 +- lib/build/recipe/jwt/recipe.d.ts | 11 +- lib/build/recipe/jwt/recipe.js | 74 +- .../recipe/jwt/recipeImplementation.d.ts | 7 +- lib/build/recipe/jwt/recipeImplementation.js | 45 +- lib/build/recipe/jwt/types.d.ts | 45 +- lib/build/recipe/jwt/utils.d.ts | 7 +- lib/build/recipe/jwt/utils.js | 14 +- .../api/getOpenIdDiscoveryConfiguration.d.ts | 6 +- .../api/getOpenIdDiscoveryConfiguration.js | 43 +- .../recipe/openid/api/implementation.d.ts | 1 - lib/build/recipe/openid/api/implementation.js | 42 +- lib/build/recipe/openid/constants.d.ts | 1 - lib/build/recipe/openid/constants.js | 1 + lib/build/recipe/openid/index.d.ts | 28 +- lib/build/recipe/openid/index.js | 1 + lib/build/recipe/openid/recipe.d.ts | 9 +- lib/build/recipe/openid/recipe.js | 99 +- .../recipe/openid/recipeImplementation.d.ts | 6 +- .../recipe/openid/recipeImplementation.js | 49 +- lib/build/recipe/openid/types.d.ts | 67 +- lib/build/recipe/openid/utils.d.ts | 6 +- lib/build/recipe/openid/utils.js | 9 +- .../recipe/passwordless/api/consumeCode.d.ts | 1 - .../recipe/passwordless/api/consumeCode.js | 73 +- .../recipe/passwordless/api/createCode.d.ts | 1 - .../recipe/passwordless/api/createCode.js | 63 +- .../recipe/passwordless/api/emailExists.d.ts | 1 - .../recipe/passwordless/api/emailExists.js | 40 +- .../passwordless/api/implementation.d.ts | 1 - .../recipe/passwordless/api/implementation.js | 184 +-- .../passwordless/api/phoneNumberExists.d.ts | 1 - .../passwordless/api/phoneNumberExists.js | 40 +- .../recipe/passwordless/api/resendCode.d.ts | 1 - .../recipe/passwordless/api/resendCode.js | 40 +- lib/build/recipe/passwordless/constants.d.ts | 1 - lib/build/recipe/passwordless/constants.js | 1 + .../services/backwardCompatibility/index.d.ts | 32 +- .../services/backwardCompatibility/index.js | 172 +- .../emaildelivery/services/index.d.ts | 1 - .../emaildelivery/services/index.js | 1 + .../emaildelivery/services/smtp/index.d.ts | 9 +- .../emaildelivery/services/smtp/index.js | 55 +- .../services/smtp/passwordlessLogin.d.ts | 9 +- .../services/smtp/passwordlessLogin.js | 45 +- .../services/smtp/serviceImplementation.d.ts | 12 +- .../services/smtp/serviceImplementation.js | 44 +- lib/build/recipe/passwordless/error.d.ts | 6 +- lib/build/recipe/passwordless/index.d.ts | 196 +-- lib/build/recipe/passwordless/index.js | 101 +- lib/build/recipe/passwordless/recipe.d.ts | 59 +- lib/build/recipe/passwordless/recipe.js | 259 ++- .../passwordless/recipeImplementation.d.ts | 1 - .../passwordless/recipeImplementation.js | 105 +- .../services/backwardCompatibility/index.d.ts | 29 +- .../services/backwardCompatibility/index.js | 222 ++- .../smsdelivery/services/index.d.ts | 1 - .../smsdelivery/services/index.js | 1 + .../services/supertokens/index.d.ts | 1 - .../smsdelivery/services/supertokens/index.js | 138 +- .../smsdelivery/services/twilio/index.d.ts | 9 +- .../smsdelivery/services/twilio/index.js | 78 +- .../services/twilio/passwordlessLogin.d.ts | 1 - .../services/twilio/passwordlessLogin.js | 6 +- .../twilio/serviceImplementation.d.ts | 5 +- .../services/twilio/serviceImplementation.js | 44 +- lib/build/recipe/passwordless/types.d.ts | 531 +++---- lib/build/recipe/passwordless/utils.d.ts | 7 +- lib/build/recipe/passwordless/utils.js | 52 +- lib/build/recipe/session/accessToken.d.ts | 9 +- lib/build/recipe/session/accessToken.js | 82 +- .../recipe/session/api/implementation.d.ts | 1 - .../recipe/session/api/implementation.js | 57 +- lib/build/recipe/session/api/refresh.d.ts | 1 - lib/build/recipe/session/api/refresh.js | 45 +- lib/build/recipe/session/api/signout.d.ts | 1 - lib/build/recipe/session/api/signout.js | 40 +- .../claimBaseClasses/booleanClaim.d.ts | 1 - .../session/claimBaseClasses/booleanClaim.js | 6 +- .../claimBaseClasses/primitiveArrayClaim.d.ts | 13 +- .../claimBaseClasses/primitiveArrayClaim.js | 315 ++-- .../claimBaseClasses/primitiveClaim.d.ts | 13 +- .../claimBaseClasses/primitiveClaim.js | 109 +- lib/build/recipe/session/claims.d.ts | 1 - lib/build/recipe/session/claims.js | 9 +- lib/build/recipe/session/constants.d.ts | 3 +- lib/build/recipe/session/constants.js | 2 + .../recipe/session/cookieAndHeaders.d.ts | 57 +- lib/build/recipe/session/cookieAndHeaders.js | 152 +- lib/build/recipe/session/error.d.ts | 51 +- lib/build/recipe/session/error.js | 13 +- .../recipe/session/framework/awsLambda.d.ts | 1 - .../recipe/session/framework/awsLambda.js | 75 +- .../recipe/session/framework/express.d.ts | 5 +- lib/build/recipe/session/framework/express.js | 72 +- .../recipe/session/framework/fastify.d.ts | 15 +- lib/build/recipe/session/framework/fastify.js | 67 +- lib/build/recipe/session/framework/hapi.d.ts | 5 +- lib/build/recipe/session/framework/hapi.js | 56 +- lib/build/recipe/session/framework/index.d.ts | 1 - lib/build/recipe/session/framework/index.js | 1 + lib/build/recipe/session/framework/koa.d.ts | 5 +- lib/build/recipe/session/framework/koa.js | 56 +- .../recipe/session/framework/loopback.d.ts | 1 - .../recipe/session/framework/loopback.js | 58 +- lib/build/recipe/session/index.d.ts | 179 +-- lib/build/recipe/session/index.js | 96 +- lib/build/recipe/session/jwt.d.ts | 19 +- lib/build/recipe/session/jwt.js | 65 +- lib/build/recipe/session/recipe.d.ts | 25 +- lib/build/recipe/session/recipe.js | 223 ++- .../recipe/session/recipeImplementation.d.ts | 17 +- .../recipe/session/recipeImplementation.js | 457 +++--- lib/build/recipe/session/sessionClass.d.ts | 23 +- lib/build/recipe/session/sessionClass.js | 94 +- .../recipe/session/sessionFunctions.d.ts | 44 +- lib/build/recipe/session/sessionFunctions.js | 197 +-- lib/build/recipe/session/types.d.ts | 276 ++-- lib/build/recipe/session/types.js | 41 +- lib/build/recipe/session/utils.d.ts | 74 +- lib/build/recipe/session/utils.js | 223 +-- .../recipe/session/with-jwt/constants.d.ts | 1 - .../recipe/session/with-jwt/constants.js | 1 + lib/build/recipe/session/with-jwt/index.d.ts | 1 - .../with-jwt/recipeImplementation.d.ts | 7 +- .../session/with-jwt/recipeImplementation.js | 76 +- .../recipe/session/with-jwt/sessionClass.d.ts | 13 +- .../recipe/session/with-jwt/sessionClass.js | 69 +- lib/build/recipe/session/with-jwt/utils.d.ts | 10 +- lib/build/recipe/session/with-jwt/utils.js | 66 +- .../recipe/thirdparty/api/appleRedirect.d.ts | 1 - .../recipe/thirdparty/api/appleRedirect.js | 40 +- .../thirdparty/api/authorisationUrl.d.ts | 1 - .../recipe/thirdparty/api/authorisationUrl.js | 40 +- .../recipe/thirdparty/api/implementation.d.ts | 1 - .../recipe/thirdparty/api/implementation.js | 97 +- lib/build/recipe/thirdparty/api/signinup.d.ts | 1 - lib/build/recipe/thirdparty/api/signinup.js | 55 +- lib/build/recipe/thirdparty/constants.d.ts | 1 - lib/build/recipe/thirdparty/constants.js | 1 + lib/build/recipe/thirdparty/error.d.ts | 6 +- lib/build/recipe/thirdparty/index.d.ts | 14 +- lib/build/recipe/thirdparty/index.js | 41 +- .../thirdparty/providers/activeDirectory.d.ts | 1 - .../recipe/thirdparty/providers/apple.d.ts | 1 - .../recipe/thirdparty/providers/apple.js | 93 +- .../recipe/thirdparty/providers/discord.d.ts | 1 - .../recipe/thirdparty/providers/discord.js | 65 +- .../recipe/thirdparty/providers/facebook.d.ts | 1 - .../recipe/thirdparty/providers/facebook.js | 40 +- .../recipe/thirdparty/providers/github.d.ts | 1 - .../recipe/thirdparty/providers/github.js | 65 +- .../recipe/thirdparty/providers/google.d.ts | 1 - .../recipe/thirdparty/providers/google.js | 58 +- .../providers/googleWorkspaces.d.ts | 1 - .../thirdparty/providers/googleWorkspaces.js | 71 +- .../recipe/thirdparty/providers/index.d.ts | 1 - .../recipe/thirdparty/providers/index.js | 1 + .../recipe/thirdparty/providers/okta.d.ts | 1 - .../recipe/thirdparty/providers/utils.d.ts | 7 +- .../recipe/thirdparty/providers/utils.js | 44 +- lib/build/recipe/thirdparty/recipe.d.ts | 18 +- lib/build/recipe/thirdparty/recipe.js | 131 +- .../thirdparty/recipeImplementation.d.ts | 1 - .../recipe/thirdparty/recipeImplementation.js | 59 +- lib/build/recipe/thirdparty/types.d.ts | 188 +-- lib/build/recipe/thirdparty/utils.d.ts | 12 +- lib/build/recipe/thirdparty/utils.js | 21 +- .../api/emailPasswordAPIImplementation.d.ts | 1 - .../api/emailPasswordAPIImplementation.js | 28 +- .../api/implementation.d.ts | 1 - .../api/implementation.js | 50 +- .../api/thirdPartyAPIImplementation.d.ts | 1 - .../api/thirdPartyAPIImplementation.js | 122 +- .../services/backwardCompatibility/index.d.ts | 27 +- .../services/backwardCompatibility/index.js | 54 +- .../emaildelivery/services/index.d.ts | 1 - .../emaildelivery/services/index.js | 1 + .../emaildelivery/services/smtp/index.d.ts | 9 +- .../emaildelivery/services/smtp/index.js | 47 +- .../recipe/thirdpartyemailpassword/error.d.ts | 6 +- .../recipe/thirdpartyemailpassword/index.d.ts | 100 +- .../recipe/thirdpartyemailpassword/index.js | 49 +- .../thirdpartyemailpassword/recipe.d.ts | 42 +- .../recipe/thirdpartyemailpassword/recipe.js | 207 +-- .../emailPasswordRecipeImplementation.d.ts | 1 - .../emailPasswordRecipeImplementation.js | 40 +- .../recipeImplementation/index.d.ts | 1 - .../recipeImplementation/index.js | 87 +- .../thirdPartyRecipeImplementation.d.ts | 1 - .../thirdPartyRecipeImplementation.js | 40 +- .../recipe/thirdpartyemailpassword/types.d.ts | 499 +++--- .../recipe/thirdpartyemailpassword/utils.d.ts | 7 +- .../recipe/thirdpartyemailpassword/utils.js | 32 +- .../api/implementation.d.ts | 1 - .../api/implementation.js | 50 +- .../api/passwordlessAPIImplementation.d.ts | 1 - .../api/passwordlessAPIImplementation.js | 24 +- .../api/thirdPartyAPIImplementation.d.ts | 1 - .../api/thirdPartyAPIImplementation.js | 122 +- .../services/backwardCompatibility/index.d.ts | 36 +- .../services/backwardCompatibility/index.js | 54 +- .../emaildelivery/services/index.d.ts | 1 - .../emaildelivery/services/index.js | 1 + .../emaildelivery/services/smtp/index.d.ts | 9 +- .../emaildelivery/services/smtp/index.js | 51 +- .../smtp/serviceImplementation/index.d.ts | 12 +- .../smtp/serviceImplementation/index.js | 45 +- .../passwordlessServiceImplementation.d.ts | 5 +- .../passwordlessServiceImplementation.js | 40 +- .../recipe/thirdpartypasswordless/error.d.ts | 6 +- .../recipe/thirdpartypasswordless/index.d.ts | 259 +-- .../recipe/thirdpartypasswordless/index.js | 101 +- .../recipe/thirdpartypasswordless/recipe.d.ts | 45 +- .../recipe/thirdpartypasswordless/recipe.js | 201 +-- .../recipeImplementation/index.d.ts | 1 - .../recipeImplementation/index.js | 115 +- .../passwordlessRecipeImplementation.d.ts | 1 - .../passwordlessRecipeImplementation.js | 40 +- .../thirdPartyRecipeImplementation.d.ts | 1 - .../thirdPartyRecipeImplementation.js | 40 +- .../services/backwardCompatibility/index.d.ts | 36 +- .../services/backwardCompatibility/index.js | 54 +- .../smsdelivery/services/index.d.ts | 1 - .../smsdelivery/services/index.js | 1 + .../services/supertokens/index.d.ts | 9 +- .../smsdelivery/services/supertokens/index.js | 47 +- .../smsdelivery/services/twilio/index.d.ts | 9 +- .../smsdelivery/services/twilio/index.js | 47 +- .../recipe/thirdpartypasswordless/types.d.ts | 753 ++++----- .../recipe/thirdpartypasswordless/utils.d.ts | 6 +- .../recipe/thirdpartypasswordless/utils.js | 49 +- lib/build/recipe/usermetadata/index.d.ts | 17 +- lib/build/recipe/usermetadata/index.js | 41 +- lib/build/recipe/usermetadata/recipe.d.ts | 9 +- lib/build/recipe/usermetadata/recipe.js | 58 +- .../usermetadata/recipeImplementation.d.ts | 1 - lib/build/recipe/usermetadata/types.d.ts | 11 +- lib/build/recipe/usermetadata/utils.d.ts | 7 +- lib/build/recipe/usermetadata/utils.js | 9 +- lib/build/recipe/userroles/index.d.ts | 106 +- lib/build/recipe/userroles/index.js | 45 +- .../recipe/userroles/permissionClaim.d.ts | 1 - lib/build/recipe/userroles/permissionClaim.js | 41 +- lib/build/recipe/userroles/recipe.d.ts | 9 +- lib/build/recipe/userroles/recipe.js | 58 +- .../userroles/recipeImplementation.d.ts | 1 - .../recipe/userroles/recipeImplementation.js | 5 +- lib/build/recipe/userroles/types.d.ts | 71 +- lib/build/recipe/userroles/userRoleClaim.d.ts | 1 - lib/build/recipe/userroles/userRoleClaim.js | 41 +- lib/build/recipe/userroles/utils.d.ts | 7 +- lib/build/recipe/userroles/utils.js | 15 +- lib/build/recipeModule.d.ts | 9 +- lib/build/recipeModule.js | 6 +- lib/build/supertokens.d.ts | 73 +- lib/build/supertokens.js | 495 +++--- lib/build/types.d.ts | 3 +- lib/build/utils.d.ts | 4 +- lib/build/utils.js | 82 +- lib/build/version.d.ts | 5 +- lib/build/version.js | 5 +- lib/ts/framework/awsLambda/framework.ts | 8 +- lib/ts/framework/express/framework.ts | 4 + lib/ts/framework/fastify/framework.ts | 4 + lib/ts/framework/hapi/framework.ts | 25 +- lib/ts/framework/koa/framework.ts | 4 + lib/ts/framework/loopback/framework.ts | 4 + lib/ts/framework/response.ts | 1 + .../dashboard/api/userdetails/userGet.ts | 11 +- .../dashboard/api/userdetails/userPut.ts | 2 +- lib/ts/recipe/dashboard/utils.ts | 56 + .../emailpassword/api/implementation.ts | 4 +- .../services/backwardCompatibility/index.ts | 4 + .../services/smtp/passwordReset.ts | 7 - .../services/smtp/emailVerify.ts | 7 - .../recipe/passwordless/api/implementation.ts | 1 + .../services/smtp/passwordlessLogin.ts | 21 - lib/ts/recipe/session/accessToken.ts | 54 +- lib/ts/recipe/session/constants.ts | 4 + lib/ts/recipe/session/cookieAndHeaders.ts | 163 +- lib/ts/recipe/session/error.ts | 4 +- lib/ts/recipe/session/index.ts | 6 + lib/ts/recipe/session/jwt.ts | 40 +- lib/ts/recipe/session/recipe.ts | 16 +- lib/ts/recipe/session/recipeImplementation.ts | 339 +++- lib/ts/recipe/session/sessionClass.ts | 53 +- lib/ts/recipe/session/sessionFunctions.ts | 34 +- lib/ts/recipe/session/types.ts | 29 +- lib/ts/recipe/session/utils.ts | 95 +- .../session/with-jwt/recipeImplementation.ts | 5 +- .../recipe/session/with-jwt/sessionClass.ts | 2 +- .../recipe/thirdparty/api/implementation.ts | 1 + lib/ts/supertokens.ts | 3 +- lib/ts/types.ts | 2 + lib/ts/utils.ts | 40 +- lib/ts/version.ts | 4 +- package-lock.json | 1398 +++++++++++------ package.json | 10 +- test/auth-modes.test.js | 1139 ++++++++++++++ test/config.test.js | 281 ++-- test/emailpassword/deleteUser.test.js | 2 +- test/emailpassword/emailDelivery.test.js | 115 +- test/emailpassword/emailExists.test.js | 18 +- test/emailpassword/emailverify.test.js | 228 +-- test/emailpassword/override.test.js | 8 +- test/emailpassword/passwordreset.test.js | 4 +- test/emailpassword/signinFeature.test.js | 40 +- test/emailpassword/signoutFeature.test.js | 60 +- test/emailpassword/signupFeature.test.js | 58 +- test/emailpassword/updateEmailPass.test.js | 2 +- test/emailpassword/users.test.js | 6 +- test/framework/awsLambda.test.js | 224 ++- test/framework/crossFramework.testgen.js | 406 +++++ .../crossframework/unauthorised.test.js | 168 ++ test/framework/fastify.test.js | 244 +-- test/framework/hapi.test.js | 182 +-- test/framework/koa.test.js | 257 +-- test/framework/loopback-server/index.js | 17 +- test/framework/loopback-server/index.ts | 15 +- test/framework/loopback.test.js | 29 +- test/frontendIntegration/index.html | 11 + test/frontendIntegration/index.js | 20 +- test/handshake.test.js | 10 +- test/middleware.test.js | 523 ++---- test/middleware2.test.js | 10 +- test/nextjs.test.js | 8 +- test/passwordless/apis.test.js | 36 +- test/passwordless/config.test.js | 48 +- test/passwordless/emailDelivery.test.js | 20 +- test/passwordless/recipeFunctions.test.js | 28 +- test/passwordless/smsDelivery.test.js | 28 +- test/querier.test.js | 43 +- test/recipeModuleManager.test.js | 29 +- test/session.test.js | 313 ++-- test/session/claims/createNewSession.test.js | 11 +- test/session/claims/fetchAndSetClaim.test.js | 6 +- test/session/claims/getClaimValue.test.js | 10 +- test/session/claims/removeClaim.test.js | 9 +- test/session/claims/setClaimValue.test.js | 10 +- .../validateClaimsForSessionHandle.test.js | 7 +- test/session/claims/verifySession.test.js | 25 +- test/session/claims/withJWT.test.js | 3 +- test/session/with-jwt/jwt.override.test.js | 4 +- test/session/with-jwt/jwtFunctions.test.js | 34 +- .../session/with-jwt/session.override.test.js | 57 +- test/session/with-jwt/sessionClass.test.js | 70 +- test/session/with-jwt/withjwt.test.js | 493 ++++-- ...sessionAccessTokenSigningKeyUpdate.test.js | 118 +- test/sessionExpress.test.js | 942 ++++------- .../authorisationUrlFeature.test.js | 16 +- test/thirdparty/override.test.js | 8 +- test/thirdparty/signinupFeature.test.js | 60 +- test/thirdparty/signoutFeature.test.js | 43 +- test/thirdparty/users.test.js | 6 +- .../authorisationUrlFeature.test.js | 10 +- .../emailDelivery.test.js | 58 +- .../emailExists.test.js | 8 +- .../emailverify.test.js | 42 +- test/thirdpartyemailpassword/override.test.js | 8 +- .../signinFeature.test.js | 36 +- .../signoutFeature.test.js | 94 +- .../signupFeature.test.js | 30 +- test/thirdpartypasswordless/api.test.js | 36 +- .../authorisationUrlFeature.test.js | 10 +- test/thirdpartypasswordless/config.test.js | 46 +- .../emailDelivery.test.js | 56 +- test/thirdpartypasswordless/override.test.js | 8 +- .../recipeFunctions.test.js | 32 +- .../signinupFeature.test.js | 60 +- .../signoutFeature.test.js | 44 +- .../smsDelivery.test.js | 28 +- test/thirdpartypasswordless/users.test.js | 6 +- test/userContext.test.js | 4 +- test/userroles/claims.test.js | 30 +- test/utils.js | 52 +- test/with-typescript/index.ts | 73 +- 633 files changed, 14142 insertions(+), 18557 deletions(-) create mode 100644 test/auth-modes.test.js create mode 100644 test/framework/crossFramework.testgen.js create mode 100644 test/framework/crossframework/unauthorised.test.js diff --git a/.circleci/setupAndTestWithAuthReact.sh b/.circleci/setupAndTestWithAuthReact.sh index c412dd17d..05fe6c919 100755 --- a/.circleci/setupAndTestWithAuthReact.sh +++ b/.circleci/setupAndTestWithAuthReact.sh @@ -51,11 +51,11 @@ git checkout $2 npm run init (cd ./examples/for-tests && npm run link) # this is there because in linux machine, postinstall in npm doesn't work.. cd ./test/server/ -npm i -d npm i git+https://github.com:supertokens/supertokens-node.git#$3 +npm i cd ../../ cd ../project/test/auth-react-server -npm i -d +npm i TEST_MODE=testing node . & pid=$! cd ../../../supertokens-auth-react/ diff --git a/.circleci/setupAndTestWithFrontend.sh b/.circleci/setupAndTestWithFrontend.sh index 4975dc44e..cb0909778 100755 --- a/.circleci/setupAndTestWithFrontend.sh +++ b/.circleci/setupAndTestWithFrontend.sh @@ -55,8 +55,8 @@ pid=$! TEST_MODE=testing NODE_PORT=8082 node . & pid2=$! cd ../../../supertokens-website/test/server -npm i -d npm i git+https://github.com:supertokens/supertokens-node.git#$3 +npm i cd ../../ npm i -d SUPERTOKENS_CORE_TAG=$coreTag NODE_PORT=8081 INSTALL_PATH=../supertokens-root npm test diff --git a/.gitignore b/.gitignore index 9aa9e5ced..eec512c0e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /node_modules +/examples/*/node_modules .DS_Store /.history *.js.map diff --git a/CHANGELOG.md b/CHANGELOG.md index c017736f1..6ffa1e2da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Functions `deleteuser`, `getUsersNewestFirst` and `getUsersOldestFirst` are now based on account linking recipe - Function `deleteuser` takes a new parameter `removeAllLinkedAccounts` which will be `true` by default +## [13.0.1] - 2023-02-06 + +- Email template updates + +## [13.0.0] - 2023-02-01 + +### Breaking changes + +- The frontend SDK should be updated to a version supporting the header-based sessions! + - supertokens-auth-react: >= 0.31.0 + - supertokens-web-js: >= 0.5.0 + - supertokens-website: >= 16.0.0 + - supertokens-react-native: >= 4.0.0 + - supertokens-ios >= 0.2.0 + - supertokens-android >= 0.3.0 + - supertokens-flutter >= 0.1.0 +- `createNewSession` now requires passing the request as well as the response. + - This only requires a change if you manually created sessions (e.g.: during testing) + - There is a migration example added below. It uses express, but the same principle applies for other supported frameworks. +- Only supporting FDI 1.16 + +### Added + +- Added support for authorizing requests using the `Authorization` header instead of cookies + - Added `getTokenTransferMethod` config option + - Check out https://supertokens.com/docs/thirdpartyemailpassword/common-customizations/sessions/token-transfer-method for more information + +### Migration + +This example uses express, but the same principle applies for other supported frameworks. + +Before: + +``` +const app = express(); +app.post("/create", async (req, res) => { + await Session.createNewSession(res, "testing-userId", {}, {}); + res.status(200).json({ message: true }); +}); +``` + +After the update: + +``` +const app = express(); +app.post("/create", async (req, res) => { + await Session.createNewSession(req, res, "testing-userId", {}, {}); + res.status(200).json({ message: true }); +}); +``` + +## [12.1.6] - 2023-01-22 + +- Updates jsonwebtoken dependency to version 9.0.0 to fix vulnerability in it's `verify` function. + +## [12.1.5] - 2022-12-10 + +- Fixes Content-type header in AWS lambda framework + +## [12.1.4] - 2022-12-26 + +- Updates dashboard version +- Updates user GET API for the dashboard recipe + +## [12.1.3] - 2022-12-12 + +- Updates some dependencies cause of `npm audit` + +## [12.1.2] - 2022-12-06 + +- Fixes issue where if sendEmail is overridden with a different email, it will reset that email. + +## [12.1.1] - 2022-11-25 + +- Fixed an issue with importing the wrong recipe in the dashboard APIs + ## [12.1.0] - 2022-11-17 ### Added: diff --git a/README.md b/README.md index b7c743d36..17efd5563 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ chat on Discord + ## About This is a NodeJS library that is used to interface between a node API process and the SuperTokens http service. diff --git a/docs/assets/highlight.css b/docs/assets/highlight.css index ab6713ab4..dd760c444 100644 --- a/docs/assets/highlight.css +++ b/docs/assets/highlight.css @@ -21,10 +21,10 @@ --dark-hl-9: #4EC9B0; --light-hl-10: #000000FF; --dark-hl-10: #D4D4D4; - --light-hl-11: #EE0000; - --dark-hl-11: #D7BA7D; - --light-hl-12: #811F3F; - --dark-hl-12: #D16969; + --light-hl-11: #811F3F; + --dark-hl-11: #D16969; + --light-hl-12: #EE0000; + --dark-hl-12: #D7BA7D; --light-code-background: #F5F5F5; --dark-code-background: #1E1E1E; } diff --git a/docs/assets/main.js b/docs/assets/main.js index bd45452db..99f331b26 100644 --- a/docs/assets/main.js +++ b/docs/assets/main.js @@ -1,5 +1,5 @@ -(()=>{var Ce=Object.create;var ue=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var Me=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var De=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oe(e))!_e.call(t,i)&&i!==r&&ue(t,i,{get:()=>e[i],enumerable:!(n=Pe(e,i))||n.enumerable});return t};var Fe=(t,e,r)=>(r=t!=null?Ce(Re(t)):{},De(e||!t||!t.__esModule?ue(r,"default",{value:t,enumerable:!0}):r,t));var pe=Me((de,fe)=>{(function(){var t=function(e){var r=new t.Builder;return r.pipeline.add(t.trimmer,t.stopWordFilter,t.stemmer),r.searchPipeline.add(t.stemmer),e.call(r,r),r.build()};t.version="2.3.9";t.utils={},t.utils.warn=function(e){return function(r){e.console&&console.warn&&console.warn(r)}}(this),t.utils.asString=function(e){return e==null?"":e.toString()},t.utils.clone=function(e){if(e==null)return e;for(var r=Object.create(null),n=Object.keys(e),i=0;i0){var h=t.utils.clone(r)||{};h.position=[a,u],h.index=s.length,s.push(new t.Token(n.slice(a,o),h))}a=o+1}}return s},t.tokenizer.separator=/[\s\-]+/;t.Pipeline=function(){this._stack=[]},t.Pipeline.registeredFunctions=Object.create(null),t.Pipeline.registerFunction=function(e,r){r in this.registeredFunctions&&t.utils.warn("Overwriting existing registered function: "+r),e.label=r,t.Pipeline.registeredFunctions[e.label]=e},t.Pipeline.warnIfFunctionNotRegistered=function(e){var r=e.label&&e.label in this.registeredFunctions;r||t.utils.warn(`Function is not registered with pipeline. This may cause problems when serialising the index. -`,e)},t.Pipeline.load=function(e){var r=new t.Pipeline;return e.forEach(function(n){var i=t.Pipeline.registeredFunctions[n];if(i)r.add(i);else throw new Error("Cannot load unregistered function: "+n)}),r},t.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach(function(r){t.Pipeline.warnIfFunctionNotRegistered(r),this._stack.push(r)},this)},t.Pipeline.prototype.after=function(e,r){t.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(e);if(n==-1)throw new Error("Cannot find existingFn");n=n+1,this._stack.splice(n,0,r)},t.Pipeline.prototype.before=function(e,r){t.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(e);if(n==-1)throw new Error("Cannot find existingFn");this._stack.splice(n,0,r)},t.Pipeline.prototype.remove=function(e){var r=this._stack.indexOf(e);r!=-1&&this._stack.splice(r,1)},t.Pipeline.prototype.run=function(e){for(var r=this._stack.length,n=0;n1&&(oe&&(n=s),o!=e);)i=n-r,s=r+Math.floor(i/2),o=this.elements[s*2];if(o==e||o>e)return s*2;if(ol?h+=2:a==l&&(r+=n[u+1]*i[h+1],u+=2,h+=2);return r},t.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},t.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),r=1,n=0;r0){var o=s.str.charAt(0),a;o in s.node.edges?a=s.node.edges[o]:(a=new t.TokenSet,s.node.edges[o]=a),s.str.length==1&&(a.final=!0),i.push({node:a,editsRemaining:s.editsRemaining,str:s.str.slice(1)})}if(s.editsRemaining!=0){if("*"in s.node.edges)var l=s.node.edges["*"];else{var l=new t.TokenSet;s.node.edges["*"]=l}if(s.str.length==0&&(l.final=!0),i.push({node:l,editsRemaining:s.editsRemaining-1,str:s.str}),s.str.length>1&&i.push({node:s.node,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)}),s.str.length==1&&(s.node.final=!0),s.str.length>=1){if("*"in s.node.edges)var u=s.node.edges["*"];else{var u=new t.TokenSet;s.node.edges["*"]=u}s.str.length==1&&(u.final=!0),i.push({node:u,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)})}if(s.str.length>1){var h=s.str.charAt(0),f=s.str.charAt(1),p;f in s.node.edges?p=s.node.edges[f]:(p=new t.TokenSet,s.node.edges[f]=p),s.str.length==1&&(p.final=!0),i.push({node:p,editsRemaining:s.editsRemaining-1,str:h+s.str.slice(2)})}}}return n},t.TokenSet.fromString=function(e){for(var r=new t.TokenSet,n=r,i=0,s=e.length;i=e;r--){var n=this.uncheckedNodes[r],i=n.child.toString();i in this.minimizedNodes?n.parent.edges[n.char]=this.minimizedNodes[i]:(n.child._str=i,this.minimizedNodes[i]=n.child),this.uncheckedNodes.pop()}};t.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},t.Index.prototype.search=function(e){return this.query(function(r){var n=new t.QueryParser(e,r);n.parse()})},t.Index.prototype.query=function(e){for(var r=new t.Query(this.fields),n=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null),a=Object.create(null),l=0;l1?this._b=1:this._b=e},t.Builder.prototype.k1=function(e){this._k1=e},t.Builder.prototype.add=function(e,r){var n=e[this._ref],i=Object.keys(this._fields);this._documents[n]=r||{},this.documentCount+=1;for(var s=0;s=this.length)return t.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},t.QueryLexer.prototype.width=function(){return this.pos-this.start},t.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},t.QueryLexer.prototype.backup=function(){this.pos-=1},t.QueryLexer.prototype.acceptDigitRun=function(){var e,r;do e=this.next(),r=e.charCodeAt(0);while(r>47&&r<58);e!=t.QueryLexer.EOS&&this.backup()},t.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(t.QueryLexer.TERM)),e.ignore(),e.more())return t.QueryLexer.lexText},t.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.EDIT_DISTANCE),t.QueryLexer.lexText},t.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.BOOST),t.QueryLexer.lexText},t.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(t.QueryLexer.TERM)},t.QueryLexer.termSeparator=t.tokenizer.separator,t.QueryLexer.lexText=function(e){for(;;){var r=e.next();if(r==t.QueryLexer.EOS)return t.QueryLexer.lexEOS;if(r.charCodeAt(0)==92){e.escapeCharacter();continue}if(r==":")return t.QueryLexer.lexField;if(r=="~")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexEditDistance;if(r=="^")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexBoost;if(r=="+"&&e.width()===1||r=="-"&&e.width()===1)return e.emit(t.QueryLexer.PRESENCE),t.QueryLexer.lexText;if(r.match(t.QueryLexer.termSeparator))return t.QueryLexer.lexTerm}},t.QueryParser=function(e,r){this.lexer=new t.QueryLexer(e),this.query=r,this.currentClause={},this.lexemeIdx=0},t.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=t.QueryParser.parseClause;e;)e=e(this);return this.query},t.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},t.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},t.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},t.QueryParser.parseClause=function(e){var r=e.peekLexeme();if(r!=null)switch(r.type){case t.QueryLexer.PRESENCE:return t.QueryParser.parsePresence;case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var n="expected either a field or a term, found "+r.type;throw r.str.length>=1&&(n+=" with value '"+r.str+"'"),new t.QueryParseError(n,r.start,r.end)}},t.QueryParser.parsePresence=function(e){var r=e.consumeLexeme();if(r!=null){switch(r.str){case"-":e.currentClause.presence=t.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=t.Query.presence.REQUIRED;break;default:var n="unrecognised presence operator'"+r.str+"'";throw new t.QueryParseError(n,r.start,r.end)}var i=e.peekLexeme();if(i==null){var n="expecting term or field, found nothing";throw new t.QueryParseError(n,r.start,r.end)}switch(i.type){case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var n="expecting term or field, found '"+i.type+"'";throw new t.QueryParseError(n,i.start,i.end)}}},t.QueryParser.parseField=function(e){var r=e.consumeLexeme();if(r!=null){if(e.query.allFields.indexOf(r.str)==-1){var n=e.query.allFields.map(function(o){return"'"+o+"'"}).join(", "),i="unrecognised field '"+r.str+"', possible fields: "+n;throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.fields=[r.str];var s=e.peekLexeme();if(s==null){var i="expecting term, found nothing";throw new t.QueryParseError(i,r.start,r.end)}switch(s.type){case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var i="expecting term, found '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseTerm=function(e){var r=e.consumeLexeme();if(r!=null){e.currentClause.term=r.str.toLowerCase(),r.str.indexOf("*")!=-1&&(e.currentClause.usePipeline=!1);var n=e.peekLexeme();if(n==null){e.nextClause();return}switch(n.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+n.type+"'";throw new t.QueryParseError(i,n.start,n.end)}}},t.QueryParser.parseEditDistance=function(e){var r=e.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="edit distance must be numeric";throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.editDistance=n;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseBoost=function(e){var r=e.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="boost must be numeric";throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.boost=n;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},function(e,r){typeof define=="function"&&define.amd?define(r):typeof de=="object"?fe.exports=r():e.lunr=r()}(this,function(){return t})})()});var ce=[];function N(t,e){ce.push({selector:e,constructor:t})}var Y=class{constructor(){this.createComponents(document.body)}createComponents(e){ce.forEach(r=>{e.querySelectorAll(r.selector).forEach(n=>{n.dataset.hasInstance||(new r.constructor({el:n}),n.dataset.hasInstance=String(!0))})})}};var k=class{constructor(e){this.el=e.el}};var J=class{constructor(){this.listeners={}}addEventListener(e,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push(r)}removeEventListener(e,r){if(!(e in this.listeners))return;let n=this.listeners[e];for(let i=0,s=n.length;i{let r=Date.now();return(...n)=>{r+e-Date.now()<0&&(t(...n),r=Date.now())}};var ie=class extends J{constructor(){super();this.scrollTop=0;this.lastY=0;this.width=0;this.height=0;this.showToolbar=!0;this.toolbar=document.querySelector(".tsd-page-toolbar"),this.secondaryNav=document.querySelector(".tsd-navigation.secondary"),window.addEventListener("scroll",ne(()=>this.onScroll(),10)),window.addEventListener("resize",ne(()=>this.onResize(),10)),this.onResize(),this.onScroll()}triggerResize(){let r=new CustomEvent("resize",{detail:{width:this.width,height:this.height}});this.dispatchEvent(r)}onResize(){this.width=window.innerWidth||0,this.height=window.innerHeight||0;let r=new CustomEvent("resize",{detail:{width:this.width,height:this.height}});this.dispatchEvent(r)}onScroll(){this.scrollTop=window.scrollY||0;let r=new CustomEvent("scroll",{detail:{scrollTop:this.scrollTop}});this.dispatchEvent(r),this.hideShowToolbar()}hideShowToolbar(){var n;let r=this.showToolbar;this.showToolbar=this.lastY>=this.scrollTop||this.scrollTop<=0,r!==this.showToolbar&&(this.toolbar.classList.toggle("tsd-page-toolbar--hide"),(n=this.secondaryNav)==null||n.classList.toggle("tsd-navigation--toolbar-hide")),this.lastY=this.scrollTop}},Q=ie;Q.instance=new ie;var X=class extends k{constructor(r){super(r);this.anchors=[];this.index=-1;Q.instance.addEventListener("resize",()=>this.onResize()),Q.instance.addEventListener("scroll",n=>this.onScroll(n)),this.createAnchors()}createAnchors(){let r=window.location.href;r.indexOf("#")!=-1&&(r=r.substr(0,r.indexOf("#"))),this.el.querySelectorAll("a").forEach(n=>{let i=n.href;if(i.indexOf("#")==-1||i.substr(0,r.length)!=r)return;let s=i.substr(i.indexOf("#")+1),o=document.querySelector("a.tsd-anchor[name="+s+"]"),a=n.parentNode;!o||!a||this.anchors.push({link:a,anchor:o,position:0})}),this.onResize()}onResize(){let r;for(let i=0,s=this.anchors.length;ii.position-s.position);let n=new CustomEvent("scroll",{detail:{scrollTop:Q.instance.scrollTop}});this.onScroll(n)}onScroll(r){let n=r.detail.scrollTop+5,i=this.anchors,s=i.length-1,o=this.index;for(;o>-1&&i[o].position>n;)o-=1;for(;o-1&&this.anchors[this.index].link.classList.remove("focus"),this.index=o,this.index>-1&&this.anchors[this.index].link.classList.add("focus"))}};var he=(t,e=100)=>{let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(n),e)}};var ge=Fe(pe());function ye(){let t=document.getElementById("tsd-search");if(!t)return;let e=document.getElementById("search-script");t.classList.add("loading"),e&&(e.addEventListener("error",()=>{t.classList.remove("loading"),t.classList.add("failure")}),e.addEventListener("load",()=>{t.classList.remove("loading"),t.classList.add("ready")}),window.searchData&&t.classList.remove("loading"));let r=document.querySelector("#tsd-search input"),n=document.querySelector("#tsd-search .results");if(!r||!n)throw new Error("The input field or the result list wrapper was not found");let i=!1;n.addEventListener("mousedown",()=>i=!0),n.addEventListener("mouseup",()=>{i=!1,t.classList.remove("has-focus")}),r.addEventListener("focus",()=>t.classList.add("has-focus")),r.addEventListener("blur",()=>{i||(i=!1,t.classList.remove("has-focus"))});let s={base:t.dataset.base+"/"};Ae(t,n,r,s)}function Ae(t,e,r,n){r.addEventListener("input",he(()=>{He(t,e,r,n)},200));let i=!1;r.addEventListener("keydown",s=>{i=!0,s.key=="Enter"?ze(e,r):s.key=="Escape"?r.blur():s.key=="ArrowUp"?me(e,-1):s.key==="ArrowDown"?me(e,1):i=!1}),r.addEventListener("keypress",s=>{i&&s.preventDefault()}),document.body.addEventListener("keydown",s=>{s.altKey||s.ctrlKey||s.metaKey||!r.matches(":focus")&&s.key==="/"&&(r.focus(),s.preventDefault())})}function Ve(t,e){t.index||window.searchData&&(e.classList.remove("loading"),e.classList.add("ready"),t.data=window.searchData,t.index=ge.Index.load(window.searchData.index))}function He(t,e,r,n){var o,a;if(Ve(n,t),!n.index||!n.data)return;e.textContent="";let i=r.value.trim(),s=i?n.index.search(`*${i}*`):[];for(let l=0;lu.score-l.score);for(let l=0,u=Math.min(10,s.length);l${ve(h.parent,i)}.${f}`);let p=document.createElement("li");p.classList.value=(a=h.classes)!=null?a:"";let E=document.createElement("a");E.href=n.base+h.url,E.classList.add("tsd-kind-icon"),E.innerHTML=f,p.append(E),e.appendChild(p)}}function me(t,e){var n,i;let r=t.querySelector(".current");if(!r)r=t.querySelector(e==1?"li:first-child":"li:last-child"),r&&r.classList.add("current");else{let s=r;if(e===1)do s=(n=s.nextElementSibling)!=null?n:void 0;while(s instanceof HTMLElement&&s.offsetParent==null);else do s=(i=s.previousElementSibling)!=null?i:void 0;while(s instanceof HTMLElement&&s.offsetParent==null);s&&(r.classList.remove("current"),s.classList.add("current"))}}function ze(t,e){let r=t.querySelector(".current");if(r||(r=t.querySelector("li:first-child")),r){let n=r.querySelector("a");n&&(window.location.href=n.href),e.blur()}}function ve(t,e){if(e==="")return t;let r=t.toLocaleLowerCase(),n=e.toLocaleLowerCase(),i=[],s=0,o=r.indexOf(n);for(;o!=-1;)i.push(se(t.substring(s,o)),`${se(t.substring(o,o+n.length))}`),s=o+n.length,o=r.indexOf(n,s);return i.push(se(t.substring(s))),i.join("")}var Ne={"&":"&","<":"<",">":">","'":"'",'"':"""};function se(t){return t.replace(/[&<>"'"]/g,e=>Ne[e])}var oe=class{constructor(e,r){this.signature=e,this.description=r}addClass(e){return this.signature.classList.add(e),this.description.classList.add(e),this}removeClass(e){return this.signature.classList.remove(e),this.description.classList.remove(e),this}},Z=class extends k{constructor(r){super(r);this.groups=[];this.index=-1;this.createGroups(),this.container&&(this.el.classList.add("active"),Array.from(this.el.children).forEach(n=>{n.addEventListener("touchstart",i=>this.onClick(i)),n.addEventListener("click",i=>this.onClick(i))}),this.container.classList.add("active"),this.setIndex(0))}setIndex(r){if(r<0&&(r=0),r>this.groups.length-1&&(r=this.groups.length-1),this.index==r)return;let n=this.groups[r];if(this.index>-1){let i=this.groups[this.index];i.removeClass("current").addClass("fade-out"),n.addClass("current"),n.addClass("fade-in"),Q.instance.triggerResize(),setTimeout(()=>{i.removeClass("fade-out"),n.removeClass("fade-in")},300)}else n.addClass("current"),Q.instance.triggerResize();this.index=r}createGroups(){let r=this.el.children;if(r.length<2)return;this.container=this.el.nextElementSibling;let n=this.container.children;this.groups=[];for(let i=0;i{n.signature===r.currentTarget&&this.setIndex(i)})}};var C="mousedown",Le="mousemove",_="mouseup",K={x:0,y:0},xe=!1,ae=!1,je=!1,A=!1,Ee=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);document.documentElement.classList.add(Ee?"is-mobile":"not-mobile");Ee&&"ontouchstart"in document.documentElement&&(je=!0,C="touchstart",Le="touchmove",_="touchend");document.addEventListener(C,t=>{ae=!0,A=!1;let e=C=="touchstart"?t.targetTouches[0]:t;K.y=e.pageY||0,K.x=e.pageX||0});document.addEventListener(Le,t=>{if(!!ae&&!A){let e=C=="touchstart"?t.targetTouches[0]:t,r=K.x-(e.pageX||0),n=K.y-(e.pageY||0);A=Math.sqrt(r*r+n*n)>10}});document.addEventListener(_,()=>{ae=!1});document.addEventListener("click",t=>{xe&&(t.preventDefault(),t.stopImmediatePropagation(),xe=!1)});var ee=class extends k{constructor(r){super(r);this.className=this.el.dataset.toggle||"",this.el.addEventListener(_,n=>this.onPointerUp(n)),this.el.addEventListener("click",n=>n.preventDefault()),document.addEventListener(C,n=>this.onDocumentPointerDown(n)),document.addEventListener(_,n=>this.onDocumentPointerUp(n))}setActive(r){if(this.active==r)return;this.active=r,document.documentElement.classList.toggle("has-"+this.className,r),this.el.classList.toggle("active",r);let n=(this.active?"to-has-":"from-has-")+this.className;document.documentElement.classList.add(n),setTimeout(()=>document.documentElement.classList.remove(n),500)}onPointerUp(r){A||(this.setActive(!0),r.preventDefault())}onDocumentPointerDown(r){if(this.active){if(r.target.closest(".col-menu, .tsd-filter-group"))return;this.setActive(!1)}}onDocumentPointerUp(r){if(!A&&this.active&&r.target.closest(".col-menu")){let n=r.target.closest("a");if(n){let i=window.location.href;i.indexOf("#")!=-1&&(i=i.substr(0,i.indexOf("#"))),n.href.substr(0,i.length)==i&&setTimeout(()=>this.setActive(!1),250)}}}};var te=class{constructor(e,r){this.key=e,this.value=r,this.defaultValue=r,this.initialize(),window.localStorage[this.key]&&this.setValue(this.fromLocalStorage(window.localStorage[this.key]))}initialize(){}setValue(e){if(this.value==e)return;let r=this.value;this.value=e,window.localStorage[this.key]=this.toLocalStorage(e),this.handleValueChange(r,e)}},re=class extends te{initialize(){let r=document.querySelector("#tsd-filter-"+this.key);!r||(this.checkbox=r,this.checkbox.addEventListener("change",()=>{this.setValue(this.checkbox.checked)}))}handleValueChange(r,n){!this.checkbox||(this.checkbox.checked=this.value,document.documentElement.classList.toggle("toggle-"+this.key,this.value!=this.defaultValue))}fromLocalStorage(r){return r=="true"}toLocalStorage(r){return r?"true":"false"}},le=class extends te{initialize(){document.documentElement.classList.add("toggle-"+this.key+this.value);let r=document.querySelector("#tsd-filter-"+this.key);if(!r)return;this.select=r;let n=()=>{this.select.classList.add("active")},i=()=>{this.select.classList.remove("active")};this.select.addEventListener(C,n),this.select.addEventListener("mouseover",n),this.select.addEventListener("mouseleave",i),this.select.querySelectorAll("li").forEach(s=>{s.addEventListener(_,o=>{r.classList.remove("active"),this.setValue(o.target.dataset.value||"")})}),document.addEventListener(C,s=>{this.select.contains(s.target)||this.select.classList.remove("active")})}handleValueChange(r,n){this.select.querySelectorAll("li.selected").forEach(o=>{o.classList.remove("selected")});let i=this.select.querySelector('li[data-value="'+n+'"]'),s=this.select.querySelector(".tsd-select-label");i&&s&&(i.classList.add("selected"),s.textContent=i.textContent),document.documentElement.classList.remove("toggle-"+r),document.documentElement.classList.add("toggle-"+n)}fromLocalStorage(r){return r}toLocalStorage(r){return r}},j=class extends k{constructor(r){super(r);this.optionVisibility=new le("visibility","private"),this.optionInherited=new re("inherited",!0),this.optionExternals=new re("externals",!0)}static isSupported(){try{return typeof window.localStorage!="undefined"}catch{return!1}}};function we(t){let e=localStorage.getItem("tsd-theme")||"os";t.value=e,be(e),t.addEventListener("change",()=>{localStorage.setItem("tsd-theme",t.value),be(t.value)})}function be(t){switch(t){case"os":document.body.classList.remove("light","dark");break;case"light":document.body.classList.remove("dark"),document.body.classList.add("light");break;case"dark":document.body.classList.remove("light"),document.body.classList.add("dark");break}}ye();N(X,".menu-highlight");N(Z,".tsd-signatures");N(ee,"a[data-toggle]");j.isSupported()?N(j,"#tsd-filter"):document.documentElement.classList.add("no-filter");var Te=document.getElementById("theme");Te&&we(Te);var Be=new Y;Object.defineProperty(window,"app",{value:Be});})(); +(()=>{var Ce=Object.create;var J=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var Me=t=>J(t,"__esModule",{value:!0});var Fe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var De=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oe(e))!_e.call(t,i)&&(r||i!=="default")&&J(t,i,{get:()=>e[i],enumerable:!(n=Pe(e,i))||n.enumerable});return t},Ae=(t,e)=>De(Me(J(t!=null?Ce(Re(t)):{},"default",!e&&t&&t.__esModule?{get:()=>t.default,enumerable:!0}:{value:t,enumerable:!0})),t);var de=Fe((ce,he)=>{(function(){var t=function(e){var r=new t.Builder;return r.pipeline.add(t.trimmer,t.stopWordFilter,t.stemmer),r.searchPipeline.add(t.stemmer),e.call(r,r),r.build()};t.version="2.3.9";t.utils={},t.utils.warn=function(e){return function(r){e.console&&console.warn&&console.warn(r)}}(this),t.utils.asString=function(e){return e==null?"":e.toString()},t.utils.clone=function(e){if(e==null)return e;for(var r=Object.create(null),n=Object.keys(e),i=0;i0){var h=t.utils.clone(r)||{};h.position=[a,l],h.index=s.length,s.push(new t.Token(n.slice(a,o),h))}a=o+1}}return s},t.tokenizer.separator=/[\s\-]+/;t.Pipeline=function(){this._stack=[]},t.Pipeline.registeredFunctions=Object.create(null),t.Pipeline.registerFunction=function(e,r){r in this.registeredFunctions&&t.utils.warn("Overwriting existing registered function: "+r),e.label=r,t.Pipeline.registeredFunctions[e.label]=e},t.Pipeline.warnIfFunctionNotRegistered=function(e){var r=e.label&&e.label in this.registeredFunctions;r||t.utils.warn(`Function is not registered with pipeline. This may cause problems when serialising the index. +`,e)},t.Pipeline.load=function(e){var r=new t.Pipeline;return e.forEach(function(n){var i=t.Pipeline.registeredFunctions[n];if(i)r.add(i);else throw new Error("Cannot load unregistered function: "+n)}),r},t.Pipeline.prototype.add=function(){var e=Array.prototype.slice.call(arguments);e.forEach(function(r){t.Pipeline.warnIfFunctionNotRegistered(r),this._stack.push(r)},this)},t.Pipeline.prototype.after=function(e,r){t.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(e);if(n==-1)throw new Error("Cannot find existingFn");n=n+1,this._stack.splice(n,0,r)},t.Pipeline.prototype.before=function(e,r){t.Pipeline.warnIfFunctionNotRegistered(r);var n=this._stack.indexOf(e);if(n==-1)throw new Error("Cannot find existingFn");this._stack.splice(n,0,r)},t.Pipeline.prototype.remove=function(e){var r=this._stack.indexOf(e);r!=-1&&this._stack.splice(r,1)},t.Pipeline.prototype.run=function(e){for(var r=this._stack.length,n=0;n1&&(oe&&(n=s),o!=e);)i=n-r,s=r+Math.floor(i/2),o=this.elements[s*2];if(o==e||o>e)return s*2;if(ou?h+=2:a==u&&(r+=n[l+1]*i[h+1],l+=2,h+=2);return r},t.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},t.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),r=1,n=0;r0){var o=s.str.charAt(0),a;o in s.node.edges?a=s.node.edges[o]:(a=new t.TokenSet,s.node.edges[o]=a),s.str.length==1&&(a.final=!0),i.push({node:a,editsRemaining:s.editsRemaining,str:s.str.slice(1)})}if(s.editsRemaining!=0){if("*"in s.node.edges)var u=s.node.edges["*"];else{var u=new t.TokenSet;s.node.edges["*"]=u}if(s.str.length==0&&(u.final=!0),i.push({node:u,editsRemaining:s.editsRemaining-1,str:s.str}),s.str.length>1&&i.push({node:s.node,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)}),s.str.length==1&&(s.node.final=!0),s.str.length>=1){if("*"in s.node.edges)var l=s.node.edges["*"];else{var l=new t.TokenSet;s.node.edges["*"]=l}s.str.length==1&&(l.final=!0),i.push({node:l,editsRemaining:s.editsRemaining-1,str:s.str.slice(1)})}if(s.str.length>1){var h=s.str.charAt(0),p=s.str.charAt(1),v;p in s.node.edges?v=s.node.edges[p]:(v=new t.TokenSet,s.node.edges[p]=v),s.str.length==1&&(v.final=!0),i.push({node:v,editsRemaining:s.editsRemaining-1,str:h+s.str.slice(2)})}}}return n},t.TokenSet.fromString=function(e){for(var r=new t.TokenSet,n=r,i=0,s=e.length;i=e;r--){var n=this.uncheckedNodes[r],i=n.child.toString();i in this.minimizedNodes?n.parent.edges[n.char]=this.minimizedNodes[i]:(n.child._str=i,this.minimizedNodes[i]=n.child),this.uncheckedNodes.pop()}};t.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},t.Index.prototype.search=function(e){return this.query(function(r){var n=new t.QueryParser(e,r);n.parse()})},t.Index.prototype.query=function(e){for(var r=new t.Query(this.fields),n=Object.create(null),i=Object.create(null),s=Object.create(null),o=Object.create(null),a=Object.create(null),u=0;u1?this._b=1:this._b=e},t.Builder.prototype.k1=function(e){this._k1=e},t.Builder.prototype.add=function(e,r){var n=e[this._ref],i=Object.keys(this._fields);this._documents[n]=r||{},this.documentCount+=1;for(var s=0;s=this.length)return t.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},t.QueryLexer.prototype.width=function(){return this.pos-this.start},t.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},t.QueryLexer.prototype.backup=function(){this.pos-=1},t.QueryLexer.prototype.acceptDigitRun=function(){var e,r;do e=this.next(),r=e.charCodeAt(0);while(r>47&&r<58);e!=t.QueryLexer.EOS&&this.backup()},t.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(t.QueryLexer.TERM)),e.ignore(),e.more())return t.QueryLexer.lexText},t.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.EDIT_DISTANCE),t.QueryLexer.lexText},t.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(t.QueryLexer.BOOST),t.QueryLexer.lexText},t.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(t.QueryLexer.TERM)},t.QueryLexer.termSeparator=t.tokenizer.separator,t.QueryLexer.lexText=function(e){for(;;){var r=e.next();if(r==t.QueryLexer.EOS)return t.QueryLexer.lexEOS;if(r.charCodeAt(0)==92){e.escapeCharacter();continue}if(r==":")return t.QueryLexer.lexField;if(r=="~")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexEditDistance;if(r=="^")return e.backup(),e.width()>0&&e.emit(t.QueryLexer.TERM),t.QueryLexer.lexBoost;if(r=="+"&&e.width()===1||r=="-"&&e.width()===1)return e.emit(t.QueryLexer.PRESENCE),t.QueryLexer.lexText;if(r.match(t.QueryLexer.termSeparator))return t.QueryLexer.lexTerm}},t.QueryParser=function(e,r){this.lexer=new t.QueryLexer(e),this.query=r,this.currentClause={},this.lexemeIdx=0},t.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=t.QueryParser.parseClause;e;)e=e(this);return this.query},t.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},t.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},t.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},t.QueryParser.parseClause=function(e){var r=e.peekLexeme();if(r!=null)switch(r.type){case t.QueryLexer.PRESENCE:return t.QueryParser.parsePresence;case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var n="expected either a field or a term, found "+r.type;throw r.str.length>=1&&(n+=" with value '"+r.str+"'"),new t.QueryParseError(n,r.start,r.end)}},t.QueryParser.parsePresence=function(e){var r=e.consumeLexeme();if(r!=null){switch(r.str){case"-":e.currentClause.presence=t.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=t.Query.presence.REQUIRED;break;default:var n="unrecognised presence operator'"+r.str+"'";throw new t.QueryParseError(n,r.start,r.end)}var i=e.peekLexeme();if(i==null){var n="expecting term or field, found nothing";throw new t.QueryParseError(n,r.start,r.end)}switch(i.type){case t.QueryLexer.FIELD:return t.QueryParser.parseField;case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var n="expecting term or field, found '"+i.type+"'";throw new t.QueryParseError(n,i.start,i.end)}}},t.QueryParser.parseField=function(e){var r=e.consumeLexeme();if(r!=null){if(e.query.allFields.indexOf(r.str)==-1){var n=e.query.allFields.map(function(o){return"'"+o+"'"}).join(", "),i="unrecognised field '"+r.str+"', possible fields: "+n;throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.fields=[r.str];var s=e.peekLexeme();if(s==null){var i="expecting term, found nothing";throw new t.QueryParseError(i,r.start,r.end)}switch(s.type){case t.QueryLexer.TERM:return t.QueryParser.parseTerm;default:var i="expecting term, found '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseTerm=function(e){var r=e.consumeLexeme();if(r!=null){e.currentClause.term=r.str.toLowerCase(),r.str.indexOf("*")!=-1&&(e.currentClause.usePipeline=!1);var n=e.peekLexeme();if(n==null){e.nextClause();return}switch(n.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+n.type+"'";throw new t.QueryParseError(i,n.start,n.end)}}},t.QueryParser.parseEditDistance=function(e){var r=e.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="edit distance must be numeric";throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.editDistance=n;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},t.QueryParser.parseBoost=function(e){var r=e.consumeLexeme();if(r!=null){var n=parseInt(r.str,10);if(isNaN(n)){var i="boost must be numeric";throw new t.QueryParseError(i,r.start,r.end)}e.currentClause.boost=n;var s=e.peekLexeme();if(s==null){e.nextClause();return}switch(s.type){case t.QueryLexer.TERM:return e.nextClause(),t.QueryParser.parseTerm;case t.QueryLexer.FIELD:return e.nextClause(),t.QueryParser.parseField;case t.QueryLexer.EDIT_DISTANCE:return t.QueryParser.parseEditDistance;case t.QueryLexer.BOOST:return t.QueryParser.parseBoost;case t.QueryLexer.PRESENCE:return e.nextClause(),t.QueryParser.parsePresence;default:var i="Unexpected lexeme type '"+s.type+"'";throw new t.QueryParseError(i,s.start,s.end)}}},function(e,r){typeof define=="function"&&define.amd?define(r):typeof ce=="object"?he.exports=r():e.lunr=r()}(this,function(){return t})})()});var le=[];function N(t,e){le.push({selector:e,constructor:t})}var X=class{constructor(){this.createComponents(document.body)}createComponents(e){le.forEach(r=>{e.querySelectorAll(r.selector).forEach(n=>{n.dataset.hasInstance||(new r.constructor({el:n}),n.dataset.hasInstance=String(!0))})})}};var Q=class{constructor(e){this.el=e.el}};var Z=class{constructor(){this.listeners={}}addEventListener(e,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push(r)}removeEventListener(e,r){if(!(e in this.listeners))return;let n=this.listeners[e];for(let i=0,s=n.length;i{let r=Date.now();return(...n)=>{r+e-Date.now()<0&&(t(...n),r=Date.now())}};var ee=class extends Z{constructor(){super();this.scrollTop=0;this.lastY=0;this.width=0;this.height=0;this.showToolbar=!0;this.toolbar=document.querySelector(".tsd-page-toolbar"),this.secondaryNav=document.querySelector(".tsd-navigation.secondary"),window.addEventListener("scroll",K(()=>this.onScroll(),10)),window.addEventListener("resize",K(()=>this.onResize(),10)),this.onResize(),this.onScroll()}triggerResize(){let e=new CustomEvent("resize",{detail:{width:this.width,height:this.height}});this.dispatchEvent(e)}onResize(){this.width=window.innerWidth||0,this.height=window.innerHeight||0;let e=new CustomEvent("resize",{detail:{width:this.width,height:this.height}});this.dispatchEvent(e)}onScroll(){this.scrollTop=window.scrollY||0;let e=new CustomEvent("scroll",{detail:{scrollTop:this.scrollTop}});this.dispatchEvent(e),this.hideShowToolbar()}hideShowToolbar(){var r;let e=this.showToolbar;this.showToolbar=this.lastY>=this.scrollTop||this.scrollTop<=0,e!==this.showToolbar&&(this.toolbar.classList.toggle("tsd-page-toolbar--hide"),(r=this.secondaryNav)==null||r.classList.toggle("tsd-navigation--toolbar-hide")),this.lastY=this.scrollTop}},I=ee;I.instance=new ee;var te=class extends Q{constructor(e){super(e);this.anchors=[];this.index=-1;I.instance.addEventListener("resize",()=>this.onResize()),I.instance.addEventListener("scroll",r=>this.onScroll(r)),this.createAnchors()}createAnchors(){let e=window.location.href;e.indexOf("#")!=-1&&(e=e.substr(0,e.indexOf("#"))),this.el.querySelectorAll("a").forEach(r=>{let n=r.href;if(n.indexOf("#")==-1||n.substr(0,e.length)!=e)return;let i=n.substr(n.indexOf("#")+1),s=document.querySelector("a.tsd-anchor[name="+i+"]"),o=r.parentNode;!s||!o||this.anchors.push({link:o,anchor:s,position:0})}),this.onResize()}onResize(){let e;for(let n=0,i=this.anchors.length;nn.position-i.position);let r=new CustomEvent("scroll",{detail:{scrollTop:I.instance.scrollTop}});this.onScroll(r)}onScroll(e){let r=e.detail.scrollTop+5,n=this.anchors,i=n.length-1,s=this.index;for(;s>-1&&n[s].position>r;)s-=1;for(;s-1&&this.anchors[this.index].link.classList.remove("focus"),this.index=s,this.index>-1&&this.anchors[this.index].link.classList.add("focus"))}};var ue=(t,e=100)=>{let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(n),e)}};var fe=Ae(de());function pe(){let t=document.getElementById("tsd-search");if(!t)return;let e=document.getElementById("search-script");t.classList.add("loading"),e&&(e.addEventListener("error",()=>{t.classList.remove("loading"),t.classList.add("failure")}),e.addEventListener("load",()=>{t.classList.remove("loading"),t.classList.add("ready")}),window.searchData&&t.classList.remove("loading"));let r=document.querySelector("#tsd-search input"),n=document.querySelector("#tsd-search .results");if(!r||!n)throw new Error("The input field or the result list wrapper was not found");let i=!1;n.addEventListener("mousedown",()=>i=!0),n.addEventListener("mouseup",()=>{i=!1,t.classList.remove("has-focus")}),r.addEventListener("focus",()=>t.classList.add("has-focus")),r.addEventListener("blur",()=>{i||(i=!1,t.classList.remove("has-focus"))});let s={base:t.dataset.base+"/"};Ve(t,n,r,s)}function Ve(t,e,r,n){r.addEventListener("input",ue(()=>{ze(t,e,r,n)},200));let i=!1;r.addEventListener("keydown",s=>{i=!0,s.key=="Enter"?Ne(e,r):s.key=="Escape"?r.blur():s.key=="ArrowUp"?me(e,-1):s.key==="ArrowDown"?me(e,1):i=!1}),r.addEventListener("keypress",s=>{i&&s.preventDefault()}),document.body.addEventListener("keydown",s=>{s.altKey||s.ctrlKey||s.metaKey||!r.matches(":focus")&&s.key==="/"&&(r.focus(),s.preventDefault())})}function He(t,e){t.index||window.searchData&&(e.classList.remove("loading"),e.classList.add("ready"),t.data=window.searchData,t.index=fe.Index.load(window.searchData.index))}function ze(t,e,r,n){if(He(n,t),!n.index||!n.data)return;e.textContent="";let i=r.value.trim(),s=n.index.search(`*${i}*`);for(let o=0,a=Math.min(10,s.length);o${ve(u.parent,i)}.${l}`);let h=document.createElement("li");h.classList.value=u.classes;let p=document.createElement("a");p.href=n.base+u.url,p.classList.add("tsd-kind-icon"),p.innerHTML=l,h.append(p),e.appendChild(h)}}function me(t,e){let r=t.querySelector(".current");if(!r)r=t.querySelector(e==1?"li:first-child":"li:last-child"),r&&r.classList.add("current");else{let n=r;if(e===1)do n=n.nextElementSibling;while(n instanceof HTMLElement&&n.offsetParent==null);else do n=n.previousElementSibling;while(n instanceof HTMLElement&&n.offsetParent==null);n&&(r.classList.remove("current"),n.classList.add("current"))}}function Ne(t,e){let r=t.querySelector(".current");if(r||(r=t.querySelector("li:first-child")),r){let n=r.querySelector("a");n&&(window.location.href=n.href),e.blur()}}function ve(t,e){if(e==="")return t;let r=t.toLocaleLowerCase(),n=e.toLocaleLowerCase(),i=[],s=0,o=r.indexOf(n);for(;o!=-1;)i.push(re(t.substring(s,o)),`${re(t.substring(o,o+n.length))}`),s=o+n.length,o=r.indexOf(n,s);return i.push(re(t.substring(s))),i.join("")}var je={"&":"&","<":"<",">":">","'":"'",'"':"""};function re(t){return t.replace(/[&<>"'"]/g,e=>je[e])}var ge=class{constructor(e,r){this.signature=e,this.description=r}addClass(e){return this.signature.classList.add(e),this.description.classList.add(e),this}removeClass(e){return this.signature.classList.remove(e),this.description.classList.remove(e),this}},ne=class extends Q{constructor(e){super(e);this.groups=[];this.index=-1;this.createGroups(),this.container&&(this.el.classList.add("active"),Array.from(this.el.children).forEach(r=>{r.addEventListener("touchstart",n=>this.onClick(n)),r.addEventListener("click",n=>this.onClick(n))}),this.container.classList.add("active"),this.setIndex(0))}setIndex(e){if(e<0&&(e=0),e>this.groups.length-1&&(e=this.groups.length-1),this.index==e)return;let r=this.groups[e];if(this.index>-1){let n=this.groups[this.index];n.removeClass("current").addClass("fade-out"),r.addClass("current"),r.addClass("fade-in"),I.instance.triggerResize(),setTimeout(()=>{n.removeClass("fade-out"),r.removeClass("fade-in")},300)}else r.addClass("current"),I.instance.triggerResize();this.index=e}createGroups(){let e=this.el.children;if(e.length<2)return;this.container=this.el.nextElementSibling;let r=this.container.children;this.groups=[];for(let n=0;n{r.signature===e.currentTarget&&this.setIndex(n)})}};var C="mousedown",ye="mousemove",_="mouseup",G={x:0,y:0},xe=!1,ie=!1,Be=!1,A=!1,Le=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);document.documentElement.classList.add(Le?"is-mobile":"not-mobile");Le&&"ontouchstart"in document.documentElement&&(Be=!0,C="touchstart",ye="touchmove",_="touchend");document.addEventListener(C,t=>{ie=!0,A=!1;let e=C=="touchstart"?t.targetTouches[0]:t;G.y=e.pageY||0,G.x=e.pageX||0});document.addEventListener(ye,t=>{if(!!ie&&!A){let e=C=="touchstart"?t.targetTouches[0]:t,r=G.x-(e.pageX||0),n=G.y-(e.pageY||0);A=Math.sqrt(r*r+n*n)>10}});document.addEventListener(_,()=>{ie=!1});document.addEventListener("click",t=>{xe&&(t.preventDefault(),t.stopImmediatePropagation(),xe=!1)});var se=class extends Q{constructor(e){super(e);this.className=this.el.dataset.toggle||"",this.el.addEventListener(_,r=>this.onPointerUp(r)),this.el.addEventListener("click",r=>r.preventDefault()),document.addEventListener(C,r=>this.onDocumentPointerDown(r)),document.addEventListener(_,r=>this.onDocumentPointerUp(r))}setActive(e){if(this.active==e)return;this.active=e,document.documentElement.classList.toggle("has-"+this.className,e),this.el.classList.toggle("active",e);let r=(this.active?"to-has-":"from-has-")+this.className;document.documentElement.classList.add(r),setTimeout(()=>document.documentElement.classList.remove(r),500)}onPointerUp(e){A||(this.setActive(!0),e.preventDefault())}onDocumentPointerDown(e){if(this.active){if(e.target.closest(".col-menu, .tsd-filter-group"))return;this.setActive(!1)}}onDocumentPointerUp(e){if(!A&&this.active&&e.target.closest(".col-menu")){let r=e.target.closest("a");if(r){let n=window.location.href;n.indexOf("#")!=-1&&(n=n.substr(0,n.indexOf("#"))),r.href.substr(0,n.length)==n&&setTimeout(()=>this.setActive(!1),250)}}}};var oe=class{constructor(e,r){this.key=e,this.value=r,this.defaultValue=r,this.initialize(),window.localStorage[this.key]&&this.setValue(this.fromLocalStorage(window.localStorage[this.key]))}initialize(){}setValue(e){if(this.value==e)return;let r=this.value;this.value=e,window.localStorage[this.key]=this.toLocalStorage(e),this.handleValueChange(r,e)}},ae=class extends oe{initialize(){let e=document.querySelector("#tsd-filter-"+this.key);!e||(this.checkbox=e,this.checkbox.addEventListener("change",()=>{this.setValue(this.checkbox.checked)}))}handleValueChange(e,r){!this.checkbox||(this.checkbox.checked=this.value,document.documentElement.classList.toggle("toggle-"+this.key,this.value!=this.defaultValue))}fromLocalStorage(e){return e=="true"}toLocalStorage(e){return e?"true":"false"}},Ee=class extends oe{initialize(){document.documentElement.classList.add("toggle-"+this.key+this.value);let e=document.querySelector("#tsd-filter-"+this.key);if(!e)return;this.select=e;let r=()=>{this.select.classList.add("active")},n=()=>{this.select.classList.remove("active")};this.select.addEventListener(C,r),this.select.addEventListener("mouseover",r),this.select.addEventListener("mouseleave",n),this.select.querySelectorAll("li").forEach(i=>{i.addEventListener(_,s=>{e.classList.remove("active"),this.setValue(s.target.dataset.value||"")})}),document.addEventListener(C,i=>{this.select.contains(i.target)||this.select.classList.remove("active")})}handleValueChange(e,r){this.select.querySelectorAll("li.selected").forEach(s=>{s.classList.remove("selected")});let n=this.select.querySelector('li[data-value="'+r+'"]'),i=this.select.querySelector(".tsd-select-label");n&&i&&(n.classList.add("selected"),i.textContent=n.textContent),document.documentElement.classList.remove("toggle-"+e),document.documentElement.classList.add("toggle-"+r)}fromLocalStorage(e){return e}toLocalStorage(e){return e}},Y=class extends Q{constructor(e){super(e);this.optionVisibility=new Ee("visibility","private"),this.optionInherited=new ae("inherited",!0),this.optionExternals=new ae("externals",!0)}static isSupported(){try{return typeof window.localStorage!="undefined"}catch{return!1}}};function be(t){let e=localStorage.getItem("tsd-theme")||"os";t.value=e,we(e),t.addEventListener("change",()=>{localStorage.setItem("tsd-theme",t.value),we(t.value)})}function we(t){switch(t){case"os":document.body.classList.remove("light","dark");break;case"light":document.body.classList.remove("dark"),document.body.classList.add("light");break;case"dark":document.body.classList.remove("light"),document.body.classList.add("dark");break}}pe();N(te,".menu-highlight");N(ne,".tsd-signatures");N(se,"a[data-toggle]");Y.isSupported()?N(Y,"#tsd-filter"):document.documentElement.classList.add("no-filter");var Te=document.getElementById("theme");Te&&be(Te);var qe=new X;Object.defineProperty(window,"app",{value:qe});})(); /*! * lunr.Builder * Copyright (C) 2020 Oliver Nightingale diff --git a/docs/assets/search.js b/docs/assets/search.js index beeab9dcd..3bdf1fc8c 100644 --- a/docs/assets/search.js +++ b/docs/assets/search.js @@ -1 +1 @@ -window.searchData = JSON.parse("{\"kinds\":{\"2\":\"Module\",\"32\":\"Variable\",\"64\":\"Function\",\"128\":\"Class\",\"256\":\"Interface\",\"512\":\"Constructor\",\"1024\":\"Property\",\"2048\":\"Method\",\"65536\":\"Type literal\",\"4194304\":\"Type alias\",\"16777216\":\"Reference\"},\"rows\":[{\"id\":0,\"kind\":2,\"name\":\"index\",\"url\":\"modules/index.html\",\"classes\":\"tsd-kind-module\"},{\"id\":1,\"kind\":64,\"name\":\"init\",\"url\":\"modules/index.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":2,\"kind\":64,\"name\":\"getAllCORSHeaders\",\"url\":\"modules/index.html#getAllCORSHeaders\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":3,\"kind\":64,\"name\":\"getUserCount\",\"url\":\"modules/index.html#getUserCount\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":4,\"kind\":64,\"name\":\"getUsersOldestFirst\",\"url\":\"modules/index.html#getUsersOldestFirst\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":5,\"kind\":64,\"name\":\"getUsersNewestFirst\",\"url\":\"modules/index.html#getUsersNewestFirst\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":6,\"kind\":64,\"name\":\"deleteUser\",\"url\":\"modules/index.html#deleteUser\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":7,\"kind\":64,\"name\":\"createUserIdMapping\",\"url\":\"modules/index.html#createUserIdMapping\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":8,\"kind\":64,\"name\":\"getUserIdMapping\",\"url\":\"modules/index.html#getUserIdMapping\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":9,\"kind\":64,\"name\":\"deleteUserIdMapping\",\"url\":\"modules/index.html#deleteUserIdMapping\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":10,\"kind\":64,\"name\":\"updateOrDeleteUserIdMappingInfo\",\"url\":\"modules/index.html#updateOrDeleteUserIdMappingInfo\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":11,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/index.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":12,\"kind\":128,\"name\":\"default\",\"url\":\"classes/index.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":13,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/index.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":14,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/index.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"index.default\"},{\"id\":15,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/index.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":16,\"kind\":2048,\"name\":\"getAllCORSHeaders\",\"url\":\"classes/index.default.html#getAllCORSHeaders\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":17,\"kind\":2048,\"name\":\"getUserCount\",\"url\":\"classes/index.default.html#getUserCount\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":18,\"kind\":2048,\"name\":\"getUsersOldestFirst\",\"url\":\"classes/index.default.html#getUsersOldestFirst\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":19,\"kind\":2048,\"name\":\"getUsersNewestFirst\",\"url\":\"classes/index.default.html#getUsersNewestFirst\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":20,\"kind\":2048,\"name\":\"deleteUser\",\"url\":\"classes/index.default.html#deleteUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":21,\"kind\":2048,\"name\":\"createUserIdMapping\",\"url\":\"classes/index.default.html#createUserIdMapping\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":22,\"kind\":2048,\"name\":\"getUserIdMapping\",\"url\":\"classes/index.default.html#getUserIdMapping\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":23,\"kind\":2048,\"name\":\"deleteUserIdMapping\",\"url\":\"classes/index.default.html#deleteUserIdMapping\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":24,\"kind\":2048,\"name\":\"updateOrDeleteUserIdMappingInfo\",\"url\":\"classes/index.default.html#updateOrDeleteUserIdMappingInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":25,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/index.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"index.default\"},{\"id\":26,\"kind\":2,\"name\":\"framework\",\"url\":\"modules/framework.html\",\"classes\":\"tsd-kind-module\"},{\"id\":27,\"kind\":32,\"name\":\"express\",\"url\":\"modules/framework.html#express-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":28,\"kind\":32,\"name\":\"fastify\",\"url\":\"modules/framework.html#fastify-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":29,\"kind\":32,\"name\":\"hapi\",\"url\":\"modules/framework.html#hapi-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":30,\"kind\":32,\"name\":\"loopback\",\"url\":\"modules/framework.html#loopback-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":31,\"kind\":32,\"name\":\"koa\",\"url\":\"modules/framework.html#koa-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":32,\"kind\":32,\"name\":\"awsLambda\",\"url\":\"modules/framework.html#awsLambda\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":33,\"kind\":32,\"name\":\"default\",\"url\":\"modules/framework.html#default\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":34,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/framework.html#default.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-variable\",\"parent\":\"framework.default\"},{\"id\":35,\"kind\":1024,\"name\":\"express\",\"url\":\"modules/framework.html#default.__type.express\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.default.__type\"},{\"id\":36,\"kind\":1024,\"name\":\"fastify\",\"url\":\"modules/framework.html#default.__type.fastify\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.default.__type\"},{\"id\":37,\"kind\":1024,\"name\":\"hapi\",\"url\":\"modules/framework.html#default.__type.hapi\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.default.__type\"},{\"id\":38,\"kind\":1024,\"name\":\"loopback\",\"url\":\"modules/framework.html#default.__type.loopback\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.default.__type\"},{\"id\":39,\"kind\":1024,\"name\":\"koa\",\"url\":\"modules/framework.html#default.__type.koa\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.default.__type\"},{\"id\":40,\"kind\":1024,\"name\":\"awsLambda\",\"url\":\"modules/framework.html#default.__type.awsLambda-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.default.__type\"},{\"id\":41,\"kind\":2,\"name\":\"framework/awsLambda\",\"url\":\"modules/framework_awsLambda.html\",\"classes\":\"tsd-kind-module\"},{\"id\":42,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_awsLambda.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":43,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_awsLambda.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":44,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_awsLambda.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":45,\"kind\":2,\"name\":\"framework/express\",\"url\":\"modules/framework_express.html\",\"classes\":\"tsd-kind-module\"},{\"id\":46,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_express.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":47,\"kind\":64,\"name\":\"errorHandler\",\"url\":\"modules/framework_express.html#errorHandler\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":48,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_express.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":49,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_express.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":50,\"kind\":2,\"name\":\"framework/fastify\",\"url\":\"modules/framework_fastify.html\",\"classes\":\"tsd-kind-module\"},{\"id\":51,\"kind\":64,\"name\":\"plugin\",\"url\":\"modules/framework_fastify.html#plugin\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":52,\"kind\":64,\"name\":\"errorHandler\",\"url\":\"modules/framework_fastify.html#errorHandler\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":53,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_fastify.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":54,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_fastify.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":55,\"kind\":2,\"name\":\"framework/hapi\",\"url\":\"modules/framework_hapi.html\",\"classes\":\"tsd-kind-module\"},{\"id\":56,\"kind\":32,\"name\":\"plugin\",\"url\":\"modules/framework_hapi.html#plugin\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":57,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_hapi.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":58,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_hapi.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":59,\"kind\":2,\"name\":\"framework/koa\",\"url\":\"modules/framework_koa.html\",\"classes\":\"tsd-kind-module\"},{\"id\":60,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_koa.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":61,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_koa.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":62,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_koa.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":63,\"kind\":2,\"name\":\"framework/loopback\",\"url\":\"modules/framework_loopback.html\",\"classes\":\"tsd-kind-module\"},{\"id\":64,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_loopback.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":65,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_loopback.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":66,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_loopback.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":67,\"kind\":2,\"name\":\"ingredients/emaildelivery\",\"url\":\"modules/ingredients_emaildelivery.html\",\"classes\":\"tsd-kind-module\"},{\"id\":68,\"kind\":128,\"name\":\"default\",\"url\":\"classes/ingredients_emaildelivery.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"ingredients/emaildelivery\"},{\"id\":69,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/ingredients_emaildelivery.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"ingredients/emaildelivery.default\"},{\"id\":70,\"kind\":1024,\"name\":\"ingredientInterfaceImpl\",\"url\":\"classes/ingredients_emaildelivery.default.html#ingredientInterfaceImpl\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"ingredients/emaildelivery.default\"},{\"id\":71,\"kind\":2,\"name\":\"ingredients/smsdelivery\",\"url\":\"modules/ingredients_smsdelivery.html\",\"classes\":\"tsd-kind-module\"},{\"id\":72,\"kind\":128,\"name\":\"default\",\"url\":\"classes/ingredients_smsdelivery.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"ingredients/smsdelivery\"},{\"id\":73,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/ingredients_smsdelivery.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"ingredients/smsdelivery.default\"},{\"id\":74,\"kind\":1024,\"name\":\"ingredientInterfaceImpl\",\"url\":\"classes/ingredients_smsdelivery.default.html#ingredientInterfaceImpl\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"ingredients/smsdelivery.default\"},{\"id\":75,\"kind\":2,\"name\":\"recipe/dashboard\",\"url\":\"modules/recipe_dashboard.html\",\"classes\":\"tsd-kind-module\"},{\"id\":76,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_dashboard.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":77,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_dashboard.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":78,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_dashboard.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/dashboard.default\"},{\"id\":79,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_dashboard.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/dashboard.default\"},{\"id\":80,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_dashboard.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/dashboard.default\"},{\"id\":81,\"kind\":2,\"name\":\"recipe/emailpassword\",\"url\":\"modules/recipe_emailpassword.html\",\"classes\":\"tsd-kind-module\"},{\"id\":82,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_emailpassword.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":83,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_emailpassword.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":84,\"kind\":64,\"name\":\"signUp\",\"url\":\"modules/recipe_emailpassword.html#signUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":85,\"kind\":64,\"name\":\"signIn\",\"url\":\"modules/recipe_emailpassword.html#signIn-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":86,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_emailpassword.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":87,\"kind\":64,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_emailpassword.html#getUserByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":88,\"kind\":64,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_emailpassword.html#createResetPasswordToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":89,\"kind\":64,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_emailpassword.html#resetPasswordUsingToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":90,\"kind\":64,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_emailpassword.html#updateEmailOrPassword-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":91,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_emailpassword.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":92,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_emailpassword.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":93,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_emailpassword.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":94,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_emailpassword.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":95,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_emailpassword.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":96,\"kind\":2048,\"name\":\"signUp\",\"url\":\"classes/recipe_emailpassword.default.html#signUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":97,\"kind\":2048,\"name\":\"signIn\",\"url\":\"classes/recipe_emailpassword.default.html#signIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":98,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_emailpassword.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":99,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"classes/recipe_emailpassword.default.html#getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":100,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"classes/recipe_emailpassword.default.html#createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":101,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"classes/recipe_emailpassword.default.html#resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":102,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"classes/recipe_emailpassword.default.html#updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":103,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_emailpassword.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":104,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_emailpassword.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":105,\"kind\":2,\"name\":\"recipe/emailverification\",\"url\":\"modules/recipe_emailverification.html\",\"classes\":\"tsd-kind-module\"},{\"id\":106,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_emailverification.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":107,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_emailverification.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":108,\"kind\":64,\"name\":\"createEmailVerificationToken\",\"url\":\"modules/recipe_emailverification.html#createEmailVerificationToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":109,\"kind\":64,\"name\":\"verifyEmailUsingToken\",\"url\":\"modules/recipe_emailverification.html#verifyEmailUsingToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":110,\"kind\":64,\"name\":\"isEmailVerified\",\"url\":\"modules/recipe_emailverification.html#isEmailVerified-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":111,\"kind\":64,\"name\":\"revokeEmailVerificationTokens\",\"url\":\"modules/recipe_emailverification.html#revokeEmailVerificationTokens-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":112,\"kind\":64,\"name\":\"unverifyEmail\",\"url\":\"modules/recipe_emailverification.html#unverifyEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":113,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_emailverification.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":114,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_emailverification.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":115,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_emailverification.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":116,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_emailverification.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/emailverification.default\"},{\"id\":117,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_emailverification.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":118,\"kind\":1024,\"name\":\"EmailVerificationClaim\",\"url\":\"classes/recipe_emailverification.default.html#EmailVerificationClaim\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":119,\"kind\":2048,\"name\":\"createEmailVerificationToken\",\"url\":\"classes/recipe_emailverification.default.html#createEmailVerificationToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":120,\"kind\":2048,\"name\":\"verifyEmailUsingToken\",\"url\":\"classes/recipe_emailverification.default.html#verifyEmailUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":121,\"kind\":2048,\"name\":\"isEmailVerified\",\"url\":\"classes/recipe_emailverification.default.html#isEmailVerified\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":122,\"kind\":2048,\"name\":\"revokeEmailVerificationTokens\",\"url\":\"classes/recipe_emailverification.default.html#revokeEmailVerificationTokens\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":123,\"kind\":2048,\"name\":\"unverifyEmail\",\"url\":\"classes/recipe_emailverification.default.html#unverifyEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":124,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_emailverification.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":125,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_emailverification.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/emailverification.default\"},{\"id\":126,\"kind\":2,\"name\":\"recipe/jwt\",\"url\":\"modules/recipe_jwt.html\",\"classes\":\"tsd-kind-module\"},{\"id\":127,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_jwt.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":128,\"kind\":64,\"name\":\"createJWT\",\"url\":\"modules/recipe_jwt.html#createJWT-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":129,\"kind\":64,\"name\":\"getJWKS\",\"url\":\"modules/recipe_jwt.html#getJWKS-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":130,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_jwt.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":131,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_jwt.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/jwt.default\"},{\"id\":132,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_jwt.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/jwt.default\"},{\"id\":133,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"classes/recipe_jwt.default.html#createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/jwt.default\"},{\"id\":134,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"classes/recipe_jwt.default.html#getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/jwt.default\"},{\"id\":135,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_jwt.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/jwt.default\"},{\"id\":136,\"kind\":2,\"name\":\"recipe/openid\",\"url\":\"modules/recipe_openid.html\",\"classes\":\"tsd-kind-module\"},{\"id\":137,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_openid.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":138,\"kind\":64,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"modules/recipe_openid.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":139,\"kind\":64,\"name\":\"createJWT\",\"url\":\"modules/recipe_openid.html#createJWT\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":140,\"kind\":64,\"name\":\"getJWKS\",\"url\":\"modules/recipe_openid.html#getJWKS\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":141,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_openid.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":142,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_openid.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":143,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_openid.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/openid.default\"},{\"id\":144,\"kind\":2048,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"classes/recipe_openid.default.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":145,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"classes/recipe_openid.default.html#createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":146,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"classes/recipe_openid.default.html#getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":147,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_openid.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/openid.default\"},{\"id\":148,\"kind\":2,\"name\":\"recipe/passwordless\",\"url\":\"modules/recipe_passwordless.html\",\"classes\":\"tsd-kind-module\"},{\"id\":149,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_passwordless.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":150,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_passwordless.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":151,\"kind\":64,\"name\":\"createCode\",\"url\":\"modules/recipe_passwordless.html#createCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":152,\"kind\":64,\"name\":\"consumeCode\",\"url\":\"modules/recipe_passwordless.html#consumeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":153,\"kind\":64,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_passwordless.html#getUserByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":154,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_passwordless.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":155,\"kind\":64,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#getUserByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":156,\"kind\":64,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_passwordless.html#listCodesByDeviceId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":157,\"kind\":64,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_passwordless.html#listCodesByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":158,\"kind\":64,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#listCodesByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":159,\"kind\":64,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_passwordless.html#listCodesByPreAuthSessionId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":160,\"kind\":64,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_passwordless.html#createNewCodeForDevice-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":161,\"kind\":64,\"name\":\"updateUser\",\"url\":\"modules/recipe_passwordless.html#updateUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":162,\"kind\":64,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_passwordless.html#revokeAllCodes-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":163,\"kind\":64,\"name\":\"revokeCode\",\"url\":\"modules/recipe_passwordless.html#revokeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":164,\"kind\":64,\"name\":\"createMagicLink\",\"url\":\"modules/recipe_passwordless.html#createMagicLink\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":165,\"kind\":64,\"name\":\"signInUp\",\"url\":\"modules/recipe_passwordless.html#signInUp\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":166,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_passwordless.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":167,\"kind\":64,\"name\":\"sendSms\",\"url\":\"modules/recipe_passwordless.html#sendSms\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":168,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_passwordless.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":169,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_passwordless.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":170,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_passwordless.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/passwordless.default\"},{\"id\":171,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_passwordless.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":172,\"kind\":2048,\"name\":\"createCode\",\"url\":\"classes/recipe_passwordless.default.html#createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":173,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"classes/recipe_passwordless.default.html#createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":174,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"classes/recipe_passwordless.default.html#consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":175,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_passwordless.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":176,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"classes/recipe_passwordless.default.html#getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":177,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"classes/recipe_passwordless.default.html#getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":178,\"kind\":2048,\"name\":\"updateUser\",\"url\":\"classes/recipe_passwordless.default.html#updateUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":179,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"classes/recipe_passwordless.default.html#revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":180,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"classes/recipe_passwordless.default.html#revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":181,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":182,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":183,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":184,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":185,\"kind\":2048,\"name\":\"createMagicLink\",\"url\":\"classes/recipe_passwordless.default.html#createMagicLink\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":186,\"kind\":2048,\"name\":\"signInUp\",\"url\":\"classes/recipe_passwordless.default.html#signInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":187,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_passwordless.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":188,\"kind\":2048,\"name\":\"sendSms\",\"url\":\"classes/recipe_passwordless.default.html#sendSms\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":189,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_passwordless.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/passwordless.default\"},{\"id\":190,\"kind\":2,\"name\":\"recipe/session\",\"url\":\"modules/recipe_session.html\",\"classes\":\"tsd-kind-module\"},{\"id\":191,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_session.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":192,\"kind\":64,\"name\":\"createNewSession\",\"url\":\"modules/recipe_session.html#createNewSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":193,\"kind\":64,\"name\":\"getSession\",\"url\":\"modules/recipe_session.html#getSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":194,\"kind\":64,\"name\":\"getSessionInformation\",\"url\":\"modules/recipe_session.html#getSessionInformation-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":195,\"kind\":64,\"name\":\"refreshSession\",\"url\":\"modules/recipe_session.html#refreshSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":196,\"kind\":64,\"name\":\"revokeAllSessionsForUser\",\"url\":\"modules/recipe_session.html#revokeAllSessionsForUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":197,\"kind\":64,\"name\":\"getAllSessionHandlesForUser\",\"url\":\"modules/recipe_session.html#getAllSessionHandlesForUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":198,\"kind\":64,\"name\":\"revokeSession\",\"url\":\"modules/recipe_session.html#revokeSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":199,\"kind\":64,\"name\":\"revokeMultipleSessions\",\"url\":\"modules/recipe_session.html#revokeMultipleSessions-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":200,\"kind\":64,\"name\":\"updateSessionData\",\"url\":\"modules/recipe_session.html#updateSessionData-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":201,\"kind\":64,\"name\":\"updateAccessTokenPayload\",\"url\":\"modules/recipe_session.html#updateAccessTokenPayload-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":202,\"kind\":64,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"modules/recipe_session.html#mergeIntoAccessTokenPayload-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":203,\"kind\":64,\"name\":\"fetchAndSetClaim\",\"url\":\"modules/recipe_session.html#fetchAndSetClaim-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":204,\"kind\":64,\"name\":\"setClaimValue\",\"url\":\"modules/recipe_session.html#setClaimValue-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"recipe/session\"},{\"id\":205,\"kind\":64,\"name\":\"getClaimValue\",\"url\":\"modules/recipe_session.html#getClaimValue-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"recipe/session\"},{\"id\":206,\"kind\":64,\"name\":\"removeClaim\",\"url\":\"modules/recipe_session.html#removeClaim-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":207,\"kind\":64,\"name\":\"validateClaimsInJWTPayload\",\"url\":\"modules/recipe_session.html#validateClaimsInJWTPayload-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":208,\"kind\":64,\"name\":\"validateClaimsForSessionHandle\",\"url\":\"modules/recipe_session.html#validateClaimsForSessionHandle\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":209,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_session.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":210,\"kind\":64,\"name\":\"createJWT\",\"url\":\"modules/recipe_session.html#createJWT\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":211,\"kind\":64,\"name\":\"getJWKS\",\"url\":\"modules/recipe_session.html#getJWKS\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":212,\"kind\":64,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"modules/recipe_session.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":213,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_session.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":214,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_session.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":215,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_session.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/session.default\"},{\"id\":216,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_session.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":217,\"kind\":2048,\"name\":\"createNewSession\",\"url\":\"classes/recipe_session.default.html#createNewSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":218,\"kind\":2048,\"name\":\"validateClaimsForSessionHandle\",\"url\":\"classes/recipe_session.default.html#validateClaimsForSessionHandle\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":219,\"kind\":2048,\"name\":\"validateClaimsInJWTPayload\",\"url\":\"classes/recipe_session.default.html#validateClaimsInJWTPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":220,\"kind\":2048,\"name\":\"getSession\",\"url\":\"classes/recipe_session.default.html#getSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":221,\"kind\":2048,\"name\":\"getSessionInformation\",\"url\":\"classes/recipe_session.default.html#getSessionInformation\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":222,\"kind\":2048,\"name\":\"refreshSession\",\"url\":\"classes/recipe_session.default.html#refreshSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":223,\"kind\":2048,\"name\":\"revokeAllSessionsForUser\",\"url\":\"classes/recipe_session.default.html#revokeAllSessionsForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":224,\"kind\":2048,\"name\":\"getAllSessionHandlesForUser\",\"url\":\"classes/recipe_session.default.html#getAllSessionHandlesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":225,\"kind\":2048,\"name\":\"revokeSession\",\"url\":\"classes/recipe_session.default.html#revokeSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":226,\"kind\":2048,\"name\":\"revokeMultipleSessions\",\"url\":\"classes/recipe_session.default.html#revokeMultipleSessions\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":227,\"kind\":2048,\"name\":\"updateSessionData\",\"url\":\"classes/recipe_session.default.html#updateSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":228,\"kind\":2048,\"name\":\"regenerateAccessToken\",\"url\":\"classes/recipe_session.default.html#regenerateAccessToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":229,\"kind\":2048,\"name\":\"updateAccessTokenPayload\",\"url\":\"classes/recipe_session.default.html#updateAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":230,\"kind\":2048,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"classes/recipe_session.default.html#mergeIntoAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":231,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"classes/recipe_session.default.html#createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":232,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"classes/recipe_session.default.html#getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":233,\"kind\":2048,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"classes/recipe_session.default.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":234,\"kind\":2048,\"name\":\"fetchAndSetClaim\",\"url\":\"classes/recipe_session.default.html#fetchAndSetClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":235,\"kind\":2048,\"name\":\"setClaimValue\",\"url\":\"classes/recipe_session.default.html#setClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":236,\"kind\":2048,\"name\":\"getClaimValue\",\"url\":\"classes/recipe_session.default.html#getClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":237,\"kind\":2048,\"name\":\"removeClaim\",\"url\":\"classes/recipe_session.default.html#removeClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":238,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_session.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/session.default\"},{\"id\":239,\"kind\":2,\"name\":\"recipe/thirdparty\",\"url\":\"modules/recipe_thirdparty.html\",\"classes\":\"tsd-kind-module\"},{\"id\":240,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_thirdparty.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":241,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_thirdparty.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":242,\"kind\":64,\"name\":\"signInUp\",\"url\":\"modules/recipe_thirdparty.html#signInUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":243,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdparty.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":244,\"kind\":64,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdparty.html#getUsersByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":245,\"kind\":64,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdparty.html#getUserByThirdPartyInfo-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":246,\"kind\":64,\"name\":\"Google\",\"url\":\"modules/recipe_thirdparty.html#Google\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":247,\"kind\":64,\"name\":\"Github\",\"url\":\"modules/recipe_thirdparty.html#Github\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":248,\"kind\":64,\"name\":\"Facebook\",\"url\":\"modules/recipe_thirdparty.html#Facebook\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":249,\"kind\":64,\"name\":\"Apple\",\"url\":\"modules/recipe_thirdparty.html#Apple\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":250,\"kind\":64,\"name\":\"Discord\",\"url\":\"modules/recipe_thirdparty.html#Discord\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":251,\"kind\":64,\"name\":\"GoogleWorkspaces\",\"url\":\"modules/recipe_thirdparty.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":252,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_thirdparty.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":253,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_thirdparty.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":254,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":255,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_thirdparty.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":256,\"kind\":2048,\"name\":\"signInUp\",\"url\":\"classes/recipe_thirdparty.default.html#signInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":257,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_thirdparty.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":258,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"classes/recipe_thirdparty.default.html#getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":259,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"classes/recipe_thirdparty.default.html#getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":260,\"kind\":1024,\"name\":\"Google\",\"url\":\"classes/recipe_thirdparty.default.html#Google\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":261,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":262,\"kind\":1024,\"name\":\"Github\",\"url\":\"classes/recipe_thirdparty.default.html#Github\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":263,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":264,\"kind\":1024,\"name\":\"Facebook\",\"url\":\"classes/recipe_thirdparty.default.html#Facebook\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":265,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":266,\"kind\":1024,\"name\":\"Apple\",\"url\":\"classes/recipe_thirdparty.default.html#Apple\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":267,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":268,\"kind\":1024,\"name\":\"Discord\",\"url\":\"classes/recipe_thirdparty.default.html#Discord\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":269,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":270,\"kind\":1024,\"name\":\"GoogleWorkspaces\",\"url\":\"classes/recipe_thirdparty.default.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":271,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":272,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_thirdparty.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":273,\"kind\":2,\"name\":\"recipe/thirdpartyemailpassword\",\"url\":\"modules/recipe_thirdpartyemailpassword.html\",\"classes\":\"tsd-kind-module\"},{\"id\":274,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":275,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":276,\"kind\":64,\"name\":\"emailPasswordSignUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#emailPasswordSignUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":277,\"kind\":64,\"name\":\"emailPasswordSignIn\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#emailPasswordSignIn-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":278,\"kind\":64,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#thirdPartySignInUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":279,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":280,\"kind\":64,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#getUserByThirdPartyInfo-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":281,\"kind\":64,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#getUsersByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":282,\"kind\":64,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#createResetPasswordToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":283,\"kind\":64,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#resetPasswordUsingToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":284,\"kind\":64,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#updateEmailOrPassword-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":285,\"kind\":64,\"name\":\"Google\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Google\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":286,\"kind\":64,\"name\":\"Github\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Github\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":287,\"kind\":64,\"name\":\"Facebook\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Facebook\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":288,\"kind\":64,\"name\":\"Apple\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Apple\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":289,\"kind\":64,\"name\":\"Discord\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Discord\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":290,\"kind\":64,\"name\":\"GoogleWorkspaces\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":291,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":292,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":293,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":294,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":295,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":296,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":297,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":298,\"kind\":2048,\"name\":\"emailPasswordSignUp\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#emailPasswordSignUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":299,\"kind\":2048,\"name\":\"emailPasswordSignIn\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#emailPasswordSignIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":300,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":301,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":302,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":303,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":304,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":305,\"kind\":1024,\"name\":\"Google\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Google\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":306,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":307,\"kind\":1024,\"name\":\"Github\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Github\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":308,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":309,\"kind\":1024,\"name\":\"Facebook\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Facebook\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":310,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":311,\"kind\":1024,\"name\":\"Apple\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Apple\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":312,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":313,\"kind\":1024,\"name\":\"Discord\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Discord\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":314,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":315,\"kind\":1024,\"name\":\"GoogleWorkspaces\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":316,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":317,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":318,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":319,\"kind\":2,\"name\":\"recipe/thirdpartypasswordless\",\"url\":\"modules/recipe_thirdpartypasswordless.html\",\"classes\":\"tsd-kind-module\"},{\"id\":320,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_thirdpartypasswordless.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":321,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":322,\"kind\":64,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartypasswordless.html#thirdPartySignInUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":323,\"kind\":64,\"name\":\"passwordlessSignInUp\",\"url\":\"modules/recipe_thirdpartypasswordless.html#passwordlessSignInUp\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":324,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":325,\"kind\":64,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUserByThirdPartyInfo-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":326,\"kind\":64,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUsersByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":327,\"kind\":64,\"name\":\"createCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#createCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":328,\"kind\":64,\"name\":\"consumeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#consumeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":329,\"kind\":64,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUserByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":330,\"kind\":64,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByDeviceId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":331,\"kind\":64,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":332,\"kind\":64,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":333,\"kind\":64,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByPreAuthSessionId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":334,\"kind\":64,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_thirdpartypasswordless.html#createNewCodeForDevice-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":335,\"kind\":64,\"name\":\"updatePasswordlessUser\",\"url\":\"modules/recipe_thirdpartypasswordless.html#updatePasswordlessUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":336,\"kind\":64,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_thirdpartypasswordless.html#revokeAllCodes-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":337,\"kind\":64,\"name\":\"revokeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#revokeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":338,\"kind\":64,\"name\":\"createMagicLink\",\"url\":\"modules/recipe_thirdpartypasswordless.html#createMagicLink\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":339,\"kind\":64,\"name\":\"Google\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Google\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":340,\"kind\":64,\"name\":\"Github\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Github\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":341,\"kind\":64,\"name\":\"Facebook\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Facebook\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":342,\"kind\":64,\"name\":\"Apple\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Apple\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":343,\"kind\":64,\"name\":\"Discord\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Discord\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":344,\"kind\":64,\"name\":\"GoogleWorkspaces\",\"url\":\"modules/recipe_thirdpartypasswordless.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":345,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":346,\"kind\":64,\"name\":\"sendSms\",\"url\":\"modules/recipe_thirdpartypasswordless.html#sendSms\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":347,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":348,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":349,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":350,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":351,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":352,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":353,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":354,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":355,\"kind\":2048,\"name\":\"createCode\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":356,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":357,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":358,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":359,\"kind\":2048,\"name\":\"updatePasswordlessUser\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#updatePasswordlessUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":360,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":361,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":362,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":363,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":364,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":365,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":366,\"kind\":2048,\"name\":\"createMagicLink\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#createMagicLink\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":367,\"kind\":2048,\"name\":\"passwordlessSignInUp\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#passwordlessSignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":368,\"kind\":1024,\"name\":\"Google\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Google\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":369,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":370,\"kind\":1024,\"name\":\"Github\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Github\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":371,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":372,\"kind\":1024,\"name\":\"Facebook\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Facebook\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":373,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":374,\"kind\":1024,\"name\":\"Apple\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Apple\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":375,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":376,\"kind\":1024,\"name\":\"Discord\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Discord\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":377,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":378,\"kind\":1024,\"name\":\"GoogleWorkspaces\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":379,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":380,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":381,\"kind\":2048,\"name\":\"sendSms\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#sendSms\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":382,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":383,\"kind\":2,\"name\":\"recipe/usermetadata\",\"url\":\"modules/recipe_usermetadata.html\",\"classes\":\"tsd-kind-module\"},{\"id\":384,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_usermetadata.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":385,\"kind\":64,\"name\":\"getUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#getUserMetadata-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":386,\"kind\":64,\"name\":\"updateUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#updateUserMetadata-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":387,\"kind\":64,\"name\":\"clearUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#clearUserMetadata-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":388,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_usermetadata.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":389,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_usermetadata.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":390,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_usermetadata.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":391,\"kind\":2048,\"name\":\"getUserMetadata\",\"url\":\"classes/recipe_usermetadata.default.html#getUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":392,\"kind\":2048,\"name\":\"updateUserMetadata\",\"url\":\"classes/recipe_usermetadata.default.html#updateUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":393,\"kind\":2048,\"name\":\"clearUserMetadata\",\"url\":\"classes/recipe_usermetadata.default.html#clearUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":394,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_usermetadata.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":395,\"kind\":2,\"name\":\"recipe/userroles\",\"url\":\"modules/recipe_userroles.html\",\"classes\":\"tsd-kind-module\"},{\"id\":396,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_userroles.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":397,\"kind\":64,\"name\":\"addRoleToUser\",\"url\":\"modules/recipe_userroles.html#addRoleToUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":398,\"kind\":64,\"name\":\"removeUserRole\",\"url\":\"modules/recipe_userroles.html#removeUserRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":399,\"kind\":64,\"name\":\"getRolesForUser\",\"url\":\"modules/recipe_userroles.html#getRolesForUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":400,\"kind\":64,\"name\":\"getUsersThatHaveRole\",\"url\":\"modules/recipe_userroles.html#getUsersThatHaveRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":401,\"kind\":64,\"name\":\"createNewRoleOrAddPermissions\",\"url\":\"modules/recipe_userroles.html#createNewRoleOrAddPermissions-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":402,\"kind\":64,\"name\":\"getPermissionsForRole\",\"url\":\"modules/recipe_userroles.html#getPermissionsForRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":403,\"kind\":64,\"name\":\"removePermissionsFromRole\",\"url\":\"modules/recipe_userroles.html#removePermissionsFromRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":404,\"kind\":64,\"name\":\"getRolesThatHavePermission\",\"url\":\"modules/recipe_userroles.html#getRolesThatHavePermission-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":405,\"kind\":64,\"name\":\"deleteRole\",\"url\":\"modules/recipe_userroles.html#deleteRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":406,\"kind\":64,\"name\":\"getAllRoles\",\"url\":\"modules/recipe_userroles.html#getAllRoles-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":407,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_userroles.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":408,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_userroles.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":409,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_userroles.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/userroles.default\"},{\"id\":410,\"kind\":1024,\"name\":\"PermissionClaim\",\"url\":\"classes/recipe_userroles.default.html#PermissionClaim\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":411,\"kind\":1024,\"name\":\"UserRoleClaim\",\"url\":\"classes/recipe_userroles.default.html#UserRoleClaim\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":412,\"kind\":2048,\"name\":\"addRoleToUser\",\"url\":\"classes/recipe_userroles.default.html#addRoleToUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":413,\"kind\":2048,\"name\":\"removeUserRole\",\"url\":\"classes/recipe_userroles.default.html#removeUserRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":414,\"kind\":2048,\"name\":\"getRolesForUser\",\"url\":\"classes/recipe_userroles.default.html#getRolesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":415,\"kind\":2048,\"name\":\"getUsersThatHaveRole\",\"url\":\"classes/recipe_userroles.default.html#getUsersThatHaveRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":416,\"kind\":2048,\"name\":\"createNewRoleOrAddPermissions\",\"url\":\"classes/recipe_userroles.default.html#createNewRoleOrAddPermissions\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":417,\"kind\":2048,\"name\":\"getPermissionsForRole\",\"url\":\"classes/recipe_userroles.default.html#getPermissionsForRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":418,\"kind\":2048,\"name\":\"removePermissionsFromRole\",\"url\":\"classes/recipe_userroles.default.html#removePermissionsFromRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":419,\"kind\":2048,\"name\":\"getRolesThatHavePermission\",\"url\":\"classes/recipe_userroles.default.html#getRolesThatHavePermission\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":420,\"kind\":2048,\"name\":\"deleteRole\",\"url\":\"classes/recipe_userroles.default.html#deleteRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":421,\"kind\":2048,\"name\":\"getAllRoles\",\"url\":\"classes/recipe_userroles.default.html#getAllRoles\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":422,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_userroles.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/userroles.default\"},{\"id\":423,\"kind\":128,\"name\":\"BaseRequest\",\"url\":\"classes/framework.BaseRequest.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":424,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/framework.BaseRequest.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":425,\"kind\":1024,\"name\":\"wrapperUsed\",\"url\":\"classes/framework.BaseRequest.html#wrapperUsed\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":426,\"kind\":1024,\"name\":\"original\",\"url\":\"classes/framework.BaseRequest.html#original\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":427,\"kind\":1024,\"name\":\"getKeyValueFromQuery\",\"url\":\"classes/framework.BaseRequest.html#getKeyValueFromQuery\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":428,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":429,\"kind\":1024,\"name\":\"getJSONBody\",\"url\":\"classes/framework.BaseRequest.html#getJSONBody\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":430,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":431,\"kind\":1024,\"name\":\"getMethod\",\"url\":\"classes/framework.BaseRequest.html#getMethod\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":432,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":433,\"kind\":1024,\"name\":\"getCookieValue\",\"url\":\"classes/framework.BaseRequest.html#getCookieValue\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":434,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":435,\"kind\":1024,\"name\":\"getHeaderValue\",\"url\":\"classes/framework.BaseRequest.html#getHeaderValue\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":436,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":437,\"kind\":1024,\"name\":\"getOriginalURL\",\"url\":\"classes/framework.BaseRequest.html#getOriginalURL\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":438,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":439,\"kind\":1024,\"name\":\"getFormData\",\"url\":\"classes/framework.BaseRequest.html#getFormData\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":440,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":441,\"kind\":128,\"name\":\"BaseResponse\",\"url\":\"classes/framework.BaseResponse.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":442,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/framework.BaseResponse.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":443,\"kind\":1024,\"name\":\"wrapperUsed\",\"url\":\"classes/framework.BaseResponse.html#wrapperUsed\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":444,\"kind\":1024,\"name\":\"original\",\"url\":\"classes/framework.BaseResponse.html#original\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":445,\"kind\":1024,\"name\":\"setHeader\",\"url\":\"classes/framework.BaseResponse.html#setHeader\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":446,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":447,\"kind\":1024,\"name\":\"setCookie\",\"url\":\"classes/framework.BaseResponse.html#setCookie\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":448,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":449,\"kind\":1024,\"name\":\"setStatusCode\",\"url\":\"classes/framework.BaseResponse.html#setStatusCode\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":450,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":451,\"kind\":1024,\"name\":\"sendJSONResponse\",\"url\":\"classes/framework.BaseResponse.html#sendJSONResponse\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":452,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":453,\"kind\":1024,\"name\":\"sendHTMLResponse\",\"url\":\"classes/framework.BaseResponse.html#sendHTMLResponse\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":454,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":455,\"kind\":256,\"name\":\"SessionEvent\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":456,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEvent\"},{\"id\":457,\"kind\":1024,\"name\":\"supertokens\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#supertokens\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited\",\"parent\":\"framework/awsLambda.SessionEvent\"},{\"id\":458,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEvent\"},{\"id\":459,\"kind\":1024,\"name\":\"response\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.response\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type\"},{\"id\":460,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type\"},{\"id\":461,\"kind\":1024,\"name\":\"headers\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.__type-1.headers-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type.__type\"},{\"id\":462,\"kind\":1024,\"name\":\"cookies\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.__type-1.cookies\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type.__type\"},{\"id\":463,\"kind\":256,\"name\":\"SessionEventV2\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":464,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":465,\"kind\":1024,\"name\":\"supertokens\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#supertokens\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":466,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":467,\"kind\":1024,\"name\":\"response\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.response\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":468,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":469,\"kind\":1024,\"name\":\"headers\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.__type-6.headers-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type\"},{\"id\":470,\"kind\":1024,\"name\":\"cookies\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.__type-6.cookies-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type\"},{\"id\":471,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":472,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":473,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-1.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type\"},{\"id\":474,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-1.__type-2.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type.__type\"},{\"id\":475,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":476,\"kind\":256,\"name\":\"SessionRequest\",\"url\":\"interfaces/framework_express.SessionRequest.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":477,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_express.SessionRequest.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/express.SessionRequest\"},{\"id\":478,\"kind\":256,\"name\":\"SessionRequest\",\"url\":\"interfaces/framework_fastify.SessionRequest.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":479,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_fastify.SessionRequest.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/fastify.SessionRequest\"},{\"id\":480,\"kind\":256,\"name\":\"SessionRequest\",\"url\":\"interfaces/framework_hapi.SessionRequest.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":481,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_hapi.SessionRequest.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/hapi.SessionRequest\"},{\"id\":482,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_hapi.SessionRequest.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/hapi.SessionRequest\"},{\"id\":483,\"kind\":256,\"name\":\"SessionContext\",\"url\":\"interfaces/framework_koa.SessionContext.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":484,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_koa.SessionContext.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/koa.SessionContext\"},{\"id\":485,\"kind\":256,\"name\":\"SessionContext\",\"url\":\"interfaces/framework_loopback.SessionContext.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":486,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_loopback.SessionContext.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/loopback.SessionContext\"},{\"id\":487,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":488,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/dashboard.RecipeInterface\"},{\"id\":489,\"kind\":2048,\"name\":\"getDashboardBundleLocation\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface.__type-2.getDashboardBundleLocation\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.RecipeInterface.__type\"},{\"id\":490,\"kind\":2048,\"name\":\"shouldAllowAccess\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface.__type-2.shouldAllowAccess\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.RecipeInterface.__type\"},{\"id\":491,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_dashboard.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":492,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/dashboard.APIOptions\"},{\"id\":493,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":494,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":495,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":496,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":497,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":498,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":499,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":500,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_dashboard.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":501,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_dashboard.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/dashboard.APIInterface\"},{\"id\":502,\"kind\":1024,\"name\":\"dashboardGET\",\"url\":\"modules/recipe_dashboard.html#APIInterface.__type.dashboardGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIInterface.__type\"},{\"id\":503,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":504,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.RecipeInterface\"},{\"id\":505,\"kind\":2048,\"name\":\"signUp\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.signUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":506,\"kind\":2048,\"name\":\"signIn\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.signIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":507,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":508,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":509,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":510,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":511,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":512,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_emailpassword.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":513,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.User\"},{\"id\":514,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.User.__type\"},{\"id\":515,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.User.__type\"},{\"id\":516,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.User.__type\"},{\"id\":517,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_emailpassword.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":518,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.APIOptions\"},{\"id\":519,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":520,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":521,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":522,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":523,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":524,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":525,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":526,\"kind\":1024,\"name\":\"emailDelivery\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.emailDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":527,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_emailpassword.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":528,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.APIInterface\"},{\"id\":529,\"kind\":1024,\"name\":\"emailExistsGET\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.emailExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":530,\"kind\":1024,\"name\":\"generatePasswordResetTokenPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.generatePasswordResetTokenPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":531,\"kind\":1024,\"name\":\"passwordResetPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.passwordResetPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":532,\"kind\":1024,\"name\":\"signInPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.signInPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":533,\"kind\":1024,\"name\":\"signUpPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.signUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":534,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":535,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.RecipeInterface\"},{\"id\":536,\"kind\":2048,\"name\":\"createEmailVerificationToken\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.createEmailVerificationToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":537,\"kind\":2048,\"name\":\"verifyEmailUsingToken\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.verifyEmailUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":538,\"kind\":2048,\"name\":\"isEmailVerified\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.isEmailVerified\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":539,\"kind\":2048,\"name\":\"revokeEmailVerificationTokens\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.revokeEmailVerificationTokens\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":540,\"kind\":2048,\"name\":\"unverifyEmail\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.unverifyEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":541,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_emailverification.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":542,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.APIOptions\"},{\"id\":543,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":544,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":545,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":546,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":547,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":548,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":549,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":550,\"kind\":1024,\"name\":\"emailDelivery\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.emailDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":551,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_emailverification.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":552,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.APIInterface\"},{\"id\":553,\"kind\":1024,\"name\":\"verifyEmailPOST\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type.verifyEmailPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIInterface.__type\"},{\"id\":554,\"kind\":1024,\"name\":\"isEmailVerifiedGET\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type.isEmailVerifiedGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIInterface.__type\"},{\"id\":555,\"kind\":1024,\"name\":\"generateEmailVerifyTokenPOST\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type.generateEmailVerifyTokenPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIInterface.__type\"},{\"id\":556,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_emailverification.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":557,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#User.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.User\"},{\"id\":558,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_emailverification.html#User.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.User.__type\"},{\"id\":559,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_emailverification.html#User.__type-3.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.User.__type\"},{\"id\":560,\"kind\":32,\"name\":\"EmailVerificationClaim\",\"url\":\"modules/recipe_emailverification.html#EmailVerificationClaim\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":561,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_jwt.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":562,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.APIInterface\"},{\"id\":563,\"kind\":1024,\"name\":\"getJWKSGET\",\"url\":\"modules/recipe_jwt.html#APIInterface.__type.getJWKSGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIInterface.__type\"},{\"id\":564,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_jwt.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":565,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.APIOptions\"},{\"id\":566,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":567,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":568,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":569,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":570,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":571,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":572,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_jwt.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":573,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#RecipeInterface.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.RecipeInterface\"},{\"id\":574,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"modules/recipe_jwt.html#RecipeInterface.__type-3.createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.RecipeInterface.__type\"},{\"id\":575,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"modules/recipe_jwt.html#RecipeInterface.__type-3.getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.RecipeInterface.__type\"},{\"id\":576,\"kind\":4194304,\"name\":\"JsonWebKey\",\"url\":\"modules/recipe_jwt.html#JsonWebKey\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":577,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.JsonWebKey\"},{\"id\":578,\"kind\":1024,\"name\":\"kty\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.kty\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":579,\"kind\":1024,\"name\":\"kid\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.kid\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":580,\"kind\":1024,\"name\":\"n\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.n\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":581,\"kind\":1024,\"name\":\"e\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.e\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":582,\"kind\":1024,\"name\":\"alg\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.alg\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":583,\"kind\":1024,\"name\":\"use\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.use\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":584,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":585,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.RecipeInterface\"},{\"id\":586,\"kind\":2048,\"name\":\"createCode\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":587,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":588,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":589,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":590,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":591,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":592,\"kind\":2048,\"name\":\"updateUser\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.updateUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":593,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":594,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":595,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":596,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":597,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":598,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":599,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_passwordless.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":600,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#User.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.User\"},{\"id\":601,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":602,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":603,\"kind\":1024,\"name\":\"phoneNumber\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.phoneNumber\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":604,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":605,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_passwordless.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":606,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.APIOptions\"},{\"id\":607,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":608,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":609,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":610,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":611,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":612,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":613,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":614,\"kind\":1024,\"name\":\"emailDelivery\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.emailDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":615,\"kind\":1024,\"name\":\"smsDelivery\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.smsDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":616,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_passwordless.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":617,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.APIInterface\"},{\"id\":618,\"kind\":2048,\"name\":\"createCodePOST\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.createCodePOST\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":619,\"kind\":2048,\"name\":\"resendCodePOST\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.resendCodePOST\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":620,\"kind\":2048,\"name\":\"consumeCodePOST\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.consumeCodePOST\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":621,\"kind\":2048,\"name\":\"emailExistsGET\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.emailExistsGET\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":622,\"kind\":2048,\"name\":\"phoneNumberExistsGET\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.phoneNumberExistsGET\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":623,\"kind\":256,\"name\":\"VerifySessionOptions\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":624,\"kind\":1024,\"name\":\"antiCsrfCheck\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html#antiCsrfCheck\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"recipe/session.VerifySessionOptions\"},{\"id\":625,\"kind\":1024,\"name\":\"sessionRequired\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html#sessionRequired\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"recipe/session.VerifySessionOptions\"},{\"id\":626,\"kind\":2048,\"name\":\"overrideGlobalClaimValidators\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html#overrideGlobalClaimValidators\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.VerifySessionOptions\"},{\"id\":627,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_session.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":628,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.RecipeInterface\"},{\"id\":629,\"kind\":2048,\"name\":\"createNewSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.createNewSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":630,\"kind\":2048,\"name\":\"getGlobalClaimValidators\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getGlobalClaimValidators\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":631,\"kind\":2048,\"name\":\"getSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":632,\"kind\":2048,\"name\":\"refreshSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.refreshSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":633,\"kind\":2048,\"name\":\"getSessionInformation\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getSessionInformation\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":634,\"kind\":2048,\"name\":\"revokeAllSessionsForUser\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.revokeAllSessionsForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":635,\"kind\":2048,\"name\":\"getAllSessionHandlesForUser\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getAllSessionHandlesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":636,\"kind\":2048,\"name\":\"revokeSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.revokeSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":637,\"kind\":2048,\"name\":\"revokeMultipleSessions\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.revokeMultipleSessions\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":638,\"kind\":2048,\"name\":\"updateSessionData\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.updateSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":639,\"kind\":2048,\"name\":\"updateAccessTokenPayload\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.updateAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":640,\"kind\":2048,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.mergeIntoAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":641,\"kind\":2048,\"name\":\"regenerateAccessToken\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.regenerateAccessToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":642,\"kind\":2048,\"name\":\"getAccessTokenLifeTimeMS\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getAccessTokenLifeTimeMS\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":643,\"kind\":2048,\"name\":\"getRefreshTokenLifeTimeMS\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getRefreshTokenLifeTimeMS\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":644,\"kind\":2048,\"name\":\"validateClaims\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.validateClaims\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":645,\"kind\":2048,\"name\":\"validateClaimsInJWTPayload\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.validateClaimsInJWTPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":646,\"kind\":2048,\"name\":\"fetchAndSetClaim\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.fetchAndSetClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":647,\"kind\":2048,\"name\":\"setClaimValue\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.setClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal tsd-has-type-parameter\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":648,\"kind\":2048,\"name\":\"getClaimValue\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal tsd-has-type-parameter\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":649,\"kind\":2048,\"name\":\"removeClaim\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.removeClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":650,\"kind\":256,\"name\":\"SessionContainer\",\"url\":\"interfaces/recipe_session.SessionContainer.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":651,\"kind\":2048,\"name\":\"revokeSession\",\"url\":\"interfaces/recipe_session.SessionContainer.html#revokeSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":652,\"kind\":2048,\"name\":\"getSessionData\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":653,\"kind\":2048,\"name\":\"updateSessionData\",\"url\":\"interfaces/recipe_session.SessionContainer.html#updateSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":654,\"kind\":2048,\"name\":\"getUserId\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getUserId\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":655,\"kind\":2048,\"name\":\"getAccessTokenPayload\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":656,\"kind\":2048,\"name\":\"getHandle\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getHandle\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":657,\"kind\":2048,\"name\":\"getAccessToken\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getAccessToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":658,\"kind\":2048,\"name\":\"updateAccessTokenPayload\",\"url\":\"interfaces/recipe_session.SessionContainer.html#updateAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":659,\"kind\":2048,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"interfaces/recipe_session.SessionContainer.html#mergeIntoAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":660,\"kind\":2048,\"name\":\"getTimeCreated\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getTimeCreated\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":661,\"kind\":2048,\"name\":\"getExpiry\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getExpiry\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":662,\"kind\":2048,\"name\":\"assertClaims\",\"url\":\"interfaces/recipe_session.SessionContainer.html#assertClaims\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":663,\"kind\":2048,\"name\":\"fetchAndSetClaim\",\"url\":\"interfaces/recipe_session.SessionContainer.html#fetchAndSetClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface tsd-has-type-parameter\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":664,\"kind\":2048,\"name\":\"setClaimValue\",\"url\":\"interfaces/recipe_session.SessionContainer.html#setClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface tsd-has-type-parameter\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":665,\"kind\":2048,\"name\":\"getClaimValue\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface tsd-has-type-parameter\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":666,\"kind\":2048,\"name\":\"removeClaim\",\"url\":\"interfaces/recipe_session.SessionContainer.html#removeClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":667,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_session.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":668,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.APIInterface\"},{\"id\":669,\"kind\":1024,\"name\":\"refreshPOST\",\"url\":\"modules/recipe_session.html#APIInterface.__type.refreshPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIInterface.__type\"},{\"id\":670,\"kind\":1024,\"name\":\"signOutPOST\",\"url\":\"modules/recipe_session.html#APIInterface.__type.signOutPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIInterface.__type\"},{\"id\":671,\"kind\":2048,\"name\":\"verifySession\",\"url\":\"modules/recipe_session.html#APIInterface.__type.verifySession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIInterface.__type\"},{\"id\":672,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_session.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":673,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.APIOptions\"},{\"id\":674,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":675,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":676,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":677,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":678,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":679,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":680,\"kind\":4194304,\"name\":\"SessionInformation\",\"url\":\"modules/recipe_session.html#SessionInformation\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":681,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.SessionInformation\"},{\"id\":682,\"kind\":1024,\"name\":\"sessionHandle\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.sessionHandle\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":683,\"kind\":1024,\"name\":\"userId\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.userId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":684,\"kind\":1024,\"name\":\"sessionData\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.sessionData\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":685,\"kind\":1024,\"name\":\"expiry\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.expiry\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":686,\"kind\":1024,\"name\":\"accessTokenPayload\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.accessTokenPayload\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":687,\"kind\":1024,\"name\":\"timeCreated\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.timeCreated\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":688,\"kind\":4194304,\"name\":\"SessionClaimValidator\",\"url\":\"modules/recipe_session.html#SessionClaimValidator\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":689,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":690,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.RecipeInterface\"},{\"id\":691,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":692,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":693,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":694,\"kind\":2048,\"name\":\"signInUp\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.signInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":695,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_thirdparty.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":696,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.User\"},{\"id\":697,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.id-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":698,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":699,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":700,\"kind\":1024,\"name\":\"thirdParty\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.thirdParty\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":701,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":702,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.__type-5.id-2\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type.__type\"},{\"id\":703,\"kind\":1024,\"name\":\"userId\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.__type-5.userId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type.__type\"},{\"id\":704,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_thirdparty.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":705,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.APIInterface\"},{\"id\":706,\"kind\":1024,\"name\":\"authorisationUrlGET\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type.authorisationUrlGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIInterface.__type\"},{\"id\":707,\"kind\":1024,\"name\":\"signInUpPOST\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type.signInUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIInterface.__type\"},{\"id\":708,\"kind\":1024,\"name\":\"appleRedirectHandlerPOST\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type.appleRedirectHandlerPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIInterface.__type\"},{\"id\":709,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_thirdparty.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":710,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.APIOptions\"},{\"id\":711,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":712,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":713,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":714,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":715,\"kind\":1024,\"name\":\"providers\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.providers\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":716,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":717,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":718,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":719,\"kind\":4194304,\"name\":\"TypeProvider\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":720,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.TypeProvider\"},{\"id\":721,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.TypeProvider.__type\"},{\"id\":722,\"kind\":2048,\"name\":\"get\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3.get\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.TypeProvider.__type\"},{\"id\":723,\"kind\":1024,\"name\":\"isDefault\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3.isDefault\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.TypeProvider.__type\"},{\"id\":724,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":725,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface\"},{\"id\":726,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":727,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":728,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":729,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":730,\"kind\":2048,\"name\":\"emailPasswordSignUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.emailPasswordSignUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":731,\"kind\":2048,\"name\":\"emailPasswordSignIn\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.emailPasswordSignIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":732,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":733,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":734,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":735,\"kind\":16777216,\"name\":\"TypeProvider\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#TypeProvider\",\"classes\":\"tsd-kind-reference tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":736,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":737,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartyemailpassword.User\"},{\"id\":738,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":739,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":740,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":741,\"kind\":1024,\"name\":\"thirdParty\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.thirdParty\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":742,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":743,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.__type-3.id-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type.__type\"},{\"id\":744,\"kind\":1024,\"name\":\"userId\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.__type-3.userId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type.__type\"},{\"id\":745,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":746,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface\"},{\"id\":747,\"kind\":1024,\"name\":\"authorisationUrlGET\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.authorisationUrlGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":748,\"kind\":1024,\"name\":\"emailPasswordEmailExistsGET\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.emailPasswordEmailExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":749,\"kind\":1024,\"name\":\"generatePasswordResetTokenPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.generatePasswordResetTokenPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":750,\"kind\":1024,\"name\":\"passwordResetPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.passwordResetPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":751,\"kind\":1024,\"name\":\"thirdPartySignInUpPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.thirdPartySignInUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":752,\"kind\":1024,\"name\":\"emailPasswordSignInPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.emailPasswordSignInPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":753,\"kind\":1024,\"name\":\"emailPasswordSignUpPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.emailPasswordSignUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":754,\"kind\":1024,\"name\":\"appleRedirectHandlerPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.appleRedirectHandlerPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":755,\"kind\":4194304,\"name\":\"EmailPasswordAPIOptions\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#EmailPasswordAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":756,\"kind\":4194304,\"name\":\"ThirdPartyAPIOptions\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#ThirdPartyAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":757,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":758,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface\"},{\"id\":759,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":760,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":761,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":762,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":763,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":764,\"kind\":2048,\"name\":\"createCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":765,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":766,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":767,\"kind\":2048,\"name\":\"updatePasswordlessUser\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.updatePasswordlessUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":768,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":769,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":770,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":771,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":772,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":773,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":774,\"kind\":16777216,\"name\":\"TypeProvider\",\"url\":\"modules/recipe_thirdpartypasswordless.html#TypeProvider\",\"classes\":\"tsd-kind-reference tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":775,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_thirdpartypasswordless.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":776,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":777,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface\"},{\"id\":778,\"kind\":1024,\"name\":\"authorisationUrlGET\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.authorisationUrlGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":779,\"kind\":1024,\"name\":\"thirdPartySignInUpPOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.thirdPartySignInUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":780,\"kind\":1024,\"name\":\"appleRedirectHandlerPOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.appleRedirectHandlerPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":781,\"kind\":1024,\"name\":\"createCodePOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.createCodePOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":782,\"kind\":1024,\"name\":\"resendCodePOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.resendCodePOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":783,\"kind\":1024,\"name\":\"consumeCodePOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.consumeCodePOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":784,\"kind\":1024,\"name\":\"passwordlessUserEmailExistsGET\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.passwordlessUserEmailExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":785,\"kind\":1024,\"name\":\"passwordlessUserPhoneNumberExistsGET\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.passwordlessUserPhoneNumberExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":786,\"kind\":4194304,\"name\":\"PasswordlessAPIOptions\",\"url\":\"modules/recipe_thirdpartypasswordless.html#PasswordlessAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":787,\"kind\":4194304,\"name\":\"ThirdPartyAPIOptions\",\"url\":\"modules/recipe_thirdpartypasswordless.html#ThirdPartyAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":788,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":789,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/usermetadata.RecipeInterface\"},{\"id\":790,\"kind\":2048,\"name\":\"getUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type.getUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/usermetadata.RecipeInterface.__type\"},{\"id\":791,\"kind\":2048,\"name\":\"updateUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type.updateUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/usermetadata.RecipeInterface.__type\"},{\"id\":792,\"kind\":2048,\"name\":\"clearUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type.clearUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/usermetadata.RecipeInterface.__type\"},{\"id\":793,\"kind\":256,\"name\":\"JSONObject\",\"url\":\"interfaces/recipe_usermetadata.JSONObject.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":794,\"kind\":32,\"name\":\"UserRoleClaim\",\"url\":\"modules/recipe_userroles.html#UserRoleClaim\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":795,\"kind\":32,\"name\":\"PermissionClaim\",\"url\":\"modules/recipe_userroles.html#PermissionClaim\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":796,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_userroles.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":797,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/userroles.RecipeInterface\"},{\"id\":798,\"kind\":2048,\"name\":\"addRoleToUser\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.addRoleToUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":799,\"kind\":2048,\"name\":\"removeUserRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.removeUserRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":800,\"kind\":2048,\"name\":\"getRolesForUser\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getRolesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":801,\"kind\":2048,\"name\":\"getUsersThatHaveRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getUsersThatHaveRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":802,\"kind\":2048,\"name\":\"createNewRoleOrAddPermissions\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.createNewRoleOrAddPermissions\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":803,\"kind\":2048,\"name\":\"getPermissionsForRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getPermissionsForRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":804,\"kind\":2048,\"name\":\"removePermissionsFromRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.removePermissionsFromRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":805,\"kind\":2048,\"name\":\"getRolesThatHavePermission\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getRolesThatHavePermission\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":806,\"kind\":2048,\"name\":\"deleteRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.deleteRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":807,\"kind\":2048,\"name\":\"getAllRoles\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getAllRoles\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"}],\"index\":{\"version\":\"2.3.9\",\"fields\":[\"name\",\"parent\"],\"fieldVectors\":[[\"name/0\",[0,40.931]],[\"parent/0\",[]],[\"name/1\",[1,34.187]],[\"parent/1\",[0,4.047]],[\"name/2\",[2,57.795]],[\"parent/2\",[0,4.047]],[\"name/3\",[3,57.795]],[\"parent/3\",[0,4.047]],[\"name/4\",[4,57.795]],[\"parent/4\",[0,4.047]],[\"name/5\",[5,57.795]],[\"parent/5\",[0,4.047]],[\"name/6\",[6,57.795]],[\"parent/6\",[0,4.047]],[\"name/7\",[7,57.795]],[\"parent/7\",[0,4.047]],[\"name/8\",[8,57.795]],[\"parent/8\",[0,4.047]],[\"name/9\",[9,57.795]],[\"parent/9\",[0,4.047]],[\"name/10\",[10,57.795]],[\"parent/10\",[0,4.047]],[\"name/11\",[11,38.924]],[\"parent/11\",[0,4.047]],[\"name/12\",[12,38.924]],[\"parent/12\",[0,4.047]],[\"name/13\",[1,34.187]],[\"parent/13\",[13,4.047]],[\"name/14\",[14,21.795]],[\"parent/14\",[13,4.047]],[\"name/15\",[11,38.924]],[\"parent/15\",[13,4.047]],[\"name/16\",[2,57.795]],[\"parent/16\",[13,4.047]],[\"name/17\",[3,57.795]],[\"parent/17\",[13,4.047]],[\"name/18\",[4,57.795]],[\"parent/18\",[13,4.047]],[\"name/19\",[5,57.795]],[\"parent/19\",[13,4.047]],[\"name/20\",[6,57.795]],[\"parent/20\",[13,4.047]],[\"name/21\",[7,57.795]],[\"parent/21\",[13,4.047]],[\"name/22\",[8,57.795]],[\"parent/22\",[13,4.047]],[\"name/23\",[9,57.795]],[\"parent/23\",[13,4.047]],[\"name/24\",[10,57.795]],[\"parent/24\",[13,4.047]],[\"name/25\",[15,38.336]],[\"parent/25\",[13,4.047]],[\"name/26\",[16,43.444]],[\"parent/26\",[]],[\"name/27\",[17,57.795]],[\"parent/27\",[16,4.295]],[\"name/28\",[18,57.795]],[\"parent/28\",[16,4.295]],[\"name/29\",[19,57.795]],[\"parent/29\",[16,4.295]],[\"name/30\",[20,57.795]],[\"parent/30\",[16,4.295]],[\"name/31\",[21,57.795]],[\"parent/31\",[16,4.295]],[\"name/32\",[22,57.795]],[\"parent/32\",[16,4.295]],[\"name/33\",[12,38.924]],[\"parent/33\",[16,4.295]],[\"name/34\",[14,21.795]],[\"parent/34\",[23,6.219]],[\"name/35\",[17,57.795]],[\"parent/35\",[24,4.769]],[\"name/36\",[18,57.795]],[\"parent/36\",[24,4.769]],[\"name/37\",[19,57.795]],[\"parent/37\",[24,4.769]],[\"name/38\",[20,57.795]],[\"parent/38\",[24,4.769]],[\"name/39\",[21,57.795]],[\"parent/39\",[24,4.769]],[\"name/40\",[22,57.795]],[\"parent/40\",[24,4.769]],[\"name/41\",[25,48.24]],[\"parent/41\",[]],[\"name/42\",[26,51.917]],[\"parent/42\",[25,4.769]],[\"name/43\",[27,48.24]],[\"parent/43\",[25,4.769]],[\"name/44\",[28,48.24]],[\"parent/44\",[25,4.769]],[\"name/45\",[29,48.24]],[\"parent/45\",[]],[\"name/46\",[26,51.917]],[\"parent/46\",[29,4.769]],[\"name/47\",[30,57.795]],[\"parent/47\",[29,4.769]],[\"name/48\",[27,48.24]],[\"parent/48\",[29,4.769]],[\"name/49\",[28,48.24]],[\"parent/49\",[29,4.769]],[\"name/50\",[31,48.24]],[\"parent/50\",[]],[\"name/51\",[32,57.795]],[\"parent/51\",[31,4.769]],[\"name/52\",[30,57.795]],[\"parent/52\",[31,4.769]],[\"name/53\",[27,48.24]],[\"parent/53\",[31,4.769]],[\"name/54\",[28,48.24]],[\"parent/54\",[31,4.769]],[\"name/55\",[33,49.911]],[\"parent/55\",[]],[\"name/56\",[32,57.795]],[\"parent/56\",[33,4.935]],[\"name/57\",[27,48.24]],[\"parent/57\",[33,4.935]],[\"name/58\",[28,48.24]],[\"parent/58\",[33,4.935]],[\"name/59\",[34,49.911]],[\"parent/59\",[]],[\"name/60\",[26,51.917]],[\"parent/60\",[34,4.935]],[\"name/61\",[27,48.24]],[\"parent/61\",[34,4.935]],[\"name/62\",[28,48.24]],[\"parent/62\",[34,4.935]],[\"name/63\",[35,49.911]],[\"parent/63\",[]],[\"name/64\",[26,51.917]],[\"parent/64\",[35,4.935]],[\"name/65\",[27,48.24]],[\"parent/65\",[35,4.935]],[\"name/66\",[28,48.24]],[\"parent/66\",[35,4.935]],[\"name/67\",[36,57.795]],[\"parent/67\",[]],[\"name/68\",[12,38.924]],[\"parent/68\",[36,5.714]],[\"name/69\",[15,38.336]],[\"parent/69\",[37,5.714]],[\"name/70\",[38,57.795]],[\"parent/70\",[37,5.714]],[\"name/71\",[39,57.795]],[\"parent/71\",[]],[\"name/72\",[12,38.924]],[\"parent/72\",[39,5.714]],[\"name/73\",[15,38.336]],[\"parent/73\",[40,5.714]],[\"name/74\",[38,57.795]],[\"parent/74\",[40,5.714]],[\"name/75\",[41,48.24]],[\"parent/75\",[]],[\"name/76\",[1,34.187]],[\"parent/76\",[41,4.769]],[\"name/77\",[12,38.924]],[\"parent/77\",[41,4.769]],[\"name/78\",[1,34.187]],[\"parent/78\",[42,5.381]],[\"name/79\",[14,21.795]],[\"parent/79\",[42,5.381]],[\"name/80\",[15,38.336]],[\"parent/80\",[42,5.381]],[\"name/81\",[43,38.924]],[\"parent/81\",[]],[\"name/82\",[1,34.187]],[\"parent/82\",[43,3.848]],[\"name/83\",[11,38.924]],[\"parent/83\",[43,3.848]],[\"name/84\",[44,54.43]],[\"parent/84\",[43,3.848]],[\"name/85\",[45,54.43]],[\"parent/85\",[43,3.848]],[\"name/86\",[46,39.55]],[\"parent/86\",[43,3.848]],[\"name/87\",[47,48.24]],[\"parent/87\",[43,3.848]],[\"name/88\",[48,48.24]],[\"parent/88\",[43,3.848]],[\"name/89\",[49,48.24]],[\"parent/89\",[43,3.848]],[\"name/90\",[50,48.24]],[\"parent/90\",[43,3.848]],[\"name/91\",[51,43.444]],[\"parent/91\",[43,3.848]],[\"name/92\",[12,38.924]],[\"parent/92\",[43,3.848]],[\"name/93\",[1,34.187]],[\"parent/93\",[52,4.123]],[\"name/94\",[14,21.795]],[\"parent/94\",[52,4.123]],[\"name/95\",[11,38.924]],[\"parent/95\",[52,4.123]],[\"name/96\",[44,54.43]],[\"parent/96\",[52,4.123]],[\"name/97\",[45,54.43]],[\"parent/97\",[52,4.123]],[\"name/98\",[46,39.55]],[\"parent/98\",[52,4.123]],[\"name/99\",[47,48.24]],[\"parent/99\",[52,4.123]],[\"name/100\",[48,48.24]],[\"parent/100\",[52,4.123]],[\"name/101\",[49,48.24]],[\"parent/101\",[52,4.123]],[\"name/102\",[50,48.24]],[\"parent/102\",[52,4.123]],[\"name/103\",[51,43.444]],[\"parent/103\",[52,4.123]],[\"name/104\",[15,38.336]],[\"parent/104\",[52,4.123]],[\"name/105\",[53,39.55]],[\"parent/105\",[]],[\"name/106\",[1,34.187]],[\"parent/106\",[53,3.91]],[\"name/107\",[11,38.924]],[\"parent/107\",[53,3.91]],[\"name/108\",[54,54.43]],[\"parent/108\",[53,3.91]],[\"name/109\",[55,54.43]],[\"parent/109\",[53,3.91]],[\"name/110\",[56,54.43]],[\"parent/110\",[53,3.91]],[\"name/111\",[57,54.43]],[\"parent/111\",[53,3.91]],[\"name/112\",[58,54.43]],[\"parent/112\",[53,3.91]],[\"name/113\",[51,43.444]],[\"parent/113\",[53,3.91]],[\"name/114\",[12,38.924]],[\"parent/114\",[53,3.91]],[\"name/115\",[1,34.187]],[\"parent/115\",[59,4.205]],[\"name/116\",[14,21.795]],[\"parent/116\",[59,4.205]],[\"name/117\",[11,38.924]],[\"parent/117\",[59,4.205]],[\"name/118\",[60,57.795]],[\"parent/118\",[59,4.205]],[\"name/119\",[54,54.43]],[\"parent/119\",[59,4.205]],[\"name/120\",[55,54.43]],[\"parent/120\",[59,4.205]],[\"name/121\",[56,54.43]],[\"parent/121\",[59,4.205]],[\"name/122\",[57,54.43]],[\"parent/122\",[59,4.205]],[\"name/123\",[58,54.43]],[\"parent/123\",[59,4.205]],[\"name/124\",[51,43.444]],[\"parent/124\",[59,4.205]],[\"name/125\",[15,38.336]],[\"parent/125\",[59,4.205]],[\"name/126\",[61,44.445]],[\"parent/126\",[]],[\"name/127\",[1,34.187]],[\"parent/127\",[61,4.394]],[\"name/128\",[62,46.809]],[\"parent/128\",[61,4.394]],[\"name/129\",[63,46.809]],[\"parent/129\",[61,4.394]],[\"name/130\",[12,38.924]],[\"parent/130\",[61,4.394]],[\"name/131\",[1,34.187]],[\"parent/131\",[64,4.935]],[\"name/132\",[14,21.795]],[\"parent/132\",[64,4.935]],[\"name/133\",[62,46.809]],[\"parent/133\",[64,4.935]],[\"name/134\",[63,46.809]],[\"parent/134\",[64,4.935]],[\"name/135\",[15,38.336]],[\"parent/135\",[64,4.935]],[\"name/136\",[65,48.24]],[\"parent/136\",[]],[\"name/137\",[1,34.187]],[\"parent/137\",[65,4.769]],[\"name/138\",[66,51.917]],[\"parent/138\",[65,4.769]],[\"name/139\",[62,46.809]],[\"parent/139\",[65,4.769]],[\"name/140\",[63,46.809]],[\"parent/140\",[65,4.769]],[\"name/141\",[12,38.924]],[\"parent/141\",[65,4.769]],[\"name/142\",[1,34.187]],[\"parent/142\",[67,4.769]],[\"name/143\",[14,21.795]],[\"parent/143\",[67,4.769]],[\"name/144\",[66,51.917]],[\"parent/144\",[67,4.769]],[\"name/145\",[62,46.809]],[\"parent/145\",[67,4.769]],[\"name/146\",[63,46.809]],[\"parent/146\",[67,4.769]],[\"name/147\",[15,38.336]],[\"parent/147\",[67,4.769]],[\"name/148\",[68,34.571]],[\"parent/148\",[]],[\"name/149\",[1,34.187]],[\"parent/149\",[68,3.418]],[\"name/150\",[11,38.924]],[\"parent/150\",[68,3.418]],[\"name/151\",[69,48.24]],[\"parent/151\",[68,3.418]],[\"name/152\",[70,48.24]],[\"parent/152\",[68,3.418]],[\"name/153\",[47,48.24]],[\"parent/153\",[68,3.418]],[\"name/154\",[46,39.55]],[\"parent/154\",[68,3.418]],[\"name/155\",[71,48.24]],[\"parent/155\",[68,3.418]],[\"name/156\",[72,48.24]],[\"parent/156\",[68,3.418]],[\"name/157\",[73,48.24]],[\"parent/157\",[68,3.418]],[\"name/158\",[74,48.24]],[\"parent/158\",[68,3.418]],[\"name/159\",[75,48.24]],[\"parent/159\",[68,3.418]],[\"name/160\",[76,48.24]],[\"parent/160\",[68,3.418]],[\"name/161\",[77,54.43]],[\"parent/161\",[68,3.418]],[\"name/162\",[78,48.24]],[\"parent/162\",[68,3.418]],[\"name/163\",[79,48.24]],[\"parent/163\",[68,3.418]],[\"name/164\",[80,51.917]],[\"parent/164\",[68,3.418]],[\"name/165\",[81,49.911]],[\"parent/165\",[68,3.418]],[\"name/166\",[51,43.444]],[\"parent/166\",[68,3.418]],[\"name/167\",[82,51.917]],[\"parent/167\",[68,3.418]],[\"name/168\",[12,38.924]],[\"parent/168\",[68,3.418]],[\"name/169\",[1,34.187]],[\"parent/169\",[83,3.587]],[\"name/170\",[14,21.795]],[\"parent/170\",[83,3.587]],[\"name/171\",[11,38.924]],[\"parent/171\",[83,3.587]],[\"name/172\",[69,48.24]],[\"parent/172\",[83,3.587]],[\"name/173\",[76,48.24]],[\"parent/173\",[83,3.587]],[\"name/174\",[70,48.24]],[\"parent/174\",[83,3.587]],[\"name/175\",[46,39.55]],[\"parent/175\",[83,3.587]],[\"name/176\",[47,48.24]],[\"parent/176\",[83,3.587]],[\"name/177\",[71,48.24]],[\"parent/177\",[83,3.587]],[\"name/178\",[77,54.43]],[\"parent/178\",[83,3.587]],[\"name/179\",[78,48.24]],[\"parent/179\",[83,3.587]],[\"name/180\",[79,48.24]],[\"parent/180\",[83,3.587]],[\"name/181\",[73,48.24]],[\"parent/181\",[83,3.587]],[\"name/182\",[74,48.24]],[\"parent/182\",[83,3.587]],[\"name/183\",[72,48.24]],[\"parent/183\",[83,3.587]],[\"name/184\",[75,48.24]],[\"parent/184\",[83,3.587]],[\"name/185\",[80,51.917]],[\"parent/185\",[83,3.587]],[\"name/186\",[81,49.911]],[\"parent/186\",[83,3.587]],[\"name/187\",[51,43.444]],[\"parent/187\",[83,3.587]],[\"name/188\",[82,51.917]],[\"parent/188\",[83,3.587]],[\"name/189\",[15,38.336]],[\"parent/189\",[83,3.587]],[\"name/190\",[84,32.458]],[\"parent/190\",[]],[\"name/191\",[1,34.187]],[\"parent/191\",[84,3.209]],[\"name/192\",[85,54.43]],[\"parent/192\",[84,3.209]],[\"name/193\",[86,54.43]],[\"parent/193\",[84,3.209]],[\"name/194\",[87,54.43]],[\"parent/194\",[84,3.209]],[\"name/195\",[88,54.43]],[\"parent/195\",[84,3.209]],[\"name/196\",[89,54.43]],[\"parent/196\",[84,3.209]],[\"name/197\",[90,54.43]],[\"parent/197\",[84,3.209]],[\"name/198\",[91,51.917]],[\"parent/198\",[84,3.209]],[\"name/199\",[92,54.43]],[\"parent/199\",[84,3.209]],[\"name/200\",[93,51.917]],[\"parent/200\",[84,3.209]],[\"name/201\",[94,51.917]],[\"parent/201\",[84,3.209]],[\"name/202\",[95,51.917]],[\"parent/202\",[84,3.209]],[\"name/203\",[96,51.917]],[\"parent/203\",[84,3.209]],[\"name/204\",[97,51.917]],[\"parent/204\",[84,3.209]],[\"name/205\",[98,51.917]],[\"parent/205\",[84,3.209]],[\"name/206\",[99,51.917]],[\"parent/206\",[84,3.209]],[\"name/207\",[100,54.43]],[\"parent/207\",[84,3.209]],[\"name/208\",[101,57.795]],[\"parent/208\",[84,3.209]],[\"name/209\",[11,38.924]],[\"parent/209\",[84,3.209]],[\"name/210\",[62,46.809]],[\"parent/210\",[84,3.209]],[\"name/211\",[63,46.809]],[\"parent/211\",[84,3.209]],[\"name/212\",[66,51.917]],[\"parent/212\",[84,3.209]],[\"name/213\",[12,38.924]],[\"parent/213\",[84,3.209]],[\"name/214\",[1,34.187]],[\"parent/214\",[102,3.418]],[\"name/215\",[14,21.795]],[\"parent/215\",[102,3.418]],[\"name/216\",[11,38.924]],[\"parent/216\",[102,3.418]],[\"name/217\",[85,54.43]],[\"parent/217\",[102,3.418]],[\"name/218\",[101,57.795]],[\"parent/218\",[102,3.418]],[\"name/219\",[100,54.43]],[\"parent/219\",[102,3.418]],[\"name/220\",[86,54.43]],[\"parent/220\",[102,3.418]],[\"name/221\",[87,54.43]],[\"parent/221\",[102,3.418]],[\"name/222\",[88,54.43]],[\"parent/222\",[102,3.418]],[\"name/223\",[89,54.43]],[\"parent/223\",[102,3.418]],[\"name/224\",[90,54.43]],[\"parent/224\",[102,3.418]],[\"name/225\",[91,51.917]],[\"parent/225\",[102,3.418]],[\"name/226\",[92,54.43]],[\"parent/226\",[102,3.418]],[\"name/227\",[93,51.917]],[\"parent/227\",[102,3.418]],[\"name/228\",[103,57.795]],[\"parent/228\",[102,3.418]],[\"name/229\",[94,51.917]],[\"parent/229\",[102,3.418]],[\"name/230\",[95,51.917]],[\"parent/230\",[102,3.418]],[\"name/231\",[62,46.809]],[\"parent/231\",[102,3.418]],[\"name/232\",[63,46.809]],[\"parent/232\",[102,3.418]],[\"name/233\",[66,51.917]],[\"parent/233\",[102,3.418]],[\"name/234\",[96,51.917]],[\"parent/234\",[102,3.418]],[\"name/235\",[97,51.917]],[\"parent/235\",[102,3.418]],[\"name/236\",[98,51.917]],[\"parent/236\",[102,3.418]],[\"name/237\",[99,51.917]],[\"parent/237\",[102,3.418]],[\"name/238\",[15,38.336]],[\"parent/238\",[102,3.418]],[\"name/239\",[104,37.254]],[\"parent/239\",[]],[\"name/240\",[1,34.187]],[\"parent/240\",[104,3.683]],[\"name/241\",[11,38.924]],[\"parent/241\",[104,3.683]],[\"name/242\",[81,49.911]],[\"parent/242\",[104,3.683]],[\"name/243\",[46,39.55]],[\"parent/243\",[104,3.683]],[\"name/244\",[105,44.445]],[\"parent/244\",[104,3.683]],[\"name/245\",[106,44.445]],[\"parent/245\",[104,3.683]],[\"name/246\",[107,48.24]],[\"parent/246\",[104,3.683]],[\"name/247\",[108,48.24]],[\"parent/247\",[104,3.683]],[\"name/248\",[109,48.24]],[\"parent/248\",[104,3.683]],[\"name/249\",[110,48.24]],[\"parent/249\",[104,3.683]],[\"name/250\",[111,48.24]],[\"parent/250\",[104,3.683]],[\"name/251\",[112,48.24]],[\"parent/251\",[104,3.683]],[\"name/252\",[12,38.924]],[\"parent/252\",[104,3.683]],[\"name/253\",[1,34.187]],[\"parent/253\",[113,3.634]],[\"name/254\",[14,21.795]],[\"parent/254\",[113,3.634]],[\"name/255\",[11,38.924]],[\"parent/255\",[113,3.634]],[\"name/256\",[81,49.911]],[\"parent/256\",[113,3.634]],[\"name/257\",[46,39.55]],[\"parent/257\",[113,3.634]],[\"name/258\",[105,44.445]],[\"parent/258\",[113,3.634]],[\"name/259\",[106,44.445]],[\"parent/259\",[113,3.634]],[\"name/260\",[107,48.24]],[\"parent/260\",[113,3.634]],[\"name/261\",[14,21.795]],[\"parent/261\",[113,3.634]],[\"name/262\",[108,48.24]],[\"parent/262\",[113,3.634]],[\"name/263\",[14,21.795]],[\"parent/263\",[113,3.634]],[\"name/264\",[109,48.24]],[\"parent/264\",[113,3.634]],[\"name/265\",[14,21.795]],[\"parent/265\",[113,3.634]],[\"name/266\",[110,48.24]],[\"parent/266\",[113,3.634]],[\"name/267\",[14,21.795]],[\"parent/267\",[113,3.634]],[\"name/268\",[111,48.24]],[\"parent/268\",[113,3.634]],[\"name/269\",[14,21.795]],[\"parent/269\",[113,3.634]],[\"name/270\",[112,48.24]],[\"parent/270\",[113,3.634]],[\"name/271\",[14,21.795]],[\"parent/271\",[113,3.634]],[\"name/272\",[15,38.336]],[\"parent/272\",[113,3.634]],[\"name/273\",[114,34.187]],[\"parent/273\",[]],[\"name/274\",[1,34.187]],[\"parent/274\",[114,3.38]],[\"name/275\",[11,38.924]],[\"parent/275\",[114,3.38]],[\"name/276\",[115,54.43]],[\"parent/276\",[114,3.38]],[\"name/277\",[116,54.43]],[\"parent/277\",[114,3.38]],[\"name/278\",[117,48.24]],[\"parent/278\",[114,3.38]],[\"name/279\",[46,39.55]],[\"parent/279\",[114,3.38]],[\"name/280\",[106,44.445]],[\"parent/280\",[114,3.38]],[\"name/281\",[105,44.445]],[\"parent/281\",[114,3.38]],[\"name/282\",[48,48.24]],[\"parent/282\",[114,3.38]],[\"name/283\",[49,48.24]],[\"parent/283\",[114,3.38]],[\"name/284\",[50,48.24]],[\"parent/284\",[114,3.38]],[\"name/285\",[107,48.24]],[\"parent/285\",[114,3.38]],[\"name/286\",[108,48.24]],[\"parent/286\",[114,3.38]],[\"name/287\",[109,48.24]],[\"parent/287\",[114,3.38]],[\"name/288\",[110,48.24]],[\"parent/288\",[114,3.38]],[\"name/289\",[111,48.24]],[\"parent/289\",[114,3.38]],[\"name/290\",[112,48.24]],[\"parent/290\",[114,3.38]],[\"name/291\",[51,43.444]],[\"parent/291\",[114,3.38]],[\"name/292\",[12,38.924]],[\"parent/292\",[114,3.38]],[\"name/293\",[1,34.187]],[\"parent/293\",[118,3.38]],[\"name/294\",[14,21.795]],[\"parent/294\",[118,3.38]],[\"name/295\",[11,38.924]],[\"parent/295\",[118,3.38]],[\"name/296\",[117,48.24]],[\"parent/296\",[118,3.38]],[\"name/297\",[106,44.445]],[\"parent/297\",[118,3.38]],[\"name/298\",[115,54.43]],[\"parent/298\",[118,3.38]],[\"name/299\",[116,54.43]],[\"parent/299\",[118,3.38]],[\"name/300\",[46,39.55]],[\"parent/300\",[118,3.38]],[\"name/301\",[105,44.445]],[\"parent/301\",[118,3.38]],[\"name/302\",[48,48.24]],[\"parent/302\",[118,3.38]],[\"name/303\",[49,48.24]],[\"parent/303\",[118,3.38]],[\"name/304\",[50,48.24]],[\"parent/304\",[118,3.38]],[\"name/305\",[107,48.24]],[\"parent/305\",[118,3.38]],[\"name/306\",[14,21.795]],[\"parent/306\",[118,3.38]],[\"name/307\",[108,48.24]],[\"parent/307\",[118,3.38]],[\"name/308\",[14,21.795]],[\"parent/308\",[118,3.38]],[\"name/309\",[109,48.24]],[\"parent/309\",[118,3.38]],[\"name/310\",[14,21.795]],[\"parent/310\",[118,3.38]],[\"name/311\",[110,48.24]],[\"parent/311\",[118,3.38]],[\"name/312\",[14,21.795]],[\"parent/312\",[118,3.38]],[\"name/313\",[111,48.24]],[\"parent/313\",[118,3.38]],[\"name/314\",[14,21.795]],[\"parent/314\",[118,3.38]],[\"name/315\",[112,48.24]],[\"parent/315\",[118,3.38]],[\"name/316\",[14,21.795]],[\"parent/316\",[118,3.38]],[\"name/317\",[51,43.444]],[\"parent/317\",[118,3.38]],[\"name/318\",[15,38.336]],[\"parent/318\",[118,3.38]],[\"name/319\",[119,31.263]],[\"parent/319\",[]],[\"name/320\",[1,34.187]],[\"parent/320\",[119,3.091]],[\"name/321\",[11,38.924]],[\"parent/321\",[119,3.091]],[\"name/322\",[117,48.24]],[\"parent/322\",[119,3.091]],[\"name/323\",[120,57.795]],[\"parent/323\",[119,3.091]],[\"name/324\",[46,39.55]],[\"parent/324\",[119,3.091]],[\"name/325\",[106,44.445]],[\"parent/325\",[119,3.091]],[\"name/326\",[105,44.445]],[\"parent/326\",[119,3.091]],[\"name/327\",[69,48.24]],[\"parent/327\",[119,3.091]],[\"name/328\",[70,48.24]],[\"parent/328\",[119,3.091]],[\"name/329\",[71,48.24]],[\"parent/329\",[119,3.091]],[\"name/330\",[72,48.24]],[\"parent/330\",[119,3.091]],[\"name/331\",[73,48.24]],[\"parent/331\",[119,3.091]],[\"name/332\",[74,48.24]],[\"parent/332\",[119,3.091]],[\"name/333\",[75,48.24]],[\"parent/333\",[119,3.091]],[\"name/334\",[76,48.24]],[\"parent/334\",[119,3.091]],[\"name/335\",[121,54.43]],[\"parent/335\",[119,3.091]],[\"name/336\",[78,48.24]],[\"parent/336\",[119,3.091]],[\"name/337\",[79,48.24]],[\"parent/337\",[119,3.091]],[\"name/338\",[80,51.917]],[\"parent/338\",[119,3.091]],[\"name/339\",[107,48.24]],[\"parent/339\",[119,3.091]],[\"name/340\",[108,48.24]],[\"parent/340\",[119,3.091]],[\"name/341\",[109,48.24]],[\"parent/341\",[119,3.091]],[\"name/342\",[110,48.24]],[\"parent/342\",[119,3.091]],[\"name/343\",[111,48.24]],[\"parent/343\",[119,3.091]],[\"name/344\",[112,48.24]],[\"parent/344\",[119,3.091]],[\"name/345\",[51,43.444]],[\"parent/345\",[119,3.091]],[\"name/346\",[82,51.917]],[\"parent/346\",[119,3.091]],[\"name/347\",[12,38.924]],[\"parent/347\",[119,3.091]],[\"name/348\",[1,34.187]],[\"parent/348\",[122,3.091]],[\"name/349\",[14,21.795]],[\"parent/349\",[122,3.091]],[\"name/350\",[11,38.924]],[\"parent/350\",[122,3.091]],[\"name/351\",[117,48.24]],[\"parent/351\",[122,3.091]],[\"name/352\",[106,44.445]],[\"parent/352\",[122,3.091]],[\"name/353\",[46,39.55]],[\"parent/353\",[122,3.091]],[\"name/354\",[105,44.445]],[\"parent/354\",[122,3.091]],[\"name/355\",[69,48.24]],[\"parent/355\",[122,3.091]],[\"name/356\",[76,48.24]],[\"parent/356\",[122,3.091]],[\"name/357\",[70,48.24]],[\"parent/357\",[122,3.091]],[\"name/358\",[71,48.24]],[\"parent/358\",[122,3.091]],[\"name/359\",[121,54.43]],[\"parent/359\",[122,3.091]],[\"name/360\",[78,48.24]],[\"parent/360\",[122,3.091]],[\"name/361\",[79,48.24]],[\"parent/361\",[122,3.091]],[\"name/362\",[73,48.24]],[\"parent/362\",[122,3.091]],[\"name/363\",[74,48.24]],[\"parent/363\",[122,3.091]],[\"name/364\",[72,48.24]],[\"parent/364\",[122,3.091]],[\"name/365\",[75,48.24]],[\"parent/365\",[122,3.091]],[\"name/366\",[80,51.917]],[\"parent/366\",[122,3.091]],[\"name/367\",[120,57.795]],[\"parent/367\",[122,3.091]],[\"name/368\",[107,48.24]],[\"parent/368\",[122,3.091]],[\"name/369\",[14,21.795]],[\"parent/369\",[122,3.091]],[\"name/370\",[108,48.24]],[\"parent/370\",[122,3.091]],[\"name/371\",[14,21.795]],[\"parent/371\",[122,3.091]],[\"name/372\",[109,48.24]],[\"parent/372\",[122,3.091]],[\"name/373\",[14,21.795]],[\"parent/373\",[122,3.091]],[\"name/374\",[110,48.24]],[\"parent/374\",[122,3.091]],[\"name/375\",[14,21.795]],[\"parent/375\",[122,3.091]],[\"name/376\",[111,48.24]],[\"parent/376\",[122,3.091]],[\"name/377\",[14,21.795]],[\"parent/377\",[122,3.091]],[\"name/378\",[112,48.24]],[\"parent/378\",[122,3.091]],[\"name/379\",[14,21.795]],[\"parent/379\",[122,3.091]],[\"name/380\",[51,43.444]],[\"parent/380\",[122,3.091]],[\"name/381\",[82,51.917]],[\"parent/381\",[122,3.091]],[\"name/382\",[15,38.336]],[\"parent/382\",[122,3.091]],[\"name/383\",[123,45.557]],[\"parent/383\",[]],[\"name/384\",[1,34.187]],[\"parent/384\",[123,4.504]],[\"name/385\",[124,54.43]],[\"parent/385\",[123,4.504]],[\"name/386\",[125,54.43]],[\"parent/386\",[123,4.504]],[\"name/387\",[126,54.43]],[\"parent/387\",[123,4.504]],[\"name/388\",[12,38.924]],[\"parent/388\",[123,4.504]],[\"name/389\",[1,34.187]],[\"parent/389\",[127,4.769]],[\"name/390\",[14,21.795]],[\"parent/390\",[127,4.769]],[\"name/391\",[124,54.43]],[\"parent/391\",[127,4.769]],[\"name/392\",[125,54.43]],[\"parent/392\",[127,4.769]],[\"name/393\",[126,54.43]],[\"parent/393\",[127,4.769]],[\"name/394\",[15,38.336]],[\"parent/394\",[127,4.769]],[\"name/395\",[128,38.924]],[\"parent/395\",[]],[\"name/396\",[1,34.187]],[\"parent/396\",[128,3.848]],[\"name/397\",[129,54.43]],[\"parent/397\",[128,3.848]],[\"name/398\",[130,54.43]],[\"parent/398\",[128,3.848]],[\"name/399\",[131,54.43]],[\"parent/399\",[128,3.848]],[\"name/400\",[132,54.43]],[\"parent/400\",[128,3.848]],[\"name/401\",[133,54.43]],[\"parent/401\",[128,3.848]],[\"name/402\",[134,54.43]],[\"parent/402\",[128,3.848]],[\"name/403\",[135,54.43]],[\"parent/403\",[128,3.848]],[\"name/404\",[136,54.43]],[\"parent/404\",[128,3.848]],[\"name/405\",[137,54.43]],[\"parent/405\",[128,3.848]],[\"name/406\",[138,54.43]],[\"parent/406\",[128,3.848]],[\"name/407\",[12,38.924]],[\"parent/407\",[128,3.848]],[\"name/408\",[1,34.187]],[\"parent/408\",[139,3.91]],[\"name/409\",[14,21.795]],[\"parent/409\",[139,3.91]],[\"name/410\",[140,57.795]],[\"parent/410\",[139,3.91]],[\"name/411\",[141,57.795]],[\"parent/411\",[139,3.91]],[\"name/412\",[129,54.43]],[\"parent/412\",[139,3.91]],[\"name/413\",[130,54.43]],[\"parent/413\",[139,3.91]],[\"name/414\",[131,54.43]],[\"parent/414\",[139,3.91]],[\"name/415\",[132,54.43]],[\"parent/415\",[139,3.91]],[\"name/416\",[133,54.43]],[\"parent/416\",[139,3.91]],[\"name/417\",[134,54.43]],[\"parent/417\",[139,3.91]],[\"name/418\",[135,54.43]],[\"parent/418\",[139,3.91]],[\"name/419\",[136,54.43]],[\"parent/419\",[139,3.91]],[\"name/420\",[137,54.43]],[\"parent/420\",[139,3.91]],[\"name/421\",[138,54.43]],[\"parent/421\",[139,3.91]],[\"name/422\",[15,38.336]],[\"parent/422\",[139,3.91]],[\"name/423\",[142,62.903]],[\"parent/423\",[16,4.295]],[\"name/424\",[15,38.336]],[\"parent/424\",[143,3.79]],[\"name/425\",[144,57.795]],[\"parent/425\",[143,3.79]],[\"name/426\",[145,57.795]],[\"parent/426\",[143,3.79]],[\"name/427\",[146,62.903]],[\"parent/427\",[143,3.79]],[\"name/428\",[14,21.795]],[\"parent/428\",[143,3.79]],[\"name/429\",[147,62.903]],[\"parent/429\",[143,3.79]],[\"name/430\",[14,21.795]],[\"parent/430\",[143,3.79]],[\"name/431\",[148,62.903]],[\"parent/431\",[143,3.79]],[\"name/432\",[14,21.795]],[\"parent/432\",[143,3.79]],[\"name/433\",[149,62.903]],[\"parent/433\",[143,3.79]],[\"name/434\",[14,21.795]],[\"parent/434\",[143,3.79]],[\"name/435\",[150,62.903]],[\"parent/435\",[143,3.79]],[\"name/436\",[14,21.795]],[\"parent/436\",[143,3.79]],[\"name/437\",[151,62.903]],[\"parent/437\",[143,3.79]],[\"name/438\",[14,21.795]],[\"parent/438\",[143,3.79]],[\"name/439\",[152,62.903]],[\"parent/439\",[143,3.79]],[\"name/440\",[14,21.795]],[\"parent/440\",[143,3.79]],[\"name/441\",[153,62.903]],[\"parent/441\",[16,4.295]],[\"name/442\",[15,38.336]],[\"parent/442\",[154,4.047]],[\"name/443\",[144,57.795]],[\"parent/443\",[154,4.047]],[\"name/444\",[145,57.795]],[\"parent/444\",[154,4.047]],[\"name/445\",[155,62.903]],[\"parent/445\",[154,4.047]],[\"name/446\",[14,21.795]],[\"parent/446\",[154,4.047]],[\"name/447\",[156,62.903]],[\"parent/447\",[154,4.047]],[\"name/448\",[14,21.795]],[\"parent/448\",[154,4.047]],[\"name/449\",[157,62.903]],[\"parent/449\",[154,4.047]],[\"name/450\",[14,21.795]],[\"parent/450\",[154,4.047]],[\"name/451\",[158,62.903]],[\"parent/451\",[154,4.047]],[\"name/452\",[14,21.795]],[\"parent/452\",[154,4.047]],[\"name/453\",[159,62.903]],[\"parent/453\",[154,4.047]],[\"name/454\",[14,21.795]],[\"parent/454\",[154,4.047]],[\"name/455\",[160,62.903]],[\"parent/455\",[25,4.769]],[\"name/456\",[161,46.809]],[\"parent/456\",[162,5.381]],[\"name/457\",[163,57.795]],[\"parent/457\",[162,5.381]],[\"name/458\",[14,21.795]],[\"parent/458\",[162,5.381]],[\"name/459\",[164,57.795]],[\"parent/459\",[165,5.714]],[\"name/460\",[14,21.795]],[\"parent/460\",[165,5.714]],[\"name/461\",[166,57.795]],[\"parent/461\",[167,5.714]],[\"name/462\",[168,57.795]],[\"parent/462\",[167,5.714]],[\"name/463\",[169,62.903]],[\"parent/463\",[25,4.769]],[\"name/464\",[161,46.809]],[\"parent/464\",[170,5.133]],[\"name/465\",[163,57.795]],[\"parent/465\",[170,5.133]],[\"name/466\",[14,21.795]],[\"parent/466\",[170,5.133]],[\"name/467\",[164,57.795]],[\"parent/467\",[171,5.133]],[\"name/468\",[14,21.795]],[\"parent/468\",[171,5.133]],[\"name/469\",[166,57.795]],[\"parent/469\",[172,5.381]],[\"name/470\",[168,57.795]],[\"parent/470\",[172,5.381]],[\"name/471\",[14,21.795]],[\"parent/471\",[170,5.133]],[\"name/472\",[14,21.795]],[\"parent/472\",[171,5.133]],[\"name/473\",[14,21.795]],[\"parent/473\",[172,5.381]],[\"name/474\",[14,21.795]],[\"parent/474\",[173,6.219]],[\"name/475\",[14,21.795]],[\"parent/475\",[171,5.133]],[\"name/476\",[174,54.43]],[\"parent/476\",[29,4.769]],[\"name/477\",[161,46.809]],[\"parent/477\",[175,6.219]],[\"name/478\",[174,54.43]],[\"parent/478\",[31,4.769]],[\"name/479\",[161,46.809]],[\"parent/479\",[176,6.219]],[\"name/480\",[174,54.43]],[\"parent/480\",[33,4.935]],[\"name/481\",[161,46.809]],[\"parent/481\",[177,5.714]],[\"name/482\",[14,21.795]],[\"parent/482\",[177,5.714]],[\"name/483\",[178,57.795]],[\"parent/483\",[34,4.935]],[\"name/484\",[161,46.809]],[\"parent/484\",[179,6.219]],[\"name/485\",[178,57.795]],[\"parent/485\",[35,4.935]],[\"name/486\",[161,46.809]],[\"parent/486\",[180,6.219]],[\"name/487\",[181,42.535]],[\"parent/487\",[41,4.769]],[\"name/488\",[14,21.795]],[\"parent/488\",[182,6.219]],[\"name/489\",[183,62.903]],[\"parent/489\",[184,5.714]],[\"name/490\",[185,62.903]],[\"parent/490\",[184,5.714]],[\"name/491\",[186,46.809]],[\"parent/491\",[41,4.769]],[\"name/492\",[14,21.795]],[\"parent/492\",[187,6.219]],[\"name/493\",[188,46.809]],[\"parent/493\",[189,4.628]],[\"name/494\",[190,46.809]],[\"parent/494\",[189,4.628]],[\"name/495\",[191,46.809]],[\"parent/495\",[189,4.628]],[\"name/496\",[192,46.809]],[\"parent/496\",[189,4.628]],[\"name/497\",[193,46.809]],[\"parent/497\",[189,4.628]],[\"name/498\",[194,46.809]],[\"parent/498\",[189,4.628]],[\"name/499\",[195,49.911]],[\"parent/499\",[189,4.628]],[\"name/500\",[196,44.445]],[\"parent/500\",[41,4.769]],[\"name/501\",[14,21.795]],[\"parent/501\",[197,6.219]],[\"name/502\",[198,62.903]],[\"parent/502\",[199,6.219]],[\"name/503\",[181,42.535]],[\"parent/503\",[43,3.848]],[\"name/504\",[14,21.795]],[\"parent/504\",[200,6.219]],[\"name/505\",[44,54.43]],[\"parent/505\",[201,4.628]],[\"name/506\",[45,54.43]],[\"parent/506\",[201,4.628]],[\"name/507\",[46,39.55]],[\"parent/507\",[201,4.628]],[\"name/508\",[47,48.24]],[\"parent/508\",[201,4.628]],[\"name/509\",[48,48.24]],[\"parent/509\",[201,4.628]],[\"name/510\",[49,48.24]],[\"parent/510\",[201,4.628]],[\"name/511\",[50,48.24]],[\"parent/511\",[201,4.628]],[\"name/512\",[202,48.24]],[\"parent/512\",[43,3.848]],[\"name/513\",[14,21.795]],[\"parent/513\",[203,6.219]],[\"name/514\",[204,45.557]],[\"parent/514\",[205,5.381]],[\"name/515\",[206,49.911]],[\"parent/515\",[205,5.381]],[\"name/516\",[207,51.917]],[\"parent/516\",[205,5.381]],[\"name/517\",[186,46.809]],[\"parent/517\",[43,3.848]],[\"name/518\",[14,21.795]],[\"parent/518\",[208,6.219]],[\"name/519\",[188,46.809]],[\"parent/519\",[209,4.504]],[\"name/520\",[195,49.911]],[\"parent/520\",[209,4.504]],[\"name/521\",[190,46.809]],[\"parent/521\",[209,4.504]],[\"name/522\",[191,46.809]],[\"parent/522\",[209,4.504]],[\"name/523\",[194,46.809]],[\"parent/523\",[209,4.504]],[\"name/524\",[192,46.809]],[\"parent/524\",[209,4.504]],[\"name/525\",[193,46.809]],[\"parent/525\",[209,4.504]],[\"name/526\",[210,54.43]],[\"parent/526\",[209,4.504]],[\"name/527\",[196,44.445]],[\"parent/527\",[43,3.848]],[\"name/528\",[14,21.795]],[\"parent/528\",[211,6.219]],[\"name/529\",[212,57.795]],[\"parent/529\",[213,4.935]],[\"name/530\",[214,57.795]],[\"parent/530\",[213,4.935]],[\"name/531\",[215,57.795]],[\"parent/531\",[213,4.935]],[\"name/532\",[216,62.903]],[\"parent/532\",[213,4.935]],[\"name/533\",[217,62.903]],[\"parent/533\",[213,4.935]],[\"name/534\",[181,42.535]],[\"parent/534\",[53,3.91]],[\"name/535\",[14,21.795]],[\"parent/535\",[218,6.219]],[\"name/536\",[54,54.43]],[\"parent/536\",[219,4.935]],[\"name/537\",[55,54.43]],[\"parent/537\",[219,4.935]],[\"name/538\",[56,54.43]],[\"parent/538\",[219,4.935]],[\"name/539\",[57,54.43]],[\"parent/539\",[219,4.935]],[\"name/540\",[58,54.43]],[\"parent/540\",[219,4.935]],[\"name/541\",[186,46.809]],[\"parent/541\",[53,3.91]],[\"name/542\",[14,21.795]],[\"parent/542\",[220,6.219]],[\"name/543\",[188,46.809]],[\"parent/543\",[221,4.504]],[\"name/544\",[195,49.911]],[\"parent/544\",[221,4.504]],[\"name/545\",[190,46.809]],[\"parent/545\",[221,4.504]],[\"name/546\",[191,46.809]],[\"parent/546\",[221,4.504]],[\"name/547\",[194,46.809]],[\"parent/547\",[221,4.504]],[\"name/548\",[192,46.809]],[\"parent/548\",[221,4.504]],[\"name/549\",[193,46.809]],[\"parent/549\",[221,4.504]],[\"name/550\",[210,54.43]],[\"parent/550\",[221,4.504]],[\"name/551\",[196,44.445]],[\"parent/551\",[53,3.91]],[\"name/552\",[14,21.795]],[\"parent/552\",[222,6.219]],[\"name/553\",[223,62.903]],[\"parent/553\",[224,5.381]],[\"name/554\",[225,62.903]],[\"parent/554\",[224,5.381]],[\"name/555\",[226,62.903]],[\"parent/555\",[224,5.381]],[\"name/556\",[202,48.24]],[\"parent/556\",[53,3.91]],[\"name/557\",[14,21.795]],[\"parent/557\",[227,6.219]],[\"name/558\",[204,45.557]],[\"parent/558\",[228,5.714]],[\"name/559\",[206,49.911]],[\"parent/559\",[228,5.714]],[\"name/560\",[60,57.795]],[\"parent/560\",[53,3.91]],[\"name/561\",[196,44.445]],[\"parent/561\",[61,4.394]],[\"name/562\",[14,21.795]],[\"parent/562\",[229,6.219]],[\"name/563\",[230,62.903]],[\"parent/563\",[231,6.219]],[\"name/564\",[186,46.809]],[\"parent/564\",[61,4.394]],[\"name/565\",[14,21.795]],[\"parent/565\",[232,6.219]],[\"name/566\",[188,46.809]],[\"parent/566\",[233,4.769]],[\"name/567\",[190,46.809]],[\"parent/567\",[233,4.769]],[\"name/568\",[191,46.809]],[\"parent/568\",[233,4.769]],[\"name/569\",[194,46.809]],[\"parent/569\",[233,4.769]],[\"name/570\",[192,46.809]],[\"parent/570\",[233,4.769]],[\"name/571\",[193,46.809]],[\"parent/571\",[233,4.769]],[\"name/572\",[181,42.535]],[\"parent/572\",[61,4.394]],[\"name/573\",[14,21.795]],[\"parent/573\",[234,6.219]],[\"name/574\",[62,46.809]],[\"parent/574\",[235,5.714]],[\"name/575\",[63,46.809]],[\"parent/575\",[235,5.714]],[\"name/576\",[236,62.903]],[\"parent/576\",[61,4.394]],[\"name/577\",[14,21.795]],[\"parent/577\",[237,6.219]],[\"name/578\",[238,62.903]],[\"parent/578\",[239,4.769]],[\"name/579\",[240,62.903]],[\"parent/579\",[239,4.769]],[\"name/580\",[241,62.903]],[\"parent/580\",[239,4.769]],[\"name/581\",[242,62.903]],[\"parent/581\",[239,4.769]],[\"name/582\",[243,62.903]],[\"parent/582\",[239,4.769]],[\"name/583\",[244,62.903]],[\"parent/583\",[239,4.769]],[\"name/584\",[181,42.535]],[\"parent/584\",[68,3.418]],[\"name/585\",[14,21.795]],[\"parent/585\",[245,6.219]],[\"name/586\",[69,48.24]],[\"parent/586\",[246,4.047]],[\"name/587\",[76,48.24]],[\"parent/587\",[246,4.047]],[\"name/588\",[70,48.24]],[\"parent/588\",[246,4.047]],[\"name/589\",[46,39.55]],[\"parent/589\",[246,4.047]],[\"name/590\",[47,48.24]],[\"parent/590\",[246,4.047]],[\"name/591\",[71,48.24]],[\"parent/591\",[246,4.047]],[\"name/592\",[77,54.43]],[\"parent/592\",[246,4.047]],[\"name/593\",[78,48.24]],[\"parent/593\",[246,4.047]],[\"name/594\",[79,48.24]],[\"parent/594\",[246,4.047]],[\"name/595\",[73,48.24]],[\"parent/595\",[246,4.047]],[\"name/596\",[74,48.24]],[\"parent/596\",[246,4.047]],[\"name/597\",[72,48.24]],[\"parent/597\",[246,4.047]],[\"name/598\",[75,48.24]],[\"parent/598\",[246,4.047]],[\"name/599\",[202,48.24]],[\"parent/599\",[68,3.418]],[\"name/600\",[14,21.795]],[\"parent/600\",[247,6.219]],[\"name/601\",[204,45.557]],[\"parent/601\",[248,5.133]],[\"name/602\",[206,49.911]],[\"parent/602\",[248,5.133]],[\"name/603\",[249,62.903]],[\"parent/603\",[248,5.133]],[\"name/604\",[207,51.917]],[\"parent/604\",[248,5.133]],[\"name/605\",[186,46.809]],[\"parent/605\",[68,3.418]],[\"name/606\",[14,21.795]],[\"parent/606\",[250,6.219]],[\"name/607\",[188,46.809]],[\"parent/607\",[251,4.394]],[\"name/608\",[195,49.911]],[\"parent/608\",[251,4.394]],[\"name/609\",[190,46.809]],[\"parent/609\",[251,4.394]],[\"name/610\",[191,46.809]],[\"parent/610\",[251,4.394]],[\"name/611\",[194,46.809]],[\"parent/611\",[251,4.394]],[\"name/612\",[192,46.809]],[\"parent/612\",[251,4.394]],[\"name/613\",[193,46.809]],[\"parent/613\",[251,4.394]],[\"name/614\",[210,54.43]],[\"parent/614\",[251,4.394]],[\"name/615\",[252,62.903]],[\"parent/615\",[251,4.394]],[\"name/616\",[196,44.445]],[\"parent/616\",[68,3.418]],[\"name/617\",[14,21.795]],[\"parent/617\",[253,6.219]],[\"name/618\",[254,57.795]],[\"parent/618\",[255,4.935]],[\"name/619\",[256,57.795]],[\"parent/619\",[255,4.935]],[\"name/620\",[257,57.795]],[\"parent/620\",[255,4.935]],[\"name/621\",[212,57.795]],[\"parent/621\",[255,4.935]],[\"name/622\",[258,62.903]],[\"parent/622\",[255,4.935]],[\"name/623\",[259,62.903]],[\"parent/623\",[84,3.209]],[\"name/624\",[260,62.903]],[\"parent/624\",[261,5.381]],[\"name/625\",[262,62.903]],[\"parent/625\",[261,5.381]],[\"name/626\",[263,62.903]],[\"parent/626\",[261,5.381]],[\"name/627\",[181,42.535]],[\"parent/627\",[84,3.209]],[\"name/628\",[14,21.795]],[\"parent/628\",[264,6.219]],[\"name/629\",[85,54.43]],[\"parent/629\",[265,3.587]],[\"name/630\",[266,62.903]],[\"parent/630\",[265,3.587]],[\"name/631\",[86,54.43]],[\"parent/631\",[265,3.587]],[\"name/632\",[88,54.43]],[\"parent/632\",[265,3.587]],[\"name/633\",[87,54.43]],[\"parent/633\",[265,3.587]],[\"name/634\",[89,54.43]],[\"parent/634\",[265,3.587]],[\"name/635\",[90,54.43]],[\"parent/635\",[265,3.587]],[\"name/636\",[91,51.917]],[\"parent/636\",[265,3.587]],[\"name/637\",[92,54.43]],[\"parent/637\",[265,3.587]],[\"name/638\",[93,51.917]],[\"parent/638\",[265,3.587]],[\"name/639\",[94,51.917]],[\"parent/639\",[265,3.587]],[\"name/640\",[95,51.917]],[\"parent/640\",[265,3.587]],[\"name/641\",[103,57.795]],[\"parent/641\",[265,3.587]],[\"name/642\",[267,62.903]],[\"parent/642\",[265,3.587]],[\"name/643\",[268,62.903]],[\"parent/643\",[265,3.587]],[\"name/644\",[269,62.903]],[\"parent/644\",[265,3.587]],[\"name/645\",[100,54.43]],[\"parent/645\",[265,3.587]],[\"name/646\",[96,51.917]],[\"parent/646\",[265,3.587]],[\"name/647\",[97,51.917]],[\"parent/647\",[265,3.587]],[\"name/648\",[98,51.917]],[\"parent/648\",[265,3.587]],[\"name/649\",[99,51.917]],[\"parent/649\",[265,3.587]],[\"name/650\",[270,62.903]],[\"parent/650\",[84,3.209]],[\"name/651\",[91,51.917]],[\"parent/651\",[271,3.848]],[\"name/652\",[272,62.903]],[\"parent/652\",[271,3.848]],[\"name/653\",[93,51.917]],[\"parent/653\",[271,3.848]],[\"name/654\",[273,62.903]],[\"parent/654\",[271,3.848]],[\"name/655\",[274,62.903]],[\"parent/655\",[271,3.848]],[\"name/656\",[275,62.903]],[\"parent/656\",[271,3.848]],[\"name/657\",[276,62.903]],[\"parent/657\",[271,3.848]],[\"name/658\",[94,51.917]],[\"parent/658\",[271,3.848]],[\"name/659\",[95,51.917]],[\"parent/659\",[271,3.848]],[\"name/660\",[277,62.903]],[\"parent/660\",[271,3.848]],[\"name/661\",[278,62.903]],[\"parent/661\",[271,3.848]],[\"name/662\",[279,62.903]],[\"parent/662\",[271,3.848]],[\"name/663\",[96,51.917]],[\"parent/663\",[271,3.848]],[\"name/664\",[97,51.917]],[\"parent/664\",[271,3.848]],[\"name/665\",[98,51.917]],[\"parent/665\",[271,3.848]],[\"name/666\",[99,51.917]],[\"parent/666\",[271,3.848]],[\"name/667\",[196,44.445]],[\"parent/667\",[84,3.209]],[\"name/668\",[14,21.795]],[\"parent/668\",[280,6.219]],[\"name/669\",[281,62.903]],[\"parent/669\",[282,5.381]],[\"name/670\",[283,62.903]],[\"parent/670\",[282,5.381]],[\"name/671\",[284,62.903]],[\"parent/671\",[282,5.381]],[\"name/672\",[186,46.809]],[\"parent/672\",[84,3.209]],[\"name/673\",[14,21.795]],[\"parent/673\",[285,6.219]],[\"name/674\",[188,46.809]],[\"parent/674\",[286,4.769]],[\"name/675\",[190,46.809]],[\"parent/675\",[286,4.769]],[\"name/676\",[191,46.809]],[\"parent/676\",[286,4.769]],[\"name/677\",[194,46.809]],[\"parent/677\",[286,4.769]],[\"name/678\",[192,46.809]],[\"parent/678\",[286,4.769]],[\"name/679\",[193,46.809]],[\"parent/679\",[286,4.769]],[\"name/680\",[287,62.903]],[\"parent/680\",[84,3.209]],[\"name/681\",[14,21.795]],[\"parent/681\",[288,6.219]],[\"name/682\",[289,62.903]],[\"parent/682\",[290,4.769]],[\"name/683\",[291,54.43]],[\"parent/683\",[290,4.769]],[\"name/684\",[292,62.903]],[\"parent/684\",[290,4.769]],[\"name/685\",[293,62.903]],[\"parent/685\",[290,4.769]],[\"name/686\",[294,62.903]],[\"parent/686\",[290,4.769]],[\"name/687\",[295,62.903]],[\"parent/687\",[290,4.769]],[\"name/688\",[296,62.903]],[\"parent/688\",[84,3.209]],[\"name/689\",[181,42.535]],[\"parent/689\",[104,3.683]],[\"name/690\",[14,21.795]],[\"parent/690\",[297,6.219]],[\"name/691\",[46,39.55]],[\"parent/691\",[298,5.133]],[\"name/692\",[105,44.445]],[\"parent/692\",[298,5.133]],[\"name/693\",[106,44.445]],[\"parent/693\",[298,5.133]],[\"name/694\",[81,49.911]],[\"parent/694\",[298,5.133]],[\"name/695\",[202,48.24]],[\"parent/695\",[104,3.683]],[\"name/696\",[14,21.795]],[\"parent/696\",[299,6.219]],[\"name/697\",[204,45.557]],[\"parent/697\",[300,4.935]],[\"name/698\",[207,51.917]],[\"parent/698\",[300,4.935]],[\"name/699\",[206,49.911]],[\"parent/699\",[300,4.935]],[\"name/700\",[301,57.795]],[\"parent/700\",[300,4.935]],[\"name/701\",[14,21.795]],[\"parent/701\",[300,4.935]],[\"name/702\",[204,45.557]],[\"parent/702\",[302,5.714]],[\"name/703\",[291,54.43]],[\"parent/703\",[302,5.714]],[\"name/704\",[196,44.445]],[\"parent/704\",[104,3.683]],[\"name/705\",[14,21.795]],[\"parent/705\",[303,6.219]],[\"name/706\",[304,54.43]],[\"parent/706\",[305,5.381]],[\"name/707\",[306,62.903]],[\"parent/707\",[305,5.381]],[\"name/708\",[307,54.43]],[\"parent/708\",[305,5.381]],[\"name/709\",[186,46.809]],[\"parent/709\",[104,3.683]],[\"name/710\",[14,21.795]],[\"parent/710\",[308,6.219]],[\"name/711\",[188,46.809]],[\"parent/711\",[309,4.504]],[\"name/712\",[190,46.809]],[\"parent/712\",[309,4.504]],[\"name/713\",[191,46.809]],[\"parent/713\",[309,4.504]],[\"name/714\",[194,46.809]],[\"parent/714\",[309,4.504]],[\"name/715\",[310,62.903]],[\"parent/715\",[309,4.504]],[\"name/716\",[192,46.809]],[\"parent/716\",[309,4.504]],[\"name/717\",[193,46.809]],[\"parent/717\",[309,4.504]],[\"name/718\",[195,49.911]],[\"parent/718\",[309,4.504]],[\"name/719\",[311,54.43]],[\"parent/719\",[104,3.683]],[\"name/720\",[14,21.795]],[\"parent/720\",[312,6.219]],[\"name/721\",[204,45.557]],[\"parent/721\",[313,5.381]],[\"name/722\",[314,62.903]],[\"parent/722\",[313,5.381]],[\"name/723\",[315,62.903]],[\"parent/723\",[313,5.381]],[\"name/724\",[181,42.535]],[\"parent/724\",[114,3.38]],[\"name/725\",[14,21.795]],[\"parent/725\",[316,6.219]],[\"name/726\",[46,39.55]],[\"parent/726\",[317,4.394]],[\"name/727\",[105,44.445]],[\"parent/727\",[317,4.394]],[\"name/728\",[106,44.445]],[\"parent/728\",[317,4.394]],[\"name/729\",[117,48.24]],[\"parent/729\",[317,4.394]],[\"name/730\",[115,54.43]],[\"parent/730\",[317,4.394]],[\"name/731\",[116,54.43]],[\"parent/731\",[317,4.394]],[\"name/732\",[48,48.24]],[\"parent/732\",[317,4.394]],[\"name/733\",[49,48.24]],[\"parent/733\",[317,4.394]],[\"name/734\",[50,48.24]],[\"parent/734\",[317,4.394]],[\"name/735\",[311,54.43]],[\"parent/735\",[114,3.38]],[\"name/736\",[202,48.24]],[\"parent/736\",[114,3.38]],[\"name/737\",[14,21.795]],[\"parent/737\",[318,6.219]],[\"name/738\",[204,45.557]],[\"parent/738\",[319,4.935]],[\"name/739\",[207,51.917]],[\"parent/739\",[319,4.935]],[\"name/740\",[206,49.911]],[\"parent/740\",[319,4.935]],[\"name/741\",[301,57.795]],[\"parent/741\",[319,4.935]],[\"name/742\",[14,21.795]],[\"parent/742\",[319,4.935]],[\"name/743\",[204,45.557]],[\"parent/743\",[320,5.714]],[\"name/744\",[291,54.43]],[\"parent/744\",[320,5.714]],[\"name/745\",[196,44.445]],[\"parent/745\",[114,3.38]],[\"name/746\",[14,21.795]],[\"parent/746\",[321,6.219]],[\"name/747\",[304,54.43]],[\"parent/747\",[322,4.504]],[\"name/748\",[323,62.903]],[\"parent/748\",[322,4.504]],[\"name/749\",[214,57.795]],[\"parent/749\",[322,4.504]],[\"name/750\",[215,57.795]],[\"parent/750\",[322,4.504]],[\"name/751\",[324,57.795]],[\"parent/751\",[322,4.504]],[\"name/752\",[325,62.903]],[\"parent/752\",[322,4.504]],[\"name/753\",[326,62.903]],[\"parent/753\",[322,4.504]],[\"name/754\",[307,54.43]],[\"parent/754\",[322,4.504]],[\"name/755\",[327,62.903]],[\"parent/755\",[114,3.38]],[\"name/756\",[328,57.795]],[\"parent/756\",[114,3.38]],[\"name/757\",[181,42.535]],[\"parent/757\",[119,3.091]],[\"name/758\",[14,21.795]],[\"parent/758\",[329,6.219]],[\"name/759\",[46,39.55]],[\"parent/759\",[330,3.91]],[\"name/760\",[105,44.445]],[\"parent/760\",[330,3.91]],[\"name/761\",[71,48.24]],[\"parent/761\",[330,3.91]],[\"name/762\",[106,44.445]],[\"parent/762\",[330,3.91]],[\"name/763\",[117,48.24]],[\"parent/763\",[330,3.91]],[\"name/764\",[69,48.24]],[\"parent/764\",[330,3.91]],[\"name/765\",[76,48.24]],[\"parent/765\",[330,3.91]],[\"name/766\",[70,48.24]],[\"parent/766\",[330,3.91]],[\"name/767\",[121,54.43]],[\"parent/767\",[330,3.91]],[\"name/768\",[78,48.24]],[\"parent/768\",[330,3.91]],[\"name/769\",[79,48.24]],[\"parent/769\",[330,3.91]],[\"name/770\",[73,48.24]],[\"parent/770\",[330,3.91]],[\"name/771\",[74,48.24]],[\"parent/771\",[330,3.91]],[\"name/772\",[72,48.24]],[\"parent/772\",[330,3.91]],[\"name/773\",[75,48.24]],[\"parent/773\",[330,3.91]],[\"name/774\",[311,54.43]],[\"parent/774\",[119,3.091]],[\"name/775\",[202,48.24]],[\"parent/775\",[119,3.091]],[\"name/776\",[196,44.445]],[\"parent/776\",[119,3.091]],[\"name/777\",[14,21.795]],[\"parent/777\",[331,6.219]],[\"name/778\",[304,54.43]],[\"parent/778\",[332,4.504]],[\"name/779\",[324,57.795]],[\"parent/779\",[332,4.504]],[\"name/780\",[307,54.43]],[\"parent/780\",[332,4.504]],[\"name/781\",[254,57.795]],[\"parent/781\",[332,4.504]],[\"name/782\",[256,57.795]],[\"parent/782\",[332,4.504]],[\"name/783\",[257,57.795]],[\"parent/783\",[332,4.504]],[\"name/784\",[333,62.903]],[\"parent/784\",[332,4.504]],[\"name/785\",[334,62.903]],[\"parent/785\",[332,4.504]],[\"name/786\",[335,62.903]],[\"parent/786\",[119,3.091]],[\"name/787\",[328,57.795]],[\"parent/787\",[119,3.091]],[\"name/788\",[181,42.535]],[\"parent/788\",[123,4.504]],[\"name/789\",[14,21.795]],[\"parent/789\",[336,6.219]],[\"name/790\",[124,54.43]],[\"parent/790\",[337,5.381]],[\"name/791\",[125,54.43]],[\"parent/791\",[337,5.381]],[\"name/792\",[126,54.43]],[\"parent/792\",[337,5.381]],[\"name/793\",[338,62.903]],[\"parent/793\",[123,4.504]],[\"name/794\",[141,57.795]],[\"parent/794\",[128,3.848]],[\"name/795\",[140,57.795]],[\"parent/795\",[128,3.848]],[\"name/796\",[181,42.535]],[\"parent/796\",[128,3.848]],[\"name/797\",[14,21.795]],[\"parent/797\",[339,6.219]],[\"name/798\",[129,54.43]],[\"parent/798\",[340,4.295]],[\"name/799\",[130,54.43]],[\"parent/799\",[340,4.295]],[\"name/800\",[131,54.43]],[\"parent/800\",[340,4.295]],[\"name/801\",[132,54.43]],[\"parent/801\",[340,4.295]],[\"name/802\",[133,54.43]],[\"parent/802\",[340,4.295]],[\"name/803\",[134,54.43]],[\"parent/803\",[340,4.295]],[\"name/804\",[135,54.43]],[\"parent/804\",[340,4.295]],[\"name/805\",[136,54.43]],[\"parent/805\",[340,4.295]],[\"name/806\",[137,54.43]],[\"parent/806\",[340,4.295]],[\"name/807\",[138,54.43]],[\"parent/807\",[340,4.295]]],\"invertedIndex\":[[\"__type\",{\"_index\":14,\"name\":{\"14\":{},\"34\":{},\"79\":{},\"94\":{},\"116\":{},\"132\":{},\"143\":{},\"170\":{},\"215\":{},\"254\":{},\"261\":{},\"263\":{},\"265\":{},\"267\":{},\"269\":{},\"271\":{},\"294\":{},\"306\":{},\"308\":{},\"310\":{},\"312\":{},\"314\":{},\"316\":{},\"349\":{},\"369\":{},\"371\":{},\"373\":{},\"375\":{},\"377\":{},\"379\":{},\"390\":{},\"409\":{},\"428\":{},\"430\":{},\"432\":{},\"434\":{},\"436\":{},\"438\":{},\"440\":{},\"446\":{},\"448\":{},\"450\":{},\"452\":{},\"454\":{},\"458\":{},\"460\":{},\"466\":{},\"468\":{},\"471\":{},\"472\":{},\"473\":{},\"474\":{},\"475\":{},\"482\":{},\"488\":{},\"492\":{},\"501\":{},\"504\":{},\"513\":{},\"518\":{},\"528\":{},\"535\":{},\"542\":{},\"552\":{},\"557\":{},\"562\":{},\"565\":{},\"573\":{},\"577\":{},\"585\":{},\"600\":{},\"606\":{},\"617\":{},\"628\":{},\"668\":{},\"673\":{},\"681\":{},\"690\":{},\"696\":{},\"701\":{},\"705\":{},\"710\":{},\"720\":{},\"725\":{},\"737\":{},\"742\":{},\"746\":{},\"758\":{},\"777\":{},\"789\":{},\"797\":{}},\"parent\":{}}],[\"accesstokenpayload\",{\"_index\":294,\"name\":{\"686\":{}},\"parent\":{}}],[\"addroletouser\",{\"_index\":129,\"name\":{\"397\":{},\"412\":{},\"798\":{}},\"parent\":{}}],[\"alg\",{\"_index\":243,\"name\":{\"582\":{}},\"parent\":{}}],[\"anticsrfcheck\",{\"_index\":260,\"name\":{\"624\":{}},\"parent\":{}}],[\"apiinterface\",{\"_index\":196,\"name\":{\"500\":{},\"527\":{},\"551\":{},\"561\":{},\"616\":{},\"667\":{},\"704\":{},\"745\":{},\"776\":{}},\"parent\":{}}],[\"apioptions\",{\"_index\":186,\"name\":{\"491\":{},\"517\":{},\"541\":{},\"564\":{},\"605\":{},\"672\":{},\"709\":{}},\"parent\":{}}],[\"appinfo\",{\"_index\":195,\"name\":{\"499\":{},\"520\":{},\"544\":{},\"608\":{},\"718\":{}},\"parent\":{}}],[\"apple\",{\"_index\":110,\"name\":{\"249\":{},\"266\":{},\"288\":{},\"311\":{},\"342\":{},\"374\":{}},\"parent\":{}}],[\"appleredirecthandlerpost\",{\"_index\":307,\"name\":{\"708\":{},\"754\":{},\"780\":{}},\"parent\":{}}],[\"assertclaims\",{\"_index\":279,\"name\":{\"662\":{}},\"parent\":{}}],[\"authorisationurlget\",{\"_index\":304,\"name\":{\"706\":{},\"747\":{},\"778\":{}},\"parent\":{}}],[\"awslambda\",{\"_index\":22,\"name\":{\"32\":{},\"40\":{}},\"parent\":{}}],[\"baserequest\",{\"_index\":142,\"name\":{\"423\":{}},\"parent\":{}}],[\"baseresponse\",{\"_index\":153,\"name\":{\"441\":{}},\"parent\":{}}],[\"clearusermetadata\",{\"_index\":126,\"name\":{\"387\":{},\"393\":{},\"792\":{}},\"parent\":{}}],[\"config\",{\"_index\":190,\"name\":{\"494\":{},\"521\":{},\"545\":{},\"567\":{},\"609\":{},\"675\":{},\"712\":{}},\"parent\":{}}],[\"constructor\",{\"_index\":15,\"name\":{\"25\":{},\"69\":{},\"73\":{},\"80\":{},\"104\":{},\"125\":{},\"135\":{},\"147\":{},\"189\":{},\"238\":{},\"272\":{},\"318\":{},\"382\":{},\"394\":{},\"422\":{},\"424\":{},\"442\":{}},\"parent\":{}}],[\"consumecode\",{\"_index\":70,\"name\":{\"152\":{},\"174\":{},\"328\":{},\"357\":{},\"588\":{},\"766\":{}},\"parent\":{}}],[\"consumecodepost\",{\"_index\":257,\"name\":{\"620\":{},\"783\":{}},\"parent\":{}}],[\"cookies\",{\"_index\":168,\"name\":{\"462\":{},\"470\":{}},\"parent\":{}}],[\"createcode\",{\"_index\":69,\"name\":{\"151\":{},\"172\":{},\"327\":{},\"355\":{},\"586\":{},\"764\":{}},\"parent\":{}}],[\"createcodepost\",{\"_index\":254,\"name\":{\"618\":{},\"781\":{}},\"parent\":{}}],[\"createemailverificationtoken\",{\"_index\":54,\"name\":{\"108\":{},\"119\":{},\"536\":{}},\"parent\":{}}],[\"createjwt\",{\"_index\":62,\"name\":{\"128\":{},\"133\":{},\"139\":{},\"145\":{},\"210\":{},\"231\":{},\"574\":{}},\"parent\":{}}],[\"createmagiclink\",{\"_index\":80,\"name\":{\"164\":{},\"185\":{},\"338\":{},\"366\":{}},\"parent\":{}}],[\"createnewcodefordevice\",{\"_index\":76,\"name\":{\"160\":{},\"173\":{},\"334\":{},\"356\":{},\"587\":{},\"765\":{}},\"parent\":{}}],[\"createnewroleoraddpermissions\",{\"_index\":133,\"name\":{\"401\":{},\"416\":{},\"802\":{}},\"parent\":{}}],[\"createnewsession\",{\"_index\":85,\"name\":{\"192\":{},\"217\":{},\"629\":{}},\"parent\":{}}],[\"createresetpasswordtoken\",{\"_index\":48,\"name\":{\"88\":{},\"100\":{},\"282\":{},\"302\":{},\"509\":{},\"732\":{}},\"parent\":{}}],[\"createuseridmapping\",{\"_index\":7,\"name\":{\"7\":{},\"21\":{}},\"parent\":{}}],[\"dashboardget\",{\"_index\":198,\"name\":{\"502\":{}},\"parent\":{}}],[\"default\",{\"_index\":12,\"name\":{\"12\":{},\"33\":{},\"68\":{},\"72\":{},\"77\":{},\"92\":{},\"114\":{},\"130\":{},\"141\":{},\"168\":{},\"213\":{},\"252\":{},\"292\":{},\"347\":{},\"388\":{},\"407\":{}},\"parent\":{}}],[\"deleterole\",{\"_index\":137,\"name\":{\"405\":{},\"420\":{},\"806\":{}},\"parent\":{}}],[\"deleteuser\",{\"_index\":6,\"name\":{\"6\":{},\"20\":{}},\"parent\":{}}],[\"deleteuseridmapping\",{\"_index\":9,\"name\":{\"9\":{},\"23\":{}},\"parent\":{}}],[\"discord\",{\"_index\":111,\"name\":{\"250\":{},\"268\":{},\"289\":{},\"313\":{},\"343\":{},\"376\":{}},\"parent\":{}}],[\"e\",{\"_index\":242,\"name\":{\"581\":{}},\"parent\":{}}],[\"email\",{\"_index\":206,\"name\":{\"515\":{},\"559\":{},\"602\":{},\"699\":{},\"740\":{}},\"parent\":{}}],[\"emaildelivery\",{\"_index\":210,\"name\":{\"526\":{},\"550\":{},\"614\":{}},\"parent\":{}}],[\"emailexistsget\",{\"_index\":212,\"name\":{\"529\":{},\"621\":{}},\"parent\":{}}],[\"emailpasswordapioptions\",{\"_index\":327,\"name\":{\"755\":{}},\"parent\":{}}],[\"emailpasswordemailexistsget\",{\"_index\":323,\"name\":{\"748\":{}},\"parent\":{}}],[\"emailpasswordsignin\",{\"_index\":116,\"name\":{\"277\":{},\"299\":{},\"731\":{}},\"parent\":{}}],[\"emailpasswordsigninpost\",{\"_index\":325,\"name\":{\"752\":{}},\"parent\":{}}],[\"emailpasswordsignup\",{\"_index\":115,\"name\":{\"276\":{},\"298\":{},\"730\":{}},\"parent\":{}}],[\"emailpasswordsignuppost\",{\"_index\":326,\"name\":{\"753\":{}},\"parent\":{}}],[\"emailverificationclaim\",{\"_index\":60,\"name\":{\"118\":{},\"560\":{}},\"parent\":{}}],[\"error\",{\"_index\":11,\"name\":{\"11\":{},\"15\":{},\"83\":{},\"95\":{},\"107\":{},\"117\":{},\"150\":{},\"171\":{},\"209\":{},\"216\":{},\"241\":{},\"255\":{},\"275\":{},\"295\":{},\"321\":{},\"350\":{}},\"parent\":{}}],[\"errorhandler\",{\"_index\":30,\"name\":{\"47\":{},\"52\":{}},\"parent\":{}}],[\"expiry\",{\"_index\":293,\"name\":{\"685\":{}},\"parent\":{}}],[\"express\",{\"_index\":17,\"name\":{\"27\":{},\"35\":{}},\"parent\":{}}],[\"facebook\",{\"_index\":109,\"name\":{\"248\":{},\"264\":{},\"287\":{},\"309\":{},\"341\":{},\"372\":{}},\"parent\":{}}],[\"fastify\",{\"_index\":18,\"name\":{\"28\":{},\"36\":{}},\"parent\":{}}],[\"fetchandsetclaim\",{\"_index\":96,\"name\":{\"203\":{},\"234\":{},\"646\":{},\"663\":{}},\"parent\":{}}],[\"framework\",{\"_index\":16,\"name\":{\"26\":{}},\"parent\":{\"27\":{},\"28\":{},\"29\":{},\"30\":{},\"31\":{},\"32\":{},\"33\":{},\"423\":{},\"441\":{}}}],[\"framework.baserequest\",{\"_index\":143,\"name\":{},\"parent\":{\"424\":{},\"425\":{},\"426\":{},\"427\":{},\"428\":{},\"429\":{},\"430\":{},\"431\":{},\"432\":{},\"433\":{},\"434\":{},\"435\":{},\"436\":{},\"437\":{},\"438\":{},\"439\":{},\"440\":{}}}],[\"framework.baseresponse\",{\"_index\":154,\"name\":{},\"parent\":{\"442\":{},\"443\":{},\"444\":{},\"445\":{},\"446\":{},\"447\":{},\"448\":{},\"449\":{},\"450\":{},\"451\":{},\"452\":{},\"453\":{},\"454\":{}}}],[\"framework.default\",{\"_index\":23,\"name\":{},\"parent\":{\"34\":{}}}],[\"framework.default.__type\",{\"_index\":24,\"name\":{},\"parent\":{\"35\":{},\"36\":{},\"37\":{},\"38\":{},\"39\":{},\"40\":{}}}],[\"framework/awslambda\",{\"_index\":25,\"name\":{\"41\":{}},\"parent\":{\"42\":{},\"43\":{},\"44\":{},\"455\":{},\"463\":{}}}],[\"framework/awslambda.sessionevent\",{\"_index\":162,\"name\":{},\"parent\":{\"456\":{},\"457\":{},\"458\":{}}}],[\"framework/awslambda.sessionevent.__type\",{\"_index\":165,\"name\":{},\"parent\":{\"459\":{},\"460\":{}}}],[\"framework/awslambda.sessionevent.__type.__type\",{\"_index\":167,\"name\":{},\"parent\":{\"461\":{},\"462\":{}}}],[\"framework/awslambda.sessioneventv2\",{\"_index\":170,\"name\":{},\"parent\":{\"464\":{},\"465\":{},\"466\":{},\"471\":{}}}],[\"framework/awslambda.sessioneventv2.__type\",{\"_index\":171,\"name\":{},\"parent\":{\"467\":{},\"468\":{},\"472\":{},\"475\":{}}}],[\"framework/awslambda.sessioneventv2.__type.__type\",{\"_index\":172,\"name\":{},\"parent\":{\"469\":{},\"470\":{},\"473\":{}}}],[\"framework/awslambda.sessioneventv2.__type.__type.__type\",{\"_index\":173,\"name\":{},\"parent\":{\"474\":{}}}],[\"framework/express\",{\"_index\":29,\"name\":{\"45\":{}},\"parent\":{\"46\":{},\"47\":{},\"48\":{},\"49\":{},\"476\":{}}}],[\"framework/express.sessionrequest\",{\"_index\":175,\"name\":{},\"parent\":{\"477\":{}}}],[\"framework/fastify\",{\"_index\":31,\"name\":{\"50\":{}},\"parent\":{\"51\":{},\"52\":{},\"53\":{},\"54\":{},\"478\":{}}}],[\"framework/fastify.sessionrequest\",{\"_index\":176,\"name\":{},\"parent\":{\"479\":{}}}],[\"framework/hapi\",{\"_index\":33,\"name\":{\"55\":{}},\"parent\":{\"56\":{},\"57\":{},\"58\":{},\"480\":{}}}],[\"framework/hapi.sessionrequest\",{\"_index\":177,\"name\":{},\"parent\":{\"481\":{},\"482\":{}}}],[\"framework/koa\",{\"_index\":34,\"name\":{\"59\":{}},\"parent\":{\"60\":{},\"61\":{},\"62\":{},\"483\":{}}}],[\"framework/koa.sessioncontext\",{\"_index\":179,\"name\":{},\"parent\":{\"484\":{}}}],[\"framework/loopback\",{\"_index\":35,\"name\":{\"63\":{}},\"parent\":{\"64\":{},\"65\":{},\"66\":{},\"485\":{}}}],[\"framework/loopback.sessioncontext\",{\"_index\":180,\"name\":{},\"parent\":{\"486\":{}}}],[\"generateemailverifytokenpost\",{\"_index\":226,\"name\":{\"555\":{}},\"parent\":{}}],[\"generatepasswordresettokenpost\",{\"_index\":214,\"name\":{\"530\":{},\"749\":{}},\"parent\":{}}],[\"get\",{\"_index\":314,\"name\":{\"722\":{}},\"parent\":{}}],[\"getaccesstoken\",{\"_index\":276,\"name\":{\"657\":{}},\"parent\":{}}],[\"getaccesstokenlifetimems\",{\"_index\":267,\"name\":{\"642\":{}},\"parent\":{}}],[\"getaccesstokenpayload\",{\"_index\":274,\"name\":{\"655\":{}},\"parent\":{}}],[\"getallcorsheaders\",{\"_index\":2,\"name\":{\"2\":{},\"16\":{}},\"parent\":{}}],[\"getallroles\",{\"_index\":138,\"name\":{\"406\":{},\"421\":{},\"807\":{}},\"parent\":{}}],[\"getallsessionhandlesforuser\",{\"_index\":90,\"name\":{\"197\":{},\"224\":{},\"635\":{}},\"parent\":{}}],[\"getclaimvalue\",{\"_index\":98,\"name\":{\"205\":{},\"236\":{},\"648\":{},\"665\":{}},\"parent\":{}}],[\"getcookievalue\",{\"_index\":149,\"name\":{\"433\":{}},\"parent\":{}}],[\"getdashboardbundlelocation\",{\"_index\":183,\"name\":{\"489\":{}},\"parent\":{}}],[\"getexpiry\",{\"_index\":278,\"name\":{\"661\":{}},\"parent\":{}}],[\"getformdata\",{\"_index\":152,\"name\":{\"439\":{}},\"parent\":{}}],[\"getglobalclaimvalidators\",{\"_index\":266,\"name\":{\"630\":{}},\"parent\":{}}],[\"gethandle\",{\"_index\":275,\"name\":{\"656\":{}},\"parent\":{}}],[\"getheadervalue\",{\"_index\":150,\"name\":{\"435\":{}},\"parent\":{}}],[\"getjsonbody\",{\"_index\":147,\"name\":{\"429\":{}},\"parent\":{}}],[\"getjwks\",{\"_index\":63,\"name\":{\"129\":{},\"134\":{},\"140\":{},\"146\":{},\"211\":{},\"232\":{},\"575\":{}},\"parent\":{}}],[\"getjwksget\",{\"_index\":230,\"name\":{\"563\":{}},\"parent\":{}}],[\"getkeyvaluefromquery\",{\"_index\":146,\"name\":{\"427\":{}},\"parent\":{}}],[\"getmethod\",{\"_index\":148,\"name\":{\"431\":{}},\"parent\":{}}],[\"getopeniddiscoveryconfiguration\",{\"_index\":66,\"name\":{\"138\":{},\"144\":{},\"212\":{},\"233\":{}},\"parent\":{}}],[\"getoriginalurl\",{\"_index\":151,\"name\":{\"437\":{}},\"parent\":{}}],[\"getpermissionsforrole\",{\"_index\":134,\"name\":{\"402\":{},\"417\":{},\"803\":{}},\"parent\":{}}],[\"getrefreshtokenlifetimems\",{\"_index\":268,\"name\":{\"643\":{}},\"parent\":{}}],[\"getrolesforuser\",{\"_index\":131,\"name\":{\"399\":{},\"414\":{},\"800\":{}},\"parent\":{}}],[\"getrolesthathavepermission\",{\"_index\":136,\"name\":{\"404\":{},\"419\":{},\"805\":{}},\"parent\":{}}],[\"getsession\",{\"_index\":86,\"name\":{\"193\":{},\"220\":{},\"631\":{}},\"parent\":{}}],[\"getsessiondata\",{\"_index\":272,\"name\":{\"652\":{}},\"parent\":{}}],[\"getsessioninformation\",{\"_index\":87,\"name\":{\"194\":{},\"221\":{},\"633\":{}},\"parent\":{}}],[\"gettimecreated\",{\"_index\":277,\"name\":{\"660\":{}},\"parent\":{}}],[\"getuserbyemail\",{\"_index\":47,\"name\":{\"87\":{},\"99\":{},\"153\":{},\"176\":{},\"508\":{},\"590\":{}},\"parent\":{}}],[\"getuserbyid\",{\"_index\":46,\"name\":{\"86\":{},\"98\":{},\"154\":{},\"175\":{},\"243\":{},\"257\":{},\"279\":{},\"300\":{},\"324\":{},\"353\":{},\"507\":{},\"589\":{},\"691\":{},\"726\":{},\"759\":{}},\"parent\":{}}],[\"getuserbyphonenumber\",{\"_index\":71,\"name\":{\"155\":{},\"177\":{},\"329\":{},\"358\":{},\"591\":{},\"761\":{}},\"parent\":{}}],[\"getuserbythirdpartyinfo\",{\"_index\":106,\"name\":{\"245\":{},\"259\":{},\"280\":{},\"297\":{},\"325\":{},\"352\":{},\"693\":{},\"728\":{},\"762\":{}},\"parent\":{}}],[\"getusercount\",{\"_index\":3,\"name\":{\"3\":{},\"17\":{}},\"parent\":{}}],[\"getuserid\",{\"_index\":273,\"name\":{\"654\":{}},\"parent\":{}}],[\"getuseridmapping\",{\"_index\":8,\"name\":{\"8\":{},\"22\":{}},\"parent\":{}}],[\"getusermetadata\",{\"_index\":124,\"name\":{\"385\":{},\"391\":{},\"790\":{}},\"parent\":{}}],[\"getusersbyemail\",{\"_index\":105,\"name\":{\"244\":{},\"258\":{},\"281\":{},\"301\":{},\"326\":{},\"354\":{},\"692\":{},\"727\":{},\"760\":{}},\"parent\":{}}],[\"getusersnewestfirst\",{\"_index\":5,\"name\":{\"5\":{},\"19\":{}},\"parent\":{}}],[\"getusersoldestfirst\",{\"_index\":4,\"name\":{\"4\":{},\"18\":{}},\"parent\":{}}],[\"getusersthathaverole\",{\"_index\":132,\"name\":{\"400\":{},\"415\":{},\"801\":{}},\"parent\":{}}],[\"github\",{\"_index\":108,\"name\":{\"247\":{},\"262\":{},\"286\":{},\"307\":{},\"340\":{},\"370\":{}},\"parent\":{}}],[\"google\",{\"_index\":107,\"name\":{\"246\":{},\"260\":{},\"285\":{},\"305\":{},\"339\":{},\"368\":{}},\"parent\":{}}],[\"googleworkspaces\",{\"_index\":112,\"name\":{\"251\":{},\"270\":{},\"290\":{},\"315\":{},\"344\":{},\"378\":{}},\"parent\":{}}],[\"hapi\",{\"_index\":19,\"name\":{\"29\":{},\"37\":{}},\"parent\":{}}],[\"headers\",{\"_index\":166,\"name\":{\"461\":{},\"469\":{}},\"parent\":{}}],[\"id\",{\"_index\":204,\"name\":{\"514\":{},\"558\":{},\"601\":{},\"697\":{},\"702\":{},\"721\":{},\"738\":{},\"743\":{}},\"parent\":{}}],[\"index\",{\"_index\":0,\"name\":{\"0\":{}},\"parent\":{\"1\":{},\"2\":{},\"3\":{},\"4\":{},\"5\":{},\"6\":{},\"7\":{},\"8\":{},\"9\":{},\"10\":{},\"11\":{},\"12\":{}}}],[\"index.default\",{\"_index\":13,\"name\":{},\"parent\":{\"13\":{},\"14\":{},\"15\":{},\"16\":{},\"17\":{},\"18\":{},\"19\":{},\"20\":{},\"21\":{},\"22\":{},\"23\":{},\"24\":{},\"25\":{}}}],[\"ingredientinterfaceimpl\",{\"_index\":38,\"name\":{\"70\":{},\"74\":{}},\"parent\":{}}],[\"ingredients/emaildelivery\",{\"_index\":36,\"name\":{\"67\":{}},\"parent\":{\"68\":{}}}],[\"ingredients/emaildelivery.default\",{\"_index\":37,\"name\":{},\"parent\":{\"69\":{},\"70\":{}}}],[\"ingredients/smsdelivery\",{\"_index\":39,\"name\":{\"71\":{}},\"parent\":{\"72\":{}}}],[\"ingredients/smsdelivery.default\",{\"_index\":40,\"name\":{},\"parent\":{\"73\":{},\"74\":{}}}],[\"init\",{\"_index\":1,\"name\":{\"1\":{},\"13\":{},\"76\":{},\"78\":{},\"82\":{},\"93\":{},\"106\":{},\"115\":{},\"127\":{},\"131\":{},\"137\":{},\"142\":{},\"149\":{},\"169\":{},\"191\":{},\"214\":{},\"240\":{},\"253\":{},\"274\":{},\"293\":{},\"320\":{},\"348\":{},\"384\":{},\"389\":{},\"396\":{},\"408\":{}},\"parent\":{}}],[\"isdefault\",{\"_index\":315,\"name\":{\"723\":{}},\"parent\":{}}],[\"isemailverified\",{\"_index\":56,\"name\":{\"110\":{},\"121\":{},\"538\":{}},\"parent\":{}}],[\"isemailverifiedget\",{\"_index\":225,\"name\":{\"554\":{}},\"parent\":{}}],[\"isinserverlessenv\",{\"_index\":194,\"name\":{\"498\":{},\"523\":{},\"547\":{},\"569\":{},\"611\":{},\"677\":{},\"714\":{}},\"parent\":{}}],[\"jsonobject\",{\"_index\":338,\"name\":{\"793\":{}},\"parent\":{}}],[\"jsonwebkey\",{\"_index\":236,\"name\":{\"576\":{}},\"parent\":{}}],[\"kid\",{\"_index\":240,\"name\":{\"579\":{}},\"parent\":{}}],[\"koa\",{\"_index\":21,\"name\":{\"31\":{},\"39\":{}},\"parent\":{}}],[\"kty\",{\"_index\":238,\"name\":{\"578\":{}},\"parent\":{}}],[\"listcodesbydeviceid\",{\"_index\":72,\"name\":{\"156\":{},\"183\":{},\"330\":{},\"364\":{},\"597\":{},\"772\":{}},\"parent\":{}}],[\"listcodesbyemail\",{\"_index\":73,\"name\":{\"157\":{},\"181\":{},\"331\":{},\"362\":{},\"595\":{},\"770\":{}},\"parent\":{}}],[\"listcodesbyphonenumber\",{\"_index\":74,\"name\":{\"158\":{},\"182\":{},\"332\":{},\"363\":{},\"596\":{},\"771\":{}},\"parent\":{}}],[\"listcodesbypreauthsessionid\",{\"_index\":75,\"name\":{\"159\":{},\"184\":{},\"333\":{},\"365\":{},\"598\":{},\"773\":{}},\"parent\":{}}],[\"loopback\",{\"_index\":20,\"name\":{\"30\":{},\"38\":{}},\"parent\":{}}],[\"mergeintoaccesstokenpayload\",{\"_index\":95,\"name\":{\"202\":{},\"230\":{},\"640\":{},\"659\":{}},\"parent\":{}}],[\"middleware\",{\"_index\":26,\"name\":{\"42\":{},\"46\":{},\"60\":{},\"64\":{}},\"parent\":{}}],[\"n\",{\"_index\":241,\"name\":{\"580\":{}},\"parent\":{}}],[\"original\",{\"_index\":145,\"name\":{\"426\":{},\"444\":{}},\"parent\":{}}],[\"overrideglobalclaimvalidators\",{\"_index\":263,\"name\":{\"626\":{}},\"parent\":{}}],[\"passwordlessapioptions\",{\"_index\":335,\"name\":{\"786\":{}},\"parent\":{}}],[\"passwordlesssigninup\",{\"_index\":120,\"name\":{\"323\":{},\"367\":{}},\"parent\":{}}],[\"passwordlessuseremailexistsget\",{\"_index\":333,\"name\":{\"784\":{}},\"parent\":{}}],[\"passwordlessuserphonenumberexistsget\",{\"_index\":334,\"name\":{\"785\":{}},\"parent\":{}}],[\"passwordresetpost\",{\"_index\":215,\"name\":{\"531\":{},\"750\":{}},\"parent\":{}}],[\"permissionclaim\",{\"_index\":140,\"name\":{\"410\":{},\"795\":{}},\"parent\":{}}],[\"phonenumber\",{\"_index\":249,\"name\":{\"603\":{}},\"parent\":{}}],[\"phonenumberexistsget\",{\"_index\":258,\"name\":{\"622\":{}},\"parent\":{}}],[\"plugin\",{\"_index\":32,\"name\":{\"51\":{},\"56\":{}},\"parent\":{}}],[\"providers\",{\"_index\":310,\"name\":{\"715\":{}},\"parent\":{}}],[\"recipe/dashboard\",{\"_index\":41,\"name\":{\"75\":{}},\"parent\":{\"76\":{},\"77\":{},\"487\":{},\"491\":{},\"500\":{}}}],[\"recipe/dashboard.apiinterface\",{\"_index\":197,\"name\":{},\"parent\":{\"501\":{}}}],[\"recipe/dashboard.apiinterface.__type\",{\"_index\":199,\"name\":{},\"parent\":{\"502\":{}}}],[\"recipe/dashboard.apioptions\",{\"_index\":187,\"name\":{},\"parent\":{\"492\":{}}}],[\"recipe/dashboard.apioptions.__type\",{\"_index\":189,\"name\":{},\"parent\":{\"493\":{},\"494\":{},\"495\":{},\"496\":{},\"497\":{},\"498\":{},\"499\":{}}}],[\"recipe/dashboard.default\",{\"_index\":42,\"name\":{},\"parent\":{\"78\":{},\"79\":{},\"80\":{}}}],[\"recipe/dashboard.recipeinterface\",{\"_index\":182,\"name\":{},\"parent\":{\"488\":{}}}],[\"recipe/dashboard.recipeinterface.__type\",{\"_index\":184,\"name\":{},\"parent\":{\"489\":{},\"490\":{}}}],[\"recipe/emailpassword\",{\"_index\":43,\"name\":{\"81\":{}},\"parent\":{\"82\":{},\"83\":{},\"84\":{},\"85\":{},\"86\":{},\"87\":{},\"88\":{},\"89\":{},\"90\":{},\"91\":{},\"92\":{},\"503\":{},\"512\":{},\"517\":{},\"527\":{}}}],[\"recipe/emailpassword.apiinterface\",{\"_index\":211,\"name\":{},\"parent\":{\"528\":{}}}],[\"recipe/emailpassword.apiinterface.__type\",{\"_index\":213,\"name\":{},\"parent\":{\"529\":{},\"530\":{},\"531\":{},\"532\":{},\"533\":{}}}],[\"recipe/emailpassword.apioptions\",{\"_index\":208,\"name\":{},\"parent\":{\"518\":{}}}],[\"recipe/emailpassword.apioptions.__type\",{\"_index\":209,\"name\":{},\"parent\":{\"519\":{},\"520\":{},\"521\":{},\"522\":{},\"523\":{},\"524\":{},\"525\":{},\"526\":{}}}],[\"recipe/emailpassword.default\",{\"_index\":52,\"name\":{},\"parent\":{\"93\":{},\"94\":{},\"95\":{},\"96\":{},\"97\":{},\"98\":{},\"99\":{},\"100\":{},\"101\":{},\"102\":{},\"103\":{},\"104\":{}}}],[\"recipe/emailpassword.recipeinterface\",{\"_index\":200,\"name\":{},\"parent\":{\"504\":{}}}],[\"recipe/emailpassword.recipeinterface.__type\",{\"_index\":201,\"name\":{},\"parent\":{\"505\":{},\"506\":{},\"507\":{},\"508\":{},\"509\":{},\"510\":{},\"511\":{}}}],[\"recipe/emailpassword.user\",{\"_index\":203,\"name\":{},\"parent\":{\"513\":{}}}],[\"recipe/emailpassword.user.__type\",{\"_index\":205,\"name\":{},\"parent\":{\"514\":{},\"515\":{},\"516\":{}}}],[\"recipe/emailverification\",{\"_index\":53,\"name\":{\"105\":{}},\"parent\":{\"106\":{},\"107\":{},\"108\":{},\"109\":{},\"110\":{},\"111\":{},\"112\":{},\"113\":{},\"114\":{},\"534\":{},\"541\":{},\"551\":{},\"556\":{},\"560\":{}}}],[\"recipe/emailverification.apiinterface\",{\"_index\":222,\"name\":{},\"parent\":{\"552\":{}}}],[\"recipe/emailverification.apiinterface.__type\",{\"_index\":224,\"name\":{},\"parent\":{\"553\":{},\"554\":{},\"555\":{}}}],[\"recipe/emailverification.apioptions\",{\"_index\":220,\"name\":{},\"parent\":{\"542\":{}}}],[\"recipe/emailverification.apioptions.__type\",{\"_index\":221,\"name\":{},\"parent\":{\"543\":{},\"544\":{},\"545\":{},\"546\":{},\"547\":{},\"548\":{},\"549\":{},\"550\":{}}}],[\"recipe/emailverification.default\",{\"_index\":59,\"name\":{},\"parent\":{\"115\":{},\"116\":{},\"117\":{},\"118\":{},\"119\":{},\"120\":{},\"121\":{},\"122\":{},\"123\":{},\"124\":{},\"125\":{}}}],[\"recipe/emailverification.recipeinterface\",{\"_index\":218,\"name\":{},\"parent\":{\"535\":{}}}],[\"recipe/emailverification.recipeinterface.__type\",{\"_index\":219,\"name\":{},\"parent\":{\"536\":{},\"537\":{},\"538\":{},\"539\":{},\"540\":{}}}],[\"recipe/emailverification.user\",{\"_index\":227,\"name\":{},\"parent\":{\"557\":{}}}],[\"recipe/emailverification.user.__type\",{\"_index\":228,\"name\":{},\"parent\":{\"558\":{},\"559\":{}}}],[\"recipe/jwt\",{\"_index\":61,\"name\":{\"126\":{}},\"parent\":{\"127\":{},\"128\":{},\"129\":{},\"130\":{},\"561\":{},\"564\":{},\"572\":{},\"576\":{}}}],[\"recipe/jwt.apiinterface\",{\"_index\":229,\"name\":{},\"parent\":{\"562\":{}}}],[\"recipe/jwt.apiinterface.__type\",{\"_index\":231,\"name\":{},\"parent\":{\"563\":{}}}],[\"recipe/jwt.apioptions\",{\"_index\":232,\"name\":{},\"parent\":{\"565\":{}}}],[\"recipe/jwt.apioptions.__type\",{\"_index\":233,\"name\":{},\"parent\":{\"566\":{},\"567\":{},\"568\":{},\"569\":{},\"570\":{},\"571\":{}}}],[\"recipe/jwt.default\",{\"_index\":64,\"name\":{},\"parent\":{\"131\":{},\"132\":{},\"133\":{},\"134\":{},\"135\":{}}}],[\"recipe/jwt.jsonwebkey\",{\"_index\":237,\"name\":{},\"parent\":{\"577\":{}}}],[\"recipe/jwt.jsonwebkey.__type\",{\"_index\":239,\"name\":{},\"parent\":{\"578\":{},\"579\":{},\"580\":{},\"581\":{},\"582\":{},\"583\":{}}}],[\"recipe/jwt.recipeinterface\",{\"_index\":234,\"name\":{},\"parent\":{\"573\":{}}}],[\"recipe/jwt.recipeinterface.__type\",{\"_index\":235,\"name\":{},\"parent\":{\"574\":{},\"575\":{}}}],[\"recipe/openid\",{\"_index\":65,\"name\":{\"136\":{}},\"parent\":{\"137\":{},\"138\":{},\"139\":{},\"140\":{},\"141\":{}}}],[\"recipe/openid.default\",{\"_index\":67,\"name\":{},\"parent\":{\"142\":{},\"143\":{},\"144\":{},\"145\":{},\"146\":{},\"147\":{}}}],[\"recipe/passwordless\",{\"_index\":68,\"name\":{\"148\":{}},\"parent\":{\"149\":{},\"150\":{},\"151\":{},\"152\":{},\"153\":{},\"154\":{},\"155\":{},\"156\":{},\"157\":{},\"158\":{},\"159\":{},\"160\":{},\"161\":{},\"162\":{},\"163\":{},\"164\":{},\"165\":{},\"166\":{},\"167\":{},\"168\":{},\"584\":{},\"599\":{},\"605\":{},\"616\":{}}}],[\"recipe/passwordless.apiinterface\",{\"_index\":253,\"name\":{},\"parent\":{\"617\":{}}}],[\"recipe/passwordless.apiinterface.__type\",{\"_index\":255,\"name\":{},\"parent\":{\"618\":{},\"619\":{},\"620\":{},\"621\":{},\"622\":{}}}],[\"recipe/passwordless.apioptions\",{\"_index\":250,\"name\":{},\"parent\":{\"606\":{}}}],[\"recipe/passwordless.apioptions.__type\",{\"_index\":251,\"name\":{},\"parent\":{\"607\":{},\"608\":{},\"609\":{},\"610\":{},\"611\":{},\"612\":{},\"613\":{},\"614\":{},\"615\":{}}}],[\"recipe/passwordless.default\",{\"_index\":83,\"name\":{},\"parent\":{\"169\":{},\"170\":{},\"171\":{},\"172\":{},\"173\":{},\"174\":{},\"175\":{},\"176\":{},\"177\":{},\"178\":{},\"179\":{},\"180\":{},\"181\":{},\"182\":{},\"183\":{},\"184\":{},\"185\":{},\"186\":{},\"187\":{},\"188\":{},\"189\":{}}}],[\"recipe/passwordless.recipeinterface\",{\"_index\":245,\"name\":{},\"parent\":{\"585\":{}}}],[\"recipe/passwordless.recipeinterface.__type\",{\"_index\":246,\"name\":{},\"parent\":{\"586\":{},\"587\":{},\"588\":{},\"589\":{},\"590\":{},\"591\":{},\"592\":{},\"593\":{},\"594\":{},\"595\":{},\"596\":{},\"597\":{},\"598\":{}}}],[\"recipe/passwordless.user\",{\"_index\":247,\"name\":{},\"parent\":{\"600\":{}}}],[\"recipe/passwordless.user.__type\",{\"_index\":248,\"name\":{},\"parent\":{\"601\":{},\"602\":{},\"603\":{},\"604\":{}}}],[\"recipe/session\",{\"_index\":84,\"name\":{\"190\":{}},\"parent\":{\"191\":{},\"192\":{},\"193\":{},\"194\":{},\"195\":{},\"196\":{},\"197\":{},\"198\":{},\"199\":{},\"200\":{},\"201\":{},\"202\":{},\"203\":{},\"204\":{},\"205\":{},\"206\":{},\"207\":{},\"208\":{},\"209\":{},\"210\":{},\"211\":{},\"212\":{},\"213\":{},\"623\":{},\"627\":{},\"650\":{},\"667\":{},\"672\":{},\"680\":{},\"688\":{}}}],[\"recipe/session.apiinterface\",{\"_index\":280,\"name\":{},\"parent\":{\"668\":{}}}],[\"recipe/session.apiinterface.__type\",{\"_index\":282,\"name\":{},\"parent\":{\"669\":{},\"670\":{},\"671\":{}}}],[\"recipe/session.apioptions\",{\"_index\":285,\"name\":{},\"parent\":{\"673\":{}}}],[\"recipe/session.apioptions.__type\",{\"_index\":286,\"name\":{},\"parent\":{\"674\":{},\"675\":{},\"676\":{},\"677\":{},\"678\":{},\"679\":{}}}],[\"recipe/session.default\",{\"_index\":102,\"name\":{},\"parent\":{\"214\":{},\"215\":{},\"216\":{},\"217\":{},\"218\":{},\"219\":{},\"220\":{},\"221\":{},\"222\":{},\"223\":{},\"224\":{},\"225\":{},\"226\":{},\"227\":{},\"228\":{},\"229\":{},\"230\":{},\"231\":{},\"232\":{},\"233\":{},\"234\":{},\"235\":{},\"236\":{},\"237\":{},\"238\":{}}}],[\"recipe/session.recipeinterface\",{\"_index\":264,\"name\":{},\"parent\":{\"628\":{}}}],[\"recipe/session.recipeinterface.__type\",{\"_index\":265,\"name\":{},\"parent\":{\"629\":{},\"630\":{},\"631\":{},\"632\":{},\"633\":{},\"634\":{},\"635\":{},\"636\":{},\"637\":{},\"638\":{},\"639\":{},\"640\":{},\"641\":{},\"642\":{},\"643\":{},\"644\":{},\"645\":{},\"646\":{},\"647\":{},\"648\":{},\"649\":{}}}],[\"recipe/session.sessioncontainer\",{\"_index\":271,\"name\":{},\"parent\":{\"651\":{},\"652\":{},\"653\":{},\"654\":{},\"655\":{},\"656\":{},\"657\":{},\"658\":{},\"659\":{},\"660\":{},\"661\":{},\"662\":{},\"663\":{},\"664\":{},\"665\":{},\"666\":{}}}],[\"recipe/session.sessioninformation\",{\"_index\":288,\"name\":{},\"parent\":{\"681\":{}}}],[\"recipe/session.sessioninformation.__type\",{\"_index\":290,\"name\":{},\"parent\":{\"682\":{},\"683\":{},\"684\":{},\"685\":{},\"686\":{},\"687\":{}}}],[\"recipe/session.verifysessionoptions\",{\"_index\":261,\"name\":{},\"parent\":{\"624\":{},\"625\":{},\"626\":{}}}],[\"recipe/thirdparty\",{\"_index\":104,\"name\":{\"239\":{}},\"parent\":{\"240\":{},\"241\":{},\"242\":{},\"243\":{},\"244\":{},\"245\":{},\"246\":{},\"247\":{},\"248\":{},\"249\":{},\"250\":{},\"251\":{},\"252\":{},\"689\":{},\"695\":{},\"704\":{},\"709\":{},\"719\":{}}}],[\"recipe/thirdparty.apiinterface\",{\"_index\":303,\"name\":{},\"parent\":{\"705\":{}}}],[\"recipe/thirdparty.apiinterface.__type\",{\"_index\":305,\"name\":{},\"parent\":{\"706\":{},\"707\":{},\"708\":{}}}],[\"recipe/thirdparty.apioptions\",{\"_index\":308,\"name\":{},\"parent\":{\"710\":{}}}],[\"recipe/thirdparty.apioptions.__type\",{\"_index\":309,\"name\":{},\"parent\":{\"711\":{},\"712\":{},\"713\":{},\"714\":{},\"715\":{},\"716\":{},\"717\":{},\"718\":{}}}],[\"recipe/thirdparty.default\",{\"_index\":113,\"name\":{},\"parent\":{\"253\":{},\"254\":{},\"255\":{},\"256\":{},\"257\":{},\"258\":{},\"259\":{},\"260\":{},\"261\":{},\"262\":{},\"263\":{},\"264\":{},\"265\":{},\"266\":{},\"267\":{},\"268\":{},\"269\":{},\"270\":{},\"271\":{},\"272\":{}}}],[\"recipe/thirdparty.recipeinterface\",{\"_index\":297,\"name\":{},\"parent\":{\"690\":{}}}],[\"recipe/thirdparty.recipeinterface.__type\",{\"_index\":298,\"name\":{},\"parent\":{\"691\":{},\"692\":{},\"693\":{},\"694\":{}}}],[\"recipe/thirdparty.typeprovider\",{\"_index\":312,\"name\":{},\"parent\":{\"720\":{}}}],[\"recipe/thirdparty.typeprovider.__type\",{\"_index\":313,\"name\":{},\"parent\":{\"721\":{},\"722\":{},\"723\":{}}}],[\"recipe/thirdparty.user\",{\"_index\":299,\"name\":{},\"parent\":{\"696\":{}}}],[\"recipe/thirdparty.user.__type\",{\"_index\":300,\"name\":{},\"parent\":{\"697\":{},\"698\":{},\"699\":{},\"700\":{},\"701\":{}}}],[\"recipe/thirdparty.user.__type.__type\",{\"_index\":302,\"name\":{},\"parent\":{\"702\":{},\"703\":{}}}],[\"recipe/thirdpartyemailpassword\",{\"_index\":114,\"name\":{\"273\":{}},\"parent\":{\"274\":{},\"275\":{},\"276\":{},\"277\":{},\"278\":{},\"279\":{},\"280\":{},\"281\":{},\"282\":{},\"283\":{},\"284\":{},\"285\":{},\"286\":{},\"287\":{},\"288\":{},\"289\":{},\"290\":{},\"291\":{},\"292\":{},\"724\":{},\"735\":{},\"736\":{},\"745\":{},\"755\":{},\"756\":{}}}],[\"recipe/thirdpartyemailpassword.apiinterface\",{\"_index\":321,\"name\":{},\"parent\":{\"746\":{}}}],[\"recipe/thirdpartyemailpassword.apiinterface.__type\",{\"_index\":322,\"name\":{},\"parent\":{\"747\":{},\"748\":{},\"749\":{},\"750\":{},\"751\":{},\"752\":{},\"753\":{},\"754\":{}}}],[\"recipe/thirdpartyemailpassword.default\",{\"_index\":118,\"name\":{},\"parent\":{\"293\":{},\"294\":{},\"295\":{},\"296\":{},\"297\":{},\"298\":{},\"299\":{},\"300\":{},\"301\":{},\"302\":{},\"303\":{},\"304\":{},\"305\":{},\"306\":{},\"307\":{},\"308\":{},\"309\":{},\"310\":{},\"311\":{},\"312\":{},\"313\":{},\"314\":{},\"315\":{},\"316\":{},\"317\":{},\"318\":{}}}],[\"recipe/thirdpartyemailpassword.recipeinterface\",{\"_index\":316,\"name\":{},\"parent\":{\"725\":{}}}],[\"recipe/thirdpartyemailpassword.recipeinterface.__type\",{\"_index\":317,\"name\":{},\"parent\":{\"726\":{},\"727\":{},\"728\":{},\"729\":{},\"730\":{},\"731\":{},\"732\":{},\"733\":{},\"734\":{}}}],[\"recipe/thirdpartyemailpassword.user\",{\"_index\":318,\"name\":{},\"parent\":{\"737\":{}}}],[\"recipe/thirdpartyemailpassword.user.__type\",{\"_index\":319,\"name\":{},\"parent\":{\"738\":{},\"739\":{},\"740\":{},\"741\":{},\"742\":{}}}],[\"recipe/thirdpartyemailpassword.user.__type.__type\",{\"_index\":320,\"name\":{},\"parent\":{\"743\":{},\"744\":{}}}],[\"recipe/thirdpartypasswordless\",{\"_index\":119,\"name\":{\"319\":{}},\"parent\":{\"320\":{},\"321\":{},\"322\":{},\"323\":{},\"324\":{},\"325\":{},\"326\":{},\"327\":{},\"328\":{},\"329\":{},\"330\":{},\"331\":{},\"332\":{},\"333\":{},\"334\":{},\"335\":{},\"336\":{},\"337\":{},\"338\":{},\"339\":{},\"340\":{},\"341\":{},\"342\":{},\"343\":{},\"344\":{},\"345\":{},\"346\":{},\"347\":{},\"757\":{},\"774\":{},\"775\":{},\"776\":{},\"786\":{},\"787\":{}}}],[\"recipe/thirdpartypasswordless.apiinterface\",{\"_index\":331,\"name\":{},\"parent\":{\"777\":{}}}],[\"recipe/thirdpartypasswordless.apiinterface.__type\",{\"_index\":332,\"name\":{},\"parent\":{\"778\":{},\"779\":{},\"780\":{},\"781\":{},\"782\":{},\"783\":{},\"784\":{},\"785\":{}}}],[\"recipe/thirdpartypasswordless.default\",{\"_index\":122,\"name\":{},\"parent\":{\"348\":{},\"349\":{},\"350\":{},\"351\":{},\"352\":{},\"353\":{},\"354\":{},\"355\":{},\"356\":{},\"357\":{},\"358\":{},\"359\":{},\"360\":{},\"361\":{},\"362\":{},\"363\":{},\"364\":{},\"365\":{},\"366\":{},\"367\":{},\"368\":{},\"369\":{},\"370\":{},\"371\":{},\"372\":{},\"373\":{},\"374\":{},\"375\":{},\"376\":{},\"377\":{},\"378\":{},\"379\":{},\"380\":{},\"381\":{},\"382\":{}}}],[\"recipe/thirdpartypasswordless.recipeinterface\",{\"_index\":329,\"name\":{},\"parent\":{\"758\":{}}}],[\"recipe/thirdpartypasswordless.recipeinterface.__type\",{\"_index\":330,\"name\":{},\"parent\":{\"759\":{},\"760\":{},\"761\":{},\"762\":{},\"763\":{},\"764\":{},\"765\":{},\"766\":{},\"767\":{},\"768\":{},\"769\":{},\"770\":{},\"771\":{},\"772\":{},\"773\":{}}}],[\"recipe/usermetadata\",{\"_index\":123,\"name\":{\"383\":{}},\"parent\":{\"384\":{},\"385\":{},\"386\":{},\"387\":{},\"388\":{},\"788\":{},\"793\":{}}}],[\"recipe/usermetadata.default\",{\"_index\":127,\"name\":{},\"parent\":{\"389\":{},\"390\":{},\"391\":{},\"392\":{},\"393\":{},\"394\":{}}}],[\"recipe/usermetadata.recipeinterface\",{\"_index\":336,\"name\":{},\"parent\":{\"789\":{}}}],[\"recipe/usermetadata.recipeinterface.__type\",{\"_index\":337,\"name\":{},\"parent\":{\"790\":{},\"791\":{},\"792\":{}}}],[\"recipe/userroles\",{\"_index\":128,\"name\":{\"395\":{}},\"parent\":{\"396\":{},\"397\":{},\"398\":{},\"399\":{},\"400\":{},\"401\":{},\"402\":{},\"403\":{},\"404\":{},\"405\":{},\"406\":{},\"407\":{},\"794\":{},\"795\":{},\"796\":{}}}],[\"recipe/userroles.default\",{\"_index\":139,\"name\":{},\"parent\":{\"408\":{},\"409\":{},\"410\":{},\"411\":{},\"412\":{},\"413\":{},\"414\":{},\"415\":{},\"416\":{},\"417\":{},\"418\":{},\"419\":{},\"420\":{},\"421\":{},\"422\":{}}}],[\"recipe/userroles.recipeinterface\",{\"_index\":339,\"name\":{},\"parent\":{\"797\":{}}}],[\"recipe/userroles.recipeinterface.__type\",{\"_index\":340,\"name\":{},\"parent\":{\"798\":{},\"799\":{},\"800\":{},\"801\":{},\"802\":{},\"803\":{},\"804\":{},\"805\":{},\"806\":{},\"807\":{}}}],[\"recipeid\",{\"_index\":191,\"name\":{\"495\":{},\"522\":{},\"546\":{},\"568\":{},\"610\":{},\"676\":{},\"713\":{}},\"parent\":{}}],[\"recipeimplementation\",{\"_index\":188,\"name\":{\"493\":{},\"519\":{},\"543\":{},\"566\":{},\"607\":{},\"674\":{},\"711\":{}},\"parent\":{}}],[\"recipeinterface\",{\"_index\":181,\"name\":{\"487\":{},\"503\":{},\"534\":{},\"572\":{},\"584\":{},\"627\":{},\"689\":{},\"724\":{},\"757\":{},\"788\":{},\"796\":{}},\"parent\":{}}],[\"refreshpost\",{\"_index\":281,\"name\":{\"669\":{}},\"parent\":{}}],[\"refreshsession\",{\"_index\":88,\"name\":{\"195\":{},\"222\":{},\"632\":{}},\"parent\":{}}],[\"regenerateaccesstoken\",{\"_index\":103,\"name\":{\"228\":{},\"641\":{}},\"parent\":{}}],[\"removeclaim\",{\"_index\":99,\"name\":{\"206\":{},\"237\":{},\"649\":{},\"666\":{}},\"parent\":{}}],[\"removepermissionsfromrole\",{\"_index\":135,\"name\":{\"403\":{},\"418\":{},\"804\":{}},\"parent\":{}}],[\"removeuserrole\",{\"_index\":130,\"name\":{\"398\":{},\"413\":{},\"799\":{}},\"parent\":{}}],[\"req\",{\"_index\":192,\"name\":{\"496\":{},\"524\":{},\"548\":{},\"570\":{},\"612\":{},\"678\":{},\"716\":{}},\"parent\":{}}],[\"res\",{\"_index\":193,\"name\":{\"497\":{},\"525\":{},\"549\":{},\"571\":{},\"613\":{},\"679\":{},\"717\":{}},\"parent\":{}}],[\"resendcodepost\",{\"_index\":256,\"name\":{\"619\":{},\"782\":{}},\"parent\":{}}],[\"resetpasswordusingtoken\",{\"_index\":49,\"name\":{\"89\":{},\"101\":{},\"283\":{},\"303\":{},\"510\":{},\"733\":{}},\"parent\":{}}],[\"response\",{\"_index\":164,\"name\":{\"459\":{},\"467\":{}},\"parent\":{}}],[\"revokeallcodes\",{\"_index\":78,\"name\":{\"162\":{},\"179\":{},\"336\":{},\"360\":{},\"593\":{},\"768\":{}},\"parent\":{}}],[\"revokeallsessionsforuser\",{\"_index\":89,\"name\":{\"196\":{},\"223\":{},\"634\":{}},\"parent\":{}}],[\"revokecode\",{\"_index\":79,\"name\":{\"163\":{},\"180\":{},\"337\":{},\"361\":{},\"594\":{},\"769\":{}},\"parent\":{}}],[\"revokeemailverificationtokens\",{\"_index\":57,\"name\":{\"111\":{},\"122\":{},\"539\":{}},\"parent\":{}}],[\"revokemultiplesessions\",{\"_index\":92,\"name\":{\"199\":{},\"226\":{},\"637\":{}},\"parent\":{}}],[\"revokesession\",{\"_index\":91,\"name\":{\"198\":{},\"225\":{},\"636\":{},\"651\":{}},\"parent\":{}}],[\"sendemail\",{\"_index\":51,\"name\":{\"91\":{},\"103\":{},\"113\":{},\"124\":{},\"166\":{},\"187\":{},\"291\":{},\"317\":{},\"345\":{},\"380\":{}},\"parent\":{}}],[\"sendhtmlresponse\",{\"_index\":159,\"name\":{\"453\":{}},\"parent\":{}}],[\"sendjsonresponse\",{\"_index\":158,\"name\":{\"451\":{}},\"parent\":{}}],[\"sendsms\",{\"_index\":82,\"name\":{\"167\":{},\"188\":{},\"346\":{},\"381\":{}},\"parent\":{}}],[\"session\",{\"_index\":161,\"name\":{\"456\":{},\"464\":{},\"477\":{},\"479\":{},\"481\":{},\"484\":{},\"486\":{}},\"parent\":{}}],[\"sessionclaimvalidator\",{\"_index\":296,\"name\":{\"688\":{}},\"parent\":{}}],[\"sessioncontainer\",{\"_index\":270,\"name\":{\"650\":{}},\"parent\":{}}],[\"sessioncontext\",{\"_index\":178,\"name\":{\"483\":{},\"485\":{}},\"parent\":{}}],[\"sessiondata\",{\"_index\":292,\"name\":{\"684\":{}},\"parent\":{}}],[\"sessionevent\",{\"_index\":160,\"name\":{\"455\":{}},\"parent\":{}}],[\"sessioneventv2\",{\"_index\":169,\"name\":{\"463\":{}},\"parent\":{}}],[\"sessionhandle\",{\"_index\":289,\"name\":{\"682\":{}},\"parent\":{}}],[\"sessioninformation\",{\"_index\":287,\"name\":{\"680\":{}},\"parent\":{}}],[\"sessionrequest\",{\"_index\":174,\"name\":{\"476\":{},\"478\":{},\"480\":{}},\"parent\":{}}],[\"sessionrequired\",{\"_index\":262,\"name\":{\"625\":{}},\"parent\":{}}],[\"setclaimvalue\",{\"_index\":97,\"name\":{\"204\":{},\"235\":{},\"647\":{},\"664\":{}},\"parent\":{}}],[\"setcookie\",{\"_index\":156,\"name\":{\"447\":{}},\"parent\":{}}],[\"setheader\",{\"_index\":155,\"name\":{\"445\":{}},\"parent\":{}}],[\"setstatuscode\",{\"_index\":157,\"name\":{\"449\":{}},\"parent\":{}}],[\"shouldallowaccess\",{\"_index\":185,\"name\":{\"490\":{}},\"parent\":{}}],[\"signin\",{\"_index\":45,\"name\":{\"85\":{},\"97\":{},\"506\":{}},\"parent\":{}}],[\"signinpost\",{\"_index\":216,\"name\":{\"532\":{}},\"parent\":{}}],[\"signinup\",{\"_index\":81,\"name\":{\"165\":{},\"186\":{},\"242\":{},\"256\":{},\"694\":{}},\"parent\":{}}],[\"signinuppost\",{\"_index\":306,\"name\":{\"707\":{}},\"parent\":{}}],[\"signoutpost\",{\"_index\":283,\"name\":{\"670\":{}},\"parent\":{}}],[\"signup\",{\"_index\":44,\"name\":{\"84\":{},\"96\":{},\"505\":{}},\"parent\":{}}],[\"signuppost\",{\"_index\":217,\"name\":{\"533\":{}},\"parent\":{}}],[\"smsdelivery\",{\"_index\":252,\"name\":{\"615\":{}},\"parent\":{}}],[\"supertokens\",{\"_index\":163,\"name\":{\"457\":{},\"465\":{}},\"parent\":{}}],[\"thirdparty\",{\"_index\":301,\"name\":{\"700\":{},\"741\":{}},\"parent\":{}}],[\"thirdpartyapioptions\",{\"_index\":328,\"name\":{\"756\":{},\"787\":{}},\"parent\":{}}],[\"thirdpartysigninup\",{\"_index\":117,\"name\":{\"278\":{},\"296\":{},\"322\":{},\"351\":{},\"729\":{},\"763\":{}},\"parent\":{}}],[\"thirdpartysigninuppost\",{\"_index\":324,\"name\":{\"751\":{},\"779\":{}},\"parent\":{}}],[\"timecreated\",{\"_index\":295,\"name\":{\"687\":{}},\"parent\":{}}],[\"timejoined\",{\"_index\":207,\"name\":{\"516\":{},\"604\":{},\"698\":{},\"739\":{}},\"parent\":{}}],[\"typeprovider\",{\"_index\":311,\"name\":{\"719\":{},\"735\":{},\"774\":{}},\"parent\":{}}],[\"unverifyemail\",{\"_index\":58,\"name\":{\"112\":{},\"123\":{},\"540\":{}},\"parent\":{}}],[\"updateaccesstokenpayload\",{\"_index\":94,\"name\":{\"201\":{},\"229\":{},\"639\":{},\"658\":{}},\"parent\":{}}],[\"updateemailorpassword\",{\"_index\":50,\"name\":{\"90\":{},\"102\":{},\"284\":{},\"304\":{},\"511\":{},\"734\":{}},\"parent\":{}}],[\"updateordeleteuseridmappinginfo\",{\"_index\":10,\"name\":{\"10\":{},\"24\":{}},\"parent\":{}}],[\"updatepasswordlessuser\",{\"_index\":121,\"name\":{\"335\":{},\"359\":{},\"767\":{}},\"parent\":{}}],[\"updatesessiondata\",{\"_index\":93,\"name\":{\"200\":{},\"227\":{},\"638\":{},\"653\":{}},\"parent\":{}}],[\"updateuser\",{\"_index\":77,\"name\":{\"161\":{},\"178\":{},\"592\":{}},\"parent\":{}}],[\"updateusermetadata\",{\"_index\":125,\"name\":{\"386\":{},\"392\":{},\"791\":{}},\"parent\":{}}],[\"use\",{\"_index\":244,\"name\":{\"583\":{}},\"parent\":{}}],[\"user\",{\"_index\":202,\"name\":{\"512\":{},\"556\":{},\"599\":{},\"695\":{},\"736\":{},\"775\":{}},\"parent\":{}}],[\"userid\",{\"_index\":291,\"name\":{\"683\":{},\"703\":{},\"744\":{}},\"parent\":{}}],[\"userroleclaim\",{\"_index\":141,\"name\":{\"411\":{},\"794\":{}},\"parent\":{}}],[\"validateclaims\",{\"_index\":269,\"name\":{\"644\":{}},\"parent\":{}}],[\"validateclaimsforsessionhandle\",{\"_index\":101,\"name\":{\"208\":{},\"218\":{}},\"parent\":{}}],[\"validateclaimsinjwtpayload\",{\"_index\":100,\"name\":{\"207\":{},\"219\":{},\"645\":{}},\"parent\":{}}],[\"verifyemailpost\",{\"_index\":223,\"name\":{\"553\":{}},\"parent\":{}}],[\"verifyemailusingtoken\",{\"_index\":55,\"name\":{\"109\":{},\"120\":{},\"537\":{}},\"parent\":{}}],[\"verifysession\",{\"_index\":284,\"name\":{\"671\":{}},\"parent\":{}}],[\"verifysessionoptions\",{\"_index\":259,\"name\":{\"623\":{}},\"parent\":{}}],[\"wrapperused\",{\"_index\":144,\"name\":{\"425\":{},\"443\":{}},\"parent\":{}}],[\"wraprequest\",{\"_index\":27,\"name\":{\"43\":{},\"48\":{},\"53\":{},\"57\":{},\"61\":{},\"65\":{}},\"parent\":{}}],[\"wrapresponse\",{\"_index\":28,\"name\":{\"44\":{},\"49\":{},\"54\":{},\"58\":{},\"62\":{},\"66\":{}},\"parent\":{}}]],\"pipeline\":[]}}"); \ No newline at end of file +window.searchData = JSON.parse("{\"kinds\":{\"2\":\"Module\",\"32\":\"Variable\",\"64\":\"Function\",\"128\":\"Class\",\"256\":\"Interface\",\"512\":\"Constructor\",\"1024\":\"Property\",\"2048\":\"Method\",\"65536\":\"Type literal\",\"4194304\":\"Type alias\",\"16777216\":\"Reference\"},\"rows\":[{\"id\":0,\"kind\":2,\"name\":\"index\",\"url\":\"modules/index.html\",\"classes\":\"tsd-kind-module\"},{\"id\":1,\"kind\":64,\"name\":\"init\",\"url\":\"modules/index.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":2,\"kind\":64,\"name\":\"getAllCORSHeaders\",\"url\":\"modules/index.html#getAllCORSHeaders\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":3,\"kind\":64,\"name\":\"getUserCount\",\"url\":\"modules/index.html#getUserCount\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":4,\"kind\":64,\"name\":\"getUsersOldestFirst\",\"url\":\"modules/index.html#getUsersOldestFirst\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":5,\"kind\":64,\"name\":\"getUsersNewestFirst\",\"url\":\"modules/index.html#getUsersNewestFirst\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":6,\"kind\":64,\"name\":\"deleteUser\",\"url\":\"modules/index.html#deleteUser\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":7,\"kind\":64,\"name\":\"createUserIdMapping\",\"url\":\"modules/index.html#createUserIdMapping\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":8,\"kind\":64,\"name\":\"getUserIdMapping\",\"url\":\"modules/index.html#getUserIdMapping\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":9,\"kind\":64,\"name\":\"deleteUserIdMapping\",\"url\":\"modules/index.html#deleteUserIdMapping\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":10,\"kind\":64,\"name\":\"updateOrDeleteUserIdMappingInfo\",\"url\":\"modules/index.html#updateOrDeleteUserIdMappingInfo\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":11,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/index.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":12,\"kind\":128,\"name\":\"default\",\"url\":\"classes/index.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"index\"},{\"id\":13,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/index.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":14,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/index.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"index.default\"},{\"id\":15,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/index.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":16,\"kind\":2048,\"name\":\"getAllCORSHeaders\",\"url\":\"classes/index.default.html#getAllCORSHeaders\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":17,\"kind\":2048,\"name\":\"getUserCount\",\"url\":\"classes/index.default.html#getUserCount\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":18,\"kind\":2048,\"name\":\"getUsersOldestFirst\",\"url\":\"classes/index.default.html#getUsersOldestFirst\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":19,\"kind\":2048,\"name\":\"getUsersNewestFirst\",\"url\":\"classes/index.default.html#getUsersNewestFirst\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":20,\"kind\":2048,\"name\":\"deleteUser\",\"url\":\"classes/index.default.html#deleteUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":21,\"kind\":2048,\"name\":\"createUserIdMapping\",\"url\":\"classes/index.default.html#createUserIdMapping\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":22,\"kind\":2048,\"name\":\"getUserIdMapping\",\"url\":\"classes/index.default.html#getUserIdMapping\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":23,\"kind\":2048,\"name\":\"deleteUserIdMapping\",\"url\":\"classes/index.default.html#deleteUserIdMapping\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":24,\"kind\":2048,\"name\":\"updateOrDeleteUserIdMappingInfo\",\"url\":\"classes/index.default.html#updateOrDeleteUserIdMappingInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"index.default\"},{\"id\":25,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/index.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"index.default\"},{\"id\":26,\"kind\":2,\"name\":\"framework\",\"url\":\"modules/framework.html\",\"classes\":\"tsd-kind-module\"},{\"id\":27,\"kind\":32,\"name\":\"express\",\"url\":\"modules/framework.html#express-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":28,\"kind\":32,\"name\":\"fastify\",\"url\":\"modules/framework.html#fastify-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":29,\"kind\":32,\"name\":\"hapi\",\"url\":\"modules/framework.html#hapi-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":30,\"kind\":32,\"name\":\"loopback\",\"url\":\"modules/framework.html#loopback-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":31,\"kind\":32,\"name\":\"koa\",\"url\":\"modules/framework.html#koa-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":32,\"kind\":32,\"name\":\"awsLambda\",\"url\":\"modules/framework.html#awsLambda-1\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":33,\"kind\":1024,\"name\":\"default\",\"url\":\"modules/framework.html#default\",\"classes\":\"tsd-kind-property tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":34,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/framework.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":35,\"kind\":1024,\"name\":\"express\",\"url\":\"modules/framework.html#__type.express\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.__type\"},{\"id\":36,\"kind\":1024,\"name\":\"fastify\",\"url\":\"modules/framework.html#__type.fastify\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.__type\"},{\"id\":37,\"kind\":1024,\"name\":\"hapi\",\"url\":\"modules/framework.html#__type.hapi\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.__type\"},{\"id\":38,\"kind\":1024,\"name\":\"loopback\",\"url\":\"modules/framework.html#__type.loopback\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.__type\"},{\"id\":39,\"kind\":1024,\"name\":\"koa\",\"url\":\"modules/framework.html#__type.koa\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.__type\"},{\"id\":40,\"kind\":1024,\"name\":\"awsLambda\",\"url\":\"modules/framework.html#__type.awsLambda\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework.__type\"},{\"id\":41,\"kind\":2,\"name\":\"framework/awsLambda\",\"url\":\"modules/framework_awsLambda.html\",\"classes\":\"tsd-kind-module\"},{\"id\":42,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_awsLambda.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":43,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_awsLambda.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":44,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_awsLambda.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":45,\"kind\":2,\"name\":\"framework/express\",\"url\":\"modules/framework_express.html\",\"classes\":\"tsd-kind-module\"},{\"id\":46,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_express.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":47,\"kind\":64,\"name\":\"errorHandler\",\"url\":\"modules/framework_express.html#errorHandler\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":48,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_express.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":49,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_express.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":50,\"kind\":2,\"name\":\"framework/fastify\",\"url\":\"modules/framework_fastify.html\",\"classes\":\"tsd-kind-module\"},{\"id\":51,\"kind\":64,\"name\":\"plugin\",\"url\":\"modules/framework_fastify.html#plugin\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":52,\"kind\":64,\"name\":\"errorHandler\",\"url\":\"modules/framework_fastify.html#errorHandler\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":53,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_fastify.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":54,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_fastify.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":55,\"kind\":2,\"name\":\"framework/hapi\",\"url\":\"modules/framework_hapi.html\",\"classes\":\"tsd-kind-module\"},{\"id\":56,\"kind\":32,\"name\":\"plugin\",\"url\":\"modules/framework_hapi.html#plugin\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":57,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_hapi.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":58,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_hapi.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":59,\"kind\":2,\"name\":\"framework/koa\",\"url\":\"modules/framework_koa.html\",\"classes\":\"tsd-kind-module\"},{\"id\":60,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_koa.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":61,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_koa.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":62,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_koa.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":63,\"kind\":2,\"name\":\"framework/loopback\",\"url\":\"modules/framework_loopback.html\",\"classes\":\"tsd-kind-module\"},{\"id\":64,\"kind\":64,\"name\":\"middleware\",\"url\":\"modules/framework_loopback.html#middleware\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":65,\"kind\":64,\"name\":\"wrapRequest\",\"url\":\"modules/framework_loopback.html#wrapRequest\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":66,\"kind\":64,\"name\":\"wrapResponse\",\"url\":\"modules/framework_loopback.html#wrapResponse\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":67,\"kind\":2,\"name\":\"ingredients/emaildelivery\",\"url\":\"modules/ingredients_emaildelivery.html\",\"classes\":\"tsd-kind-module\"},{\"id\":68,\"kind\":128,\"name\":\"default\",\"url\":\"classes/ingredients_emaildelivery.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"ingredients/emaildelivery\"},{\"id\":69,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/ingredients_emaildelivery.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"ingredients/emaildelivery.default\"},{\"id\":70,\"kind\":1024,\"name\":\"ingredientInterfaceImpl\",\"url\":\"classes/ingredients_emaildelivery.default.html#ingredientInterfaceImpl\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"ingredients/emaildelivery.default\"},{\"id\":71,\"kind\":2,\"name\":\"ingredients/smsdelivery\",\"url\":\"modules/ingredients_smsdelivery.html\",\"classes\":\"tsd-kind-module\"},{\"id\":72,\"kind\":128,\"name\":\"default\",\"url\":\"classes/ingredients_smsdelivery.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"ingredients/smsdelivery\"},{\"id\":73,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/ingredients_smsdelivery.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"ingredients/smsdelivery.default\"},{\"id\":74,\"kind\":1024,\"name\":\"ingredientInterfaceImpl\",\"url\":\"classes/ingredients_smsdelivery.default.html#ingredientInterfaceImpl\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"ingredients/smsdelivery.default\"},{\"id\":75,\"kind\":2,\"name\":\"recipe/dashboard\",\"url\":\"modules/recipe_dashboard.html\",\"classes\":\"tsd-kind-module\"},{\"id\":76,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_dashboard.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":77,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_dashboard.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":78,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_dashboard.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/dashboard.default\"},{\"id\":79,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_dashboard.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/dashboard.default\"},{\"id\":80,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_dashboard.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/dashboard.default\"},{\"id\":81,\"kind\":2,\"name\":\"recipe/emailpassword\",\"url\":\"modules/recipe_emailpassword.html\",\"classes\":\"tsd-kind-module\"},{\"id\":82,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_emailpassword.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":83,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_emailpassword.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":84,\"kind\":64,\"name\":\"signUp\",\"url\":\"modules/recipe_emailpassword.html#signUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":85,\"kind\":64,\"name\":\"signIn\",\"url\":\"modules/recipe_emailpassword.html#signIn-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":86,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_emailpassword.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":87,\"kind\":64,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_emailpassword.html#getUserByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":88,\"kind\":64,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_emailpassword.html#createResetPasswordToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":89,\"kind\":64,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_emailpassword.html#resetPasswordUsingToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":90,\"kind\":64,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_emailpassword.html#updateEmailOrPassword-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":91,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_emailpassword.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":92,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_emailpassword.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":93,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_emailpassword.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":94,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_emailpassword.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":95,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_emailpassword.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":96,\"kind\":2048,\"name\":\"signUp\",\"url\":\"classes/recipe_emailpassword.default.html#signUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":97,\"kind\":2048,\"name\":\"signIn\",\"url\":\"classes/recipe_emailpassword.default.html#signIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":98,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_emailpassword.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":99,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"classes/recipe_emailpassword.default.html#getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":100,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"classes/recipe_emailpassword.default.html#createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":101,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"classes/recipe_emailpassword.default.html#resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":102,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"classes/recipe_emailpassword.default.html#updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":103,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_emailpassword.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":104,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_emailpassword.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/emailpassword.default\"},{\"id\":105,\"kind\":2,\"name\":\"recipe/emailverification\",\"url\":\"modules/recipe_emailverification.html\",\"classes\":\"tsd-kind-module\"},{\"id\":106,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_emailverification.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":107,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_emailverification.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":108,\"kind\":64,\"name\":\"createEmailVerificationToken\",\"url\":\"modules/recipe_emailverification.html#createEmailVerificationToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":109,\"kind\":64,\"name\":\"verifyEmailUsingToken\",\"url\":\"modules/recipe_emailverification.html#verifyEmailUsingToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":110,\"kind\":64,\"name\":\"isEmailVerified\",\"url\":\"modules/recipe_emailverification.html#isEmailVerified-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":111,\"kind\":64,\"name\":\"revokeEmailVerificationTokens\",\"url\":\"modules/recipe_emailverification.html#revokeEmailVerificationTokens-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":112,\"kind\":64,\"name\":\"unverifyEmail\",\"url\":\"modules/recipe_emailverification.html#unverifyEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":113,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_emailverification.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":114,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_emailverification.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":115,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_emailverification.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":116,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_emailverification.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/emailverification.default\"},{\"id\":117,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_emailverification.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":118,\"kind\":1024,\"name\":\"EmailVerificationClaim\",\"url\":\"classes/recipe_emailverification.default.html#EmailVerificationClaim\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":119,\"kind\":2048,\"name\":\"createEmailVerificationToken\",\"url\":\"classes/recipe_emailverification.default.html#createEmailVerificationToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":120,\"kind\":2048,\"name\":\"verifyEmailUsingToken\",\"url\":\"classes/recipe_emailverification.default.html#verifyEmailUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":121,\"kind\":2048,\"name\":\"isEmailVerified\",\"url\":\"classes/recipe_emailverification.default.html#isEmailVerified\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":122,\"kind\":2048,\"name\":\"revokeEmailVerificationTokens\",\"url\":\"classes/recipe_emailverification.default.html#revokeEmailVerificationTokens\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":123,\"kind\":2048,\"name\":\"unverifyEmail\",\"url\":\"classes/recipe_emailverification.default.html#unverifyEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":124,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_emailverification.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/emailverification.default\"},{\"id\":125,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_emailverification.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/emailverification.default\"},{\"id\":126,\"kind\":2,\"name\":\"recipe/jwt\",\"url\":\"modules/recipe_jwt.html\",\"classes\":\"tsd-kind-module\"},{\"id\":127,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_jwt.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":128,\"kind\":64,\"name\":\"createJWT\",\"url\":\"modules/recipe_jwt.html#createJWT-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":129,\"kind\":64,\"name\":\"getJWKS\",\"url\":\"modules/recipe_jwt.html#getJWKS-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":130,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_jwt.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":131,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_jwt.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/jwt.default\"},{\"id\":132,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_jwt.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/jwt.default\"},{\"id\":133,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"classes/recipe_jwt.default.html#createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/jwt.default\"},{\"id\":134,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"classes/recipe_jwt.default.html#getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/jwt.default\"},{\"id\":135,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_jwt.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/jwt.default\"},{\"id\":136,\"kind\":2,\"name\":\"recipe/openid\",\"url\":\"modules/recipe_openid.html\",\"classes\":\"tsd-kind-module\"},{\"id\":137,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_openid.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":138,\"kind\":64,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"modules/recipe_openid.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":139,\"kind\":64,\"name\":\"createJWT\",\"url\":\"modules/recipe_openid.html#createJWT\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":140,\"kind\":64,\"name\":\"getJWKS\",\"url\":\"modules/recipe_openid.html#getJWKS\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":141,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_openid.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/openid\"},{\"id\":142,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_openid.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":143,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_openid.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/openid.default\"},{\"id\":144,\"kind\":2048,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"classes/recipe_openid.default.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":145,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"classes/recipe_openid.default.html#createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":146,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"classes/recipe_openid.default.html#getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/openid.default\"},{\"id\":147,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_openid.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/openid.default\"},{\"id\":148,\"kind\":2,\"name\":\"recipe/passwordless\",\"url\":\"modules/recipe_passwordless.html\",\"classes\":\"tsd-kind-module\"},{\"id\":149,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_passwordless.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":150,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_passwordless.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":151,\"kind\":64,\"name\":\"createCode\",\"url\":\"modules/recipe_passwordless.html#createCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":152,\"kind\":64,\"name\":\"consumeCode\",\"url\":\"modules/recipe_passwordless.html#consumeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":153,\"kind\":64,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_passwordless.html#getUserByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":154,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_passwordless.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":155,\"kind\":64,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#getUserByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":156,\"kind\":64,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_passwordless.html#listCodesByDeviceId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":157,\"kind\":64,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_passwordless.html#listCodesByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":158,\"kind\":64,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#listCodesByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":159,\"kind\":64,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_passwordless.html#listCodesByPreAuthSessionId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":160,\"kind\":64,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_passwordless.html#createNewCodeForDevice-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":161,\"kind\":64,\"name\":\"updateUser\",\"url\":\"modules/recipe_passwordless.html#updateUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":162,\"kind\":64,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_passwordless.html#revokeAllCodes-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":163,\"kind\":64,\"name\":\"revokeCode\",\"url\":\"modules/recipe_passwordless.html#revokeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":164,\"kind\":64,\"name\":\"createMagicLink\",\"url\":\"modules/recipe_passwordless.html#createMagicLink\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":165,\"kind\":64,\"name\":\"signInUp\",\"url\":\"modules/recipe_passwordless.html#signInUp\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":166,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_passwordless.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":167,\"kind\":64,\"name\":\"sendSms\",\"url\":\"modules/recipe_passwordless.html#sendSms\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":168,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_passwordless.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":169,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_passwordless.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":170,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_passwordless.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/passwordless.default\"},{\"id\":171,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_passwordless.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":172,\"kind\":2048,\"name\":\"createCode\",\"url\":\"classes/recipe_passwordless.default.html#createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":173,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"classes/recipe_passwordless.default.html#createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":174,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"classes/recipe_passwordless.default.html#consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":175,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_passwordless.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":176,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"classes/recipe_passwordless.default.html#getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":177,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"classes/recipe_passwordless.default.html#getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":178,\"kind\":2048,\"name\":\"updateUser\",\"url\":\"classes/recipe_passwordless.default.html#updateUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":179,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"classes/recipe_passwordless.default.html#revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":180,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"classes/recipe_passwordless.default.html#revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":181,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":182,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":183,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":184,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"classes/recipe_passwordless.default.html#listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":185,\"kind\":2048,\"name\":\"createMagicLink\",\"url\":\"classes/recipe_passwordless.default.html#createMagicLink\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":186,\"kind\":2048,\"name\":\"signInUp\",\"url\":\"classes/recipe_passwordless.default.html#signInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":187,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_passwordless.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":188,\"kind\":2048,\"name\":\"sendSms\",\"url\":\"classes/recipe_passwordless.default.html#sendSms\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/passwordless.default\"},{\"id\":189,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_passwordless.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/passwordless.default\"},{\"id\":190,\"kind\":2,\"name\":\"recipe/session\",\"url\":\"modules/recipe_session.html\",\"classes\":\"tsd-kind-module\"},{\"id\":191,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_session.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":192,\"kind\":64,\"name\":\"createNewSession\",\"url\":\"modules/recipe_session.html#createNewSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":193,\"kind\":64,\"name\":\"getSession\",\"url\":\"modules/recipe_session.html#getSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":194,\"kind\":64,\"name\":\"getSessionInformation\",\"url\":\"modules/recipe_session.html#getSessionInformation-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":195,\"kind\":64,\"name\":\"refreshSession\",\"url\":\"modules/recipe_session.html#refreshSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":196,\"kind\":64,\"name\":\"revokeAllSessionsForUser\",\"url\":\"modules/recipe_session.html#revokeAllSessionsForUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":197,\"kind\":64,\"name\":\"getAllSessionHandlesForUser\",\"url\":\"modules/recipe_session.html#getAllSessionHandlesForUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":198,\"kind\":64,\"name\":\"revokeSession\",\"url\":\"modules/recipe_session.html#revokeSession-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":199,\"kind\":64,\"name\":\"revokeMultipleSessions\",\"url\":\"modules/recipe_session.html#revokeMultipleSessions-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":200,\"kind\":64,\"name\":\"updateSessionData\",\"url\":\"modules/recipe_session.html#updateSessionData-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":201,\"kind\":64,\"name\":\"updateAccessTokenPayload\",\"url\":\"modules/recipe_session.html#updateAccessTokenPayload-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":202,\"kind\":64,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"modules/recipe_session.html#mergeIntoAccessTokenPayload-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":203,\"kind\":64,\"name\":\"fetchAndSetClaim\",\"url\":\"modules/recipe_session.html#fetchAndSetClaim-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":204,\"kind\":64,\"name\":\"setClaimValue\",\"url\":\"modules/recipe_session.html#setClaimValue-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"recipe/session\"},{\"id\":205,\"kind\":64,\"name\":\"getClaimValue\",\"url\":\"modules/recipe_session.html#getClaimValue-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module tsd-has-type-parameter\",\"parent\":\"recipe/session\"},{\"id\":206,\"kind\":64,\"name\":\"removeClaim\",\"url\":\"modules/recipe_session.html#removeClaim-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":207,\"kind\":64,\"name\":\"validateClaimsInJWTPayload\",\"url\":\"modules/recipe_session.html#validateClaimsInJWTPayload-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":208,\"kind\":64,\"name\":\"validateClaimsForSessionHandle\",\"url\":\"modules/recipe_session.html#validateClaimsForSessionHandle\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":209,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_session.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":210,\"kind\":64,\"name\":\"createJWT\",\"url\":\"modules/recipe_session.html#createJWT\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":211,\"kind\":64,\"name\":\"getJWKS\",\"url\":\"modules/recipe_session.html#getJWKS\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":212,\"kind\":64,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"modules/recipe_session.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":213,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_session.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":214,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_session.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":215,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_session.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/session.default\"},{\"id\":216,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_session.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":217,\"kind\":2048,\"name\":\"createNewSession\",\"url\":\"classes/recipe_session.default.html#createNewSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":218,\"kind\":2048,\"name\":\"validateClaimsForSessionHandle\",\"url\":\"classes/recipe_session.default.html#validateClaimsForSessionHandle\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":219,\"kind\":2048,\"name\":\"validateClaimsInJWTPayload\",\"url\":\"classes/recipe_session.default.html#validateClaimsInJWTPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":220,\"kind\":2048,\"name\":\"getSession\",\"url\":\"classes/recipe_session.default.html#getSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":221,\"kind\":2048,\"name\":\"getSessionInformation\",\"url\":\"classes/recipe_session.default.html#getSessionInformation\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":222,\"kind\":2048,\"name\":\"refreshSession\",\"url\":\"classes/recipe_session.default.html#refreshSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":223,\"kind\":2048,\"name\":\"revokeAllSessionsForUser\",\"url\":\"classes/recipe_session.default.html#revokeAllSessionsForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":224,\"kind\":2048,\"name\":\"getAllSessionHandlesForUser\",\"url\":\"classes/recipe_session.default.html#getAllSessionHandlesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":225,\"kind\":2048,\"name\":\"revokeSession\",\"url\":\"classes/recipe_session.default.html#revokeSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":226,\"kind\":2048,\"name\":\"revokeMultipleSessions\",\"url\":\"classes/recipe_session.default.html#revokeMultipleSessions\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":227,\"kind\":2048,\"name\":\"updateSessionData\",\"url\":\"classes/recipe_session.default.html#updateSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":228,\"kind\":2048,\"name\":\"regenerateAccessToken\",\"url\":\"classes/recipe_session.default.html#regenerateAccessToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":229,\"kind\":2048,\"name\":\"updateAccessTokenPayload\",\"url\":\"classes/recipe_session.default.html#updateAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":230,\"kind\":2048,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"classes/recipe_session.default.html#mergeIntoAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":231,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"classes/recipe_session.default.html#createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":232,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"classes/recipe_session.default.html#getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":233,\"kind\":2048,\"name\":\"getOpenIdDiscoveryConfiguration\",\"url\":\"classes/recipe_session.default.html#getOpenIdDiscoveryConfiguration\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":234,\"kind\":2048,\"name\":\"fetchAndSetClaim\",\"url\":\"classes/recipe_session.default.html#fetchAndSetClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":235,\"kind\":2048,\"name\":\"setClaimValue\",\"url\":\"classes/recipe_session.default.html#setClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":236,\"kind\":2048,\"name\":\"getClaimValue\",\"url\":\"classes/recipe_session.default.html#getClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":237,\"kind\":2048,\"name\":\"removeClaim\",\"url\":\"classes/recipe_session.default.html#removeClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/session.default\"},{\"id\":238,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_session.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/session.default\"},{\"id\":239,\"kind\":2,\"name\":\"recipe/thirdparty\",\"url\":\"modules/recipe_thirdparty.html\",\"classes\":\"tsd-kind-module\"},{\"id\":240,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_thirdparty.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":241,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_thirdparty.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":242,\"kind\":64,\"name\":\"signInUp\",\"url\":\"modules/recipe_thirdparty.html#signInUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":243,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdparty.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":244,\"kind\":64,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdparty.html#getUsersByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":245,\"kind\":64,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdparty.html#getUserByThirdPartyInfo-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":246,\"kind\":64,\"name\":\"Google\",\"url\":\"modules/recipe_thirdparty.html#Google\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":247,\"kind\":64,\"name\":\"Github\",\"url\":\"modules/recipe_thirdparty.html#Github\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":248,\"kind\":64,\"name\":\"Facebook\",\"url\":\"modules/recipe_thirdparty.html#Facebook\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":249,\"kind\":64,\"name\":\"Apple\",\"url\":\"modules/recipe_thirdparty.html#Apple\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":250,\"kind\":64,\"name\":\"Discord\",\"url\":\"modules/recipe_thirdparty.html#Discord\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":251,\"kind\":64,\"name\":\"GoogleWorkspaces\",\"url\":\"modules/recipe_thirdparty.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":252,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_thirdparty.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":253,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_thirdparty.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":254,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":255,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_thirdparty.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":256,\"kind\":2048,\"name\":\"signInUp\",\"url\":\"classes/recipe_thirdparty.default.html#signInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":257,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_thirdparty.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":258,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"classes/recipe_thirdparty.default.html#getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":259,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"classes/recipe_thirdparty.default.html#getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":260,\"kind\":1024,\"name\":\"Google\",\"url\":\"classes/recipe_thirdparty.default.html#Google\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":261,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":262,\"kind\":1024,\"name\":\"Github\",\"url\":\"classes/recipe_thirdparty.default.html#Github\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":263,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":264,\"kind\":1024,\"name\":\"Facebook\",\"url\":\"classes/recipe_thirdparty.default.html#Facebook\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":265,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":266,\"kind\":1024,\"name\":\"Apple\",\"url\":\"classes/recipe_thirdparty.default.html#Apple\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":267,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":268,\"kind\":1024,\"name\":\"Discord\",\"url\":\"classes/recipe_thirdparty.default.html#Discord\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":269,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":270,\"kind\":1024,\"name\":\"GoogleWorkspaces\",\"url\":\"classes/recipe_thirdparty.default.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":271,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdparty.default.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":272,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_thirdparty.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/thirdparty.default\"},{\"id\":273,\"kind\":2,\"name\":\"recipe/thirdpartyemailpassword\",\"url\":\"modules/recipe_thirdpartyemailpassword.html\",\"classes\":\"tsd-kind-module\"},{\"id\":274,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":275,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":276,\"kind\":64,\"name\":\"emailPasswordSignUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#emailPasswordSignUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":277,\"kind\":64,\"name\":\"emailPasswordSignIn\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#emailPasswordSignIn-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":278,\"kind\":64,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#thirdPartySignInUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":279,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":280,\"kind\":64,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#getUserByThirdPartyInfo-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":281,\"kind\":64,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#getUsersByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":282,\"kind\":64,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#createResetPasswordToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":283,\"kind\":64,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#resetPasswordUsingToken-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":284,\"kind\":64,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#updateEmailOrPassword-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":285,\"kind\":64,\"name\":\"Google\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Google\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":286,\"kind\":64,\"name\":\"Github\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Github\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":287,\"kind\":64,\"name\":\"Facebook\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Facebook\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":288,\"kind\":64,\"name\":\"Apple\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Apple\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":289,\"kind\":64,\"name\":\"Discord\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#Discord\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":290,\"kind\":64,\"name\":\"GoogleWorkspaces\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":291,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":292,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":293,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":294,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":295,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":296,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":297,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":298,\"kind\":2048,\"name\":\"emailPasswordSignUp\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#emailPasswordSignUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":299,\"kind\":2048,\"name\":\"emailPasswordSignIn\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#emailPasswordSignIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":300,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":301,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":302,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":303,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":304,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":305,\"kind\":1024,\"name\":\"Google\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Google\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":306,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":307,\"kind\":1024,\"name\":\"Github\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Github\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":308,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":309,\"kind\":1024,\"name\":\"Facebook\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Facebook\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":310,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":311,\"kind\":1024,\"name\":\"Apple\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Apple\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":312,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":313,\"kind\":1024,\"name\":\"Discord\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#Discord\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":314,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":315,\"kind\":1024,\"name\":\"GoogleWorkspaces\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":316,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":317,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":318,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_thirdpartyemailpassword.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartyemailpassword.default\"},{\"id\":319,\"kind\":2,\"name\":\"recipe/thirdpartypasswordless\",\"url\":\"modules/recipe_thirdpartypasswordless.html\",\"classes\":\"tsd-kind-module\"},{\"id\":320,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_thirdpartypasswordless.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":321,\"kind\":32,\"name\":\"Error\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Error\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":322,\"kind\":64,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartypasswordless.html#thirdPartySignInUp-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":323,\"kind\":64,\"name\":\"passwordlessSignInUp\",\"url\":\"modules/recipe_thirdpartypasswordless.html#passwordlessSignInUp\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":324,\"kind\":64,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUserById-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":325,\"kind\":64,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUserByThirdPartyInfo-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":326,\"kind\":64,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUsersByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":327,\"kind\":64,\"name\":\"createCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#createCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":328,\"kind\":64,\"name\":\"consumeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#consumeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":329,\"kind\":64,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#getUserByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":330,\"kind\":64,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByDeviceId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":331,\"kind\":64,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByEmail-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":332,\"kind\":64,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByPhoneNumber-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":333,\"kind\":64,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#listCodesByPreAuthSessionId-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":334,\"kind\":64,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_thirdpartypasswordless.html#createNewCodeForDevice-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":335,\"kind\":64,\"name\":\"updatePasswordlessUser\",\"url\":\"modules/recipe_thirdpartypasswordless.html#updatePasswordlessUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":336,\"kind\":64,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_thirdpartypasswordless.html#revokeAllCodes-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":337,\"kind\":64,\"name\":\"revokeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#revokeCode-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":338,\"kind\":64,\"name\":\"createMagicLink\",\"url\":\"modules/recipe_thirdpartypasswordless.html#createMagicLink\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":339,\"kind\":64,\"name\":\"Google\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Google\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":340,\"kind\":64,\"name\":\"Github\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Github\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":341,\"kind\":64,\"name\":\"Facebook\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Facebook\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":342,\"kind\":64,\"name\":\"Apple\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Apple\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":343,\"kind\":64,\"name\":\"Discord\",\"url\":\"modules/recipe_thirdpartypasswordless.html#Discord\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":344,\"kind\":64,\"name\":\"GoogleWorkspaces\",\"url\":\"modules/recipe_thirdpartypasswordless.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":345,\"kind\":64,\"name\":\"sendEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#sendEmail\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":346,\"kind\":64,\"name\":\"sendSms\",\"url\":\"modules/recipe_thirdpartypasswordless.html#sendSms\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":347,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":348,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":349,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":350,\"kind\":1024,\"name\":\"Error\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Error\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":351,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":352,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":353,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":354,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":355,\"kind\":2048,\"name\":\"createCode\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":356,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":357,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":358,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":359,\"kind\":2048,\"name\":\"updatePasswordlessUser\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#updatePasswordlessUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":360,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":361,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":362,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":363,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":364,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":365,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":366,\"kind\":2048,\"name\":\"createMagicLink\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#createMagicLink\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":367,\"kind\":2048,\"name\":\"passwordlessSignInUp\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#passwordlessSignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":368,\"kind\":1024,\"name\":\"Google\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Google\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":369,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":370,\"kind\":1024,\"name\":\"Github\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Github\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":371,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":372,\"kind\":1024,\"name\":\"Facebook\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Facebook\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":373,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":374,\"kind\":1024,\"name\":\"Apple\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Apple\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":375,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":376,\"kind\":1024,\"name\":\"Discord\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#Discord\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":377,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":378,\"kind\":1024,\"name\":\"GoogleWorkspaces\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#GoogleWorkspaces\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":379,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":380,\"kind\":2048,\"name\":\"sendEmail\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#sendEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":381,\"kind\":2048,\"name\":\"sendSms\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#sendSms\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":382,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_thirdpartypasswordless.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/thirdpartypasswordless.default\"},{\"id\":383,\"kind\":2,\"name\":\"recipe/usermetadata\",\"url\":\"modules/recipe_usermetadata.html\",\"classes\":\"tsd-kind-module\"},{\"id\":384,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_usermetadata.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":385,\"kind\":64,\"name\":\"getUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#getUserMetadata-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":386,\"kind\":64,\"name\":\"updateUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#updateUserMetadata-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":387,\"kind\":64,\"name\":\"clearUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#clearUserMetadata-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":388,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_usermetadata.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":389,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_usermetadata.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":390,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_usermetadata.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":391,\"kind\":2048,\"name\":\"getUserMetadata\",\"url\":\"classes/recipe_usermetadata.default.html#getUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":392,\"kind\":2048,\"name\":\"updateUserMetadata\",\"url\":\"classes/recipe_usermetadata.default.html#updateUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":393,\"kind\":2048,\"name\":\"clearUserMetadata\",\"url\":\"classes/recipe_usermetadata.default.html#clearUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":394,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_usermetadata.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/usermetadata.default\"},{\"id\":395,\"kind\":2,\"name\":\"recipe/userroles\",\"url\":\"modules/recipe_userroles.html\",\"classes\":\"tsd-kind-module\"},{\"id\":396,\"kind\":64,\"name\":\"init\",\"url\":\"modules/recipe_userroles.html#init\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":397,\"kind\":64,\"name\":\"addRoleToUser\",\"url\":\"modules/recipe_userroles.html#addRoleToUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":398,\"kind\":64,\"name\":\"removeUserRole\",\"url\":\"modules/recipe_userroles.html#removeUserRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":399,\"kind\":64,\"name\":\"getRolesForUser\",\"url\":\"modules/recipe_userroles.html#getRolesForUser-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":400,\"kind\":64,\"name\":\"getUsersThatHaveRole\",\"url\":\"modules/recipe_userroles.html#getUsersThatHaveRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":401,\"kind\":64,\"name\":\"createNewRoleOrAddPermissions\",\"url\":\"modules/recipe_userroles.html#createNewRoleOrAddPermissions-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":402,\"kind\":64,\"name\":\"getPermissionsForRole\",\"url\":\"modules/recipe_userroles.html#getPermissionsForRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":403,\"kind\":64,\"name\":\"removePermissionsFromRole\",\"url\":\"modules/recipe_userroles.html#removePermissionsFromRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":404,\"kind\":64,\"name\":\"getRolesThatHavePermission\",\"url\":\"modules/recipe_userroles.html#getRolesThatHavePermission-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":405,\"kind\":64,\"name\":\"deleteRole\",\"url\":\"modules/recipe_userroles.html#deleteRole-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":406,\"kind\":64,\"name\":\"getAllRoles\",\"url\":\"modules/recipe_userroles.html#getAllRoles-1\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":407,\"kind\":128,\"name\":\"default\",\"url\":\"classes/recipe_userroles.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":408,\"kind\":1024,\"name\":\"init\",\"url\":\"classes/recipe_userroles.default.html#init\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":409,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/recipe_userroles.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"recipe/userroles.default\"},{\"id\":410,\"kind\":1024,\"name\":\"PermissionClaim\",\"url\":\"classes/recipe_userroles.default.html#PermissionClaim\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":411,\"kind\":1024,\"name\":\"UserRoleClaim\",\"url\":\"classes/recipe_userroles.default.html#UserRoleClaim\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":412,\"kind\":2048,\"name\":\"addRoleToUser\",\"url\":\"classes/recipe_userroles.default.html#addRoleToUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":413,\"kind\":2048,\"name\":\"removeUserRole\",\"url\":\"classes/recipe_userroles.default.html#removeUserRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":414,\"kind\":2048,\"name\":\"getRolesForUser\",\"url\":\"classes/recipe_userroles.default.html#getRolesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":415,\"kind\":2048,\"name\":\"getUsersThatHaveRole\",\"url\":\"classes/recipe_userroles.default.html#getUsersThatHaveRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":416,\"kind\":2048,\"name\":\"createNewRoleOrAddPermissions\",\"url\":\"classes/recipe_userroles.default.html#createNewRoleOrAddPermissions\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":417,\"kind\":2048,\"name\":\"getPermissionsForRole\",\"url\":\"classes/recipe_userroles.default.html#getPermissionsForRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":418,\"kind\":2048,\"name\":\"removePermissionsFromRole\",\"url\":\"classes/recipe_userroles.default.html#removePermissionsFromRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":419,\"kind\":2048,\"name\":\"getRolesThatHavePermission\",\"url\":\"classes/recipe_userroles.default.html#getRolesThatHavePermission\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":420,\"kind\":2048,\"name\":\"deleteRole\",\"url\":\"classes/recipe_userroles.default.html#deleteRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":421,\"kind\":2048,\"name\":\"getAllRoles\",\"url\":\"classes/recipe_userroles.default.html#getAllRoles\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-static\",\"parent\":\"recipe/userroles.default\"},{\"id\":422,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/recipe_userroles.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"recipe/userroles.default\"},{\"id\":423,\"kind\":128,\"name\":\"BaseRequest\",\"url\":\"classes/framework.BaseRequest.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":424,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/framework.BaseRequest.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":425,\"kind\":1024,\"name\":\"wrapperUsed\",\"url\":\"classes/framework.BaseRequest.html#wrapperUsed\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":426,\"kind\":1024,\"name\":\"original\",\"url\":\"classes/framework.BaseRequest.html#original\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":427,\"kind\":1024,\"name\":\"getKeyValueFromQuery\",\"url\":\"classes/framework.BaseRequest.html#getKeyValueFromQuery\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":428,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":429,\"kind\":1024,\"name\":\"getJSONBody\",\"url\":\"classes/framework.BaseRequest.html#getJSONBody\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":430,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":431,\"kind\":1024,\"name\":\"getMethod\",\"url\":\"classes/framework.BaseRequest.html#getMethod\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":432,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":433,\"kind\":1024,\"name\":\"getCookieValue\",\"url\":\"classes/framework.BaseRequest.html#getCookieValue\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":434,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":435,\"kind\":1024,\"name\":\"getHeaderValue\",\"url\":\"classes/framework.BaseRequest.html#getHeaderValue\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":436,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":437,\"kind\":1024,\"name\":\"getOriginalURL\",\"url\":\"classes/framework.BaseRequest.html#getOriginalURL\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":438,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":439,\"kind\":1024,\"name\":\"getFormData\",\"url\":\"classes/framework.BaseRequest.html#getFormData\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":440,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseRequest.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseRequest\"},{\"id\":441,\"kind\":128,\"name\":\"BaseResponse\",\"url\":\"classes/framework.BaseResponse.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"framework\"},{\"id\":442,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/framework.BaseResponse.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":443,\"kind\":1024,\"name\":\"wrapperUsed\",\"url\":\"classes/framework.BaseResponse.html#wrapperUsed\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":444,\"kind\":1024,\"name\":\"original\",\"url\":\"classes/framework.BaseResponse.html#original\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":445,\"kind\":1024,\"name\":\"setHeader\",\"url\":\"classes/framework.BaseResponse.html#setHeader\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":446,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":447,\"kind\":1024,\"name\":\"removeHeader\",\"url\":\"classes/framework.BaseResponse.html#removeHeader\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":448,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":449,\"kind\":1024,\"name\":\"setCookie\",\"url\":\"classes/framework.BaseResponse.html#setCookie\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":450,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":451,\"kind\":1024,\"name\":\"setStatusCode\",\"url\":\"classes/framework.BaseResponse.html#setStatusCode\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":452,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":453,\"kind\":1024,\"name\":\"sendJSONResponse\",\"url\":\"classes/framework.BaseResponse.html#sendJSONResponse\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":454,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":455,\"kind\":1024,\"name\":\"sendHTMLResponse\",\"url\":\"classes/framework.BaseResponse.html#sendHTMLResponse\",\"classes\":\"tsd-kind-property tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":456,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/framework.BaseResponse.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"framework.BaseResponse\"},{\"id\":457,\"kind\":256,\"name\":\"SessionEvent\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":458,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEvent\"},{\"id\":459,\"kind\":1024,\"name\":\"supertokens\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#supertokens\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited\",\"parent\":\"framework/awsLambda.SessionEvent\"},{\"id\":460,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEvent\"},{\"id\":461,\"kind\":1024,\"name\":\"response\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.response\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type\"},{\"id\":462,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type\"},{\"id\":463,\"kind\":1024,\"name\":\"headers\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.__type-1.headers-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type.__type\"},{\"id\":464,\"kind\":1024,\"name\":\"cookies\",\"url\":\"interfaces/framework_awsLambda.SessionEvent.html#__type.__type-1.cookies\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEvent.__type.__type\"},{\"id\":465,\"kind\":256,\"name\":\"SessionEventV2\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/awsLambda\"},{\"id\":466,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":467,\"kind\":1024,\"name\":\"supertokens\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#supertokens\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":468,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":469,\"kind\":1024,\"name\":\"response\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.response\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":470,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.__type-6\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":471,\"kind\":1024,\"name\":\"headers\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.__type-6.headers-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type\"},{\"id\":472,\"kind\":1024,\"name\":\"cookies\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type-5.__type-6.cookies-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type\"},{\"id\":473,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/awsLambda.SessionEventV2\"},{\"id\":474,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":475,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-1.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type\"},{\"id\":476,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-1.__type-2.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type.__type.__type\"},{\"id\":477,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_awsLambda.SessionEventV2.html#__type.__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"framework/awsLambda.SessionEventV2.__type\"},{\"id\":478,\"kind\":256,\"name\":\"SessionRequest\",\"url\":\"interfaces/framework_express.SessionRequest.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/express\"},{\"id\":479,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_express.SessionRequest.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/express.SessionRequest\"},{\"id\":480,\"kind\":256,\"name\":\"SessionRequest\",\"url\":\"interfaces/framework_fastify.SessionRequest.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/fastify\"},{\"id\":481,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_fastify.SessionRequest.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/fastify.SessionRequest\"},{\"id\":482,\"kind\":256,\"name\":\"SessionRequest\",\"url\":\"interfaces/framework_hapi.SessionRequest.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/hapi\"},{\"id\":483,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_hapi.SessionRequest.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/hapi.SessionRequest\"},{\"id\":484,\"kind\":65536,\"name\":\"__type\",\"url\":\"interfaces/framework_hapi.SessionRequest.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-interface\",\"parent\":\"framework/hapi.SessionRequest\"},{\"id\":485,\"kind\":256,\"name\":\"SessionContext\",\"url\":\"interfaces/framework_koa.SessionContext.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/koa\"},{\"id\":486,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_koa.SessionContext.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/koa.SessionContext\"},{\"id\":487,\"kind\":256,\"name\":\"SessionContext\",\"url\":\"interfaces/framework_loopback.SessionContext.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"framework/loopback\"},{\"id\":488,\"kind\":1024,\"name\":\"session\",\"url\":\"interfaces/framework_loopback.SessionContext.html#session\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"framework/loopback.SessionContext\"},{\"id\":489,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":490,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/dashboard.RecipeInterface\"},{\"id\":491,\"kind\":2048,\"name\":\"getDashboardBundleLocation\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface.__type-2.getDashboardBundleLocation\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.RecipeInterface.__type\"},{\"id\":492,\"kind\":2048,\"name\":\"shouldAllowAccess\",\"url\":\"modules/recipe_dashboard.html#RecipeInterface.__type-2.shouldAllowAccess\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.RecipeInterface.__type\"},{\"id\":493,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_dashboard.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":494,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/dashboard.APIOptions\"},{\"id\":495,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":496,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":497,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":498,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":499,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":500,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":501,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_dashboard.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIOptions.__type\"},{\"id\":502,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_dashboard.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/dashboard\"},{\"id\":503,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_dashboard.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/dashboard.APIInterface\"},{\"id\":504,\"kind\":1024,\"name\":\"dashboardGET\",\"url\":\"modules/recipe_dashboard.html#APIInterface.__type.dashboardGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/dashboard.APIInterface.__type\"},{\"id\":505,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":506,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.RecipeInterface\"},{\"id\":507,\"kind\":2048,\"name\":\"signUp\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.signUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":508,\"kind\":2048,\"name\":\"signIn\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.signIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":509,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":510,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":511,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":512,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":513,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_emailpassword.html#RecipeInterface.__type-2.updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.RecipeInterface.__type\"},{\"id\":514,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_emailpassword.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":515,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.User\"},{\"id\":516,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.User.__type\"},{\"id\":517,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.User.__type\"},{\"id\":518,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_emailpassword.html#User.__type-3.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.User.__type\"},{\"id\":519,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_emailpassword.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":520,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.APIOptions\"},{\"id\":521,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":522,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":523,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":524,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":525,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":526,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":527,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":528,\"kind\":1024,\"name\":\"emailDelivery\",\"url\":\"modules/recipe_emailpassword.html#APIOptions.__type-1.emailDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIOptions.__type\"},{\"id\":529,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_emailpassword.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailpassword\"},{\"id\":530,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailpassword.APIInterface\"},{\"id\":531,\"kind\":1024,\"name\":\"emailExistsGET\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.emailExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":532,\"kind\":1024,\"name\":\"generatePasswordResetTokenPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.generatePasswordResetTokenPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":533,\"kind\":1024,\"name\":\"passwordResetPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.passwordResetPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":534,\"kind\":1024,\"name\":\"signInPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.signInPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":535,\"kind\":1024,\"name\":\"signUpPOST\",\"url\":\"modules/recipe_emailpassword.html#APIInterface.__type.signUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailpassword.APIInterface.__type\"},{\"id\":536,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":537,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.RecipeInterface\"},{\"id\":538,\"kind\":2048,\"name\":\"createEmailVerificationToken\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.createEmailVerificationToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":539,\"kind\":2048,\"name\":\"verifyEmailUsingToken\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.verifyEmailUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":540,\"kind\":2048,\"name\":\"isEmailVerified\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.isEmailVerified\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":541,\"kind\":2048,\"name\":\"revokeEmailVerificationTokens\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.revokeEmailVerificationTokens\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":542,\"kind\":2048,\"name\":\"unverifyEmail\",\"url\":\"modules/recipe_emailverification.html#RecipeInterface.__type-2.unverifyEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.RecipeInterface.__type\"},{\"id\":543,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_emailverification.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":544,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.APIOptions\"},{\"id\":545,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":546,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":547,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":548,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":549,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":550,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":551,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":552,\"kind\":1024,\"name\":\"emailDelivery\",\"url\":\"modules/recipe_emailverification.html#APIOptions.__type-1.emailDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIOptions.__type\"},{\"id\":553,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_emailverification.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":554,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.APIInterface\"},{\"id\":555,\"kind\":1024,\"name\":\"verifyEmailPOST\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type.verifyEmailPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIInterface.__type\"},{\"id\":556,\"kind\":1024,\"name\":\"isEmailVerifiedGET\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type.isEmailVerifiedGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIInterface.__type\"},{\"id\":557,\"kind\":1024,\"name\":\"generateEmailVerifyTokenPOST\",\"url\":\"modules/recipe_emailverification.html#APIInterface.__type.generateEmailVerifyTokenPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.APIInterface.__type\"},{\"id\":558,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_emailverification.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":559,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_emailverification.html#User.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/emailverification.User\"},{\"id\":560,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_emailverification.html#User.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.User.__type\"},{\"id\":561,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_emailverification.html#User.__type-3.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/emailverification.User.__type\"},{\"id\":562,\"kind\":32,\"name\":\"EmailVerificationClaim\",\"url\":\"modules/recipe_emailverification.html#EmailVerificationClaim\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/emailverification\"},{\"id\":563,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_jwt.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":564,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.APIInterface\"},{\"id\":565,\"kind\":1024,\"name\":\"getJWKSGET\",\"url\":\"modules/recipe_jwt.html#APIInterface.__type.getJWKSGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIInterface.__type\"},{\"id\":566,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_jwt.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":567,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.APIOptions\"},{\"id\":568,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":569,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":570,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":571,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":572,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":573,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_jwt.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.APIOptions.__type\"},{\"id\":574,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_jwt.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":575,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#RecipeInterface.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.RecipeInterface\"},{\"id\":576,\"kind\":2048,\"name\":\"createJWT\",\"url\":\"modules/recipe_jwt.html#RecipeInterface.__type-3.createJWT\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.RecipeInterface.__type\"},{\"id\":577,\"kind\":2048,\"name\":\"getJWKS\",\"url\":\"modules/recipe_jwt.html#RecipeInterface.__type-3.getJWKS\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.RecipeInterface.__type\"},{\"id\":578,\"kind\":4194304,\"name\":\"JsonWebKey\",\"url\":\"modules/recipe_jwt.html#JsonWebKey\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/jwt\"},{\"id\":579,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/jwt.JsonWebKey\"},{\"id\":580,\"kind\":1024,\"name\":\"kty\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.kty\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":581,\"kind\":1024,\"name\":\"kid\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.kid\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":582,\"kind\":1024,\"name\":\"n\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.n\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":583,\"kind\":1024,\"name\":\"e\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.e\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":584,\"kind\":1024,\"name\":\"alg\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.alg\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":585,\"kind\":1024,\"name\":\"use\",\"url\":\"modules/recipe_jwt.html#JsonWebKey.__type-2.use\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/jwt.JsonWebKey.__type\"},{\"id\":586,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":587,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.RecipeInterface\"},{\"id\":588,\"kind\":2048,\"name\":\"createCode\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":589,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":590,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":591,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":592,\"kind\":2048,\"name\":\"getUserByEmail\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.getUserByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":593,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":594,\"kind\":2048,\"name\":\"updateUser\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.updateUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":595,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":596,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":597,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":598,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":599,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":600,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_passwordless.html#RecipeInterface.__type-2.listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.RecipeInterface.__type\"},{\"id\":601,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_passwordless.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":602,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#User.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.User\"},{\"id\":603,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":604,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":605,\"kind\":1024,\"name\":\"phoneNumber\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.phoneNumber\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":606,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_passwordless.html#User.__type-3.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.User.__type\"},{\"id\":607,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_passwordless.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":608,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.APIOptions\"},{\"id\":609,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":610,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":611,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":612,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":613,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":614,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":615,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":616,\"kind\":1024,\"name\":\"emailDelivery\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.emailDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":617,\"kind\":1024,\"name\":\"smsDelivery\",\"url\":\"modules/recipe_passwordless.html#APIOptions.__type-1.smsDelivery\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIOptions.__type\"},{\"id\":618,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_passwordless.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/passwordless\"},{\"id\":619,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/passwordless.APIInterface\"},{\"id\":620,\"kind\":2048,\"name\":\"createCodePOST\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.createCodePOST\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":621,\"kind\":2048,\"name\":\"resendCodePOST\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.resendCodePOST\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":622,\"kind\":2048,\"name\":\"consumeCodePOST\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.consumeCodePOST\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":623,\"kind\":2048,\"name\":\"emailExistsGET\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.emailExistsGET\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":624,\"kind\":2048,\"name\":\"phoneNumberExistsGET\",\"url\":\"modules/recipe_passwordless.html#APIInterface.__type.phoneNumberExistsGET\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/passwordless.APIInterface.__type\"},{\"id\":625,\"kind\":256,\"name\":\"VerifySessionOptions\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":626,\"kind\":1024,\"name\":\"antiCsrfCheck\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html#antiCsrfCheck\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"recipe/session.VerifySessionOptions\"},{\"id\":627,\"kind\":1024,\"name\":\"sessionRequired\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html#sessionRequired\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"recipe/session.VerifySessionOptions\"},{\"id\":628,\"kind\":2048,\"name\":\"overrideGlobalClaimValidators\",\"url\":\"interfaces/recipe_session.VerifySessionOptions.html#overrideGlobalClaimValidators\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.VerifySessionOptions\"},{\"id\":629,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_session.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":630,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.RecipeInterface\"},{\"id\":631,\"kind\":2048,\"name\":\"createNewSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.createNewSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":632,\"kind\":2048,\"name\":\"getGlobalClaimValidators\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getGlobalClaimValidators\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":633,\"kind\":2048,\"name\":\"getSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":634,\"kind\":2048,\"name\":\"refreshSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.refreshSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":635,\"kind\":2048,\"name\":\"getSessionInformation\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getSessionInformation\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":636,\"kind\":2048,\"name\":\"revokeAllSessionsForUser\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.revokeAllSessionsForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":637,\"kind\":2048,\"name\":\"getAllSessionHandlesForUser\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getAllSessionHandlesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":638,\"kind\":2048,\"name\":\"revokeSession\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.revokeSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":639,\"kind\":2048,\"name\":\"revokeMultipleSessions\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.revokeMultipleSessions\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":640,\"kind\":2048,\"name\":\"updateSessionData\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.updateSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":641,\"kind\":2048,\"name\":\"updateAccessTokenPayload\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.updateAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":642,\"kind\":2048,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.mergeIntoAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":643,\"kind\":2048,\"name\":\"regenerateAccessToken\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.regenerateAccessToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":644,\"kind\":2048,\"name\":\"getAccessTokenLifeTimeMS\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getAccessTokenLifeTimeMS\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":645,\"kind\":2048,\"name\":\"getRefreshTokenLifeTimeMS\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getRefreshTokenLifeTimeMS\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":646,\"kind\":2048,\"name\":\"validateClaims\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.validateClaims\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":647,\"kind\":2048,\"name\":\"validateClaimsInJWTPayload\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.validateClaimsInJWTPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":648,\"kind\":2048,\"name\":\"fetchAndSetClaim\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.fetchAndSetClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":649,\"kind\":2048,\"name\":\"setClaimValue\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.setClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal tsd-has-type-parameter\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":650,\"kind\":2048,\"name\":\"getClaimValue\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.getClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal tsd-has-type-parameter\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":651,\"kind\":2048,\"name\":\"removeClaim\",\"url\":\"modules/recipe_session.html#RecipeInterface.__type-2.removeClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.RecipeInterface.__type\"},{\"id\":652,\"kind\":256,\"name\":\"SessionContainer\",\"url\":\"interfaces/recipe_session.SessionContainer.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":653,\"kind\":2048,\"name\":\"revokeSession\",\"url\":\"interfaces/recipe_session.SessionContainer.html#revokeSession\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":654,\"kind\":2048,\"name\":\"getSessionData\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":655,\"kind\":2048,\"name\":\"updateSessionData\",\"url\":\"interfaces/recipe_session.SessionContainer.html#updateSessionData\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":656,\"kind\":2048,\"name\":\"getUserId\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getUserId\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":657,\"kind\":2048,\"name\":\"getAccessTokenPayload\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":658,\"kind\":2048,\"name\":\"getHandle\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getHandle\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":659,\"kind\":2048,\"name\":\"getAccessToken\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getAccessToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":660,\"kind\":2048,\"name\":\"updateAccessTokenPayload\",\"url\":\"interfaces/recipe_session.SessionContainer.html#updateAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":661,\"kind\":2048,\"name\":\"mergeIntoAccessTokenPayload\",\"url\":\"interfaces/recipe_session.SessionContainer.html#mergeIntoAccessTokenPayload\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":662,\"kind\":2048,\"name\":\"getTimeCreated\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getTimeCreated\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":663,\"kind\":2048,\"name\":\"getExpiry\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getExpiry\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":664,\"kind\":2048,\"name\":\"assertClaims\",\"url\":\"interfaces/recipe_session.SessionContainer.html#assertClaims\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":665,\"kind\":2048,\"name\":\"fetchAndSetClaim\",\"url\":\"interfaces/recipe_session.SessionContainer.html#fetchAndSetClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface tsd-has-type-parameter\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":666,\"kind\":2048,\"name\":\"setClaimValue\",\"url\":\"interfaces/recipe_session.SessionContainer.html#setClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface tsd-has-type-parameter\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":667,\"kind\":2048,\"name\":\"getClaimValue\",\"url\":\"interfaces/recipe_session.SessionContainer.html#getClaimValue\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface tsd-has-type-parameter\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":668,\"kind\":2048,\"name\":\"removeClaim\",\"url\":\"interfaces/recipe_session.SessionContainer.html#removeClaim\",\"classes\":\"tsd-kind-method tsd-parent-kind-interface\",\"parent\":\"recipe/session.SessionContainer\"},{\"id\":669,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_session.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":670,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.APIInterface\"},{\"id\":671,\"kind\":1024,\"name\":\"refreshPOST\",\"url\":\"modules/recipe_session.html#APIInterface.__type.refreshPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIInterface.__type\"},{\"id\":672,\"kind\":1024,\"name\":\"signOutPOST\",\"url\":\"modules/recipe_session.html#APIInterface.__type.signOutPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIInterface.__type\"},{\"id\":673,\"kind\":2048,\"name\":\"verifySession\",\"url\":\"modules/recipe_session.html#APIInterface.__type.verifySession\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIInterface.__type\"},{\"id\":674,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_session.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":675,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.APIOptions\"},{\"id\":676,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":677,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":678,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":679,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":680,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":681,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_session.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.APIOptions.__type\"},{\"id\":682,\"kind\":4194304,\"name\":\"SessionInformation\",\"url\":\"modules/recipe_session.html#SessionInformation\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":683,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/session.SessionInformation\"},{\"id\":684,\"kind\":1024,\"name\":\"sessionHandle\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.sessionHandle\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":685,\"kind\":1024,\"name\":\"userId\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.userId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":686,\"kind\":1024,\"name\":\"sessionData\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.sessionData\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":687,\"kind\":1024,\"name\":\"expiry\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.expiry\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":688,\"kind\":1024,\"name\":\"accessTokenPayload\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.accessTokenPayload\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":689,\"kind\":1024,\"name\":\"timeCreated\",\"url\":\"modules/recipe_session.html#SessionInformation.__type-3.timeCreated\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/session.SessionInformation.__type\"},{\"id\":690,\"kind\":4194304,\"name\":\"SessionClaimValidator\",\"url\":\"modules/recipe_session.html#SessionClaimValidator\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/session\"},{\"id\":691,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":692,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.RecipeInterface\"},{\"id\":693,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":694,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":695,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":696,\"kind\":2048,\"name\":\"signInUp\",\"url\":\"modules/recipe_thirdparty.html#RecipeInterface.__type-2.signInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.RecipeInterface.__type\"},{\"id\":697,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_thirdparty.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":698,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.User\"},{\"id\":699,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.id-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":700,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":701,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":702,\"kind\":1024,\"name\":\"thirdParty\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.thirdParty\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":703,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.__type-5\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type\"},{\"id\":704,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.__type-5.id-2\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type.__type\"},{\"id\":705,\"kind\":1024,\"name\":\"userId\",\"url\":\"modules/recipe_thirdparty.html#User.__type-4.__type-5.userId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.User.__type.__type\"},{\"id\":706,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_thirdparty.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":707,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.APIInterface\"},{\"id\":708,\"kind\":1024,\"name\":\"authorisationUrlGET\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type.authorisationUrlGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIInterface.__type\"},{\"id\":709,\"kind\":1024,\"name\":\"signInUpPOST\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type.signInUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIInterface.__type\"},{\"id\":710,\"kind\":1024,\"name\":\"appleRedirectHandlerPOST\",\"url\":\"modules/recipe_thirdparty.html#APIInterface.__type.appleRedirectHandlerPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIInterface.__type\"},{\"id\":711,\"kind\":4194304,\"name\":\"APIOptions\",\"url\":\"modules/recipe_thirdparty.html#APIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":712,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.APIOptions\"},{\"id\":713,\"kind\":1024,\"name\":\"recipeImplementation\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.recipeImplementation\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":714,\"kind\":1024,\"name\":\"config\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.config\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":715,\"kind\":1024,\"name\":\"recipeId\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.recipeId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":716,\"kind\":1024,\"name\":\"isInServerlessEnv\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.isInServerlessEnv\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":717,\"kind\":1024,\"name\":\"providers\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.providers\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":718,\"kind\":1024,\"name\":\"req\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.req\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":719,\"kind\":1024,\"name\":\"res\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.res\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":720,\"kind\":1024,\"name\":\"appInfo\",\"url\":\"modules/recipe_thirdparty.html#APIOptions.__type-1.appInfo\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.APIOptions.__type\"},{\"id\":721,\"kind\":4194304,\"name\":\"TypeProvider\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdparty\"},{\"id\":722,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdparty.TypeProvider\"},{\"id\":723,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.TypeProvider.__type\"},{\"id\":724,\"kind\":2048,\"name\":\"get\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3.get\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.TypeProvider.__type\"},{\"id\":725,\"kind\":1024,\"name\":\"isDefault\",\"url\":\"modules/recipe_thirdparty.html#TypeProvider.__type-3.isDefault\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdparty.TypeProvider.__type\"},{\"id\":726,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":727,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface\"},{\"id\":728,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":729,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":730,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":731,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":732,\"kind\":2048,\"name\":\"emailPasswordSignUp\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.emailPasswordSignUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":733,\"kind\":2048,\"name\":\"emailPasswordSignIn\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.emailPasswordSignIn\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":734,\"kind\":2048,\"name\":\"createResetPasswordToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.createResetPasswordToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":735,\"kind\":2048,\"name\":\"resetPasswordUsingToken\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.resetPasswordUsingToken\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":736,\"kind\":2048,\"name\":\"updateEmailOrPassword\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#RecipeInterface.__type-1.updateEmailOrPassword\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.RecipeInterface.__type\"},{\"id\":737,\"kind\":16777216,\"name\":\"TypeProvider\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#TypeProvider\",\"classes\":\"tsd-kind-reference tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":738,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":739,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartyemailpassword.User\"},{\"id\":740,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.id\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":741,\"kind\":1024,\"name\":\"timeJoined\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.timeJoined\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":742,\"kind\":1024,\"name\":\"email\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.email\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":743,\"kind\":1024,\"name\":\"thirdParty\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.thirdParty\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":744,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.__type-3\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type\"},{\"id\":745,\"kind\":1024,\"name\":\"id\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.__type-3.id-1\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type.__type\"},{\"id\":746,\"kind\":1024,\"name\":\"userId\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#User.__type-2.__type-3.userId\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.User.__type.__type\"},{\"id\":747,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":748,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface\"},{\"id\":749,\"kind\":1024,\"name\":\"authorisationUrlGET\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.authorisationUrlGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":750,\"kind\":1024,\"name\":\"emailPasswordEmailExistsGET\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.emailPasswordEmailExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":751,\"kind\":1024,\"name\":\"generatePasswordResetTokenPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.generatePasswordResetTokenPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":752,\"kind\":1024,\"name\":\"passwordResetPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.passwordResetPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":753,\"kind\":1024,\"name\":\"thirdPartySignInUpPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.thirdPartySignInUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":754,\"kind\":1024,\"name\":\"emailPasswordSignInPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.emailPasswordSignInPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":755,\"kind\":1024,\"name\":\"emailPasswordSignUpPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.emailPasswordSignUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":756,\"kind\":1024,\"name\":\"appleRedirectHandlerPOST\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#APIInterface.__type.appleRedirectHandlerPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartyemailpassword.APIInterface.__type\"},{\"id\":757,\"kind\":4194304,\"name\":\"EmailPasswordAPIOptions\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#EmailPasswordAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":758,\"kind\":4194304,\"name\":\"ThirdPartyAPIOptions\",\"url\":\"modules/recipe_thirdpartyemailpassword.html#ThirdPartyAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartyemailpassword\"},{\"id\":759,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":760,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface\"},{\"id\":761,\"kind\":2048,\"name\":\"getUserById\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUserById\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":762,\"kind\":2048,\"name\":\"getUsersByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUsersByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":763,\"kind\":2048,\"name\":\"getUserByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUserByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":764,\"kind\":2048,\"name\":\"getUserByThirdPartyInfo\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.getUserByThirdPartyInfo\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":765,\"kind\":2048,\"name\":\"thirdPartySignInUp\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.thirdPartySignInUp\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":766,\"kind\":2048,\"name\":\"createCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.createCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":767,\"kind\":2048,\"name\":\"createNewCodeForDevice\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.createNewCodeForDevice\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":768,\"kind\":2048,\"name\":\"consumeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.consumeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":769,\"kind\":2048,\"name\":\"updatePasswordlessUser\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.updatePasswordlessUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":770,\"kind\":2048,\"name\":\"revokeAllCodes\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.revokeAllCodes\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":771,\"kind\":2048,\"name\":\"revokeCode\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.revokeCode\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":772,\"kind\":2048,\"name\":\"listCodesByEmail\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByEmail\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":773,\"kind\":2048,\"name\":\"listCodesByPhoneNumber\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByPhoneNumber\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":774,\"kind\":2048,\"name\":\"listCodesByDeviceId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByDeviceId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":775,\"kind\":2048,\"name\":\"listCodesByPreAuthSessionId\",\"url\":\"modules/recipe_thirdpartypasswordless.html#RecipeInterface.__type-1.listCodesByPreAuthSessionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.RecipeInterface.__type\"},{\"id\":776,\"kind\":16777216,\"name\":\"TypeProvider\",\"url\":\"modules/recipe_thirdpartypasswordless.html#TypeProvider\",\"classes\":\"tsd-kind-reference tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":777,\"kind\":4194304,\"name\":\"User\",\"url\":\"modules/recipe_thirdpartypasswordless.html#User\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":778,\"kind\":4194304,\"name\":\"APIInterface\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":779,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface\"},{\"id\":780,\"kind\":1024,\"name\":\"authorisationUrlGET\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.authorisationUrlGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":781,\"kind\":1024,\"name\":\"thirdPartySignInUpPOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.thirdPartySignInUpPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":782,\"kind\":1024,\"name\":\"appleRedirectHandlerPOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.appleRedirectHandlerPOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":783,\"kind\":1024,\"name\":\"createCodePOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.createCodePOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":784,\"kind\":1024,\"name\":\"resendCodePOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.resendCodePOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":785,\"kind\":1024,\"name\":\"consumeCodePOST\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.consumeCodePOST\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":786,\"kind\":1024,\"name\":\"passwordlessUserEmailExistsGET\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.passwordlessUserEmailExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":787,\"kind\":1024,\"name\":\"passwordlessUserPhoneNumberExistsGET\",\"url\":\"modules/recipe_thirdpartypasswordless.html#APIInterface.__type.passwordlessUserPhoneNumberExistsGET\",\"classes\":\"tsd-kind-property tsd-parent-kind-type-literal\",\"parent\":\"recipe/thirdpartypasswordless.APIInterface.__type\"},{\"id\":788,\"kind\":4194304,\"name\":\"PasswordlessAPIOptions\",\"url\":\"modules/recipe_thirdpartypasswordless.html#PasswordlessAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":789,\"kind\":4194304,\"name\":\"ThirdPartyAPIOptions\",\"url\":\"modules/recipe_thirdpartypasswordless.html#ThirdPartyAPIOptions\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/thirdpartypasswordless\"},{\"id\":790,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":791,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/usermetadata.RecipeInterface\"},{\"id\":792,\"kind\":2048,\"name\":\"getUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type.getUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/usermetadata.RecipeInterface.__type\"},{\"id\":793,\"kind\":2048,\"name\":\"updateUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type.updateUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/usermetadata.RecipeInterface.__type\"},{\"id\":794,\"kind\":2048,\"name\":\"clearUserMetadata\",\"url\":\"modules/recipe_usermetadata.html#RecipeInterface.__type.clearUserMetadata\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/usermetadata.RecipeInterface.__type\"},{\"id\":795,\"kind\":256,\"name\":\"JSONObject\",\"url\":\"interfaces/recipe_usermetadata.JSONObject.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"recipe/usermetadata\"},{\"id\":796,\"kind\":32,\"name\":\"UserRoleClaim\",\"url\":\"modules/recipe_userroles.html#UserRoleClaim\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":797,\"kind\":32,\"name\":\"PermissionClaim\",\"url\":\"modules/recipe_userroles.html#PermissionClaim\",\"classes\":\"tsd-kind-variable tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":798,\"kind\":4194304,\"name\":\"RecipeInterface\",\"url\":\"modules/recipe_userroles.html#RecipeInterface\",\"classes\":\"tsd-kind-type-alias tsd-parent-kind-module\",\"parent\":\"recipe/userroles\"},{\"id\":799,\"kind\":65536,\"name\":\"__type\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-type-alias\",\"parent\":\"recipe/userroles.RecipeInterface\"},{\"id\":800,\"kind\":2048,\"name\":\"addRoleToUser\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.addRoleToUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":801,\"kind\":2048,\"name\":\"removeUserRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.removeUserRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":802,\"kind\":2048,\"name\":\"getRolesForUser\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getRolesForUser\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":803,\"kind\":2048,\"name\":\"getUsersThatHaveRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getUsersThatHaveRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":804,\"kind\":2048,\"name\":\"createNewRoleOrAddPermissions\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.createNewRoleOrAddPermissions\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":805,\"kind\":2048,\"name\":\"getPermissionsForRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getPermissionsForRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":806,\"kind\":2048,\"name\":\"removePermissionsFromRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.removePermissionsFromRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":807,\"kind\":2048,\"name\":\"getRolesThatHavePermission\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getRolesThatHavePermission\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":808,\"kind\":2048,\"name\":\"deleteRole\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.deleteRole\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"},{\"id\":809,\"kind\":2048,\"name\":\"getAllRoles\",\"url\":\"modules/recipe_userroles.html#RecipeInterface.__type.getAllRoles\",\"classes\":\"tsd-kind-method tsd-parent-kind-type-literal\",\"parent\":\"recipe/userroles.RecipeInterface.__type\"}],\"index\":{\"version\":\"2.3.9\",\"fields\":[\"name\",\"parent\"],\"fieldVectors\":[[\"name/0\",[0,40.956]],[\"parent/0\",[]],[\"name/1\",[1,34.211]],[\"parent/1\",[0,4.049]],[\"name/2\",[2,57.82]],[\"parent/2\",[0,4.049]],[\"name/3\",[3,57.82]],[\"parent/3\",[0,4.049]],[\"name/4\",[4,57.82]],[\"parent/4\",[0,4.049]],[\"name/5\",[5,57.82]],[\"parent/5\",[0,4.049]],[\"name/6\",[6,57.82]],[\"parent/6\",[0,4.049]],[\"name/7\",[7,57.82]],[\"parent/7\",[0,4.049]],[\"name/8\",[8,57.82]],[\"parent/8\",[0,4.049]],[\"name/9\",[9,57.82]],[\"parent/9\",[0,4.049]],[\"name/10\",[10,57.82]],[\"parent/10\",[0,4.049]],[\"name/11\",[11,38.949]],[\"parent/11\",[0,4.049]],[\"name/12\",[12,38.949]],[\"parent/12\",[0,4.049]],[\"name/13\",[1,34.211]],[\"parent/13\",[13,4.049]],[\"name/14\",[14,21.711]],[\"parent/14\",[13,4.049]],[\"name/15\",[11,38.949]],[\"parent/15\",[13,4.049]],[\"name/16\",[2,57.82]],[\"parent/16\",[13,4.049]],[\"name/17\",[3,57.82]],[\"parent/17\",[13,4.049]],[\"name/18\",[4,57.82]],[\"parent/18\",[13,4.049]],[\"name/19\",[5,57.82]],[\"parent/19\",[13,4.049]],[\"name/20\",[6,57.82]],[\"parent/20\",[13,4.049]],[\"name/21\",[7,57.82]],[\"parent/21\",[13,4.049]],[\"name/22\",[8,57.82]],[\"parent/22\",[13,4.049]],[\"name/23\",[9,57.82]],[\"parent/23\",[13,4.049]],[\"name/24\",[10,57.82]],[\"parent/24\",[13,4.049]],[\"name/25\",[15,38.361]],[\"parent/25\",[13,4.049]],[\"name/26\",[16,42.559]],[\"parent/26\",[]],[\"name/27\",[17,57.82]],[\"parent/27\",[16,4.208]],[\"name/28\",[18,57.82]],[\"parent/28\",[16,4.208]],[\"name/29\",[19,57.82]],[\"parent/29\",[16,4.208]],[\"name/30\",[20,57.82]],[\"parent/30\",[16,4.208]],[\"name/31\",[21,57.82]],[\"parent/31\",[16,4.208]],[\"name/32\",[22,57.82]],[\"parent/32\",[16,4.208]],[\"name/33\",[12,38.949]],[\"parent/33\",[16,4.208]],[\"name/34\",[14,21.711]],[\"parent/34\",[16,4.208]],[\"name/35\",[17,57.82]],[\"parent/35\",[23,4.772]],[\"name/36\",[18,57.82]],[\"parent/36\",[23,4.772]],[\"name/37\",[19,57.82]],[\"parent/37\",[23,4.772]],[\"name/38\",[20,57.82]],[\"parent/38\",[23,4.772]],[\"name/39\",[21,57.82]],[\"parent/39\",[23,4.772]],[\"name/40\",[22,57.82]],[\"parent/40\",[23,4.772]],[\"name/41\",[24,48.265]],[\"parent/41\",[]],[\"name/42\",[25,51.942]],[\"parent/42\",[24,4.772]],[\"name/43\",[26,48.265]],[\"parent/43\",[24,4.772]],[\"name/44\",[27,48.265]],[\"parent/44\",[24,4.772]],[\"name/45\",[28,48.265]],[\"parent/45\",[]],[\"name/46\",[25,51.942]],[\"parent/46\",[28,4.772]],[\"name/47\",[29,57.82]],[\"parent/47\",[28,4.772]],[\"name/48\",[26,48.265]],[\"parent/48\",[28,4.772]],[\"name/49\",[27,48.265]],[\"parent/49\",[28,4.772]],[\"name/50\",[30,48.265]],[\"parent/50\",[]],[\"name/51\",[31,57.82]],[\"parent/51\",[30,4.772]],[\"name/52\",[29,57.82]],[\"parent/52\",[30,4.772]],[\"name/53\",[26,48.265]],[\"parent/53\",[30,4.772]],[\"name/54\",[27,48.265]],[\"parent/54\",[30,4.772]],[\"name/55\",[32,49.935]],[\"parent/55\",[]],[\"name/56\",[31,57.82]],[\"parent/56\",[32,4.937]],[\"name/57\",[26,48.265]],[\"parent/57\",[32,4.937]],[\"name/58\",[27,48.265]],[\"parent/58\",[32,4.937]],[\"name/59\",[33,49.935]],[\"parent/59\",[]],[\"name/60\",[25,51.942]],[\"parent/60\",[33,4.937]],[\"name/61\",[26,48.265]],[\"parent/61\",[33,4.937]],[\"name/62\",[27,48.265]],[\"parent/62\",[33,4.937]],[\"name/63\",[34,49.935]],[\"parent/63\",[]],[\"name/64\",[25,51.942]],[\"parent/64\",[34,4.937]],[\"name/65\",[26,48.265]],[\"parent/65\",[34,4.937]],[\"name/66\",[27,48.265]],[\"parent/66\",[34,4.937]],[\"name/67\",[35,57.82]],[\"parent/67\",[]],[\"name/68\",[12,38.949]],[\"parent/68\",[35,5.717]],[\"name/69\",[15,38.361]],[\"parent/69\",[36,5.717]],[\"name/70\",[37,57.82]],[\"parent/70\",[36,5.717]],[\"name/71\",[38,57.82]],[\"parent/71\",[]],[\"name/72\",[12,38.949]],[\"parent/72\",[38,5.717]],[\"name/73\",[15,38.361]],[\"parent/73\",[39,5.717]],[\"name/74\",[37,57.82]],[\"parent/74\",[39,5.717]],[\"name/75\",[40,48.265]],[\"parent/75\",[]],[\"name/76\",[1,34.211]],[\"parent/76\",[40,4.772]],[\"name/77\",[12,38.949]],[\"parent/77\",[40,4.772]],[\"name/78\",[1,34.211]],[\"parent/78\",[41,5.384]],[\"name/79\",[14,21.711]],[\"parent/79\",[41,5.384]],[\"name/80\",[15,38.361]],[\"parent/80\",[41,5.384]],[\"name/81\",[42,38.949]],[\"parent/81\",[]],[\"name/82\",[1,34.211]],[\"parent/82\",[42,3.851]],[\"name/83\",[11,38.949]],[\"parent/83\",[42,3.851]],[\"name/84\",[43,54.455]],[\"parent/84\",[42,3.851]],[\"name/85\",[44,54.455]],[\"parent/85\",[42,3.851]],[\"name/86\",[45,39.574]],[\"parent/86\",[42,3.851]],[\"name/87\",[46,48.265]],[\"parent/87\",[42,3.851]],[\"name/88\",[47,48.265]],[\"parent/88\",[42,3.851]],[\"name/89\",[48,48.265]],[\"parent/89\",[42,3.851]],[\"name/90\",[49,48.265]],[\"parent/90\",[42,3.851]],[\"name/91\",[50,43.469]],[\"parent/91\",[42,3.851]],[\"name/92\",[12,38.949]],[\"parent/92\",[42,3.851]],[\"name/93\",[1,34.211]],[\"parent/93\",[51,4.125]],[\"name/94\",[14,21.711]],[\"parent/94\",[51,4.125]],[\"name/95\",[11,38.949]],[\"parent/95\",[51,4.125]],[\"name/96\",[43,54.455]],[\"parent/96\",[51,4.125]],[\"name/97\",[44,54.455]],[\"parent/97\",[51,4.125]],[\"name/98\",[45,39.574]],[\"parent/98\",[51,4.125]],[\"name/99\",[46,48.265]],[\"parent/99\",[51,4.125]],[\"name/100\",[47,48.265]],[\"parent/100\",[51,4.125]],[\"name/101\",[48,48.265]],[\"parent/101\",[51,4.125]],[\"name/102\",[49,48.265]],[\"parent/102\",[51,4.125]],[\"name/103\",[50,43.469]],[\"parent/103\",[51,4.125]],[\"name/104\",[15,38.361]],[\"parent/104\",[51,4.125]],[\"name/105\",[52,39.574]],[\"parent/105\",[]],[\"name/106\",[1,34.211]],[\"parent/106\",[52,3.913]],[\"name/107\",[11,38.949]],[\"parent/107\",[52,3.913]],[\"name/108\",[53,54.455]],[\"parent/108\",[52,3.913]],[\"name/109\",[54,54.455]],[\"parent/109\",[52,3.913]],[\"name/110\",[55,54.455]],[\"parent/110\",[52,3.913]],[\"name/111\",[56,54.455]],[\"parent/111\",[52,3.913]],[\"name/112\",[57,54.455]],[\"parent/112\",[52,3.913]],[\"name/113\",[50,43.469]],[\"parent/113\",[52,3.913]],[\"name/114\",[12,38.949]],[\"parent/114\",[52,3.913]],[\"name/115\",[1,34.211]],[\"parent/115\",[58,4.208]],[\"name/116\",[14,21.711]],[\"parent/116\",[58,4.208]],[\"name/117\",[11,38.949]],[\"parent/117\",[58,4.208]],[\"name/118\",[59,57.82]],[\"parent/118\",[58,4.208]],[\"name/119\",[53,54.455]],[\"parent/119\",[58,4.208]],[\"name/120\",[54,54.455]],[\"parent/120\",[58,4.208]],[\"name/121\",[55,54.455]],[\"parent/121\",[58,4.208]],[\"name/122\",[56,54.455]],[\"parent/122\",[58,4.208]],[\"name/123\",[57,54.455]],[\"parent/123\",[58,4.208]],[\"name/124\",[50,43.469]],[\"parent/124\",[58,4.208]],[\"name/125\",[15,38.361]],[\"parent/125\",[58,4.208]],[\"name/126\",[60,44.47]],[\"parent/126\",[]],[\"name/127\",[1,34.211]],[\"parent/127\",[60,4.397]],[\"name/128\",[61,46.834]],[\"parent/128\",[60,4.397]],[\"name/129\",[62,46.834]],[\"parent/129\",[60,4.397]],[\"name/130\",[12,38.949]],[\"parent/130\",[60,4.397]],[\"name/131\",[1,34.211]],[\"parent/131\",[63,4.937]],[\"name/132\",[14,21.711]],[\"parent/132\",[63,4.937]],[\"name/133\",[61,46.834]],[\"parent/133\",[63,4.937]],[\"name/134\",[62,46.834]],[\"parent/134\",[63,4.937]],[\"name/135\",[15,38.361]],[\"parent/135\",[63,4.937]],[\"name/136\",[64,48.265]],[\"parent/136\",[]],[\"name/137\",[1,34.211]],[\"parent/137\",[64,4.772]],[\"name/138\",[65,51.942]],[\"parent/138\",[64,4.772]],[\"name/139\",[61,46.834]],[\"parent/139\",[64,4.772]],[\"name/140\",[62,46.834]],[\"parent/140\",[64,4.772]],[\"name/141\",[12,38.949]],[\"parent/141\",[64,4.772]],[\"name/142\",[1,34.211]],[\"parent/142\",[66,4.772]],[\"name/143\",[14,21.711]],[\"parent/143\",[66,4.772]],[\"name/144\",[65,51.942]],[\"parent/144\",[66,4.772]],[\"name/145\",[61,46.834]],[\"parent/145\",[66,4.772]],[\"name/146\",[62,46.834]],[\"parent/146\",[66,4.772]],[\"name/147\",[15,38.361]],[\"parent/147\",[66,4.772]],[\"name/148\",[67,34.596]],[\"parent/148\",[]],[\"name/149\",[1,34.211]],[\"parent/149\",[67,3.421]],[\"name/150\",[11,38.949]],[\"parent/150\",[67,3.421]],[\"name/151\",[68,48.265]],[\"parent/151\",[67,3.421]],[\"name/152\",[69,48.265]],[\"parent/152\",[67,3.421]],[\"name/153\",[46,48.265]],[\"parent/153\",[67,3.421]],[\"name/154\",[45,39.574]],[\"parent/154\",[67,3.421]],[\"name/155\",[70,48.265]],[\"parent/155\",[67,3.421]],[\"name/156\",[71,48.265]],[\"parent/156\",[67,3.421]],[\"name/157\",[72,48.265]],[\"parent/157\",[67,3.421]],[\"name/158\",[73,48.265]],[\"parent/158\",[67,3.421]],[\"name/159\",[74,48.265]],[\"parent/159\",[67,3.421]],[\"name/160\",[75,48.265]],[\"parent/160\",[67,3.421]],[\"name/161\",[76,54.455]],[\"parent/161\",[67,3.421]],[\"name/162\",[77,48.265]],[\"parent/162\",[67,3.421]],[\"name/163\",[78,48.265]],[\"parent/163\",[67,3.421]],[\"name/164\",[79,51.942]],[\"parent/164\",[67,3.421]],[\"name/165\",[80,49.935]],[\"parent/165\",[67,3.421]],[\"name/166\",[50,43.469]],[\"parent/166\",[67,3.421]],[\"name/167\",[81,51.942]],[\"parent/167\",[67,3.421]],[\"name/168\",[12,38.949]],[\"parent/168\",[67,3.421]],[\"name/169\",[1,34.211]],[\"parent/169\",[82,3.589]],[\"name/170\",[14,21.711]],[\"parent/170\",[82,3.589]],[\"name/171\",[11,38.949]],[\"parent/171\",[82,3.589]],[\"name/172\",[68,48.265]],[\"parent/172\",[82,3.589]],[\"name/173\",[75,48.265]],[\"parent/173\",[82,3.589]],[\"name/174\",[69,48.265]],[\"parent/174\",[82,3.589]],[\"name/175\",[45,39.574]],[\"parent/175\",[82,3.589]],[\"name/176\",[46,48.265]],[\"parent/176\",[82,3.589]],[\"name/177\",[70,48.265]],[\"parent/177\",[82,3.589]],[\"name/178\",[76,54.455]],[\"parent/178\",[82,3.589]],[\"name/179\",[77,48.265]],[\"parent/179\",[82,3.589]],[\"name/180\",[78,48.265]],[\"parent/180\",[82,3.589]],[\"name/181\",[72,48.265]],[\"parent/181\",[82,3.589]],[\"name/182\",[73,48.265]],[\"parent/182\",[82,3.589]],[\"name/183\",[71,48.265]],[\"parent/183\",[82,3.589]],[\"name/184\",[74,48.265]],[\"parent/184\",[82,3.589]],[\"name/185\",[79,51.942]],[\"parent/185\",[82,3.589]],[\"name/186\",[80,49.935]],[\"parent/186\",[82,3.589]],[\"name/187\",[50,43.469]],[\"parent/187\",[82,3.589]],[\"name/188\",[81,51.942]],[\"parent/188\",[82,3.589]],[\"name/189\",[15,38.361]],[\"parent/189\",[82,3.589]],[\"name/190\",[83,32.483]],[\"parent/190\",[]],[\"name/191\",[1,34.211]],[\"parent/191\",[83,3.212]],[\"name/192\",[84,54.455]],[\"parent/192\",[83,3.212]],[\"name/193\",[85,54.455]],[\"parent/193\",[83,3.212]],[\"name/194\",[86,54.455]],[\"parent/194\",[83,3.212]],[\"name/195\",[87,54.455]],[\"parent/195\",[83,3.212]],[\"name/196\",[88,54.455]],[\"parent/196\",[83,3.212]],[\"name/197\",[89,54.455]],[\"parent/197\",[83,3.212]],[\"name/198\",[90,51.942]],[\"parent/198\",[83,3.212]],[\"name/199\",[91,54.455]],[\"parent/199\",[83,3.212]],[\"name/200\",[92,51.942]],[\"parent/200\",[83,3.212]],[\"name/201\",[93,51.942]],[\"parent/201\",[83,3.212]],[\"name/202\",[94,51.942]],[\"parent/202\",[83,3.212]],[\"name/203\",[95,51.942]],[\"parent/203\",[83,3.212]],[\"name/204\",[96,51.942]],[\"parent/204\",[83,3.212]],[\"name/205\",[97,51.942]],[\"parent/205\",[83,3.212]],[\"name/206\",[98,51.942]],[\"parent/206\",[83,3.212]],[\"name/207\",[99,54.455]],[\"parent/207\",[83,3.212]],[\"name/208\",[100,57.82]],[\"parent/208\",[83,3.212]],[\"name/209\",[11,38.949]],[\"parent/209\",[83,3.212]],[\"name/210\",[61,46.834]],[\"parent/210\",[83,3.212]],[\"name/211\",[62,46.834]],[\"parent/211\",[83,3.212]],[\"name/212\",[65,51.942]],[\"parent/212\",[83,3.212]],[\"name/213\",[12,38.949]],[\"parent/213\",[83,3.212]],[\"name/214\",[1,34.211]],[\"parent/214\",[101,3.421]],[\"name/215\",[14,21.711]],[\"parent/215\",[101,3.421]],[\"name/216\",[11,38.949]],[\"parent/216\",[101,3.421]],[\"name/217\",[84,54.455]],[\"parent/217\",[101,3.421]],[\"name/218\",[100,57.82]],[\"parent/218\",[101,3.421]],[\"name/219\",[99,54.455]],[\"parent/219\",[101,3.421]],[\"name/220\",[85,54.455]],[\"parent/220\",[101,3.421]],[\"name/221\",[86,54.455]],[\"parent/221\",[101,3.421]],[\"name/222\",[87,54.455]],[\"parent/222\",[101,3.421]],[\"name/223\",[88,54.455]],[\"parent/223\",[101,3.421]],[\"name/224\",[89,54.455]],[\"parent/224\",[101,3.421]],[\"name/225\",[90,51.942]],[\"parent/225\",[101,3.421]],[\"name/226\",[91,54.455]],[\"parent/226\",[101,3.421]],[\"name/227\",[92,51.942]],[\"parent/227\",[101,3.421]],[\"name/228\",[102,57.82]],[\"parent/228\",[101,3.421]],[\"name/229\",[93,51.942]],[\"parent/229\",[101,3.421]],[\"name/230\",[94,51.942]],[\"parent/230\",[101,3.421]],[\"name/231\",[61,46.834]],[\"parent/231\",[101,3.421]],[\"name/232\",[62,46.834]],[\"parent/232\",[101,3.421]],[\"name/233\",[65,51.942]],[\"parent/233\",[101,3.421]],[\"name/234\",[95,51.942]],[\"parent/234\",[101,3.421]],[\"name/235\",[96,51.942]],[\"parent/235\",[101,3.421]],[\"name/236\",[97,51.942]],[\"parent/236\",[101,3.421]],[\"name/237\",[98,51.942]],[\"parent/237\",[101,3.421]],[\"name/238\",[15,38.361]],[\"parent/238\",[101,3.421]],[\"name/239\",[103,37.279]],[\"parent/239\",[]],[\"name/240\",[1,34.211]],[\"parent/240\",[103,3.686]],[\"name/241\",[11,38.949]],[\"parent/241\",[103,3.686]],[\"name/242\",[80,49.935]],[\"parent/242\",[103,3.686]],[\"name/243\",[45,39.574]],[\"parent/243\",[103,3.686]],[\"name/244\",[104,44.47]],[\"parent/244\",[103,3.686]],[\"name/245\",[105,44.47]],[\"parent/245\",[103,3.686]],[\"name/246\",[106,48.265]],[\"parent/246\",[103,3.686]],[\"name/247\",[107,48.265]],[\"parent/247\",[103,3.686]],[\"name/248\",[108,48.265]],[\"parent/248\",[103,3.686]],[\"name/249\",[109,48.265]],[\"parent/249\",[103,3.686]],[\"name/250\",[110,48.265]],[\"parent/250\",[103,3.686]],[\"name/251\",[111,48.265]],[\"parent/251\",[103,3.686]],[\"name/252\",[12,38.949]],[\"parent/252\",[103,3.686]],[\"name/253\",[1,34.211]],[\"parent/253\",[112,3.636]],[\"name/254\",[14,21.711]],[\"parent/254\",[112,3.636]],[\"name/255\",[11,38.949]],[\"parent/255\",[112,3.636]],[\"name/256\",[80,49.935]],[\"parent/256\",[112,3.636]],[\"name/257\",[45,39.574]],[\"parent/257\",[112,3.636]],[\"name/258\",[104,44.47]],[\"parent/258\",[112,3.636]],[\"name/259\",[105,44.47]],[\"parent/259\",[112,3.636]],[\"name/260\",[106,48.265]],[\"parent/260\",[112,3.636]],[\"name/261\",[14,21.711]],[\"parent/261\",[112,3.636]],[\"name/262\",[107,48.265]],[\"parent/262\",[112,3.636]],[\"name/263\",[14,21.711]],[\"parent/263\",[112,3.636]],[\"name/264\",[108,48.265]],[\"parent/264\",[112,3.636]],[\"name/265\",[14,21.711]],[\"parent/265\",[112,3.636]],[\"name/266\",[109,48.265]],[\"parent/266\",[112,3.636]],[\"name/267\",[14,21.711]],[\"parent/267\",[112,3.636]],[\"name/268\",[110,48.265]],[\"parent/268\",[112,3.636]],[\"name/269\",[14,21.711]],[\"parent/269\",[112,3.636]],[\"name/270\",[111,48.265]],[\"parent/270\",[112,3.636]],[\"name/271\",[14,21.711]],[\"parent/271\",[112,3.636]],[\"name/272\",[15,38.361]],[\"parent/272\",[112,3.636]],[\"name/273\",[113,34.211]],[\"parent/273\",[]],[\"name/274\",[1,34.211]],[\"parent/274\",[113,3.382]],[\"name/275\",[11,38.949]],[\"parent/275\",[113,3.382]],[\"name/276\",[114,54.455]],[\"parent/276\",[113,3.382]],[\"name/277\",[115,54.455]],[\"parent/277\",[113,3.382]],[\"name/278\",[116,48.265]],[\"parent/278\",[113,3.382]],[\"name/279\",[45,39.574]],[\"parent/279\",[113,3.382]],[\"name/280\",[105,44.47]],[\"parent/280\",[113,3.382]],[\"name/281\",[104,44.47]],[\"parent/281\",[113,3.382]],[\"name/282\",[47,48.265]],[\"parent/282\",[113,3.382]],[\"name/283\",[48,48.265]],[\"parent/283\",[113,3.382]],[\"name/284\",[49,48.265]],[\"parent/284\",[113,3.382]],[\"name/285\",[106,48.265]],[\"parent/285\",[113,3.382]],[\"name/286\",[107,48.265]],[\"parent/286\",[113,3.382]],[\"name/287\",[108,48.265]],[\"parent/287\",[113,3.382]],[\"name/288\",[109,48.265]],[\"parent/288\",[113,3.382]],[\"name/289\",[110,48.265]],[\"parent/289\",[113,3.382]],[\"name/290\",[111,48.265]],[\"parent/290\",[113,3.382]],[\"name/291\",[50,43.469]],[\"parent/291\",[113,3.382]],[\"name/292\",[12,38.949]],[\"parent/292\",[113,3.382]],[\"name/293\",[1,34.211]],[\"parent/293\",[117,3.382]],[\"name/294\",[14,21.711]],[\"parent/294\",[117,3.382]],[\"name/295\",[11,38.949]],[\"parent/295\",[117,3.382]],[\"name/296\",[116,48.265]],[\"parent/296\",[117,3.382]],[\"name/297\",[105,44.47]],[\"parent/297\",[117,3.382]],[\"name/298\",[114,54.455]],[\"parent/298\",[117,3.382]],[\"name/299\",[115,54.455]],[\"parent/299\",[117,3.382]],[\"name/300\",[45,39.574]],[\"parent/300\",[117,3.382]],[\"name/301\",[104,44.47]],[\"parent/301\",[117,3.382]],[\"name/302\",[47,48.265]],[\"parent/302\",[117,3.382]],[\"name/303\",[48,48.265]],[\"parent/303\",[117,3.382]],[\"name/304\",[49,48.265]],[\"parent/304\",[117,3.382]],[\"name/305\",[106,48.265]],[\"parent/305\",[117,3.382]],[\"name/306\",[14,21.711]],[\"parent/306\",[117,3.382]],[\"name/307\",[107,48.265]],[\"parent/307\",[117,3.382]],[\"name/308\",[14,21.711]],[\"parent/308\",[117,3.382]],[\"name/309\",[108,48.265]],[\"parent/309\",[117,3.382]],[\"name/310\",[14,21.711]],[\"parent/310\",[117,3.382]],[\"name/311\",[109,48.265]],[\"parent/311\",[117,3.382]],[\"name/312\",[14,21.711]],[\"parent/312\",[117,3.382]],[\"name/313\",[110,48.265]],[\"parent/313\",[117,3.382]],[\"name/314\",[14,21.711]],[\"parent/314\",[117,3.382]],[\"name/315\",[111,48.265]],[\"parent/315\",[117,3.382]],[\"name/316\",[14,21.711]],[\"parent/316\",[117,3.382]],[\"name/317\",[50,43.469]],[\"parent/317\",[117,3.382]],[\"name/318\",[15,38.361]],[\"parent/318\",[117,3.382]],[\"name/319\",[118,31.287]],[\"parent/319\",[]],[\"name/320\",[1,34.211]],[\"parent/320\",[118,3.093]],[\"name/321\",[11,38.949]],[\"parent/321\",[118,3.093]],[\"name/322\",[116,48.265]],[\"parent/322\",[118,3.093]],[\"name/323\",[119,57.82]],[\"parent/323\",[118,3.093]],[\"name/324\",[45,39.574]],[\"parent/324\",[118,3.093]],[\"name/325\",[105,44.47]],[\"parent/325\",[118,3.093]],[\"name/326\",[104,44.47]],[\"parent/326\",[118,3.093]],[\"name/327\",[68,48.265]],[\"parent/327\",[118,3.093]],[\"name/328\",[69,48.265]],[\"parent/328\",[118,3.093]],[\"name/329\",[70,48.265]],[\"parent/329\",[118,3.093]],[\"name/330\",[71,48.265]],[\"parent/330\",[118,3.093]],[\"name/331\",[72,48.265]],[\"parent/331\",[118,3.093]],[\"name/332\",[73,48.265]],[\"parent/332\",[118,3.093]],[\"name/333\",[74,48.265]],[\"parent/333\",[118,3.093]],[\"name/334\",[75,48.265]],[\"parent/334\",[118,3.093]],[\"name/335\",[120,54.455]],[\"parent/335\",[118,3.093]],[\"name/336\",[77,48.265]],[\"parent/336\",[118,3.093]],[\"name/337\",[78,48.265]],[\"parent/337\",[118,3.093]],[\"name/338\",[79,51.942]],[\"parent/338\",[118,3.093]],[\"name/339\",[106,48.265]],[\"parent/339\",[118,3.093]],[\"name/340\",[107,48.265]],[\"parent/340\",[118,3.093]],[\"name/341\",[108,48.265]],[\"parent/341\",[118,3.093]],[\"name/342\",[109,48.265]],[\"parent/342\",[118,3.093]],[\"name/343\",[110,48.265]],[\"parent/343\",[118,3.093]],[\"name/344\",[111,48.265]],[\"parent/344\",[118,3.093]],[\"name/345\",[50,43.469]],[\"parent/345\",[118,3.093]],[\"name/346\",[81,51.942]],[\"parent/346\",[118,3.093]],[\"name/347\",[12,38.949]],[\"parent/347\",[118,3.093]],[\"name/348\",[1,34.211]],[\"parent/348\",[121,3.093]],[\"name/349\",[14,21.711]],[\"parent/349\",[121,3.093]],[\"name/350\",[11,38.949]],[\"parent/350\",[121,3.093]],[\"name/351\",[116,48.265]],[\"parent/351\",[121,3.093]],[\"name/352\",[105,44.47]],[\"parent/352\",[121,3.093]],[\"name/353\",[45,39.574]],[\"parent/353\",[121,3.093]],[\"name/354\",[104,44.47]],[\"parent/354\",[121,3.093]],[\"name/355\",[68,48.265]],[\"parent/355\",[121,3.093]],[\"name/356\",[75,48.265]],[\"parent/356\",[121,3.093]],[\"name/357\",[69,48.265]],[\"parent/357\",[121,3.093]],[\"name/358\",[70,48.265]],[\"parent/358\",[121,3.093]],[\"name/359\",[120,54.455]],[\"parent/359\",[121,3.093]],[\"name/360\",[77,48.265]],[\"parent/360\",[121,3.093]],[\"name/361\",[78,48.265]],[\"parent/361\",[121,3.093]],[\"name/362\",[72,48.265]],[\"parent/362\",[121,3.093]],[\"name/363\",[73,48.265]],[\"parent/363\",[121,3.093]],[\"name/364\",[71,48.265]],[\"parent/364\",[121,3.093]],[\"name/365\",[74,48.265]],[\"parent/365\",[121,3.093]],[\"name/366\",[79,51.942]],[\"parent/366\",[121,3.093]],[\"name/367\",[119,57.82]],[\"parent/367\",[121,3.093]],[\"name/368\",[106,48.265]],[\"parent/368\",[121,3.093]],[\"name/369\",[14,21.711]],[\"parent/369\",[121,3.093]],[\"name/370\",[107,48.265]],[\"parent/370\",[121,3.093]],[\"name/371\",[14,21.711]],[\"parent/371\",[121,3.093]],[\"name/372\",[108,48.265]],[\"parent/372\",[121,3.093]],[\"name/373\",[14,21.711]],[\"parent/373\",[121,3.093]],[\"name/374\",[109,48.265]],[\"parent/374\",[121,3.093]],[\"name/375\",[14,21.711]],[\"parent/375\",[121,3.093]],[\"name/376\",[110,48.265]],[\"parent/376\",[121,3.093]],[\"name/377\",[14,21.711]],[\"parent/377\",[121,3.093]],[\"name/378\",[111,48.265]],[\"parent/378\",[121,3.093]],[\"name/379\",[14,21.711]],[\"parent/379\",[121,3.093]],[\"name/380\",[50,43.469]],[\"parent/380\",[121,3.093]],[\"name/381\",[81,51.942]],[\"parent/381\",[121,3.093]],[\"name/382\",[15,38.361]],[\"parent/382\",[121,3.093]],[\"name/383\",[122,45.582]],[\"parent/383\",[]],[\"name/384\",[1,34.211]],[\"parent/384\",[122,4.507]],[\"name/385\",[123,54.455]],[\"parent/385\",[122,4.507]],[\"name/386\",[124,54.455]],[\"parent/386\",[122,4.507]],[\"name/387\",[125,54.455]],[\"parent/387\",[122,4.507]],[\"name/388\",[12,38.949]],[\"parent/388\",[122,4.507]],[\"name/389\",[1,34.211]],[\"parent/389\",[126,4.772]],[\"name/390\",[14,21.711]],[\"parent/390\",[126,4.772]],[\"name/391\",[123,54.455]],[\"parent/391\",[126,4.772]],[\"name/392\",[124,54.455]],[\"parent/392\",[126,4.772]],[\"name/393\",[125,54.455]],[\"parent/393\",[126,4.772]],[\"name/394\",[15,38.361]],[\"parent/394\",[126,4.772]],[\"name/395\",[127,38.949]],[\"parent/395\",[]],[\"name/396\",[1,34.211]],[\"parent/396\",[127,3.851]],[\"name/397\",[128,54.455]],[\"parent/397\",[127,3.851]],[\"name/398\",[129,54.455]],[\"parent/398\",[127,3.851]],[\"name/399\",[130,54.455]],[\"parent/399\",[127,3.851]],[\"name/400\",[131,54.455]],[\"parent/400\",[127,3.851]],[\"name/401\",[132,54.455]],[\"parent/401\",[127,3.851]],[\"name/402\",[133,54.455]],[\"parent/402\",[127,3.851]],[\"name/403\",[134,54.455]],[\"parent/403\",[127,3.851]],[\"name/404\",[135,54.455]],[\"parent/404\",[127,3.851]],[\"name/405\",[136,54.455]],[\"parent/405\",[127,3.851]],[\"name/406\",[137,54.455]],[\"parent/406\",[127,3.851]],[\"name/407\",[12,38.949]],[\"parent/407\",[127,3.851]],[\"name/408\",[1,34.211]],[\"parent/408\",[138,3.913]],[\"name/409\",[14,21.711]],[\"parent/409\",[138,3.913]],[\"name/410\",[139,57.82]],[\"parent/410\",[138,3.913]],[\"name/411\",[140,57.82]],[\"parent/411\",[138,3.913]],[\"name/412\",[128,54.455]],[\"parent/412\",[138,3.913]],[\"name/413\",[129,54.455]],[\"parent/413\",[138,3.913]],[\"name/414\",[130,54.455]],[\"parent/414\",[138,3.913]],[\"name/415\",[131,54.455]],[\"parent/415\",[138,3.913]],[\"name/416\",[132,54.455]],[\"parent/416\",[138,3.913]],[\"name/417\",[133,54.455]],[\"parent/417\",[138,3.913]],[\"name/418\",[134,54.455]],[\"parent/418\",[138,3.913]],[\"name/419\",[135,54.455]],[\"parent/419\",[138,3.913]],[\"name/420\",[136,54.455]],[\"parent/420\",[138,3.913]],[\"name/421\",[137,54.455]],[\"parent/421\",[138,3.913]],[\"name/422\",[15,38.361]],[\"parent/422\",[138,3.913]],[\"name/423\",[141,62.928]],[\"parent/423\",[16,4.208]],[\"name/424\",[15,38.361]],[\"parent/424\",[142,3.793]],[\"name/425\",[143,57.82]],[\"parent/425\",[142,3.793]],[\"name/426\",[144,57.82]],[\"parent/426\",[142,3.793]],[\"name/427\",[145,62.928]],[\"parent/427\",[142,3.793]],[\"name/428\",[14,21.711]],[\"parent/428\",[142,3.793]],[\"name/429\",[146,62.928]],[\"parent/429\",[142,3.793]],[\"name/430\",[14,21.711]],[\"parent/430\",[142,3.793]],[\"name/431\",[147,62.928]],[\"parent/431\",[142,3.793]],[\"name/432\",[14,21.711]],[\"parent/432\",[142,3.793]],[\"name/433\",[148,62.928]],[\"parent/433\",[142,3.793]],[\"name/434\",[14,21.711]],[\"parent/434\",[142,3.793]],[\"name/435\",[149,62.928]],[\"parent/435\",[142,3.793]],[\"name/436\",[14,21.711]],[\"parent/436\",[142,3.793]],[\"name/437\",[150,62.928]],[\"parent/437\",[142,3.793]],[\"name/438\",[14,21.711]],[\"parent/438\",[142,3.793]],[\"name/439\",[151,62.928]],[\"parent/439\",[142,3.793]],[\"name/440\",[14,21.711]],[\"parent/440\",[142,3.793]],[\"name/441\",[152,62.928]],[\"parent/441\",[16,4.208]],[\"name/442\",[15,38.361]],[\"parent/442\",[153,3.913]],[\"name/443\",[143,57.82]],[\"parent/443\",[153,3.913]],[\"name/444\",[144,57.82]],[\"parent/444\",[153,3.913]],[\"name/445\",[154,62.928]],[\"parent/445\",[153,3.913]],[\"name/446\",[14,21.711]],[\"parent/446\",[153,3.913]],[\"name/447\",[155,62.928]],[\"parent/447\",[153,3.913]],[\"name/448\",[14,21.711]],[\"parent/448\",[153,3.913]],[\"name/449\",[156,62.928]],[\"parent/449\",[153,3.913]],[\"name/450\",[14,21.711]],[\"parent/450\",[153,3.913]],[\"name/451\",[157,62.928]],[\"parent/451\",[153,3.913]],[\"name/452\",[14,21.711]],[\"parent/452\",[153,3.913]],[\"name/453\",[158,62.928]],[\"parent/453\",[153,3.913]],[\"name/454\",[14,21.711]],[\"parent/454\",[153,3.913]],[\"name/455\",[159,62.928]],[\"parent/455\",[153,3.913]],[\"name/456\",[14,21.711]],[\"parent/456\",[153,3.913]],[\"name/457\",[160,62.928]],[\"parent/457\",[24,4.772]],[\"name/458\",[161,46.834]],[\"parent/458\",[162,5.384]],[\"name/459\",[163,57.82]],[\"parent/459\",[162,5.384]],[\"name/460\",[14,21.711]],[\"parent/460\",[162,5.384]],[\"name/461\",[164,57.82]],[\"parent/461\",[165,5.717]],[\"name/462\",[14,21.711]],[\"parent/462\",[165,5.717]],[\"name/463\",[166,57.82]],[\"parent/463\",[167,5.717]],[\"name/464\",[168,57.82]],[\"parent/464\",[167,5.717]],[\"name/465\",[169,62.928]],[\"parent/465\",[24,4.772]],[\"name/466\",[161,46.834]],[\"parent/466\",[170,5.136]],[\"name/467\",[163,57.82]],[\"parent/467\",[170,5.136]],[\"name/468\",[14,21.711]],[\"parent/468\",[170,5.136]],[\"name/469\",[164,57.82]],[\"parent/469\",[171,5.136]],[\"name/470\",[14,21.711]],[\"parent/470\",[171,5.136]],[\"name/471\",[166,57.82]],[\"parent/471\",[172,5.384]],[\"name/472\",[168,57.82]],[\"parent/472\",[172,5.384]],[\"name/473\",[14,21.711]],[\"parent/473\",[170,5.136]],[\"name/474\",[14,21.711]],[\"parent/474\",[171,5.136]],[\"name/475\",[14,21.711]],[\"parent/475\",[172,5.384]],[\"name/476\",[14,21.711]],[\"parent/476\",[173,6.222]],[\"name/477\",[14,21.711]],[\"parent/477\",[171,5.136]],[\"name/478\",[174,54.455]],[\"parent/478\",[28,4.772]],[\"name/479\",[161,46.834]],[\"parent/479\",[175,6.222]],[\"name/480\",[174,54.455]],[\"parent/480\",[30,4.772]],[\"name/481\",[161,46.834]],[\"parent/481\",[176,6.222]],[\"name/482\",[174,54.455]],[\"parent/482\",[32,4.937]],[\"name/483\",[161,46.834]],[\"parent/483\",[177,5.717]],[\"name/484\",[14,21.711]],[\"parent/484\",[177,5.717]],[\"name/485\",[178,57.82]],[\"parent/485\",[33,4.937]],[\"name/486\",[161,46.834]],[\"parent/486\",[179,6.222]],[\"name/487\",[178,57.82]],[\"parent/487\",[34,4.937]],[\"name/488\",[161,46.834]],[\"parent/488\",[180,6.222]],[\"name/489\",[181,42.559]],[\"parent/489\",[40,4.772]],[\"name/490\",[14,21.711]],[\"parent/490\",[182,6.222]],[\"name/491\",[183,62.928]],[\"parent/491\",[184,5.717]],[\"name/492\",[185,62.928]],[\"parent/492\",[184,5.717]],[\"name/493\",[186,46.834]],[\"parent/493\",[40,4.772]],[\"name/494\",[14,21.711]],[\"parent/494\",[187,6.222]],[\"name/495\",[188,46.834]],[\"parent/495\",[189,4.63]],[\"name/496\",[190,46.834]],[\"parent/496\",[189,4.63]],[\"name/497\",[191,46.834]],[\"parent/497\",[189,4.63]],[\"name/498\",[192,46.834]],[\"parent/498\",[189,4.63]],[\"name/499\",[193,46.834]],[\"parent/499\",[189,4.63]],[\"name/500\",[194,46.834]],[\"parent/500\",[189,4.63]],[\"name/501\",[195,49.935]],[\"parent/501\",[189,4.63]],[\"name/502\",[196,44.47]],[\"parent/502\",[40,4.772]],[\"name/503\",[14,21.711]],[\"parent/503\",[197,6.222]],[\"name/504\",[198,62.928]],[\"parent/504\",[199,6.222]],[\"name/505\",[181,42.559]],[\"parent/505\",[42,3.851]],[\"name/506\",[14,21.711]],[\"parent/506\",[200,6.222]],[\"name/507\",[43,54.455]],[\"parent/507\",[201,4.63]],[\"name/508\",[44,54.455]],[\"parent/508\",[201,4.63]],[\"name/509\",[45,39.574]],[\"parent/509\",[201,4.63]],[\"name/510\",[46,48.265]],[\"parent/510\",[201,4.63]],[\"name/511\",[47,48.265]],[\"parent/511\",[201,4.63]],[\"name/512\",[48,48.265]],[\"parent/512\",[201,4.63]],[\"name/513\",[49,48.265]],[\"parent/513\",[201,4.63]],[\"name/514\",[202,48.265]],[\"parent/514\",[42,3.851]],[\"name/515\",[14,21.711]],[\"parent/515\",[203,6.222]],[\"name/516\",[204,45.582]],[\"parent/516\",[205,5.384]],[\"name/517\",[206,49.935]],[\"parent/517\",[205,5.384]],[\"name/518\",[207,51.942]],[\"parent/518\",[205,5.384]],[\"name/519\",[186,46.834]],[\"parent/519\",[42,3.851]],[\"name/520\",[14,21.711]],[\"parent/520\",[208,6.222]],[\"name/521\",[188,46.834]],[\"parent/521\",[209,4.507]],[\"name/522\",[195,49.935]],[\"parent/522\",[209,4.507]],[\"name/523\",[190,46.834]],[\"parent/523\",[209,4.507]],[\"name/524\",[191,46.834]],[\"parent/524\",[209,4.507]],[\"name/525\",[194,46.834]],[\"parent/525\",[209,4.507]],[\"name/526\",[192,46.834]],[\"parent/526\",[209,4.507]],[\"name/527\",[193,46.834]],[\"parent/527\",[209,4.507]],[\"name/528\",[210,54.455]],[\"parent/528\",[209,4.507]],[\"name/529\",[196,44.47]],[\"parent/529\",[42,3.851]],[\"name/530\",[14,21.711]],[\"parent/530\",[211,6.222]],[\"name/531\",[212,57.82]],[\"parent/531\",[213,4.937]],[\"name/532\",[214,57.82]],[\"parent/532\",[213,4.937]],[\"name/533\",[215,57.82]],[\"parent/533\",[213,4.937]],[\"name/534\",[216,62.928]],[\"parent/534\",[213,4.937]],[\"name/535\",[217,62.928]],[\"parent/535\",[213,4.937]],[\"name/536\",[181,42.559]],[\"parent/536\",[52,3.913]],[\"name/537\",[14,21.711]],[\"parent/537\",[218,6.222]],[\"name/538\",[53,54.455]],[\"parent/538\",[219,4.937]],[\"name/539\",[54,54.455]],[\"parent/539\",[219,4.937]],[\"name/540\",[55,54.455]],[\"parent/540\",[219,4.937]],[\"name/541\",[56,54.455]],[\"parent/541\",[219,4.937]],[\"name/542\",[57,54.455]],[\"parent/542\",[219,4.937]],[\"name/543\",[186,46.834]],[\"parent/543\",[52,3.913]],[\"name/544\",[14,21.711]],[\"parent/544\",[220,6.222]],[\"name/545\",[188,46.834]],[\"parent/545\",[221,4.507]],[\"name/546\",[195,49.935]],[\"parent/546\",[221,4.507]],[\"name/547\",[190,46.834]],[\"parent/547\",[221,4.507]],[\"name/548\",[191,46.834]],[\"parent/548\",[221,4.507]],[\"name/549\",[194,46.834]],[\"parent/549\",[221,4.507]],[\"name/550\",[192,46.834]],[\"parent/550\",[221,4.507]],[\"name/551\",[193,46.834]],[\"parent/551\",[221,4.507]],[\"name/552\",[210,54.455]],[\"parent/552\",[221,4.507]],[\"name/553\",[196,44.47]],[\"parent/553\",[52,3.913]],[\"name/554\",[14,21.711]],[\"parent/554\",[222,6.222]],[\"name/555\",[223,62.928]],[\"parent/555\",[224,5.384]],[\"name/556\",[225,62.928]],[\"parent/556\",[224,5.384]],[\"name/557\",[226,62.928]],[\"parent/557\",[224,5.384]],[\"name/558\",[202,48.265]],[\"parent/558\",[52,3.913]],[\"name/559\",[14,21.711]],[\"parent/559\",[227,6.222]],[\"name/560\",[204,45.582]],[\"parent/560\",[228,5.717]],[\"name/561\",[206,49.935]],[\"parent/561\",[228,5.717]],[\"name/562\",[59,57.82]],[\"parent/562\",[52,3.913]],[\"name/563\",[196,44.47]],[\"parent/563\",[60,4.397]],[\"name/564\",[14,21.711]],[\"parent/564\",[229,6.222]],[\"name/565\",[230,62.928]],[\"parent/565\",[231,6.222]],[\"name/566\",[186,46.834]],[\"parent/566\",[60,4.397]],[\"name/567\",[14,21.711]],[\"parent/567\",[232,6.222]],[\"name/568\",[188,46.834]],[\"parent/568\",[233,4.772]],[\"name/569\",[190,46.834]],[\"parent/569\",[233,4.772]],[\"name/570\",[191,46.834]],[\"parent/570\",[233,4.772]],[\"name/571\",[194,46.834]],[\"parent/571\",[233,4.772]],[\"name/572\",[192,46.834]],[\"parent/572\",[233,4.772]],[\"name/573\",[193,46.834]],[\"parent/573\",[233,4.772]],[\"name/574\",[181,42.559]],[\"parent/574\",[60,4.397]],[\"name/575\",[14,21.711]],[\"parent/575\",[234,6.222]],[\"name/576\",[61,46.834]],[\"parent/576\",[235,5.717]],[\"name/577\",[62,46.834]],[\"parent/577\",[235,5.717]],[\"name/578\",[236,62.928]],[\"parent/578\",[60,4.397]],[\"name/579\",[14,21.711]],[\"parent/579\",[237,6.222]],[\"name/580\",[238,62.928]],[\"parent/580\",[239,4.772]],[\"name/581\",[240,62.928]],[\"parent/581\",[239,4.772]],[\"name/582\",[241,62.928]],[\"parent/582\",[239,4.772]],[\"name/583\",[242,62.928]],[\"parent/583\",[239,4.772]],[\"name/584\",[243,62.928]],[\"parent/584\",[239,4.772]],[\"name/585\",[244,62.928]],[\"parent/585\",[239,4.772]],[\"name/586\",[181,42.559]],[\"parent/586\",[67,3.421]],[\"name/587\",[14,21.711]],[\"parent/587\",[245,6.222]],[\"name/588\",[68,48.265]],[\"parent/588\",[246,4.049]],[\"name/589\",[75,48.265]],[\"parent/589\",[246,4.049]],[\"name/590\",[69,48.265]],[\"parent/590\",[246,4.049]],[\"name/591\",[45,39.574]],[\"parent/591\",[246,4.049]],[\"name/592\",[46,48.265]],[\"parent/592\",[246,4.049]],[\"name/593\",[70,48.265]],[\"parent/593\",[246,4.049]],[\"name/594\",[76,54.455]],[\"parent/594\",[246,4.049]],[\"name/595\",[77,48.265]],[\"parent/595\",[246,4.049]],[\"name/596\",[78,48.265]],[\"parent/596\",[246,4.049]],[\"name/597\",[72,48.265]],[\"parent/597\",[246,4.049]],[\"name/598\",[73,48.265]],[\"parent/598\",[246,4.049]],[\"name/599\",[71,48.265]],[\"parent/599\",[246,4.049]],[\"name/600\",[74,48.265]],[\"parent/600\",[246,4.049]],[\"name/601\",[202,48.265]],[\"parent/601\",[67,3.421]],[\"name/602\",[14,21.711]],[\"parent/602\",[247,6.222]],[\"name/603\",[204,45.582]],[\"parent/603\",[248,5.136]],[\"name/604\",[206,49.935]],[\"parent/604\",[248,5.136]],[\"name/605\",[249,62.928]],[\"parent/605\",[248,5.136]],[\"name/606\",[207,51.942]],[\"parent/606\",[248,5.136]],[\"name/607\",[186,46.834]],[\"parent/607\",[67,3.421]],[\"name/608\",[14,21.711]],[\"parent/608\",[250,6.222]],[\"name/609\",[188,46.834]],[\"parent/609\",[251,4.397]],[\"name/610\",[195,49.935]],[\"parent/610\",[251,4.397]],[\"name/611\",[190,46.834]],[\"parent/611\",[251,4.397]],[\"name/612\",[191,46.834]],[\"parent/612\",[251,4.397]],[\"name/613\",[194,46.834]],[\"parent/613\",[251,4.397]],[\"name/614\",[192,46.834]],[\"parent/614\",[251,4.397]],[\"name/615\",[193,46.834]],[\"parent/615\",[251,4.397]],[\"name/616\",[210,54.455]],[\"parent/616\",[251,4.397]],[\"name/617\",[252,62.928]],[\"parent/617\",[251,4.397]],[\"name/618\",[196,44.47]],[\"parent/618\",[67,3.421]],[\"name/619\",[14,21.711]],[\"parent/619\",[253,6.222]],[\"name/620\",[254,57.82]],[\"parent/620\",[255,4.937]],[\"name/621\",[256,57.82]],[\"parent/621\",[255,4.937]],[\"name/622\",[257,57.82]],[\"parent/622\",[255,4.937]],[\"name/623\",[212,57.82]],[\"parent/623\",[255,4.937]],[\"name/624\",[258,62.928]],[\"parent/624\",[255,4.937]],[\"name/625\",[259,62.928]],[\"parent/625\",[83,3.212]],[\"name/626\",[260,62.928]],[\"parent/626\",[261,5.384]],[\"name/627\",[262,62.928]],[\"parent/627\",[261,5.384]],[\"name/628\",[263,62.928]],[\"parent/628\",[261,5.384]],[\"name/629\",[181,42.559]],[\"parent/629\",[83,3.212]],[\"name/630\",[14,21.711]],[\"parent/630\",[264,6.222]],[\"name/631\",[84,54.455]],[\"parent/631\",[265,3.589]],[\"name/632\",[266,62.928]],[\"parent/632\",[265,3.589]],[\"name/633\",[85,54.455]],[\"parent/633\",[265,3.589]],[\"name/634\",[87,54.455]],[\"parent/634\",[265,3.589]],[\"name/635\",[86,54.455]],[\"parent/635\",[265,3.589]],[\"name/636\",[88,54.455]],[\"parent/636\",[265,3.589]],[\"name/637\",[89,54.455]],[\"parent/637\",[265,3.589]],[\"name/638\",[90,51.942]],[\"parent/638\",[265,3.589]],[\"name/639\",[91,54.455]],[\"parent/639\",[265,3.589]],[\"name/640\",[92,51.942]],[\"parent/640\",[265,3.589]],[\"name/641\",[93,51.942]],[\"parent/641\",[265,3.589]],[\"name/642\",[94,51.942]],[\"parent/642\",[265,3.589]],[\"name/643\",[102,57.82]],[\"parent/643\",[265,3.589]],[\"name/644\",[267,62.928]],[\"parent/644\",[265,3.589]],[\"name/645\",[268,62.928]],[\"parent/645\",[265,3.589]],[\"name/646\",[269,62.928]],[\"parent/646\",[265,3.589]],[\"name/647\",[99,54.455]],[\"parent/647\",[265,3.589]],[\"name/648\",[95,51.942]],[\"parent/648\",[265,3.589]],[\"name/649\",[96,51.942]],[\"parent/649\",[265,3.589]],[\"name/650\",[97,51.942]],[\"parent/650\",[265,3.589]],[\"name/651\",[98,51.942]],[\"parent/651\",[265,3.589]],[\"name/652\",[270,62.928]],[\"parent/652\",[83,3.212]],[\"name/653\",[90,51.942]],[\"parent/653\",[271,3.851]],[\"name/654\",[272,62.928]],[\"parent/654\",[271,3.851]],[\"name/655\",[92,51.942]],[\"parent/655\",[271,3.851]],[\"name/656\",[273,62.928]],[\"parent/656\",[271,3.851]],[\"name/657\",[274,62.928]],[\"parent/657\",[271,3.851]],[\"name/658\",[275,62.928]],[\"parent/658\",[271,3.851]],[\"name/659\",[276,62.928]],[\"parent/659\",[271,3.851]],[\"name/660\",[93,51.942]],[\"parent/660\",[271,3.851]],[\"name/661\",[94,51.942]],[\"parent/661\",[271,3.851]],[\"name/662\",[277,62.928]],[\"parent/662\",[271,3.851]],[\"name/663\",[278,62.928]],[\"parent/663\",[271,3.851]],[\"name/664\",[279,62.928]],[\"parent/664\",[271,3.851]],[\"name/665\",[95,51.942]],[\"parent/665\",[271,3.851]],[\"name/666\",[96,51.942]],[\"parent/666\",[271,3.851]],[\"name/667\",[97,51.942]],[\"parent/667\",[271,3.851]],[\"name/668\",[98,51.942]],[\"parent/668\",[271,3.851]],[\"name/669\",[196,44.47]],[\"parent/669\",[83,3.212]],[\"name/670\",[14,21.711]],[\"parent/670\",[280,6.222]],[\"name/671\",[281,62.928]],[\"parent/671\",[282,5.384]],[\"name/672\",[283,62.928]],[\"parent/672\",[282,5.384]],[\"name/673\",[284,62.928]],[\"parent/673\",[282,5.384]],[\"name/674\",[186,46.834]],[\"parent/674\",[83,3.212]],[\"name/675\",[14,21.711]],[\"parent/675\",[285,6.222]],[\"name/676\",[188,46.834]],[\"parent/676\",[286,4.772]],[\"name/677\",[190,46.834]],[\"parent/677\",[286,4.772]],[\"name/678\",[191,46.834]],[\"parent/678\",[286,4.772]],[\"name/679\",[194,46.834]],[\"parent/679\",[286,4.772]],[\"name/680\",[192,46.834]],[\"parent/680\",[286,4.772]],[\"name/681\",[193,46.834]],[\"parent/681\",[286,4.772]],[\"name/682\",[287,62.928]],[\"parent/682\",[83,3.212]],[\"name/683\",[14,21.711]],[\"parent/683\",[288,6.222]],[\"name/684\",[289,62.928]],[\"parent/684\",[290,4.772]],[\"name/685\",[291,54.455]],[\"parent/685\",[290,4.772]],[\"name/686\",[292,62.928]],[\"parent/686\",[290,4.772]],[\"name/687\",[293,62.928]],[\"parent/687\",[290,4.772]],[\"name/688\",[294,62.928]],[\"parent/688\",[290,4.772]],[\"name/689\",[295,62.928]],[\"parent/689\",[290,4.772]],[\"name/690\",[296,62.928]],[\"parent/690\",[83,3.212]],[\"name/691\",[181,42.559]],[\"parent/691\",[103,3.686]],[\"name/692\",[14,21.711]],[\"parent/692\",[297,6.222]],[\"name/693\",[45,39.574]],[\"parent/693\",[298,5.136]],[\"name/694\",[104,44.47]],[\"parent/694\",[298,5.136]],[\"name/695\",[105,44.47]],[\"parent/695\",[298,5.136]],[\"name/696\",[80,49.935]],[\"parent/696\",[298,5.136]],[\"name/697\",[202,48.265]],[\"parent/697\",[103,3.686]],[\"name/698\",[14,21.711]],[\"parent/698\",[299,6.222]],[\"name/699\",[204,45.582]],[\"parent/699\",[300,4.937]],[\"name/700\",[207,51.942]],[\"parent/700\",[300,4.937]],[\"name/701\",[206,49.935]],[\"parent/701\",[300,4.937]],[\"name/702\",[301,57.82]],[\"parent/702\",[300,4.937]],[\"name/703\",[14,21.711]],[\"parent/703\",[300,4.937]],[\"name/704\",[204,45.582]],[\"parent/704\",[302,5.717]],[\"name/705\",[291,54.455]],[\"parent/705\",[302,5.717]],[\"name/706\",[196,44.47]],[\"parent/706\",[103,3.686]],[\"name/707\",[14,21.711]],[\"parent/707\",[303,6.222]],[\"name/708\",[304,54.455]],[\"parent/708\",[305,5.384]],[\"name/709\",[306,62.928]],[\"parent/709\",[305,5.384]],[\"name/710\",[307,54.455]],[\"parent/710\",[305,5.384]],[\"name/711\",[186,46.834]],[\"parent/711\",[103,3.686]],[\"name/712\",[14,21.711]],[\"parent/712\",[308,6.222]],[\"name/713\",[188,46.834]],[\"parent/713\",[309,4.507]],[\"name/714\",[190,46.834]],[\"parent/714\",[309,4.507]],[\"name/715\",[191,46.834]],[\"parent/715\",[309,4.507]],[\"name/716\",[194,46.834]],[\"parent/716\",[309,4.507]],[\"name/717\",[310,62.928]],[\"parent/717\",[309,4.507]],[\"name/718\",[192,46.834]],[\"parent/718\",[309,4.507]],[\"name/719\",[193,46.834]],[\"parent/719\",[309,4.507]],[\"name/720\",[195,49.935]],[\"parent/720\",[309,4.507]],[\"name/721\",[311,54.455]],[\"parent/721\",[103,3.686]],[\"name/722\",[14,21.711]],[\"parent/722\",[312,6.222]],[\"name/723\",[204,45.582]],[\"parent/723\",[313,5.384]],[\"name/724\",[314,62.928]],[\"parent/724\",[313,5.384]],[\"name/725\",[315,62.928]],[\"parent/725\",[313,5.384]],[\"name/726\",[181,42.559]],[\"parent/726\",[113,3.382]],[\"name/727\",[14,21.711]],[\"parent/727\",[316,6.222]],[\"name/728\",[45,39.574]],[\"parent/728\",[317,4.397]],[\"name/729\",[104,44.47]],[\"parent/729\",[317,4.397]],[\"name/730\",[105,44.47]],[\"parent/730\",[317,4.397]],[\"name/731\",[116,48.265]],[\"parent/731\",[317,4.397]],[\"name/732\",[114,54.455]],[\"parent/732\",[317,4.397]],[\"name/733\",[115,54.455]],[\"parent/733\",[317,4.397]],[\"name/734\",[47,48.265]],[\"parent/734\",[317,4.397]],[\"name/735\",[48,48.265]],[\"parent/735\",[317,4.397]],[\"name/736\",[49,48.265]],[\"parent/736\",[317,4.397]],[\"name/737\",[311,54.455]],[\"parent/737\",[113,3.382]],[\"name/738\",[202,48.265]],[\"parent/738\",[113,3.382]],[\"name/739\",[14,21.711]],[\"parent/739\",[318,6.222]],[\"name/740\",[204,45.582]],[\"parent/740\",[319,4.937]],[\"name/741\",[207,51.942]],[\"parent/741\",[319,4.937]],[\"name/742\",[206,49.935]],[\"parent/742\",[319,4.937]],[\"name/743\",[301,57.82]],[\"parent/743\",[319,4.937]],[\"name/744\",[14,21.711]],[\"parent/744\",[319,4.937]],[\"name/745\",[204,45.582]],[\"parent/745\",[320,5.717]],[\"name/746\",[291,54.455]],[\"parent/746\",[320,5.717]],[\"name/747\",[196,44.47]],[\"parent/747\",[113,3.382]],[\"name/748\",[14,21.711]],[\"parent/748\",[321,6.222]],[\"name/749\",[304,54.455]],[\"parent/749\",[322,4.507]],[\"name/750\",[323,62.928]],[\"parent/750\",[322,4.507]],[\"name/751\",[214,57.82]],[\"parent/751\",[322,4.507]],[\"name/752\",[215,57.82]],[\"parent/752\",[322,4.507]],[\"name/753\",[324,57.82]],[\"parent/753\",[322,4.507]],[\"name/754\",[325,62.928]],[\"parent/754\",[322,4.507]],[\"name/755\",[326,62.928]],[\"parent/755\",[322,4.507]],[\"name/756\",[307,54.455]],[\"parent/756\",[322,4.507]],[\"name/757\",[327,62.928]],[\"parent/757\",[113,3.382]],[\"name/758\",[328,57.82]],[\"parent/758\",[113,3.382]],[\"name/759\",[181,42.559]],[\"parent/759\",[118,3.093]],[\"name/760\",[14,21.711]],[\"parent/760\",[329,6.222]],[\"name/761\",[45,39.574]],[\"parent/761\",[330,3.913]],[\"name/762\",[104,44.47]],[\"parent/762\",[330,3.913]],[\"name/763\",[70,48.265]],[\"parent/763\",[330,3.913]],[\"name/764\",[105,44.47]],[\"parent/764\",[330,3.913]],[\"name/765\",[116,48.265]],[\"parent/765\",[330,3.913]],[\"name/766\",[68,48.265]],[\"parent/766\",[330,3.913]],[\"name/767\",[75,48.265]],[\"parent/767\",[330,3.913]],[\"name/768\",[69,48.265]],[\"parent/768\",[330,3.913]],[\"name/769\",[120,54.455]],[\"parent/769\",[330,3.913]],[\"name/770\",[77,48.265]],[\"parent/770\",[330,3.913]],[\"name/771\",[78,48.265]],[\"parent/771\",[330,3.913]],[\"name/772\",[72,48.265]],[\"parent/772\",[330,3.913]],[\"name/773\",[73,48.265]],[\"parent/773\",[330,3.913]],[\"name/774\",[71,48.265]],[\"parent/774\",[330,3.913]],[\"name/775\",[74,48.265]],[\"parent/775\",[330,3.913]],[\"name/776\",[311,54.455]],[\"parent/776\",[118,3.093]],[\"name/777\",[202,48.265]],[\"parent/777\",[118,3.093]],[\"name/778\",[196,44.47]],[\"parent/778\",[118,3.093]],[\"name/779\",[14,21.711]],[\"parent/779\",[331,6.222]],[\"name/780\",[304,54.455]],[\"parent/780\",[332,4.507]],[\"name/781\",[324,57.82]],[\"parent/781\",[332,4.507]],[\"name/782\",[307,54.455]],[\"parent/782\",[332,4.507]],[\"name/783\",[254,57.82]],[\"parent/783\",[332,4.507]],[\"name/784\",[256,57.82]],[\"parent/784\",[332,4.507]],[\"name/785\",[257,57.82]],[\"parent/785\",[332,4.507]],[\"name/786\",[333,62.928]],[\"parent/786\",[332,4.507]],[\"name/787\",[334,62.928]],[\"parent/787\",[332,4.507]],[\"name/788\",[335,62.928]],[\"parent/788\",[118,3.093]],[\"name/789\",[328,57.82]],[\"parent/789\",[118,3.093]],[\"name/790\",[181,42.559]],[\"parent/790\",[122,4.507]],[\"name/791\",[14,21.711]],[\"parent/791\",[336,6.222]],[\"name/792\",[123,54.455]],[\"parent/792\",[337,5.384]],[\"name/793\",[124,54.455]],[\"parent/793\",[337,5.384]],[\"name/794\",[125,54.455]],[\"parent/794\",[337,5.384]],[\"name/795\",[338,62.928]],[\"parent/795\",[122,4.507]],[\"name/796\",[140,57.82]],[\"parent/796\",[127,3.851]],[\"name/797\",[139,57.82]],[\"parent/797\",[127,3.851]],[\"name/798\",[181,42.559]],[\"parent/798\",[127,3.851]],[\"name/799\",[14,21.711]],[\"parent/799\",[339,6.222]],[\"name/800\",[128,54.455]],[\"parent/800\",[340,4.298]],[\"name/801\",[129,54.455]],[\"parent/801\",[340,4.298]],[\"name/802\",[130,54.455]],[\"parent/802\",[340,4.298]],[\"name/803\",[131,54.455]],[\"parent/803\",[340,4.298]],[\"name/804\",[132,54.455]],[\"parent/804\",[340,4.298]],[\"name/805\",[133,54.455]],[\"parent/805\",[340,4.298]],[\"name/806\",[134,54.455]],[\"parent/806\",[340,4.298]],[\"name/807\",[135,54.455]],[\"parent/807\",[340,4.298]],[\"name/808\",[136,54.455]],[\"parent/808\",[340,4.298]],[\"name/809\",[137,54.455]],[\"parent/809\",[340,4.298]]],\"invertedIndex\":[[\"__type\",{\"_index\":14,\"name\":{\"14\":{},\"34\":{},\"79\":{},\"94\":{},\"116\":{},\"132\":{},\"143\":{},\"170\":{},\"215\":{},\"254\":{},\"261\":{},\"263\":{},\"265\":{},\"267\":{},\"269\":{},\"271\":{},\"294\":{},\"306\":{},\"308\":{},\"310\":{},\"312\":{},\"314\":{},\"316\":{},\"349\":{},\"369\":{},\"371\":{},\"373\":{},\"375\":{},\"377\":{},\"379\":{},\"390\":{},\"409\":{},\"428\":{},\"430\":{},\"432\":{},\"434\":{},\"436\":{},\"438\":{},\"440\":{},\"446\":{},\"448\":{},\"450\":{},\"452\":{},\"454\":{},\"456\":{},\"460\":{},\"462\":{},\"468\":{},\"470\":{},\"473\":{},\"474\":{},\"475\":{},\"476\":{},\"477\":{},\"484\":{},\"490\":{},\"494\":{},\"503\":{},\"506\":{},\"515\":{},\"520\":{},\"530\":{},\"537\":{},\"544\":{},\"554\":{},\"559\":{},\"564\":{},\"567\":{},\"575\":{},\"579\":{},\"587\":{},\"602\":{},\"608\":{},\"619\":{},\"630\":{},\"670\":{},\"675\":{},\"683\":{},\"692\":{},\"698\":{},\"703\":{},\"707\":{},\"712\":{},\"722\":{},\"727\":{},\"739\":{},\"744\":{},\"748\":{},\"760\":{},\"779\":{},\"791\":{},\"799\":{}},\"parent\":{}}],[\"accesstokenpayload\",{\"_index\":294,\"name\":{\"688\":{}},\"parent\":{}}],[\"addroletouser\",{\"_index\":128,\"name\":{\"397\":{},\"412\":{},\"800\":{}},\"parent\":{}}],[\"alg\",{\"_index\":243,\"name\":{\"584\":{}},\"parent\":{}}],[\"anticsrfcheck\",{\"_index\":260,\"name\":{\"626\":{}},\"parent\":{}}],[\"apiinterface\",{\"_index\":196,\"name\":{\"502\":{},\"529\":{},\"553\":{},\"563\":{},\"618\":{},\"669\":{},\"706\":{},\"747\":{},\"778\":{}},\"parent\":{}}],[\"apioptions\",{\"_index\":186,\"name\":{\"493\":{},\"519\":{},\"543\":{},\"566\":{},\"607\":{},\"674\":{},\"711\":{}},\"parent\":{}}],[\"appinfo\",{\"_index\":195,\"name\":{\"501\":{},\"522\":{},\"546\":{},\"610\":{},\"720\":{}},\"parent\":{}}],[\"apple\",{\"_index\":109,\"name\":{\"249\":{},\"266\":{},\"288\":{},\"311\":{},\"342\":{},\"374\":{}},\"parent\":{}}],[\"appleredirecthandlerpost\",{\"_index\":307,\"name\":{\"710\":{},\"756\":{},\"782\":{}},\"parent\":{}}],[\"assertclaims\",{\"_index\":279,\"name\":{\"664\":{}},\"parent\":{}}],[\"authorisationurlget\",{\"_index\":304,\"name\":{\"708\":{},\"749\":{},\"780\":{}},\"parent\":{}}],[\"awslambda\",{\"_index\":22,\"name\":{\"32\":{},\"40\":{}},\"parent\":{}}],[\"baserequest\",{\"_index\":141,\"name\":{\"423\":{}},\"parent\":{}}],[\"baseresponse\",{\"_index\":152,\"name\":{\"441\":{}},\"parent\":{}}],[\"clearusermetadata\",{\"_index\":125,\"name\":{\"387\":{},\"393\":{},\"794\":{}},\"parent\":{}}],[\"config\",{\"_index\":190,\"name\":{\"496\":{},\"523\":{},\"547\":{},\"569\":{},\"611\":{},\"677\":{},\"714\":{}},\"parent\":{}}],[\"constructor\",{\"_index\":15,\"name\":{\"25\":{},\"69\":{},\"73\":{},\"80\":{},\"104\":{},\"125\":{},\"135\":{},\"147\":{},\"189\":{},\"238\":{},\"272\":{},\"318\":{},\"382\":{},\"394\":{},\"422\":{},\"424\":{},\"442\":{}},\"parent\":{}}],[\"consumecode\",{\"_index\":69,\"name\":{\"152\":{},\"174\":{},\"328\":{},\"357\":{},\"590\":{},\"768\":{}},\"parent\":{}}],[\"consumecodepost\",{\"_index\":257,\"name\":{\"622\":{},\"785\":{}},\"parent\":{}}],[\"cookies\",{\"_index\":168,\"name\":{\"464\":{},\"472\":{}},\"parent\":{}}],[\"createcode\",{\"_index\":68,\"name\":{\"151\":{},\"172\":{},\"327\":{},\"355\":{},\"588\":{},\"766\":{}},\"parent\":{}}],[\"createcodepost\",{\"_index\":254,\"name\":{\"620\":{},\"783\":{}},\"parent\":{}}],[\"createemailverificationtoken\",{\"_index\":53,\"name\":{\"108\":{},\"119\":{},\"538\":{}},\"parent\":{}}],[\"createjwt\",{\"_index\":61,\"name\":{\"128\":{},\"133\":{},\"139\":{},\"145\":{},\"210\":{},\"231\":{},\"576\":{}},\"parent\":{}}],[\"createmagiclink\",{\"_index\":79,\"name\":{\"164\":{},\"185\":{},\"338\":{},\"366\":{}},\"parent\":{}}],[\"createnewcodefordevice\",{\"_index\":75,\"name\":{\"160\":{},\"173\":{},\"334\":{},\"356\":{},\"589\":{},\"767\":{}},\"parent\":{}}],[\"createnewroleoraddpermissions\",{\"_index\":132,\"name\":{\"401\":{},\"416\":{},\"804\":{}},\"parent\":{}}],[\"createnewsession\",{\"_index\":84,\"name\":{\"192\":{},\"217\":{},\"631\":{}},\"parent\":{}}],[\"createresetpasswordtoken\",{\"_index\":47,\"name\":{\"88\":{},\"100\":{},\"282\":{},\"302\":{},\"511\":{},\"734\":{}},\"parent\":{}}],[\"createuseridmapping\",{\"_index\":7,\"name\":{\"7\":{},\"21\":{}},\"parent\":{}}],[\"dashboardget\",{\"_index\":198,\"name\":{\"504\":{}},\"parent\":{}}],[\"default\",{\"_index\":12,\"name\":{\"12\":{},\"33\":{},\"68\":{},\"72\":{},\"77\":{},\"92\":{},\"114\":{},\"130\":{},\"141\":{},\"168\":{},\"213\":{},\"252\":{},\"292\":{},\"347\":{},\"388\":{},\"407\":{}},\"parent\":{}}],[\"deleterole\",{\"_index\":136,\"name\":{\"405\":{},\"420\":{},\"808\":{}},\"parent\":{}}],[\"deleteuser\",{\"_index\":6,\"name\":{\"6\":{},\"20\":{}},\"parent\":{}}],[\"deleteuseridmapping\",{\"_index\":9,\"name\":{\"9\":{},\"23\":{}},\"parent\":{}}],[\"discord\",{\"_index\":110,\"name\":{\"250\":{},\"268\":{},\"289\":{},\"313\":{},\"343\":{},\"376\":{}},\"parent\":{}}],[\"e\",{\"_index\":242,\"name\":{\"583\":{}},\"parent\":{}}],[\"email\",{\"_index\":206,\"name\":{\"517\":{},\"561\":{},\"604\":{},\"701\":{},\"742\":{}},\"parent\":{}}],[\"emaildelivery\",{\"_index\":210,\"name\":{\"528\":{},\"552\":{},\"616\":{}},\"parent\":{}}],[\"emailexistsget\",{\"_index\":212,\"name\":{\"531\":{},\"623\":{}},\"parent\":{}}],[\"emailpasswordapioptions\",{\"_index\":327,\"name\":{\"757\":{}},\"parent\":{}}],[\"emailpasswordemailexistsget\",{\"_index\":323,\"name\":{\"750\":{}},\"parent\":{}}],[\"emailpasswordsignin\",{\"_index\":115,\"name\":{\"277\":{},\"299\":{},\"733\":{}},\"parent\":{}}],[\"emailpasswordsigninpost\",{\"_index\":325,\"name\":{\"754\":{}},\"parent\":{}}],[\"emailpasswordsignup\",{\"_index\":114,\"name\":{\"276\":{},\"298\":{},\"732\":{}},\"parent\":{}}],[\"emailpasswordsignuppost\",{\"_index\":326,\"name\":{\"755\":{}},\"parent\":{}}],[\"emailverificationclaim\",{\"_index\":59,\"name\":{\"118\":{},\"562\":{}},\"parent\":{}}],[\"error\",{\"_index\":11,\"name\":{\"11\":{},\"15\":{},\"83\":{},\"95\":{},\"107\":{},\"117\":{},\"150\":{},\"171\":{},\"209\":{},\"216\":{},\"241\":{},\"255\":{},\"275\":{},\"295\":{},\"321\":{},\"350\":{}},\"parent\":{}}],[\"errorhandler\",{\"_index\":29,\"name\":{\"47\":{},\"52\":{}},\"parent\":{}}],[\"expiry\",{\"_index\":293,\"name\":{\"687\":{}},\"parent\":{}}],[\"express\",{\"_index\":17,\"name\":{\"27\":{},\"35\":{}},\"parent\":{}}],[\"facebook\",{\"_index\":108,\"name\":{\"248\":{},\"264\":{},\"287\":{},\"309\":{},\"341\":{},\"372\":{}},\"parent\":{}}],[\"fastify\",{\"_index\":18,\"name\":{\"28\":{},\"36\":{}},\"parent\":{}}],[\"fetchandsetclaim\",{\"_index\":95,\"name\":{\"203\":{},\"234\":{},\"648\":{},\"665\":{}},\"parent\":{}}],[\"framework\",{\"_index\":16,\"name\":{\"26\":{}},\"parent\":{\"27\":{},\"28\":{},\"29\":{},\"30\":{},\"31\":{},\"32\":{},\"33\":{},\"34\":{},\"423\":{},\"441\":{}}}],[\"framework.__type\",{\"_index\":23,\"name\":{},\"parent\":{\"35\":{},\"36\":{},\"37\":{},\"38\":{},\"39\":{},\"40\":{}}}],[\"framework.baserequest\",{\"_index\":142,\"name\":{},\"parent\":{\"424\":{},\"425\":{},\"426\":{},\"427\":{},\"428\":{},\"429\":{},\"430\":{},\"431\":{},\"432\":{},\"433\":{},\"434\":{},\"435\":{},\"436\":{},\"437\":{},\"438\":{},\"439\":{},\"440\":{}}}],[\"framework.baseresponse\",{\"_index\":153,\"name\":{},\"parent\":{\"442\":{},\"443\":{},\"444\":{},\"445\":{},\"446\":{},\"447\":{},\"448\":{},\"449\":{},\"450\":{},\"451\":{},\"452\":{},\"453\":{},\"454\":{},\"455\":{},\"456\":{}}}],[\"framework/awslambda\",{\"_index\":24,\"name\":{\"41\":{}},\"parent\":{\"42\":{},\"43\":{},\"44\":{},\"457\":{},\"465\":{}}}],[\"framework/awslambda.sessionevent\",{\"_index\":162,\"name\":{},\"parent\":{\"458\":{},\"459\":{},\"460\":{}}}],[\"framework/awslambda.sessionevent.__type\",{\"_index\":165,\"name\":{},\"parent\":{\"461\":{},\"462\":{}}}],[\"framework/awslambda.sessionevent.__type.__type\",{\"_index\":167,\"name\":{},\"parent\":{\"463\":{},\"464\":{}}}],[\"framework/awslambda.sessioneventv2\",{\"_index\":170,\"name\":{},\"parent\":{\"466\":{},\"467\":{},\"468\":{},\"473\":{}}}],[\"framework/awslambda.sessioneventv2.__type\",{\"_index\":171,\"name\":{},\"parent\":{\"469\":{},\"470\":{},\"474\":{},\"477\":{}}}],[\"framework/awslambda.sessioneventv2.__type.__type\",{\"_index\":172,\"name\":{},\"parent\":{\"471\":{},\"472\":{},\"475\":{}}}],[\"framework/awslambda.sessioneventv2.__type.__type.__type\",{\"_index\":173,\"name\":{},\"parent\":{\"476\":{}}}],[\"framework/express\",{\"_index\":28,\"name\":{\"45\":{}},\"parent\":{\"46\":{},\"47\":{},\"48\":{},\"49\":{},\"478\":{}}}],[\"framework/express.sessionrequest\",{\"_index\":175,\"name\":{},\"parent\":{\"479\":{}}}],[\"framework/fastify\",{\"_index\":30,\"name\":{\"50\":{}},\"parent\":{\"51\":{},\"52\":{},\"53\":{},\"54\":{},\"480\":{}}}],[\"framework/fastify.sessionrequest\",{\"_index\":176,\"name\":{},\"parent\":{\"481\":{}}}],[\"framework/hapi\",{\"_index\":32,\"name\":{\"55\":{}},\"parent\":{\"56\":{},\"57\":{},\"58\":{},\"482\":{}}}],[\"framework/hapi.sessionrequest\",{\"_index\":177,\"name\":{},\"parent\":{\"483\":{},\"484\":{}}}],[\"framework/koa\",{\"_index\":33,\"name\":{\"59\":{}},\"parent\":{\"60\":{},\"61\":{},\"62\":{},\"485\":{}}}],[\"framework/koa.sessioncontext\",{\"_index\":179,\"name\":{},\"parent\":{\"486\":{}}}],[\"framework/loopback\",{\"_index\":34,\"name\":{\"63\":{}},\"parent\":{\"64\":{},\"65\":{},\"66\":{},\"487\":{}}}],[\"framework/loopback.sessioncontext\",{\"_index\":180,\"name\":{},\"parent\":{\"488\":{}}}],[\"generateemailverifytokenpost\",{\"_index\":226,\"name\":{\"557\":{}},\"parent\":{}}],[\"generatepasswordresettokenpost\",{\"_index\":214,\"name\":{\"532\":{},\"751\":{}},\"parent\":{}}],[\"get\",{\"_index\":314,\"name\":{\"724\":{}},\"parent\":{}}],[\"getaccesstoken\",{\"_index\":276,\"name\":{\"659\":{}},\"parent\":{}}],[\"getaccesstokenlifetimems\",{\"_index\":267,\"name\":{\"644\":{}},\"parent\":{}}],[\"getaccesstokenpayload\",{\"_index\":274,\"name\":{\"657\":{}},\"parent\":{}}],[\"getallcorsheaders\",{\"_index\":2,\"name\":{\"2\":{},\"16\":{}},\"parent\":{}}],[\"getallroles\",{\"_index\":137,\"name\":{\"406\":{},\"421\":{},\"809\":{}},\"parent\":{}}],[\"getallsessionhandlesforuser\",{\"_index\":89,\"name\":{\"197\":{},\"224\":{},\"637\":{}},\"parent\":{}}],[\"getclaimvalue\",{\"_index\":97,\"name\":{\"205\":{},\"236\":{},\"650\":{},\"667\":{}},\"parent\":{}}],[\"getcookievalue\",{\"_index\":148,\"name\":{\"433\":{}},\"parent\":{}}],[\"getdashboardbundlelocation\",{\"_index\":183,\"name\":{\"491\":{}},\"parent\":{}}],[\"getexpiry\",{\"_index\":278,\"name\":{\"663\":{}},\"parent\":{}}],[\"getformdata\",{\"_index\":151,\"name\":{\"439\":{}},\"parent\":{}}],[\"getglobalclaimvalidators\",{\"_index\":266,\"name\":{\"632\":{}},\"parent\":{}}],[\"gethandle\",{\"_index\":275,\"name\":{\"658\":{}},\"parent\":{}}],[\"getheadervalue\",{\"_index\":149,\"name\":{\"435\":{}},\"parent\":{}}],[\"getjsonbody\",{\"_index\":146,\"name\":{\"429\":{}},\"parent\":{}}],[\"getjwks\",{\"_index\":62,\"name\":{\"129\":{},\"134\":{},\"140\":{},\"146\":{},\"211\":{},\"232\":{},\"577\":{}},\"parent\":{}}],[\"getjwksget\",{\"_index\":230,\"name\":{\"565\":{}},\"parent\":{}}],[\"getkeyvaluefromquery\",{\"_index\":145,\"name\":{\"427\":{}},\"parent\":{}}],[\"getmethod\",{\"_index\":147,\"name\":{\"431\":{}},\"parent\":{}}],[\"getopeniddiscoveryconfiguration\",{\"_index\":65,\"name\":{\"138\":{},\"144\":{},\"212\":{},\"233\":{}},\"parent\":{}}],[\"getoriginalurl\",{\"_index\":150,\"name\":{\"437\":{}},\"parent\":{}}],[\"getpermissionsforrole\",{\"_index\":133,\"name\":{\"402\":{},\"417\":{},\"805\":{}},\"parent\":{}}],[\"getrefreshtokenlifetimems\",{\"_index\":268,\"name\":{\"645\":{}},\"parent\":{}}],[\"getrolesforuser\",{\"_index\":130,\"name\":{\"399\":{},\"414\":{},\"802\":{}},\"parent\":{}}],[\"getrolesthathavepermission\",{\"_index\":135,\"name\":{\"404\":{},\"419\":{},\"807\":{}},\"parent\":{}}],[\"getsession\",{\"_index\":85,\"name\":{\"193\":{},\"220\":{},\"633\":{}},\"parent\":{}}],[\"getsessiondata\",{\"_index\":272,\"name\":{\"654\":{}},\"parent\":{}}],[\"getsessioninformation\",{\"_index\":86,\"name\":{\"194\":{},\"221\":{},\"635\":{}},\"parent\":{}}],[\"gettimecreated\",{\"_index\":277,\"name\":{\"662\":{}},\"parent\":{}}],[\"getuserbyemail\",{\"_index\":46,\"name\":{\"87\":{},\"99\":{},\"153\":{},\"176\":{},\"510\":{},\"592\":{}},\"parent\":{}}],[\"getuserbyid\",{\"_index\":45,\"name\":{\"86\":{},\"98\":{},\"154\":{},\"175\":{},\"243\":{},\"257\":{},\"279\":{},\"300\":{},\"324\":{},\"353\":{},\"509\":{},\"591\":{},\"693\":{},\"728\":{},\"761\":{}},\"parent\":{}}],[\"getuserbyphonenumber\",{\"_index\":70,\"name\":{\"155\":{},\"177\":{},\"329\":{},\"358\":{},\"593\":{},\"763\":{}},\"parent\":{}}],[\"getuserbythirdpartyinfo\",{\"_index\":105,\"name\":{\"245\":{},\"259\":{},\"280\":{},\"297\":{},\"325\":{},\"352\":{},\"695\":{},\"730\":{},\"764\":{}},\"parent\":{}}],[\"getusercount\",{\"_index\":3,\"name\":{\"3\":{},\"17\":{}},\"parent\":{}}],[\"getuserid\",{\"_index\":273,\"name\":{\"656\":{}},\"parent\":{}}],[\"getuseridmapping\",{\"_index\":8,\"name\":{\"8\":{},\"22\":{}},\"parent\":{}}],[\"getusermetadata\",{\"_index\":123,\"name\":{\"385\":{},\"391\":{},\"792\":{}},\"parent\":{}}],[\"getusersbyemail\",{\"_index\":104,\"name\":{\"244\":{},\"258\":{},\"281\":{},\"301\":{},\"326\":{},\"354\":{},\"694\":{},\"729\":{},\"762\":{}},\"parent\":{}}],[\"getusersnewestfirst\",{\"_index\":5,\"name\":{\"5\":{},\"19\":{}},\"parent\":{}}],[\"getusersoldestfirst\",{\"_index\":4,\"name\":{\"4\":{},\"18\":{}},\"parent\":{}}],[\"getusersthathaverole\",{\"_index\":131,\"name\":{\"400\":{},\"415\":{},\"803\":{}},\"parent\":{}}],[\"github\",{\"_index\":107,\"name\":{\"247\":{},\"262\":{},\"286\":{},\"307\":{},\"340\":{},\"370\":{}},\"parent\":{}}],[\"google\",{\"_index\":106,\"name\":{\"246\":{},\"260\":{},\"285\":{},\"305\":{},\"339\":{},\"368\":{}},\"parent\":{}}],[\"googleworkspaces\",{\"_index\":111,\"name\":{\"251\":{},\"270\":{},\"290\":{},\"315\":{},\"344\":{},\"378\":{}},\"parent\":{}}],[\"hapi\",{\"_index\":19,\"name\":{\"29\":{},\"37\":{}},\"parent\":{}}],[\"headers\",{\"_index\":166,\"name\":{\"463\":{},\"471\":{}},\"parent\":{}}],[\"id\",{\"_index\":204,\"name\":{\"516\":{},\"560\":{},\"603\":{},\"699\":{},\"704\":{},\"723\":{},\"740\":{},\"745\":{}},\"parent\":{}}],[\"index\",{\"_index\":0,\"name\":{\"0\":{}},\"parent\":{\"1\":{},\"2\":{},\"3\":{},\"4\":{},\"5\":{},\"6\":{},\"7\":{},\"8\":{},\"9\":{},\"10\":{},\"11\":{},\"12\":{}}}],[\"index.default\",{\"_index\":13,\"name\":{},\"parent\":{\"13\":{},\"14\":{},\"15\":{},\"16\":{},\"17\":{},\"18\":{},\"19\":{},\"20\":{},\"21\":{},\"22\":{},\"23\":{},\"24\":{},\"25\":{}}}],[\"ingredientinterfaceimpl\",{\"_index\":37,\"name\":{\"70\":{},\"74\":{}},\"parent\":{}}],[\"ingredients/emaildelivery\",{\"_index\":35,\"name\":{\"67\":{}},\"parent\":{\"68\":{}}}],[\"ingredients/emaildelivery.default\",{\"_index\":36,\"name\":{},\"parent\":{\"69\":{},\"70\":{}}}],[\"ingredients/smsdelivery\",{\"_index\":38,\"name\":{\"71\":{}},\"parent\":{\"72\":{}}}],[\"ingredients/smsdelivery.default\",{\"_index\":39,\"name\":{},\"parent\":{\"73\":{},\"74\":{}}}],[\"init\",{\"_index\":1,\"name\":{\"1\":{},\"13\":{},\"76\":{},\"78\":{},\"82\":{},\"93\":{},\"106\":{},\"115\":{},\"127\":{},\"131\":{},\"137\":{},\"142\":{},\"149\":{},\"169\":{},\"191\":{},\"214\":{},\"240\":{},\"253\":{},\"274\":{},\"293\":{},\"320\":{},\"348\":{},\"384\":{},\"389\":{},\"396\":{},\"408\":{}},\"parent\":{}}],[\"isdefault\",{\"_index\":315,\"name\":{\"725\":{}},\"parent\":{}}],[\"isemailverified\",{\"_index\":55,\"name\":{\"110\":{},\"121\":{},\"540\":{}},\"parent\":{}}],[\"isemailverifiedget\",{\"_index\":225,\"name\":{\"556\":{}},\"parent\":{}}],[\"isinserverlessenv\",{\"_index\":194,\"name\":{\"500\":{},\"525\":{},\"549\":{},\"571\":{},\"613\":{},\"679\":{},\"716\":{}},\"parent\":{}}],[\"jsonobject\",{\"_index\":338,\"name\":{\"795\":{}},\"parent\":{}}],[\"jsonwebkey\",{\"_index\":236,\"name\":{\"578\":{}},\"parent\":{}}],[\"kid\",{\"_index\":240,\"name\":{\"581\":{}},\"parent\":{}}],[\"koa\",{\"_index\":21,\"name\":{\"31\":{},\"39\":{}},\"parent\":{}}],[\"kty\",{\"_index\":238,\"name\":{\"580\":{}},\"parent\":{}}],[\"listcodesbydeviceid\",{\"_index\":71,\"name\":{\"156\":{},\"183\":{},\"330\":{},\"364\":{},\"599\":{},\"774\":{}},\"parent\":{}}],[\"listcodesbyemail\",{\"_index\":72,\"name\":{\"157\":{},\"181\":{},\"331\":{},\"362\":{},\"597\":{},\"772\":{}},\"parent\":{}}],[\"listcodesbyphonenumber\",{\"_index\":73,\"name\":{\"158\":{},\"182\":{},\"332\":{},\"363\":{},\"598\":{},\"773\":{}},\"parent\":{}}],[\"listcodesbypreauthsessionid\",{\"_index\":74,\"name\":{\"159\":{},\"184\":{},\"333\":{},\"365\":{},\"600\":{},\"775\":{}},\"parent\":{}}],[\"loopback\",{\"_index\":20,\"name\":{\"30\":{},\"38\":{}},\"parent\":{}}],[\"mergeintoaccesstokenpayload\",{\"_index\":94,\"name\":{\"202\":{},\"230\":{},\"642\":{},\"661\":{}},\"parent\":{}}],[\"middleware\",{\"_index\":25,\"name\":{\"42\":{},\"46\":{},\"60\":{},\"64\":{}},\"parent\":{}}],[\"n\",{\"_index\":241,\"name\":{\"582\":{}},\"parent\":{}}],[\"original\",{\"_index\":144,\"name\":{\"426\":{},\"444\":{}},\"parent\":{}}],[\"overrideglobalclaimvalidators\",{\"_index\":263,\"name\":{\"628\":{}},\"parent\":{}}],[\"passwordlessapioptions\",{\"_index\":335,\"name\":{\"788\":{}},\"parent\":{}}],[\"passwordlesssigninup\",{\"_index\":119,\"name\":{\"323\":{},\"367\":{}},\"parent\":{}}],[\"passwordlessuseremailexistsget\",{\"_index\":333,\"name\":{\"786\":{}},\"parent\":{}}],[\"passwordlessuserphonenumberexistsget\",{\"_index\":334,\"name\":{\"787\":{}},\"parent\":{}}],[\"passwordresetpost\",{\"_index\":215,\"name\":{\"533\":{},\"752\":{}},\"parent\":{}}],[\"permissionclaim\",{\"_index\":139,\"name\":{\"410\":{},\"797\":{}},\"parent\":{}}],[\"phonenumber\",{\"_index\":249,\"name\":{\"605\":{}},\"parent\":{}}],[\"phonenumberexistsget\",{\"_index\":258,\"name\":{\"624\":{}},\"parent\":{}}],[\"plugin\",{\"_index\":31,\"name\":{\"51\":{},\"56\":{}},\"parent\":{}}],[\"providers\",{\"_index\":310,\"name\":{\"717\":{}},\"parent\":{}}],[\"recipe/dashboard\",{\"_index\":40,\"name\":{\"75\":{}},\"parent\":{\"76\":{},\"77\":{},\"489\":{},\"493\":{},\"502\":{}}}],[\"recipe/dashboard.apiinterface\",{\"_index\":197,\"name\":{},\"parent\":{\"503\":{}}}],[\"recipe/dashboard.apiinterface.__type\",{\"_index\":199,\"name\":{},\"parent\":{\"504\":{}}}],[\"recipe/dashboard.apioptions\",{\"_index\":187,\"name\":{},\"parent\":{\"494\":{}}}],[\"recipe/dashboard.apioptions.__type\",{\"_index\":189,\"name\":{},\"parent\":{\"495\":{},\"496\":{},\"497\":{},\"498\":{},\"499\":{},\"500\":{},\"501\":{}}}],[\"recipe/dashboard.default\",{\"_index\":41,\"name\":{},\"parent\":{\"78\":{},\"79\":{},\"80\":{}}}],[\"recipe/dashboard.recipeinterface\",{\"_index\":182,\"name\":{},\"parent\":{\"490\":{}}}],[\"recipe/dashboard.recipeinterface.__type\",{\"_index\":184,\"name\":{},\"parent\":{\"491\":{},\"492\":{}}}],[\"recipe/emailpassword\",{\"_index\":42,\"name\":{\"81\":{}},\"parent\":{\"82\":{},\"83\":{},\"84\":{},\"85\":{},\"86\":{},\"87\":{},\"88\":{},\"89\":{},\"90\":{},\"91\":{},\"92\":{},\"505\":{},\"514\":{},\"519\":{},\"529\":{}}}],[\"recipe/emailpassword.apiinterface\",{\"_index\":211,\"name\":{},\"parent\":{\"530\":{}}}],[\"recipe/emailpassword.apiinterface.__type\",{\"_index\":213,\"name\":{},\"parent\":{\"531\":{},\"532\":{},\"533\":{},\"534\":{},\"535\":{}}}],[\"recipe/emailpassword.apioptions\",{\"_index\":208,\"name\":{},\"parent\":{\"520\":{}}}],[\"recipe/emailpassword.apioptions.__type\",{\"_index\":209,\"name\":{},\"parent\":{\"521\":{},\"522\":{},\"523\":{},\"524\":{},\"525\":{},\"526\":{},\"527\":{},\"528\":{}}}],[\"recipe/emailpassword.default\",{\"_index\":51,\"name\":{},\"parent\":{\"93\":{},\"94\":{},\"95\":{},\"96\":{},\"97\":{},\"98\":{},\"99\":{},\"100\":{},\"101\":{},\"102\":{},\"103\":{},\"104\":{}}}],[\"recipe/emailpassword.recipeinterface\",{\"_index\":200,\"name\":{},\"parent\":{\"506\":{}}}],[\"recipe/emailpassword.recipeinterface.__type\",{\"_index\":201,\"name\":{},\"parent\":{\"507\":{},\"508\":{},\"509\":{},\"510\":{},\"511\":{},\"512\":{},\"513\":{}}}],[\"recipe/emailpassword.user\",{\"_index\":203,\"name\":{},\"parent\":{\"515\":{}}}],[\"recipe/emailpassword.user.__type\",{\"_index\":205,\"name\":{},\"parent\":{\"516\":{},\"517\":{},\"518\":{}}}],[\"recipe/emailverification\",{\"_index\":52,\"name\":{\"105\":{}},\"parent\":{\"106\":{},\"107\":{},\"108\":{},\"109\":{},\"110\":{},\"111\":{},\"112\":{},\"113\":{},\"114\":{},\"536\":{},\"543\":{},\"553\":{},\"558\":{},\"562\":{}}}],[\"recipe/emailverification.apiinterface\",{\"_index\":222,\"name\":{},\"parent\":{\"554\":{}}}],[\"recipe/emailverification.apiinterface.__type\",{\"_index\":224,\"name\":{},\"parent\":{\"555\":{},\"556\":{},\"557\":{}}}],[\"recipe/emailverification.apioptions\",{\"_index\":220,\"name\":{},\"parent\":{\"544\":{}}}],[\"recipe/emailverification.apioptions.__type\",{\"_index\":221,\"name\":{},\"parent\":{\"545\":{},\"546\":{},\"547\":{},\"548\":{},\"549\":{},\"550\":{},\"551\":{},\"552\":{}}}],[\"recipe/emailverification.default\",{\"_index\":58,\"name\":{},\"parent\":{\"115\":{},\"116\":{},\"117\":{},\"118\":{},\"119\":{},\"120\":{},\"121\":{},\"122\":{},\"123\":{},\"124\":{},\"125\":{}}}],[\"recipe/emailverification.recipeinterface\",{\"_index\":218,\"name\":{},\"parent\":{\"537\":{}}}],[\"recipe/emailverification.recipeinterface.__type\",{\"_index\":219,\"name\":{},\"parent\":{\"538\":{},\"539\":{},\"540\":{},\"541\":{},\"542\":{}}}],[\"recipe/emailverification.user\",{\"_index\":227,\"name\":{},\"parent\":{\"559\":{}}}],[\"recipe/emailverification.user.__type\",{\"_index\":228,\"name\":{},\"parent\":{\"560\":{},\"561\":{}}}],[\"recipe/jwt\",{\"_index\":60,\"name\":{\"126\":{}},\"parent\":{\"127\":{},\"128\":{},\"129\":{},\"130\":{},\"563\":{},\"566\":{},\"574\":{},\"578\":{}}}],[\"recipe/jwt.apiinterface\",{\"_index\":229,\"name\":{},\"parent\":{\"564\":{}}}],[\"recipe/jwt.apiinterface.__type\",{\"_index\":231,\"name\":{},\"parent\":{\"565\":{}}}],[\"recipe/jwt.apioptions\",{\"_index\":232,\"name\":{},\"parent\":{\"567\":{}}}],[\"recipe/jwt.apioptions.__type\",{\"_index\":233,\"name\":{},\"parent\":{\"568\":{},\"569\":{},\"570\":{},\"571\":{},\"572\":{},\"573\":{}}}],[\"recipe/jwt.default\",{\"_index\":63,\"name\":{},\"parent\":{\"131\":{},\"132\":{},\"133\":{},\"134\":{},\"135\":{}}}],[\"recipe/jwt.jsonwebkey\",{\"_index\":237,\"name\":{},\"parent\":{\"579\":{}}}],[\"recipe/jwt.jsonwebkey.__type\",{\"_index\":239,\"name\":{},\"parent\":{\"580\":{},\"581\":{},\"582\":{},\"583\":{},\"584\":{},\"585\":{}}}],[\"recipe/jwt.recipeinterface\",{\"_index\":234,\"name\":{},\"parent\":{\"575\":{}}}],[\"recipe/jwt.recipeinterface.__type\",{\"_index\":235,\"name\":{},\"parent\":{\"576\":{},\"577\":{}}}],[\"recipe/openid\",{\"_index\":64,\"name\":{\"136\":{}},\"parent\":{\"137\":{},\"138\":{},\"139\":{},\"140\":{},\"141\":{}}}],[\"recipe/openid.default\",{\"_index\":66,\"name\":{},\"parent\":{\"142\":{},\"143\":{},\"144\":{},\"145\":{},\"146\":{},\"147\":{}}}],[\"recipe/passwordless\",{\"_index\":67,\"name\":{\"148\":{}},\"parent\":{\"149\":{},\"150\":{},\"151\":{},\"152\":{},\"153\":{},\"154\":{},\"155\":{},\"156\":{},\"157\":{},\"158\":{},\"159\":{},\"160\":{},\"161\":{},\"162\":{},\"163\":{},\"164\":{},\"165\":{},\"166\":{},\"167\":{},\"168\":{},\"586\":{},\"601\":{},\"607\":{},\"618\":{}}}],[\"recipe/passwordless.apiinterface\",{\"_index\":253,\"name\":{},\"parent\":{\"619\":{}}}],[\"recipe/passwordless.apiinterface.__type\",{\"_index\":255,\"name\":{},\"parent\":{\"620\":{},\"621\":{},\"622\":{},\"623\":{},\"624\":{}}}],[\"recipe/passwordless.apioptions\",{\"_index\":250,\"name\":{},\"parent\":{\"608\":{}}}],[\"recipe/passwordless.apioptions.__type\",{\"_index\":251,\"name\":{},\"parent\":{\"609\":{},\"610\":{},\"611\":{},\"612\":{},\"613\":{},\"614\":{},\"615\":{},\"616\":{},\"617\":{}}}],[\"recipe/passwordless.default\",{\"_index\":82,\"name\":{},\"parent\":{\"169\":{},\"170\":{},\"171\":{},\"172\":{},\"173\":{},\"174\":{},\"175\":{},\"176\":{},\"177\":{},\"178\":{},\"179\":{},\"180\":{},\"181\":{},\"182\":{},\"183\":{},\"184\":{},\"185\":{},\"186\":{},\"187\":{},\"188\":{},\"189\":{}}}],[\"recipe/passwordless.recipeinterface\",{\"_index\":245,\"name\":{},\"parent\":{\"587\":{}}}],[\"recipe/passwordless.recipeinterface.__type\",{\"_index\":246,\"name\":{},\"parent\":{\"588\":{},\"589\":{},\"590\":{},\"591\":{},\"592\":{},\"593\":{},\"594\":{},\"595\":{},\"596\":{},\"597\":{},\"598\":{},\"599\":{},\"600\":{}}}],[\"recipe/passwordless.user\",{\"_index\":247,\"name\":{},\"parent\":{\"602\":{}}}],[\"recipe/passwordless.user.__type\",{\"_index\":248,\"name\":{},\"parent\":{\"603\":{},\"604\":{},\"605\":{},\"606\":{}}}],[\"recipe/session\",{\"_index\":83,\"name\":{\"190\":{}},\"parent\":{\"191\":{},\"192\":{},\"193\":{},\"194\":{},\"195\":{},\"196\":{},\"197\":{},\"198\":{},\"199\":{},\"200\":{},\"201\":{},\"202\":{},\"203\":{},\"204\":{},\"205\":{},\"206\":{},\"207\":{},\"208\":{},\"209\":{},\"210\":{},\"211\":{},\"212\":{},\"213\":{},\"625\":{},\"629\":{},\"652\":{},\"669\":{},\"674\":{},\"682\":{},\"690\":{}}}],[\"recipe/session.apiinterface\",{\"_index\":280,\"name\":{},\"parent\":{\"670\":{}}}],[\"recipe/session.apiinterface.__type\",{\"_index\":282,\"name\":{},\"parent\":{\"671\":{},\"672\":{},\"673\":{}}}],[\"recipe/session.apioptions\",{\"_index\":285,\"name\":{},\"parent\":{\"675\":{}}}],[\"recipe/session.apioptions.__type\",{\"_index\":286,\"name\":{},\"parent\":{\"676\":{},\"677\":{},\"678\":{},\"679\":{},\"680\":{},\"681\":{}}}],[\"recipe/session.default\",{\"_index\":101,\"name\":{},\"parent\":{\"214\":{},\"215\":{},\"216\":{},\"217\":{},\"218\":{},\"219\":{},\"220\":{},\"221\":{},\"222\":{},\"223\":{},\"224\":{},\"225\":{},\"226\":{},\"227\":{},\"228\":{},\"229\":{},\"230\":{},\"231\":{},\"232\":{},\"233\":{},\"234\":{},\"235\":{},\"236\":{},\"237\":{},\"238\":{}}}],[\"recipe/session.recipeinterface\",{\"_index\":264,\"name\":{},\"parent\":{\"630\":{}}}],[\"recipe/session.recipeinterface.__type\",{\"_index\":265,\"name\":{},\"parent\":{\"631\":{},\"632\":{},\"633\":{},\"634\":{},\"635\":{},\"636\":{},\"637\":{},\"638\":{},\"639\":{},\"640\":{},\"641\":{},\"642\":{},\"643\":{},\"644\":{},\"645\":{},\"646\":{},\"647\":{},\"648\":{},\"649\":{},\"650\":{},\"651\":{}}}],[\"recipe/session.sessioncontainer\",{\"_index\":271,\"name\":{},\"parent\":{\"653\":{},\"654\":{},\"655\":{},\"656\":{},\"657\":{},\"658\":{},\"659\":{},\"660\":{},\"661\":{},\"662\":{},\"663\":{},\"664\":{},\"665\":{},\"666\":{},\"667\":{},\"668\":{}}}],[\"recipe/session.sessioninformation\",{\"_index\":288,\"name\":{},\"parent\":{\"683\":{}}}],[\"recipe/session.sessioninformation.__type\",{\"_index\":290,\"name\":{},\"parent\":{\"684\":{},\"685\":{},\"686\":{},\"687\":{},\"688\":{},\"689\":{}}}],[\"recipe/session.verifysessionoptions\",{\"_index\":261,\"name\":{},\"parent\":{\"626\":{},\"627\":{},\"628\":{}}}],[\"recipe/thirdparty\",{\"_index\":103,\"name\":{\"239\":{}},\"parent\":{\"240\":{},\"241\":{},\"242\":{},\"243\":{},\"244\":{},\"245\":{},\"246\":{},\"247\":{},\"248\":{},\"249\":{},\"250\":{},\"251\":{},\"252\":{},\"691\":{},\"697\":{},\"706\":{},\"711\":{},\"721\":{}}}],[\"recipe/thirdparty.apiinterface\",{\"_index\":303,\"name\":{},\"parent\":{\"707\":{}}}],[\"recipe/thirdparty.apiinterface.__type\",{\"_index\":305,\"name\":{},\"parent\":{\"708\":{},\"709\":{},\"710\":{}}}],[\"recipe/thirdparty.apioptions\",{\"_index\":308,\"name\":{},\"parent\":{\"712\":{}}}],[\"recipe/thirdparty.apioptions.__type\",{\"_index\":309,\"name\":{},\"parent\":{\"713\":{},\"714\":{},\"715\":{},\"716\":{},\"717\":{},\"718\":{},\"719\":{},\"720\":{}}}],[\"recipe/thirdparty.default\",{\"_index\":112,\"name\":{},\"parent\":{\"253\":{},\"254\":{},\"255\":{},\"256\":{},\"257\":{},\"258\":{},\"259\":{},\"260\":{},\"261\":{},\"262\":{},\"263\":{},\"264\":{},\"265\":{},\"266\":{},\"267\":{},\"268\":{},\"269\":{},\"270\":{},\"271\":{},\"272\":{}}}],[\"recipe/thirdparty.recipeinterface\",{\"_index\":297,\"name\":{},\"parent\":{\"692\":{}}}],[\"recipe/thirdparty.recipeinterface.__type\",{\"_index\":298,\"name\":{},\"parent\":{\"693\":{},\"694\":{},\"695\":{},\"696\":{}}}],[\"recipe/thirdparty.typeprovider\",{\"_index\":312,\"name\":{},\"parent\":{\"722\":{}}}],[\"recipe/thirdparty.typeprovider.__type\",{\"_index\":313,\"name\":{},\"parent\":{\"723\":{},\"724\":{},\"725\":{}}}],[\"recipe/thirdparty.user\",{\"_index\":299,\"name\":{},\"parent\":{\"698\":{}}}],[\"recipe/thirdparty.user.__type\",{\"_index\":300,\"name\":{},\"parent\":{\"699\":{},\"700\":{},\"701\":{},\"702\":{},\"703\":{}}}],[\"recipe/thirdparty.user.__type.__type\",{\"_index\":302,\"name\":{},\"parent\":{\"704\":{},\"705\":{}}}],[\"recipe/thirdpartyemailpassword\",{\"_index\":113,\"name\":{\"273\":{}},\"parent\":{\"274\":{},\"275\":{},\"276\":{},\"277\":{},\"278\":{},\"279\":{},\"280\":{},\"281\":{},\"282\":{},\"283\":{},\"284\":{},\"285\":{},\"286\":{},\"287\":{},\"288\":{},\"289\":{},\"290\":{},\"291\":{},\"292\":{},\"726\":{},\"737\":{},\"738\":{},\"747\":{},\"757\":{},\"758\":{}}}],[\"recipe/thirdpartyemailpassword.apiinterface\",{\"_index\":321,\"name\":{},\"parent\":{\"748\":{}}}],[\"recipe/thirdpartyemailpassword.apiinterface.__type\",{\"_index\":322,\"name\":{},\"parent\":{\"749\":{},\"750\":{},\"751\":{},\"752\":{},\"753\":{},\"754\":{},\"755\":{},\"756\":{}}}],[\"recipe/thirdpartyemailpassword.default\",{\"_index\":117,\"name\":{},\"parent\":{\"293\":{},\"294\":{},\"295\":{},\"296\":{},\"297\":{},\"298\":{},\"299\":{},\"300\":{},\"301\":{},\"302\":{},\"303\":{},\"304\":{},\"305\":{},\"306\":{},\"307\":{},\"308\":{},\"309\":{},\"310\":{},\"311\":{},\"312\":{},\"313\":{},\"314\":{},\"315\":{},\"316\":{},\"317\":{},\"318\":{}}}],[\"recipe/thirdpartyemailpassword.recipeinterface\",{\"_index\":316,\"name\":{},\"parent\":{\"727\":{}}}],[\"recipe/thirdpartyemailpassword.recipeinterface.__type\",{\"_index\":317,\"name\":{},\"parent\":{\"728\":{},\"729\":{},\"730\":{},\"731\":{},\"732\":{},\"733\":{},\"734\":{},\"735\":{},\"736\":{}}}],[\"recipe/thirdpartyemailpassword.user\",{\"_index\":318,\"name\":{},\"parent\":{\"739\":{}}}],[\"recipe/thirdpartyemailpassword.user.__type\",{\"_index\":319,\"name\":{},\"parent\":{\"740\":{},\"741\":{},\"742\":{},\"743\":{},\"744\":{}}}],[\"recipe/thirdpartyemailpassword.user.__type.__type\",{\"_index\":320,\"name\":{},\"parent\":{\"745\":{},\"746\":{}}}],[\"recipe/thirdpartypasswordless\",{\"_index\":118,\"name\":{\"319\":{}},\"parent\":{\"320\":{},\"321\":{},\"322\":{},\"323\":{},\"324\":{},\"325\":{},\"326\":{},\"327\":{},\"328\":{},\"329\":{},\"330\":{},\"331\":{},\"332\":{},\"333\":{},\"334\":{},\"335\":{},\"336\":{},\"337\":{},\"338\":{},\"339\":{},\"340\":{},\"341\":{},\"342\":{},\"343\":{},\"344\":{},\"345\":{},\"346\":{},\"347\":{},\"759\":{},\"776\":{},\"777\":{},\"778\":{},\"788\":{},\"789\":{}}}],[\"recipe/thirdpartypasswordless.apiinterface\",{\"_index\":331,\"name\":{},\"parent\":{\"779\":{}}}],[\"recipe/thirdpartypasswordless.apiinterface.__type\",{\"_index\":332,\"name\":{},\"parent\":{\"780\":{},\"781\":{},\"782\":{},\"783\":{},\"784\":{},\"785\":{},\"786\":{},\"787\":{}}}],[\"recipe/thirdpartypasswordless.default\",{\"_index\":121,\"name\":{},\"parent\":{\"348\":{},\"349\":{},\"350\":{},\"351\":{},\"352\":{},\"353\":{},\"354\":{},\"355\":{},\"356\":{},\"357\":{},\"358\":{},\"359\":{},\"360\":{},\"361\":{},\"362\":{},\"363\":{},\"364\":{},\"365\":{},\"366\":{},\"367\":{},\"368\":{},\"369\":{},\"370\":{},\"371\":{},\"372\":{},\"373\":{},\"374\":{},\"375\":{},\"376\":{},\"377\":{},\"378\":{},\"379\":{},\"380\":{},\"381\":{},\"382\":{}}}],[\"recipe/thirdpartypasswordless.recipeinterface\",{\"_index\":329,\"name\":{},\"parent\":{\"760\":{}}}],[\"recipe/thirdpartypasswordless.recipeinterface.__type\",{\"_index\":330,\"name\":{},\"parent\":{\"761\":{},\"762\":{},\"763\":{},\"764\":{},\"765\":{},\"766\":{},\"767\":{},\"768\":{},\"769\":{},\"770\":{},\"771\":{},\"772\":{},\"773\":{},\"774\":{},\"775\":{}}}],[\"recipe/usermetadata\",{\"_index\":122,\"name\":{\"383\":{}},\"parent\":{\"384\":{},\"385\":{},\"386\":{},\"387\":{},\"388\":{},\"790\":{},\"795\":{}}}],[\"recipe/usermetadata.default\",{\"_index\":126,\"name\":{},\"parent\":{\"389\":{},\"390\":{},\"391\":{},\"392\":{},\"393\":{},\"394\":{}}}],[\"recipe/usermetadata.recipeinterface\",{\"_index\":336,\"name\":{},\"parent\":{\"791\":{}}}],[\"recipe/usermetadata.recipeinterface.__type\",{\"_index\":337,\"name\":{},\"parent\":{\"792\":{},\"793\":{},\"794\":{}}}],[\"recipe/userroles\",{\"_index\":127,\"name\":{\"395\":{}},\"parent\":{\"396\":{},\"397\":{},\"398\":{},\"399\":{},\"400\":{},\"401\":{},\"402\":{},\"403\":{},\"404\":{},\"405\":{},\"406\":{},\"407\":{},\"796\":{},\"797\":{},\"798\":{}}}],[\"recipe/userroles.default\",{\"_index\":138,\"name\":{},\"parent\":{\"408\":{},\"409\":{},\"410\":{},\"411\":{},\"412\":{},\"413\":{},\"414\":{},\"415\":{},\"416\":{},\"417\":{},\"418\":{},\"419\":{},\"420\":{},\"421\":{},\"422\":{}}}],[\"recipe/userroles.recipeinterface\",{\"_index\":339,\"name\":{},\"parent\":{\"799\":{}}}],[\"recipe/userroles.recipeinterface.__type\",{\"_index\":340,\"name\":{},\"parent\":{\"800\":{},\"801\":{},\"802\":{},\"803\":{},\"804\":{},\"805\":{},\"806\":{},\"807\":{},\"808\":{},\"809\":{}}}],[\"recipeid\",{\"_index\":191,\"name\":{\"497\":{},\"524\":{},\"548\":{},\"570\":{},\"612\":{},\"678\":{},\"715\":{}},\"parent\":{}}],[\"recipeimplementation\",{\"_index\":188,\"name\":{\"495\":{},\"521\":{},\"545\":{},\"568\":{},\"609\":{},\"676\":{},\"713\":{}},\"parent\":{}}],[\"recipeinterface\",{\"_index\":181,\"name\":{\"489\":{},\"505\":{},\"536\":{},\"574\":{},\"586\":{},\"629\":{},\"691\":{},\"726\":{},\"759\":{},\"790\":{},\"798\":{}},\"parent\":{}}],[\"refreshpost\",{\"_index\":281,\"name\":{\"671\":{}},\"parent\":{}}],[\"refreshsession\",{\"_index\":87,\"name\":{\"195\":{},\"222\":{},\"634\":{}},\"parent\":{}}],[\"regenerateaccesstoken\",{\"_index\":102,\"name\":{\"228\":{},\"643\":{}},\"parent\":{}}],[\"removeclaim\",{\"_index\":98,\"name\":{\"206\":{},\"237\":{},\"651\":{},\"668\":{}},\"parent\":{}}],[\"removeheader\",{\"_index\":155,\"name\":{\"447\":{}},\"parent\":{}}],[\"removepermissionsfromrole\",{\"_index\":134,\"name\":{\"403\":{},\"418\":{},\"806\":{}},\"parent\":{}}],[\"removeuserrole\",{\"_index\":129,\"name\":{\"398\":{},\"413\":{},\"801\":{}},\"parent\":{}}],[\"req\",{\"_index\":192,\"name\":{\"498\":{},\"526\":{},\"550\":{},\"572\":{},\"614\":{},\"680\":{},\"718\":{}},\"parent\":{}}],[\"res\",{\"_index\":193,\"name\":{\"499\":{},\"527\":{},\"551\":{},\"573\":{},\"615\":{},\"681\":{},\"719\":{}},\"parent\":{}}],[\"resendcodepost\",{\"_index\":256,\"name\":{\"621\":{},\"784\":{}},\"parent\":{}}],[\"resetpasswordusingtoken\",{\"_index\":48,\"name\":{\"89\":{},\"101\":{},\"283\":{},\"303\":{},\"512\":{},\"735\":{}},\"parent\":{}}],[\"response\",{\"_index\":164,\"name\":{\"461\":{},\"469\":{}},\"parent\":{}}],[\"revokeallcodes\",{\"_index\":77,\"name\":{\"162\":{},\"179\":{},\"336\":{},\"360\":{},\"595\":{},\"770\":{}},\"parent\":{}}],[\"revokeallsessionsforuser\",{\"_index\":88,\"name\":{\"196\":{},\"223\":{},\"636\":{}},\"parent\":{}}],[\"revokecode\",{\"_index\":78,\"name\":{\"163\":{},\"180\":{},\"337\":{},\"361\":{},\"596\":{},\"771\":{}},\"parent\":{}}],[\"revokeemailverificationtokens\",{\"_index\":56,\"name\":{\"111\":{},\"122\":{},\"541\":{}},\"parent\":{}}],[\"revokemultiplesessions\",{\"_index\":91,\"name\":{\"199\":{},\"226\":{},\"639\":{}},\"parent\":{}}],[\"revokesession\",{\"_index\":90,\"name\":{\"198\":{},\"225\":{},\"638\":{},\"653\":{}},\"parent\":{}}],[\"sendemail\",{\"_index\":50,\"name\":{\"91\":{},\"103\":{},\"113\":{},\"124\":{},\"166\":{},\"187\":{},\"291\":{},\"317\":{},\"345\":{},\"380\":{}},\"parent\":{}}],[\"sendhtmlresponse\",{\"_index\":159,\"name\":{\"455\":{}},\"parent\":{}}],[\"sendjsonresponse\",{\"_index\":158,\"name\":{\"453\":{}},\"parent\":{}}],[\"sendsms\",{\"_index\":81,\"name\":{\"167\":{},\"188\":{},\"346\":{},\"381\":{}},\"parent\":{}}],[\"session\",{\"_index\":161,\"name\":{\"458\":{},\"466\":{},\"479\":{},\"481\":{},\"483\":{},\"486\":{},\"488\":{}},\"parent\":{}}],[\"sessionclaimvalidator\",{\"_index\":296,\"name\":{\"690\":{}},\"parent\":{}}],[\"sessioncontainer\",{\"_index\":270,\"name\":{\"652\":{}},\"parent\":{}}],[\"sessioncontext\",{\"_index\":178,\"name\":{\"485\":{},\"487\":{}},\"parent\":{}}],[\"sessiondata\",{\"_index\":292,\"name\":{\"686\":{}},\"parent\":{}}],[\"sessionevent\",{\"_index\":160,\"name\":{\"457\":{}},\"parent\":{}}],[\"sessioneventv2\",{\"_index\":169,\"name\":{\"465\":{}},\"parent\":{}}],[\"sessionhandle\",{\"_index\":289,\"name\":{\"684\":{}},\"parent\":{}}],[\"sessioninformation\",{\"_index\":287,\"name\":{\"682\":{}},\"parent\":{}}],[\"sessionrequest\",{\"_index\":174,\"name\":{\"478\":{},\"480\":{},\"482\":{}},\"parent\":{}}],[\"sessionrequired\",{\"_index\":262,\"name\":{\"627\":{}},\"parent\":{}}],[\"setclaimvalue\",{\"_index\":96,\"name\":{\"204\":{},\"235\":{},\"649\":{},\"666\":{}},\"parent\":{}}],[\"setcookie\",{\"_index\":156,\"name\":{\"449\":{}},\"parent\":{}}],[\"setheader\",{\"_index\":154,\"name\":{\"445\":{}},\"parent\":{}}],[\"setstatuscode\",{\"_index\":157,\"name\":{\"451\":{}},\"parent\":{}}],[\"shouldallowaccess\",{\"_index\":185,\"name\":{\"492\":{}},\"parent\":{}}],[\"signin\",{\"_index\":44,\"name\":{\"85\":{},\"97\":{},\"508\":{}},\"parent\":{}}],[\"signinpost\",{\"_index\":216,\"name\":{\"534\":{}},\"parent\":{}}],[\"signinup\",{\"_index\":80,\"name\":{\"165\":{},\"186\":{},\"242\":{},\"256\":{},\"696\":{}},\"parent\":{}}],[\"signinuppost\",{\"_index\":306,\"name\":{\"709\":{}},\"parent\":{}}],[\"signoutpost\",{\"_index\":283,\"name\":{\"672\":{}},\"parent\":{}}],[\"signup\",{\"_index\":43,\"name\":{\"84\":{},\"96\":{},\"507\":{}},\"parent\":{}}],[\"signuppost\",{\"_index\":217,\"name\":{\"535\":{}},\"parent\":{}}],[\"smsdelivery\",{\"_index\":252,\"name\":{\"617\":{}},\"parent\":{}}],[\"supertokens\",{\"_index\":163,\"name\":{\"459\":{},\"467\":{}},\"parent\":{}}],[\"thirdparty\",{\"_index\":301,\"name\":{\"702\":{},\"743\":{}},\"parent\":{}}],[\"thirdpartyapioptions\",{\"_index\":328,\"name\":{\"758\":{},\"789\":{}},\"parent\":{}}],[\"thirdpartysigninup\",{\"_index\":116,\"name\":{\"278\":{},\"296\":{},\"322\":{},\"351\":{},\"731\":{},\"765\":{}},\"parent\":{}}],[\"thirdpartysigninuppost\",{\"_index\":324,\"name\":{\"753\":{},\"781\":{}},\"parent\":{}}],[\"timecreated\",{\"_index\":295,\"name\":{\"689\":{}},\"parent\":{}}],[\"timejoined\",{\"_index\":207,\"name\":{\"518\":{},\"606\":{},\"700\":{},\"741\":{}},\"parent\":{}}],[\"typeprovider\",{\"_index\":311,\"name\":{\"721\":{},\"737\":{},\"776\":{}},\"parent\":{}}],[\"unverifyemail\",{\"_index\":57,\"name\":{\"112\":{},\"123\":{},\"542\":{}},\"parent\":{}}],[\"updateaccesstokenpayload\",{\"_index\":93,\"name\":{\"201\":{},\"229\":{},\"641\":{},\"660\":{}},\"parent\":{}}],[\"updateemailorpassword\",{\"_index\":49,\"name\":{\"90\":{},\"102\":{},\"284\":{},\"304\":{},\"513\":{},\"736\":{}},\"parent\":{}}],[\"updateordeleteuseridmappinginfo\",{\"_index\":10,\"name\":{\"10\":{},\"24\":{}},\"parent\":{}}],[\"updatepasswordlessuser\",{\"_index\":120,\"name\":{\"335\":{},\"359\":{},\"769\":{}},\"parent\":{}}],[\"updatesessiondata\",{\"_index\":92,\"name\":{\"200\":{},\"227\":{},\"640\":{},\"655\":{}},\"parent\":{}}],[\"updateuser\",{\"_index\":76,\"name\":{\"161\":{},\"178\":{},\"594\":{}},\"parent\":{}}],[\"updateusermetadata\",{\"_index\":124,\"name\":{\"386\":{},\"392\":{},\"793\":{}},\"parent\":{}}],[\"use\",{\"_index\":244,\"name\":{\"585\":{}},\"parent\":{}}],[\"user\",{\"_index\":202,\"name\":{\"514\":{},\"558\":{},\"601\":{},\"697\":{},\"738\":{},\"777\":{}},\"parent\":{}}],[\"userid\",{\"_index\":291,\"name\":{\"685\":{},\"705\":{},\"746\":{}},\"parent\":{}}],[\"userroleclaim\",{\"_index\":140,\"name\":{\"411\":{},\"796\":{}},\"parent\":{}}],[\"validateclaims\",{\"_index\":269,\"name\":{\"646\":{}},\"parent\":{}}],[\"validateclaimsforsessionhandle\",{\"_index\":100,\"name\":{\"208\":{},\"218\":{}},\"parent\":{}}],[\"validateclaimsinjwtpayload\",{\"_index\":99,\"name\":{\"207\":{},\"219\":{},\"647\":{}},\"parent\":{}}],[\"verifyemailpost\",{\"_index\":223,\"name\":{\"555\":{}},\"parent\":{}}],[\"verifyemailusingtoken\",{\"_index\":54,\"name\":{\"109\":{},\"120\":{},\"539\":{}},\"parent\":{}}],[\"verifysession\",{\"_index\":284,\"name\":{\"673\":{}},\"parent\":{}}],[\"verifysessionoptions\",{\"_index\":259,\"name\":{\"625\":{}},\"parent\":{}}],[\"wrapperused\",{\"_index\":143,\"name\":{\"425\":{},\"443\":{}},\"parent\":{}}],[\"wraprequest\",{\"_index\":26,\"name\":{\"43\":{},\"48\":{},\"53\":{},\"57\":{},\"61\":{},\"65\":{}},\"parent\":{}}],[\"wrapresponse\",{\"_index\":27,\"name\":{\"44\":{},\"49\":{},\"54\":{},\"58\":{},\"62\":{},\"66\":{}},\"parent\":{}}]],\"pipeline\":[]}}"); \ No newline at end of file diff --git a/docs/assets/style.css b/docs/assets/style.css index 6127b27cd..a16ed029e 100644 --- a/docs/assets/style.css +++ b/docs/assets/style.css @@ -766,13 +766,12 @@ footer .tsd-legend { .tsd-flag { display: inline-block; - padding: 0.25em 0.4em; + padding: 1px 5px; border-radius: 4px; color: var(--color-comment-tag-text); background-color: var(--color-comment-tag); text-indent: 0; - font-size: 75%; - line-height: 1; + font-size: 14px; font-weight: normal; } diff --git a/docs/classes/framework.BaseRequest.html b/docs/classes/framework.BaseRequest.html index c91a8eb16..0c0d5b7c1 100644 --- a/docs/classes/framework.BaseRequest.html +++ b/docs/classes/framework.BaseRequest.html @@ -1 +1 @@ -BaseRequest | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class BaseRequest Abstract

Hierarchy

  • BaseRequest

Index

Constructors

Properties

getCookieValue: ((key_: string) => undefined | string)

Type declaration

    • (key_: string): undefined | string
    • Parameters

      • key_: string

      Returns undefined | string

getFormData: (() => Promise<any>)

Type declaration

    • (): Promise<any>
    • Returns Promise<any>

getHeaderValue: ((key: string) => undefined | string)

Type declaration

    • (key: string): undefined | string
    • Parameters

      • key: string

      Returns undefined | string

getJSONBody: (() => Promise<any>)

Type declaration

    • (): Promise<any>
    • Returns Promise<any>

getKeyValueFromQuery: ((key: string) => undefined | string)

Type declaration

    • (key: string): undefined | string
    • Parameters

      • key: string

      Returns undefined | string

getMethod: (() => HTTPMethod)

Type declaration

    • (): HTTPMethod
    • Returns HTTPMethod

getOriginalURL: (() => string)

Type declaration

    • (): string
    • Returns string

original: any
wrapperUsed: boolean

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +BaseRequest | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • BaseRequest

Index

Constructors

Properties

getCookieValue: (key_: string) => undefined | string

Type declaration

    • (key_: string): undefined | string
    • Parameters

      • key_: string

      Returns undefined | string

getFormData: () => Promise<any>

Type declaration

    • (): Promise<any>
    • Returns Promise<any>

getHeaderValue: (key: string) => undefined | string

Type declaration

    • (key: string): undefined | string
    • Parameters

      • key: string

      Returns undefined | string

getJSONBody: () => Promise<any>

Type declaration

    • (): Promise<any>
    • Returns Promise<any>

getKeyValueFromQuery: (key: string) => undefined | string

Type declaration

    • (key: string): undefined | string
    • Parameters

      • key: string

      Returns undefined | string

getMethod: () => HTTPMethod

Type declaration

    • (): HTTPMethod
    • Returns HTTPMethod

getOriginalURL: () => string

Type declaration

    • (): string
    • Returns string

original: any
wrapperUsed: boolean

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/framework.BaseResponse.html b/docs/classes/framework.BaseResponse.html index 70046c080..cb453c882 100644 --- a/docs/classes/framework.BaseResponse.html +++ b/docs/classes/framework.BaseResponse.html @@ -1 +1 @@ -BaseResponse | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Class BaseResponse Abstract

Hierarchy

  • BaseResponse

Index

Constructors

Properties

original: any
sendHTMLResponse: ((html: string) => void)

Type declaration

    • (html: string): void
    • Parameters

      • html: string

      Returns void

sendJSONResponse: ((content: any) => void)

Type declaration

    • (content: any): void
    • Parameters

      • content: any

      Returns void

setCookie: ((key: string, value: string, domain: undefined | string, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void)

Type declaration

    • (key: string, value: string, domain: undefined | string, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none"): void
    • Parameters

      • key: string
      • value: string
      • domain: undefined | string
      • secure: boolean
      • httpOnly: boolean
      • expires: number
      • path: string
      • sameSite: "strict" | "lax" | "none"

      Returns void

setHeader: ((key: string, value: string, allowDuplicateKey: boolean) => void)

Type declaration

    • (key: string, value: string, allowDuplicateKey: boolean): void
    • Parameters

      • key: string
      • value: string
      • allowDuplicateKey: boolean

      Returns void

setStatusCode: ((statusCode: number) => void)

Type declaration

    • (statusCode: number): void
    • Parameters

      • statusCode: number

      Returns void

wrapperUsed: boolean

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +BaseResponse | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • BaseResponse

Index

Constructors

Properties

original: any
removeHeader: (key: string) => void

Type declaration

    • (key: string): void
    • Parameters

      • key: string

      Returns void

sendHTMLResponse: (html: string) => void

Type declaration

    • (html: string): void
    • Parameters

      • html: string

      Returns void

sendJSONResponse: (content: any) => void

Type declaration

    • (content: any): void
    • Parameters

      • content: any

      Returns void

setCookie: (key: string, value: string, domain: undefined | string, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void

Type declaration

    • (key: string, value: string, domain: undefined | string, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none"): void
    • Parameters

      • key: string
      • value: string
      • domain: undefined | string
      • secure: boolean
      • httpOnly: boolean
      • expires: number
      • path: string
      • sameSite: "strict" | "lax" | "none"

      Returns void

setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void

Type declaration

    • (key: string, value: string, allowDuplicateKey: boolean): void
    • Parameters

      • key: string
      • value: string
      • allowDuplicateKey: boolean

      Returns void

setStatusCode: (statusCode: number) => void

Type declaration

    • (statusCode: number): void
    • Parameters

      • statusCode: number

      Returns void

wrapperUsed: boolean

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/index.default.html b/docs/classes/index.default.html index 3c54e3055..914c8eea8 100644 --- a/docs/classes/index.default.html +++ b/docs/classes/index.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: ((config: TypeInput) => void) = SuperTokens.init

Type declaration

    • (config: TypeInput): void
    • Parameters

      • config: TypeInput

      Returns void

Methods

  • createUserIdMapping(input: { externalUserId: string; externalUserIdInfo?: string; force?: (false) | (true); superTokensUserId: string }): Promise<{ status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR" } | { doesExternalUserIdExist: boolean; doesSuperTokensUserIdExist: boolean; status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR" }>
  • Parameters

    • input: { externalUserId: string; externalUserIdInfo?: string; force?: (false) | (true); superTokensUserId: string }
      • externalUserId: string
      • Optional externalUserIdInfo?: string
      • Optional force?: (false) | (true)
      • superTokensUserId: string

    Returns Promise<{ status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR" } | { doesExternalUserIdExist: boolean; doesSuperTokensUserIdExist: boolean; status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR" }>

  • deleteUser(userId: string): Promise<{ status: "OK" }>
  • deleteUserIdMapping(input: { force?: (false) | (true); userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }): Promise<{ didMappingExist: boolean; status: "OK" }>
  • Parameters

    • input: { force?: (false) | (true); userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }
      • Optional force?: (false) | (true)
      • userId: string
      • Optional userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"

    Returns Promise<{ didMappingExist: boolean; status: "OK" }>

  • getAllCORSHeaders(): string[]
  • getUserCount(includeRecipeIds?: string[]): Promise<number>
  • Parameters

    • Optional includeRecipeIds: string[]

    Returns Promise<number>

  • getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }): Promise<{ externalUserId: string; externalUserIdInfo: undefined | string; status: "OK"; superTokensUserId: string } | { status: "UNKNOWN_MAPPING_ERROR" }>
  • Parameters

    • input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }
      • userId: string
      • Optional userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"

    Returns Promise<{ externalUserId: string; externalUserIdInfo: undefined | string; status: "OK"; superTokensUserId: string } | { status: "UNKNOWN_MAPPING_ERROR" }>

  • getUsersNewestFirst(input?: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }): Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>
  • Parameters

    • Optional input: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }
      • Optional includeRecipeIds?: string[]
      • Optional limit?: number
      • Optional paginationToken?: string

    Returns Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>

  • getUsersOldestFirst(input?: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }): Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>
  • Parameters

    • Optional input: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }
      • Optional includeRecipeIds?: string[]
      • Optional limit?: number
      • Optional paginationToken?: string

    Returns Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>

  • updateOrDeleteUserIdMappingInfo(input: { externalUserIdInfo?: string; userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }): Promise<{ status: "OK" | "UNKNOWN_MAPPING_ERROR" }>
  • Parameters

    • input: { externalUserIdInfo?: string; userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }
      • Optional externalUserIdInfo?: string
      • userId: string
      • Optional userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"

    Returns Promise<{ status: "OK" | "UNKNOWN_MAPPING_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: (config: TypeInput) => void = SuperTokens.init

Type declaration

    • (config: TypeInput): void
    • Parameters

      • config: TypeInput

      Returns void

Methods

  • createUserIdMapping(input: { externalUserId: string; externalUserIdInfo?: string; force?: false | true; superTokensUserId: string }): Promise<{ status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR" } | { doesExternalUserIdExist: boolean; doesSuperTokensUserIdExist: boolean; status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR" }>
  • Parameters

    • input: { externalUserId: string; externalUserIdInfo?: string; force?: false | true; superTokensUserId: string }
      • externalUserId: string
      • Optional externalUserIdInfo?: string
      • Optional force?: false | true
      • superTokensUserId: string

    Returns Promise<{ status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR" } | { doesExternalUserIdExist: boolean; doesSuperTokensUserIdExist: boolean; status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR" }>

  • deleteUser(userId: string): Promise<{ status: "OK" }>
  • deleteUserIdMapping(input: { force?: false | true; userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }): Promise<{ didMappingExist: boolean; status: "OK" }>
  • Parameters

    • input: { force?: false | true; userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }
      • Optional force?: false | true
      • userId: string
      • Optional userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"

    Returns Promise<{ didMappingExist: boolean; status: "OK" }>

  • getAllCORSHeaders(): string[]
  • getUserCount(includeRecipeIds?: string[]): Promise<number>
  • Parameters

    • Optional includeRecipeIds: string[]

    Returns Promise<number>

  • getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }): Promise<{ externalUserId: string; externalUserIdInfo: undefined | string; status: "OK"; superTokensUserId: string } | { status: "UNKNOWN_MAPPING_ERROR" }>
  • Parameters

    • input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }
      • userId: string
      • Optional userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"

    Returns Promise<{ externalUserId: string; externalUserIdInfo: undefined | string; status: "OK"; superTokensUserId: string } | { status: "UNKNOWN_MAPPING_ERROR" }>

  • getUsersNewestFirst(input?: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }): Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>
  • Parameters

    • Optional input: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }
      • Optional includeRecipeIds?: string[]
      • Optional limit?: number
      • Optional paginationToken?: string

    Returns Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>

  • getUsersOldestFirst(input?: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }): Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>
  • Parameters

    • Optional input: { includeRecipeIds?: string[]; limit?: number; paginationToken?: string }
      • Optional includeRecipeIds?: string[]
      • Optional limit?: number
      • Optional paginationToken?: string

    Returns Promise<{ nextPaginationToken?: string; users: { recipeId: string; user: any }[] }>

  • updateOrDeleteUserIdMappingInfo(input: { externalUserIdInfo?: string; userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }): Promise<{ status: "OK" | "UNKNOWN_MAPPING_ERROR" }>
  • Parameters

    • input: { externalUserIdInfo?: string; userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }
      • Optional externalUserIdInfo?: string
      • userId: string
      • Optional userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"

    Returns Promise<{ status: "OK" | "UNKNOWN_MAPPING_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/ingredients_emaildelivery.default.html b/docs/classes/ingredients_emaildelivery.default.html index c64898969..0384e0e22 100644 --- a/docs/classes/ingredients_emaildelivery.default.html +++ b/docs/classes/ingredients_emaildelivery.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/ingredients_smsdelivery.default.html b/docs/classes/ingredients_smsdelivery.default.html index 4ef880978..3e196932e 100644 --- a/docs/classes/ingredients_smsdelivery.default.html +++ b/docs/classes/ingredients_smsdelivery.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Property
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_dashboard.default.html b/docs/classes/recipe_dashboard.default.html index 2752298a2..e4839627e 100644 --- a/docs/classes/recipe_dashboard.default.html +++ b/docs/classes/recipe_dashboard.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Interface
  • Static property

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Interface
  • Static property

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_emailpassword.default.html b/docs/classes/recipe_emailpassword.default.html index 413cfbabc..b33bf3c8c 100644 --- a/docs/classes/recipe_emailpassword.default.html +++ b/docs/classes/recipe_emailpassword.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: ((config?: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createResetPasswordToken(userId: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
  • getUserByEmail(email: string, userContext?: any): Promise<undefined | User>
  • getUserById(userId: string, userContext?: any): Promise<undefined | User>
  • resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
  • Parameters

    • token: string
    • newPassword: string
    • Optional userContext: any

    Returns Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>

  • sendEmail(input: TypeEmailPasswordPasswordResetEmailDeliveryInput & { userContext?: any }): Promise<void>
  • signIn(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
  • signUp(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
  • updateEmailOrPassword(input: { email?: string; password?: string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>
  • Parameters

    • input: { email?: string; password?: string; userContext?: any; userId: string }
      • Optional email?: string
      • Optional password?: string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: (config?: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createResetPasswordToken(userId: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
  • getUserByEmail(email: string, userContext?: any): Promise<undefined | User>
  • getUserById(userId: string, userContext?: any): Promise<undefined | User>
  • resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
  • Parameters

    • token: string
    • newPassword: string
    • Optional userContext: any

    Returns Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>

  • sendEmail(input: TypeEmailPasswordPasswordResetEmailDeliveryInput & { userContext?: any }): Promise<void>
  • signIn(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
  • signUp(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
  • updateEmailOrPassword(input: { email?: string; password?: string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>
  • Parameters

    • input: { email?: string; password?: string; userContext?: any; userId: string }
      • Optional email?: string
      • Optional password?: string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_emailverification.default.html b/docs/classes/recipe_emailverification.default.html index b6bbaf2e3..86322599c 100644 --- a/docs/classes/recipe_emailverification.default.html +++ b/docs/classes/recipe_emailverification.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

EmailVerificationClaim: EmailVerificationClaimClass = EmailVerificationClaim
Error: typeof default = SuperTokensError
init: ((config: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • createEmailVerificationToken(userId: string, email?: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "EMAIL_ALREADY_VERIFIED_ERROR" }>
  • Parameters

    • userId: string
    • Optional email: string
    • Optional userContext: any

    Returns Promise<{ status: "OK"; token: string } | { status: "EMAIL_ALREADY_VERIFIED_ERROR" }>

  • isEmailVerified(userId: string, email?: string, userContext?: any): Promise<boolean>
  • revokeEmailVerificationTokens(userId: string, email?: string, userContext?: any): Promise<{ status: string }>
  • sendEmail(input: TypeEmailVerificationEmailDeliveryInput & { userContext?: any }): Promise<void>
  • unverifyEmail(userId: string, email?: string, userContext?: any): Promise<{ status: string }>
  • verifyEmailUsingToken(token: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

EmailVerificationClaim: EmailVerificationClaimClass = EmailVerificationClaim
Error: typeof default = SuperTokensError
init: (config: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • createEmailVerificationToken(userId: string, email?: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "EMAIL_ALREADY_VERIFIED_ERROR" }>
  • Parameters

    • userId: string
    • Optional email: string
    • Optional userContext: any

    Returns Promise<{ status: "OK"; token: string } | { status: "EMAIL_ALREADY_VERIFIED_ERROR" }>

  • isEmailVerified(userId: string, email?: string, userContext?: any): Promise<boolean>
  • revokeEmailVerificationTokens(userId: string, email?: string, userContext?: any): Promise<{ status: string }>
  • sendEmail(input: TypeEmailVerificationEmailDeliveryInput & { userContext?: any }): Promise<void>
  • unverifyEmail(userId: string, email?: string, userContext?: any): Promise<{ status: string }>
  • verifyEmailUsingToken(token: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_jwt.default.html b/docs/classes/recipe_jwt.default.html index 0d7ac936c..8e1842fab 100644 --- a/docs/classes/recipe_jwt.default.html +++ b/docs/classes/recipe_jwt.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Methods

Constructors

Properties

init: ((config?: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createJWT(payload: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
  • Parameters

    • payload: any
    • Optional validitySeconds: number
    • Optional userContext: any

    Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

  • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Methods

Constructors

Properties

init: (config?: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createJWT(payload: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
  • Parameters

    • payload: any
    • Optional validitySeconds: number
    • Optional userContext: any

    Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

  • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_openid.default.html b/docs/classes/recipe_openid.default.html index 44234610a..64bbe8acd 100644 --- a/docs/classes/recipe_openid.default.html +++ b/docs/classes/recipe_openid.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

init: ((config?: TypeInput) => RecipeListFunction) = OpenIdRecipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
  • Parameters

    • Optional payload: any
    • Optional validitySeconds: number
    • Optional userContext: any

    Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

  • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>
  • getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ issuer: string; jwks_uri: string; status: "OK" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

init: (config?: TypeInput) => RecipeListFunction = OpenIdRecipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
  • Parameters

    • Optional payload: any
    • Optional validitySeconds: number
    • Optional userContext: any

    Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

  • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>
  • getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ issuer: string; jwks_uri: string; status: "OK" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_passwordless.default.html b/docs/classes/recipe_passwordless.default.html index 333c877c3..130b947a6 100644 --- a/docs/classes/recipe_passwordless.default.html +++ b/docs/classes/recipe_passwordless.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: ((config: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
  • Parameters

    • input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }

    Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

  • createCode(input: { email: string } & { userContext?: any; userInputCode?: string } | { phoneNumber: string } & { userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
  • Parameters

    • input: { email: string } & { userContext?: any; userInputCode?: string } | { phoneNumber: string } & { userContext?: any; userInputCode?: string }

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

  • createMagicLink(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<string>
  • createNewCodeForDevice(input: { deviceId: string; userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
  • Parameters

    • input: { deviceId: string; userContext?: any; userInputCode?: string }
      • deviceId: string
      • Optional userContext?: any
      • Optional userInputCode?: string

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

  • getUserByEmail(input: { email: string; userContext?: any }): Promise<undefined | User>
  • getUserById(input: { userContext?: any; userId: string }): Promise<undefined | User>
  • getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<undefined | User>
  • listCodesByDeviceId(input: { deviceId: string; userContext?: any }): Promise<undefined | DeviceType>
  • listCodesByEmail(input: { email: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext?: any }): Promise<undefined | DeviceType>
  • Parameters

    • input: { preAuthSessionId: string; userContext?: any }
      • preAuthSessionId: string
      • Optional userContext?: any

    Returns Promise<undefined | DeviceType>

  • revokeAllCodes(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ status: "OK" }>
  • revokeCode(input: { codeId: string; userContext?: any }): Promise<{ status: "OK" }>
  • sendEmail(input: TypePasswordlessEmailDeliveryInput & { userContext?: any }): Promise<void>
  • sendSms(input: TypePasswordlessSmsDeliveryInput & { userContext?: any }): Promise<void>
  • signInUp(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: string; user: User }>
  • Parameters

    • input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }

    Returns Promise<{ createdNewUser: boolean; status: string; user: User }>

  • updateUser(input: { email?: (null) | string; phoneNumber?: (null) | string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
  • Parameters

    • input: { email?: (null) | string; phoneNumber?: (null) | string; userContext?: any; userId: string }
      • Optional email?: (null) | string
      • Optional phoneNumber?: (null) | string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: (config: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
  • Parameters

    • input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }

    Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

  • createCode(input: ({ email: string } & { userContext?: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext?: any; userInputCode?: string })): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
  • Parameters

    • input: ({ email: string } & { userContext?: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext?: any; userInputCode?: string })

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

  • createMagicLink(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<string>
  • createNewCodeForDevice(input: { deviceId: string; userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
  • Parameters

    • input: { deviceId: string; userContext?: any; userInputCode?: string }
      • deviceId: string
      • Optional userContext?: any
      • Optional userInputCode?: string

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

  • getUserByEmail(input: { email: string; userContext?: any }): Promise<undefined | User>
  • getUserById(input: { userContext?: any; userId: string }): Promise<undefined | User>
  • getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<undefined | User>
  • listCodesByDeviceId(input: { deviceId: string; userContext?: any }): Promise<undefined | DeviceType>
  • listCodesByEmail(input: { email: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext?: any }): Promise<undefined | DeviceType>
  • Parameters

    • input: { preAuthSessionId: string; userContext?: any }
      • preAuthSessionId: string
      • Optional userContext?: any

    Returns Promise<undefined | DeviceType>

  • revokeAllCodes(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ status: "OK" }>
  • revokeCode(input: { codeId: string; userContext?: any }): Promise<{ status: "OK" }>
  • sendEmail(input: TypePasswordlessEmailDeliveryInput & { userContext?: any }): Promise<void>
  • sendSms(input: TypePasswordlessSmsDeliveryInput & { userContext?: any }): Promise<void>
  • signInUp(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: string; user: User }>
  • Parameters

    • input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }

    Returns Promise<{ createdNewUser: boolean; status: string; user: User }>

  • updateUser(input: { email?: null | string; phoneNumber?: null | string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
  • Parameters

    • input: { email?: null | string; phoneNumber?: null | string; userContext?: any; userId: string }
      • Optional email?: null | string
      • Optional phoneNumber?: null | string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_session.default.html b/docs/classes/recipe_session.default.html index d6afcf1ce..0eaad1ffc 100644 --- a/docs/classes/recipe_session.default.html +++ b/docs/classes/recipe_session.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: ((config?: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
  • Parameters

    • Optional payload: any
    • Optional validitySeconds: number
    • userContext: any = {}

    Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

  • createNewSession(res: any, userId: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise<SessionContainer>
  • fetchAndSetClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
  • getAllSessionHandlesForUser(userId: string, userContext?: any): Promise<string[]>
  • getClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, userContext?: any): Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>
  • Type Parameters

    • T

    Parameters

    • sessionHandle: string
    • claim: SessionClaim<T>
    • userContext: any = {}

    Returns Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>

  • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>
  • getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ issuer: string; jwks_uri: string; status: "OK" }>
  • getSessionInformation(sessionHandle: string, userContext?: any): Promise<undefined | SessionInformation>
  • mergeIntoAccessTokenPayload(sessionHandle: string, accessTokenPayloadUpdate: JSONObject, userContext?: any): Promise<boolean>
  • refreshSession(req: any, res: any, userContext?: any): Promise<SessionContainer>
  • regenerateAccessToken(accessToken: string, newAccessTokenPayload?: any, userContext?: any): Promise<undefined | { accessToken?: { createdTime: number; expiry: number; token: string }; session: { handle: string; userDataInJWT: any; userId: string }; status: "OK" }>
  • Parameters

    • accessToken: string
    • Optional newAccessTokenPayload: any
    • userContext: any = {}

    Returns Promise<undefined | { accessToken?: { createdTime: number; expiry: number; token: string }; session: { handle: string; userDataInJWT: any; userId: string }; status: "OK" }>

  • removeClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
  • revokeAllSessionsForUser(userId: string, userContext?: any): Promise<string[]>
  • revokeMultipleSessions(sessionHandles: string[], userContext?: any): Promise<string[]>
  • revokeSession(sessionHandle: string, userContext?: any): Promise<boolean>
  • setClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, value: T, userContext?: any): Promise<boolean>
  • updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, userContext?: any): Promise<boolean>
  • updateSessionData(sessionHandle: string, newSessionData: any, userContext?: any): Promise<boolean>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Error: typeof default = SuperTokensError
init: (config?: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
  • Parameters

    • Optional payload: any
    • Optional validitySeconds: number
    • userContext: any = {}

    Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

  • createNewSession(req: any, res: any, userId: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise<SessionContainer>
  • fetchAndSetClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
  • getAllSessionHandlesForUser(userId: string, userContext?: any): Promise<string[]>
  • getClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, userContext?: any): Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>
  • Type parameters

    • T

    Parameters

    • sessionHandle: string
    • claim: SessionClaim<T>
    • userContext: any = {}

    Returns Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>

  • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>
  • getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ issuer: string; jwks_uri: string; status: "OK" }>
  • getSessionInformation(sessionHandle: string, userContext?: any): Promise<undefined | SessionInformation>
  • mergeIntoAccessTokenPayload(sessionHandle: string, accessTokenPayloadUpdate: JSONObject, userContext?: any): Promise<boolean>
  • refreshSession(req: any, res: any, userContext?: any): Promise<SessionContainer>
  • regenerateAccessToken(accessToken: string, newAccessTokenPayload?: any, userContext?: any): Promise<undefined | { accessToken?: { createdTime: number; expiry: number; token: string }; session: { handle: string; userDataInJWT: any; userId: string }; status: "OK" }>
  • Parameters

    • accessToken: string
    • Optional newAccessTokenPayload: any
    • userContext: any = {}

    Returns Promise<undefined | { accessToken?: { createdTime: number; expiry: number; token: string }; session: { handle: string; userDataInJWT: any; userId: string }; status: "OK" }>

  • removeClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
  • revokeAllSessionsForUser(userId: string, userContext?: any): Promise<string[]>
  • revokeMultipleSessions(sessionHandles: string[], userContext?: any): Promise<string[]>
  • revokeSession(sessionHandle: string, userContext?: any): Promise<boolean>
  • setClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, value: T, userContext?: any): Promise<boolean>
  • updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, userContext?: any): Promise<boolean>
  • updateSessionData(sessionHandle: string, newSessionData: any, userContext?: any): Promise<boolean>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_thirdparty.default.html b/docs/classes/recipe_thirdparty.default.html index dc8f0a38c..eff25f71a 100644 --- a/docs/classes/recipe_thirdparty.default.html +++ b/docs/classes/recipe_thirdparty.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Apple: ((config: TypeThirdPartyProviderAppleConfig) => TypeProvider) = thirdPartyProviders.Apple

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderAppleConfig

      Returns TypeProvider

Discord: ((config: TypeThirdPartyProviderDiscordConfig) => TypeProvider) = thirdPartyProviders.Discord

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderDiscordConfig

      Returns TypeProvider

Error: typeof default = SuperTokensError
Facebook: ((config: TypeThirdPartyProviderFacebookConfig) => TypeProvider) = thirdPartyProviders.Facebook

Type declaration

    • (config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderFacebookConfig

      Returns TypeProvider

Github: ((config: TypeThirdPartyProviderGithubConfig) => TypeProvider) = thirdPartyProviders.Github

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGithubConfig

      Returns TypeProvider

Google: ((config: TypeThirdPartyProviderGoogleConfig) => TypeProvider) = thirdPartyProviders.Google

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGoogleConfig

      Returns TypeProvider

GoogleWorkspaces: ((config: TypeThirdPartyProviderGoogleWorkspacesConfig) => TypeProvider) = thirdPartyProviders.GoogleWorkspaces

Type declaration

    • (config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderGoogleWorkspacesConfig

      Returns TypeProvider

init: ((config: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • getUserById(userId: string, userContext?: any): Promise<undefined | User>
  • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
  • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
  • signInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
  • Parameters

    • thirdPartyId: string
    • thirdPartyUserId: string
    • email: string
    • userContext: any = {}

    Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Apple: (config: TypeThirdPartyProviderAppleConfig) => TypeProvider = thirdPartyProviders.Apple

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderAppleConfig

      Returns TypeProvider

Discord: (config: TypeThirdPartyProviderDiscordConfig) => TypeProvider = thirdPartyProviders.Discord

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderDiscordConfig

      Returns TypeProvider

Error: typeof default = SuperTokensError
Facebook: (config: TypeThirdPartyProviderFacebookConfig) => TypeProvider = thirdPartyProviders.Facebook

Type declaration

    • (config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderFacebookConfig

      Returns TypeProvider

Github: (config: TypeThirdPartyProviderGithubConfig) => TypeProvider = thirdPartyProviders.Github

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGithubConfig

      Returns TypeProvider

Google: (config: TypeThirdPartyProviderGoogleConfig) => TypeProvider = thirdPartyProviders.Google

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGoogleConfig

      Returns TypeProvider

GoogleWorkspaces: (config: TypeThirdPartyProviderGoogleWorkspacesConfig) => TypeProvider = thirdPartyProviders.GoogleWorkspaces

Type declaration

    • (config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderGoogleWorkspacesConfig

      Returns TypeProvider

init: (config: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • getUserById(userId: string, userContext?: any): Promise<undefined | User>
  • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
  • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
  • signInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
  • Parameters

    • thirdPartyId: string
    • thirdPartyUserId: string
    • email: string
    • userContext: any = {}

    Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_thirdpartyemailpassword.default.html b/docs/classes/recipe_thirdpartyemailpassword.default.html index 2ba3aa048..cb030c7d7 100644 --- a/docs/classes/recipe_thirdpartyemailpassword.default.html +++ b/docs/classes/recipe_thirdpartyemailpassword.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Apple: ((config: TypeThirdPartyProviderAppleConfig) => TypeProvider) = thirdPartyProviders.Apple

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderAppleConfig

      Returns TypeProvider

Discord: ((config: TypeThirdPartyProviderDiscordConfig) => TypeProvider) = thirdPartyProviders.Discord

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderDiscordConfig

      Returns TypeProvider

Error: typeof default = SuperTokensError
Facebook: ((config: TypeThirdPartyProviderFacebookConfig) => TypeProvider) = thirdPartyProviders.Facebook

Type declaration

    • (config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderFacebookConfig

      Returns TypeProvider

Github: ((config: TypeThirdPartyProviderGithubConfig) => TypeProvider) = thirdPartyProviders.Github

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGithubConfig

      Returns TypeProvider

Google: ((config: TypeThirdPartyProviderGoogleConfig) => TypeProvider) = thirdPartyProviders.Google

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGoogleConfig

      Returns TypeProvider

GoogleWorkspaces: ((config: TypeThirdPartyProviderGoogleWorkspacesConfig) => TypeProvider) = thirdPartyProviders.GoogleWorkspaces

Type declaration

    • (config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderGoogleWorkspacesConfig

      Returns TypeProvider

init: ((config: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • createResetPasswordToken(userId: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
  • emailPasswordSignIn(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
  • emailPasswordSignUp(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
  • getUserById(userId: string, userContext?: any): Promise<undefined | User>
  • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
  • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
  • resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
  • sendEmail(input: TypeEmailPasswordPasswordResetEmailDeliveryInput & { userContext?: any }): Promise<void>
  • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
  • updateEmailOrPassword(input: { email?: string; password?: string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>
  • Parameters

    • input: { email?: string; password?: string; userContext?: any; userId: string }
      • Optional email?: string
      • Optional password?: string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Apple: (config: TypeThirdPartyProviderAppleConfig) => TypeProvider = thirdPartyProviders.Apple

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderAppleConfig

      Returns TypeProvider

Discord: (config: TypeThirdPartyProviderDiscordConfig) => TypeProvider = thirdPartyProviders.Discord

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderDiscordConfig

      Returns TypeProvider

Error: typeof default = SuperTokensError
Facebook: (config: TypeThirdPartyProviderFacebookConfig) => TypeProvider = thirdPartyProviders.Facebook

Type declaration

    • (config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderFacebookConfig

      Returns TypeProvider

Github: (config: TypeThirdPartyProviderGithubConfig) => TypeProvider = thirdPartyProviders.Github

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGithubConfig

      Returns TypeProvider

Google: (config: TypeThirdPartyProviderGoogleConfig) => TypeProvider = thirdPartyProviders.Google

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGoogleConfig

      Returns TypeProvider

GoogleWorkspaces: (config: TypeThirdPartyProviderGoogleWorkspacesConfig) => TypeProvider = thirdPartyProviders.GoogleWorkspaces

Type declaration

    • (config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderGoogleWorkspacesConfig

      Returns TypeProvider

init: (config: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • createResetPasswordToken(userId: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
  • emailPasswordSignIn(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
  • emailPasswordSignUp(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
  • getUserById(userId: string, userContext?: any): Promise<undefined | User>
  • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
  • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
  • resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
  • sendEmail(input: TypeEmailPasswordPasswordResetEmailDeliveryInput & { userContext?: any }): Promise<void>
  • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
  • updateEmailOrPassword(input: { email?: string; password?: string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>
  • Parameters

    • input: { email?: string; password?: string; userContext?: any; userId: string }
      • Optional email?: string
      • Optional password?: string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_thirdpartypasswordless.default.html b/docs/classes/recipe_thirdpartypasswordless.default.html index 28fdc07a4..b36f35448 100644 --- a/docs/classes/recipe_thirdpartypasswordless.default.html +++ b/docs/classes/recipe_thirdpartypasswordless.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Apple: ((config: TypeThirdPartyProviderAppleConfig) => TypeProvider) = thirdPartyProviders.Apple

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderAppleConfig

      Returns TypeProvider

Discord: ((config: TypeThirdPartyProviderDiscordConfig) => TypeProvider) = thirdPartyProviders.Discord

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderDiscordConfig

      Returns TypeProvider

Error: typeof default = SuperTokensError
Facebook: ((config: TypeThirdPartyProviderFacebookConfig) => TypeProvider) = thirdPartyProviders.Facebook

Type declaration

    • (config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderFacebookConfig

      Returns TypeProvider

Github: ((config: TypeThirdPartyProviderGithubConfig) => TypeProvider) = thirdPartyProviders.Github

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGithubConfig

      Returns TypeProvider

Google: ((config: TypeThirdPartyProviderGoogleConfig) => TypeProvider) = thirdPartyProviders.Google

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGoogleConfig

      Returns TypeProvider

GoogleWorkspaces: ((config: TypeThirdPartyProviderGoogleWorkspacesConfig) => TypeProvider) = thirdPartyProviders.GoogleWorkspaces

Type declaration

    • (config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderGoogleWorkspacesConfig

      Returns TypeProvider

init: ((config: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
  • Parameters

    • input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }

    Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

  • createCode(input: { email: string } & { userContext?: any; userInputCode?: string } | { phoneNumber: string } & { userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
  • Parameters

    • input: { email: string } & { userContext?: any; userInputCode?: string } | { phoneNumber: string } & { userContext?: any; userInputCode?: string }

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

  • createMagicLink(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<string>
  • createNewCodeForDevice(input: { deviceId: string; userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
  • Parameters

    • input: { deviceId: string; userContext?: any; userInputCode?: string }
      • deviceId: string
      • Optional userContext?: any
      • Optional userInputCode?: string

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

  • getUserById(userId: string, userContext?: any): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
  • Parameters

    • userId: string
    • userContext: any = {}

    Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

  • getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
  • Parameters

    • input: { phoneNumber: string; userContext?: any }
      • phoneNumber: string
      • Optional userContext?: any

    Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

  • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
  • Parameters

    • thirdPartyId: string
    • thirdPartyUserId: string
    • userContext: any = {}

    Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

  • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
  • listCodesByDeviceId(input: { deviceId: string; userContext?: any }): Promise<undefined | DeviceType>
  • listCodesByEmail(input: { email: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext?: any }): Promise<undefined | DeviceType>
  • passwordlessSignInUp(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: string; user: User }>
  • revokeAllCodes(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ status: "OK" }>
  • revokeCode(input: { codeId: string; userContext?: any }): Promise<{ status: "OK" }>
  • sendEmail(input: TypePasswordlessEmailDeliveryInput & { userContext?: any }): Promise<void>
  • sendSms(input: TypePasswordlessSmsDeliveryInput & { userContext?: any }): Promise<void>
  • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
  • updatePasswordlessUser(input: { email?: (null) | string; phoneNumber?: (null) | string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
  • Parameters

    • input: { email?: (null) | string; phoneNumber?: (null) | string; userContext?: any; userId: string }
      • Optional email?: (null) | string
      • Optional phoneNumber?: (null) | string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

Apple: (config: TypeThirdPartyProviderAppleConfig) => TypeProvider = thirdPartyProviders.Apple

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderAppleConfig

      Returns TypeProvider

Discord: (config: TypeThirdPartyProviderDiscordConfig) => TypeProvider = thirdPartyProviders.Discord

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderDiscordConfig

      Returns TypeProvider

Error: typeof default = SuperTokensError
Facebook: (config: TypeThirdPartyProviderFacebookConfig) => TypeProvider = thirdPartyProviders.Facebook

Type declaration

    • (config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderFacebookConfig

      Returns TypeProvider

Github: (config: TypeThirdPartyProviderGithubConfig) => TypeProvider = thirdPartyProviders.Github

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGithubConfig

      Returns TypeProvider

Google: (config: TypeThirdPartyProviderGoogleConfig) => TypeProvider = thirdPartyProviders.Google

Type declaration

    • Parameters

      • config: TypeThirdPartyProviderGoogleConfig

      Returns TypeProvider

GoogleWorkspaces: (config: TypeThirdPartyProviderGoogleWorkspacesConfig) => TypeProvider = thirdPartyProviders.GoogleWorkspaces

Type declaration

    • (config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • Parameters

      • config: TypeThirdPartyProviderGoogleWorkspacesConfig

      Returns TypeProvider

init: (config: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config: TypeInput): RecipeListFunction
    • Parameters

      • config: TypeInput

      Returns RecipeListFunction

Methods

  • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
  • Parameters

    • input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }

    Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

  • createCode(input: ({ email: string } & { userContext?: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext?: any; userInputCode?: string })): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
  • Parameters

    • input: ({ email: string } & { userContext?: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext?: any; userInputCode?: string })

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

  • createMagicLink(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<string>
  • createNewCodeForDevice(input: { deviceId: string; userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
  • Parameters

    • input: { deviceId: string; userContext?: any; userInputCode?: string }
      • deviceId: string
      • Optional userContext?: any
      • Optional userInputCode?: string

    Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

  • getUserById(userId: string, userContext?: any): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
  • Parameters

    • userId: string
    • userContext: any = {}

    Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

  • getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
  • Parameters

    • input: { phoneNumber: string; userContext?: any }
      • phoneNumber: string
      • Optional userContext?: any

    Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

  • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
  • Parameters

    • thirdPartyId: string
    • thirdPartyUserId: string
    • userContext: any = {}

    Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

  • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
  • listCodesByDeviceId(input: { deviceId: string; userContext?: any }): Promise<undefined | DeviceType>
  • listCodesByEmail(input: { email: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<DeviceType[]>
  • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext?: any }): Promise<undefined | DeviceType>
  • passwordlessSignInUp(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: string; user: User }>
  • revokeAllCodes(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ status: "OK" }>
  • revokeCode(input: { codeId: string; userContext?: any }): Promise<{ status: "OK" }>
  • sendEmail(input: TypePasswordlessEmailDeliveryInput & { userContext?: any }): Promise<void>
  • sendSms(input: TypePasswordlessSmsDeliveryInput & { userContext?: any }): Promise<void>
  • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
  • updatePasswordlessUser(input: { email?: null | string; phoneNumber?: null | string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
  • Parameters

    • input: { email?: null | string; phoneNumber?: null | string; userContext?: any; userId: string }
      • Optional email?: null | string
      • Optional phoneNumber?: null | string
      • Optional userContext?: any
      • userId: string

    Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_usermetadata.default.html b/docs/classes/recipe_usermetadata.default.html index bdbe5477f..16fa4b380 100644 --- a/docs/classes/recipe_usermetadata.default.html +++ b/docs/classes/recipe_usermetadata.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

init: ((config?: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • clearUserMetadata(userId: string, userContext?: any): Promise<{ status: "OK" }>
  • getUserMetadata(userId: string, userContext?: any): Promise<{ metadata: any; status: "OK" }>
  • updateUserMetadata(userId: string, metadataUpdate: JSONObject, userContext?: any): Promise<{ metadata: JSONObject; status: "OK" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

init: (config?: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • clearUserMetadata(userId: string, userContext?: any): Promise<{ status: "OK" }>
  • getUserMetadata(userId: string, userContext?: any): Promise<{ metadata: any; status: "OK" }>
  • updateUserMetadata(userId: string, metadataUpdate: JSONObject, userContext?: any): Promise<{ metadata: JSONObject; status: "OK" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/classes/recipe_userroles.default.html b/docs/classes/recipe_userroles.default.html index c01d3273f..55d2727a4 100644 --- a/docs/classes/recipe_userroles.default.html +++ b/docs/classes/recipe_userroles.default.html @@ -1 +1 @@ -default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

PermissionClaim: PermissionClaimClass = PermissionClaim
UserRoleClaim: UserRoleClaimClass = UserRoleClaim
init: ((config?: TypeInput) => RecipeListFunction) = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • addRoleToUser(userId: string, role: string, userContext?: any): Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • userId: string
    • role: string
    • Optional userContext: any

    Returns Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

  • createNewRoleOrAddPermissions(role: string, permissions: string[], userContext?: any): Promise<{ createdNewRole: boolean; status: "OK" }>
  • deleteRole(role: string, userContext?: any): Promise<{ didRoleExist: boolean; status: "OK" }>
  • getAllRoles(userContext?: any): Promise<{ roles: string[]; status: "OK" }>
  • getPermissionsForRole(role: string, userContext?: any): Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • role: string
    • Optional userContext: any

    Returns Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

  • getRolesForUser(userId: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
  • getRolesThatHavePermission(permission: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
  • getUsersThatHaveRole(role: string, userContext?: any): Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • role: string
    • Optional userContext: any

    Returns Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>

  • removePermissionsFromRole(role: string, permissions: string[], userContext?: any): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>
  • removeUserRole(userId: string, role: string, userContext?: any): Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • userId: string
    • role: string
    • Optional userContext: any

    Returns Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +default | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • default

Index

Constructors

Properties

PermissionClaim: PermissionClaimClass = PermissionClaim
UserRoleClaim: UserRoleClaimClass = UserRoleClaim
init: (config?: TypeInput) => RecipeListFunction = Recipe.init

Type declaration

    • (config?: TypeInput): RecipeListFunction
    • Parameters

      • Optional config: TypeInput

      Returns RecipeListFunction

Methods

  • addRoleToUser(userId: string, role: string, userContext?: any): Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • userId: string
    • role: string
    • Optional userContext: any

    Returns Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

  • createNewRoleOrAddPermissions(role: string, permissions: string[], userContext?: any): Promise<{ createdNewRole: boolean; status: "OK" }>
  • deleteRole(role: string, userContext?: any): Promise<{ didRoleExist: boolean; status: "OK" }>
  • getAllRoles(userContext?: any): Promise<{ roles: string[]; status: "OK" }>
  • getPermissionsForRole(role: string, userContext?: any): Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • role: string
    • Optional userContext: any

    Returns Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

  • getRolesForUser(userId: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
  • getRolesThatHavePermission(permission: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
  • getUsersThatHaveRole(role: string, userContext?: any): Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • role: string
    • Optional userContext: any

    Returns Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>

  • removePermissionsFromRole(role: string, permissions: string[], userContext?: any): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>
  • removeUserRole(userId: string, role: string, userContext?: any): Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
  • Parameters

    • userId: string
    • role: string
    • Optional userContext: any

    Returns Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Constructor
  • Static property
  • Static method
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index dc33d5e84..6af2b272b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ -supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

supertokens-node

SuperTokens banner

+supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

supertokens-node

SuperTokens banner

SuperTokens Node driver

@@ -6,6 +6,7 @@

SuperTokens Node driver

chat on Discord + diff --git a/docs/interfaces/framework_awsLambda.SessionEvent.html b/docs/interfaces/framework_awsLambda.SessionEvent.html index a3106a919..aa3e88955 100644 --- a/docs/interfaces/framework_awsLambda.SessionEvent.html +++ b/docs/interfaces/framework_awsLambda.SessionEvent.html @@ -1 +1 @@ -SessionEvent | supertokens-node

Hierarchy

  • SupertokensLambdaEvent
    • SessionEvent

Index

Properties

body: (null) | string
headers: APIGatewayProxyEventHeaders
httpMethod: string
isBase64Encoded: boolean
multiValueHeaders: APIGatewayProxyEventMultiValueHeaders
multiValueQueryStringParameters: (null) | APIGatewayProxyEventMultiValueQueryStringParameters
path: string
pathParameters: (null) | APIGatewayProxyEventPathParameters
queryStringParameters: (null) | APIGatewayProxyEventQueryStringParameters
requestContext: APIGatewayEventRequestContextWithAuthorizer<APIGatewayEventDefaultAuthorizerContext>
resource: string
stageVariables: (null) | APIGatewayProxyEventStageVariables
supertokens: { response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | (false) | (true) }[] } }

Type declaration

  • response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | (false) | (true) }[] }
    • cookies: string[]
    • headers: { allowDuplicateKey: boolean; key: string; value: string | number | (false) | (true) }[]

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Interface
  • Property
  • Class
  • Class with type parameter

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +SessionEvent | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • SupertokensLambdaEvent
    • SessionEvent

Index

Properties

body: null | string
headers: APIGatewayProxyEventHeaders
httpMethod: string
isBase64Encoded: boolean
multiValueHeaders: APIGatewayProxyEventMultiValueHeaders
multiValueQueryStringParameters: null | APIGatewayProxyEventMultiValueQueryStringParameters
path: string
pathParameters: null | APIGatewayProxyEventPathParameters
queryStringParameters: null | APIGatewayProxyEventQueryStringParameters
requestContext: APIGatewayEventRequestContextWithAuthorizer<APIGatewayEventDefaultAuthorizerContext>
resource: string
stageVariables: null | APIGatewayProxyEventStageVariables
supertokens: { response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | false | true }[] } }

Type declaration

  • response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | false | true }[] }
    • cookies: string[]
    • headers: { allowDuplicateKey: boolean; key: string; value: string | number | false | true }[]

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Interface
  • Property
  • Class
  • Class with type parameter

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/framework_awsLambda.SessionEventV2.html b/docs/interfaces/framework_awsLambda.SessionEventV2.html index 94dcf426d..c1aef5b5b 100644 --- a/docs/interfaces/framework_awsLambda.SessionEventV2.html +++ b/docs/interfaces/framework_awsLambda.SessionEventV2.html @@ -1 +1 @@ -SessionEventV2 | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • SupertokensLambdaEventV2
    • SessionEventV2

Index

Properties

body?: string
cookies?: string[]
headers: APIGatewayProxyEventHeaders
isBase64Encoded: boolean
pathParameters?: APIGatewayProxyEventPathParameters
queryStringParameters?: APIGatewayProxyEventQueryStringParameters
rawPath: string
rawQueryString: string
requestContext: { accountId: string; apiId: string; authorizer?: { jwt: { claims: {}; scopes: string[] } }; domainName: string; domainPrefix: string; http: { method: string; path: string; protocol: string; sourceIp: string; userAgent: string }; requestId: string; routeKey: string; stage: string; time: string; timeEpoch: number }

Type declaration

  • accountId: string
  • apiId: string
  • Optional authorizer?: { jwt: { claims: {}; scopes: string[] } }
    • jwt: { claims: {}; scopes: string[] }
      • claims: {}
        • [name: string]: string | number | boolean | string[]
      • scopes: string[]
  • domainName: string
  • domainPrefix: string
  • http: { method: string; path: string; protocol: string; sourceIp: string; userAgent: string }
    • method: string
    • path: string
    • protocol: string
    • sourceIp: string
    • userAgent: string
  • requestId: string
  • routeKey: string
  • stage: string
  • time: string
  • timeEpoch: number
routeKey: string
stageVariables?: APIGatewayProxyEventStageVariables
supertokens: { response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | (false) | (true) }[] } }

Type declaration

  • response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | (false) | (true) }[] }
    • cookies: string[]
    • headers: { allowDuplicateKey: boolean; key: string; value: string | number | (false) | (true) }[]
version: string

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Interface
  • Property
  • Class
  • Class with type parameter

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +SessionEventV2 | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • SupertokensLambdaEventV2
    • SessionEventV2

Index

Properties

body?: string
cookies?: string[]
headers: APIGatewayProxyEventHeaders
isBase64Encoded: boolean
pathParameters?: APIGatewayProxyEventPathParameters
queryStringParameters?: APIGatewayProxyEventQueryStringParameters
rawPath: string
rawQueryString: string
requestContext: { accountId: string; apiId: string; authorizer?: { jwt: { claims: {}; scopes: string[] } }; domainName: string; domainPrefix: string; http: { method: string; path: string; protocol: string; sourceIp: string; userAgent: string }; requestId: string; routeKey: string; stage: string; time: string; timeEpoch: number }

Type declaration

  • accountId: string
  • apiId: string
  • Optional authorizer?: { jwt: { claims: {}; scopes: string[] } }
    • jwt: { claims: {}; scopes: string[] }
      • claims: {}
        • [name: string]: string | number | boolean | string[]
      • scopes: string[]
  • domainName: string
  • domainPrefix: string
  • http: { method: string; path: string; protocol: string; sourceIp: string; userAgent: string }
    • method: string
    • path: string
    • protocol: string
    • sourceIp: string
    • userAgent: string
  • requestId: string
  • routeKey: string
  • stage: string
  • time: string
  • timeEpoch: number
routeKey: string
stageVariables?: APIGatewayProxyEventStageVariables
supertokens: { response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | false | true }[] } }

Type declaration

  • response: { cookies: string[]; headers: { allowDuplicateKey: boolean; key: string; value: string | number | false | true }[] }
    • cookies: string[]
    • headers: { allowDuplicateKey: boolean; key: string; value: string | number | false | true }[]
version: string

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Interface
  • Property
  • Class
  • Class with type parameter

Settings

Theme

Generated using TypeDoc

\ No newline at end of file diff --git a/docs/interfaces/framework_express.SessionRequest.html b/docs/interfaces/framework_express.SessionRequest.html index f4fa93cf5..6eecd202d 100644 --- a/docs/interfaces/framework_express.SessionRequest.html +++ b/docs/interfaces/framework_express.SessionRequest.html @@ -1,12 +1,12 @@ -SessionRequest | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • Request
    • SessionRequest

Index

Properties

aborted: boolean
+SessionRequest | supertokens-node
Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • Request
    • SessionRequest

Index

Properties

aborted: boolean

The message.aborted property will be true if the request has been aborted.

since

v10.1.0

-
deprecated

Since v17.0.0,v16.12.0 - Check message.destroyed from stream.Readable.

+
deprecated

Since v17.0.0 - Check message.destroyed from stream.Readable.

accepted: MediaType[]

Return an array of Accepted media types ordered from highest quality to lowest.

-
app: Application<Record<string, any>>
baseUrl: string
body: any
complete: boolean
+
app: Application<Record<string, any>>
baseUrl: string
body: any
complete: boolean

The message.complete property will be true if a complete HTTP message has been received and successfully parsed.

This property is particularly useful as a means of determining if a client or @@ -14,21 +14,21 @@

const req = http.request({
host: '127.0.0.1',
port: 8080,
method: 'POST'
}, (res) => {
res.resume();
res.on('end', () => {
if (!res.complete)
console.error(
'The connection was terminated while the message was still being sent');
});
});
since

v0.3.0

-
connection: Socket
+
connection: Socket

Alias for message.socket.

since

v0.1.90

deprecated

Since v16.0.0 - Use socket.

-
cookies: any
destroyed: boolean
+
cookies: any
destroyed: boolean

Is true after readable.destroy() has been called.

-
since

v18.0.0

+
since

v8.0.0

fresh: boolean

Check if the request is fresh, aka Last-Modified and/or the ETag still match.

-
headers: IncomingHttpHeaders
+
headers: IncomingHttpHeaders

The request/response headers object.

Key-value pairs of header names and values. Header names are lower-cased.

-
// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*' }
console.log(request.getHeaders()); +
// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*' }
console.log(request.headers);

Duplicates in raw headers are handled in the following ways, depending on the header name:

@@ -43,13 +43,13 @@
host: string
deprecated

Use hostname instead.

hostname: string

Parse the "Host" header field hostname.

-
httpVersion: string
+
httpVersion: string

In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either '1.1' or '1.0'.

Also message.httpVersionMajor is the first integer andmessage.httpVersionMinor is the second.

since

v0.1.1

-
httpVersionMajor: number
httpVersionMinor: number
ip: string
+
httpVersionMajor: number
httpVersionMinor: number
ip: string

Return the remote address, or when "trust proxy" is true return the upstream addr.

@@ -68,7 +68,7 @@ field will be trusted. If you're running behind a reverse proxy that supplies https for you this may be enabled.

-
query: ParsedQs
rawHeaders: string[]
+
query: ParsedQs
rawHeaders: string[]

The raw request/response headers list exactly as they were received.

The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the @@ -77,39 +77,39 @@

// Prints something like:
//
// [ 'user-agent',
// 'this is invalid because there can be only one',
// 'User-Agent',
// 'curl/7.22.0',
// 'Host',
// '127.0.0.1:8000',
// 'ACCEPT',
// '*' ]
console.log(request.rawHeaders);
since

v0.11.6

-
rawTrailers: string[]
+
rawTrailers: string[]

The raw request/response trailer keys and values exactly as they were received. Only populated at the 'end' event.

since

v0.11.6

-
readable: boolean
+
readable: boolean

Is true if it is safe to call readable.read(), which means the stream has not been destroyed or emitted 'error' or 'end'.

since

v11.4.0

-
readableAborted: boolean
+
readableAborted: boolean

Returns whether the stream was destroyed or errored before emitting 'end'.

since

v16.8.0

-
experimental
readableDidRead: boolean
+
experimental
readableDidRead: boolean

Returns whether 'data' has been emitted.

since

v16.7.0, v14.18.0

-
experimental
readableEncoding: (null) | "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"
+
experimental
readableEncoding: null | "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"

Getter for the property encoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.

since

v12.7.0

-
readableEnded: boolean
+
readableEnded: boolean

Becomes true when 'end' event is emitted.

since

v12.9.0

-
readableFlowing: (null) | (false) | (true)
+
readableFlowing: null | false | true

This property reflects the current state of a Readable stream as described in the Three states section.

since

v9.4.0

-
readableHighWaterMark: number
+
readableHighWaterMark: number

Returns the value of highWaterMark passed when creating this Readable.

since

v9.3.0

-
readableLength: number
+
readableLength: number

This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the highWaterMark.

since

v9.4.0

-
readableObjectMode: boolean
+
readableObjectMode: boolean

Getter for the property objectMode of a given Readable stream.

since

v12.3.0

res?: Response<any, Record<string, any>, number>
@@ -118,23 +118,23 @@
route: any
secure: boolean

Short-hand for:

req.protocol == 'https'

-
signedCookies: any
socket: Socket
+
signedCookies: any
socket: Socket

The net.Socket object associated with the connection.

With HTTPS support, use request.socket.getPeerCertificate() to obtain the client's authentication details.

This property is guaranteed to be an instance of the net.Socket class, a subclass of stream.Duplex, unless the user specified a socket -type other than net.Socket or internally nulled.

+type other than net.Socket.

since

v0.3.0

stale: boolean

Check if the request is stale, aka "Last-Modified" and / or the "ETag" for the resource has changed.

-
statusCode?: number
+
statusCode?: number

Only valid for response obtained from {@link ClientRequest}.

The 3-digit HTTP response status code. E.G. 404.

since

v0.1.1

-
statusMessage?: string
+
statusMessage?: string

Only valid for response obtained from {@link ClientRequest}.

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

since

v0.11.10

@@ -146,12 +146,12 @@

For example, if the domain is "tobi.ferrets.example.com": If "subdomain offset" is not set, req.subdomains is ["ferrets", "tobi"]. If "subdomain offset" is 3, req.subdomains is ["tobi"].

-
trailers: Dict<string>
+
trailers: Dict<string>

The request/response trailers object. Only populated at the 'end' event.

since

v0.3.0

url: string
xhr: boolean

Check if the request was an XMLHttpRequest.

-

Methods

  • [Symbol.asyncIterator](): AsyncIterableIterator<any>
  • Returns AsyncIterableIterator<any>

  • _construct(callback: ((error?: (null) | Error) => void)): void
  • Parameters

    • callback: ((error?: (null) | Error) => void)
        • (error?: (null) | Error): void
        • Parameters

          • Optional error: (null) | Error

          Returns void

    Returns void

  • _destroy(error: (null) | Error, callback: ((error?: (null) | Error) => void)): void
  • Parameters

    • error: (null) | Error
    • callback: ((error?: (null) | Error) => void)
        • (error?: (null) | Error): void
        • Parameters

          • Optional error: (null) | Error

          Returns void

    Returns void

  • _read(size: number): void
  • Parameters

    • size: number

    Returns void

  • accepts(): string[]
  • accepts(type: string): string | (false)
  • accepts(type: string[]): string | (false)
  • accepts(...type: string[]): string | (false)
  • +

Methods

  • [Symbol.asyncIterator](): AsyncIterableIterator<any>
  • Returns AsyncIterableIterator<any>

  • _construct(callback: (error?: null | Error) => void): void
  • Parameters

    • callback: (error?: null | Error) => void
        • (error?: null | Error): void
        • Parameters

          • Optional error: null | Error

          Returns void

    Returns void

  • _destroy(error: null | Error, callback: (error?: null | Error) => void): void
  • Parameters

    • error: null | Error
    • callback: (error?: null | Error) => void
        • (error?: null | Error): void
        • Parameters

          • Optional error: null | Error

          Returns void

    Returns void

  • _read(size: number): void
  • Parameters

    • size: number

    Returns void

  • accepts(): string[]
  • accepts(type: string): string | false
  • accepts(type: string[]): string | false
  • accepts(...type: string[]): string | false
  • Check if the given type(s) is acceptable, returning the best match when true, otherwise undefined, in which case you should respond with 406 "Not Acceptable".

    @@ -163,22 +163,22 @@

    Examples:

    // Accept: text/html
    req.accepts('html');
    // => "html"

    // Accept: text/*, application/json
    req.accepts('html');
    // => "html"
    req.accepts('text/html');
    // => "text/html"
    req.accepts('json, text');
    // => "json"
    req.accepts('application/json');
    // => "application/json"

    // Accept: text/*, application/json
    req.accepts('image/png');
    req.accepts('png');
    // => undefined

    // Accept: text/*;q=.5, application/json
    req.accepts(['html', 'json']);
    req.accepts('html, json');
    // => "json"
    -

    Returns string[]

  • Parameters

    • type: string

    Returns string | (false)

  • Parameters

    • type: string[]

    Returns string | (false)

  • Parameters

    • Rest ...type: string[]

    Returns string | (false)

  • acceptsCharsets(): string[]
  • acceptsCharsets(charset: string): string | (false)
  • acceptsCharsets(charset: string[]): string | (false)
  • acceptsCharsets(...charset: string[]): string | (false)
  • +

    Returns string[]

  • Parameters

    • type: string

    Returns string | false

  • Parameters

    • type: string[]

    Returns string | false

  • Parameters

    • Rest ...type: string[]

    Returns string | false

  • acceptsCharsets(): string[]
  • acceptsCharsets(charset: string): string | false
  • acceptsCharsets(charset: string[]): string | false
  • acceptsCharsets(...charset: string[]): string | false
  • Returns the first accepted charset of the specified character sets, based on the request's Accept-Charset HTTP header field. If none of the specified charsets is accepted, returns false.

    For more information, or if you have issues or concerns, see accepts.

    -

    Returns string[]

  • Parameters

    • charset: string

    Returns string | (false)

  • Parameters

    • charset: string[]

    Returns string | (false)

  • Parameters

    • Rest ...charset: string[]

    Returns string | (false)

  • acceptsEncodings(): string[]
  • acceptsEncodings(encoding: string): string | (false)
  • acceptsEncodings(encoding: string[]): string | (false)
  • acceptsEncodings(...encoding: string[]): string | (false)
  • +

    Returns string[]

  • Parameters

    • charset: string

    Returns string | false

  • Parameters

    • charset: string[]

    Returns string | false

  • Parameters

    • Rest ...charset: string[]

    Returns string | false

  • acceptsEncodings(): string[]
  • acceptsEncodings(encoding: string): string | false
  • acceptsEncodings(encoding: string[]): string | false
  • acceptsEncodings(...encoding: string[]): string | false
  • Returns the first accepted encoding of the specified encodings, based on the request's Accept-Encoding HTTP header field. If none of the specified encodings is accepted, returns false.

    For more information, or if you have issues or concerns, see accepts.

    -

    Returns string[]

  • Parameters

    • encoding: string

    Returns string | (false)

  • Parameters

    • encoding: string[]

    Returns string | (false)

  • Parameters

    • Rest ...encoding: string[]

    Returns string | (false)

  • acceptsLanguages(): string[]
  • acceptsLanguages(lang: string): string | (false)
  • acceptsLanguages(lang: string[]): string | (false)
  • acceptsLanguages(...lang: string[]): string | (false)
  • +

    Returns string[]

  • Parameters

    • encoding: string

    Returns string | false

  • Parameters

    • encoding: string[]

    Returns string | false

  • Parameters

    • Rest ...encoding: string[]

    Returns string | false

  • acceptsLanguages(): string[]
  • acceptsLanguages(lang: string): string | false
  • acceptsLanguages(lang: string[]): string | false
  • acceptsLanguages(...lang: string[]): string | false
  • Returns the first accepted language of the specified languages, based on the request's Accept-Language HTTP header field. If none of the specified languages is accepted, returns false.

    For more information, or if you have issues or concerns, see accepts.

    -

    Returns string[]

  • Parameters

    • lang: string

    Returns string | (false)

  • Parameters

    • lang: string[]

    Returns string | (false)

  • Parameters

    • Rest ...lang: string[]

    Returns string | (false)

  • addListener(event: "close", listener: (() => void)): SessionRequest
  • addListener(event: "data", listener: ((chunk: any) => void)): SessionRequest
  • addListener(event: "end", listener: (() => void)): SessionRequest
  • addListener(event: "error", listener: ((err: Error) => void)): SessionRequest
  • addListener(event: "pause", listener: (() => void)): SessionRequest
  • addListener(event: "readable", listener: (() => void)): SessionRequest
  • addListener(event: "resume", listener: (() => void)): SessionRequest
  • addListener(event: string | symbol, listener: ((...args: any[]) => void)): SessionRequest
  • +

    Returns string[]

  • Parameters

    • lang: string

    Returns string | false

  • Parameters

    • lang: string[]

    Returns string | false

  • Parameters

    • Rest ...lang: string[]

    Returns string | false

  • addListener(event: "close", listener: () => void): SessionRequest
  • addListener(event: "data", listener: (chunk: any) => void): SessionRequest
  • addListener(event: "end", listener: () => void): SessionRequest
  • addListener(event: "error", listener: (err: Error) => void): SessionRequest
  • addListener(event: "pause", listener: () => void): SessionRequest
  • addListener(event: "readable", listener: () => void): SessionRequest
  • addListener(event: "resume", listener: () => void): SessionRequest
  • addListener(event: string | symbol, listener: (...args: any[]) => void): SessionRequest
  • Event emitter The defined events on documents including:

      @@ -190,11 +190,11 @@
    1. readable
    2. resume
    -

    Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: ((chunk: any) => void)
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: ((err: Error) => void)
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • +

    Parameters

    • event: "close"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: (chunk: any) => void
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: (err: Error) => void
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • Calls destroy() on the socket that received the IncomingMessage. If erroris provided, an 'error' event is emitted on the socket and error is passed as an argument to any listeners on the event.

    since

    v0.3.0

    -

    Parameters

    • Optional error: Error

    Returns SessionRequest

  • emit(event: "close"): boolean
  • emit(event: "data", chunk: any): boolean
  • emit(event: "end"): boolean
  • emit(event: "error", err: Error): boolean
  • emit(event: "pause"): boolean
  • emit(event: "readable"): boolean
  • emit(event: "resume"): boolean
  • emit(event: string | symbol, ...args: any[]): boolean
  • Parameters

    • event: "close"

    Returns boolean

  • Parameters

    • event: "data"
    • chunk: any

    Returns boolean

  • Parameters

    • event: "end"

    Returns boolean

  • Parameters

    • event: "error"
    • err: Error

    Returns boolean

  • Parameters

    • event: "pause"

    Returns boolean

  • Parameters

    • event: "readable"

    Returns boolean

  • Parameters

    • event: "resume"

    Returns boolean

  • Parameters

    • event: string | symbol
    • Rest ...args: any[]

    Returns boolean

  • eventNames(): (string | symbol)[]
  • +

    Parameters

    • Optional error: Error

    Returns SessionRequest

  • emit(event: "close"): boolean
  • emit(event: "data", chunk: any): boolean
  • emit(event: "end"): boolean
  • emit(event: "error", err: Error): boolean
  • emit(event: "pause"): boolean
  • emit(event: "readable"): boolean
  • emit(event: "resume"): boolean
  • emit(event: string | symbol, ...args: any[]): boolean
  • Parameters

    • event: "close"

    Returns boolean

  • Parameters

    • event: "data"
    • chunk: any

    Returns boolean

  • Parameters

    • event: "end"

    Returns boolean

  • Parameters

    • event: "error"
    • err: Error

    Returns boolean

  • Parameters

    • event: "pause"

    Returns boolean

  • Parameters

    • event: "readable"

    Returns boolean

  • Parameters

    • event: "resume"

    Returns boolean

  • Parameters

    • event: string | symbol
    • Rest ...args: any[]

    Returns boolean

  • eventNames(): (string | symbol)[]
  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    const EventEmitter = require('events');
    const myEE = new EventEmitter();
    myEE.on('foo', () => {});
    myEE.on('bar', () => {});

    const sym = Symbol('symbol');
    myEE.on(sym, () => {});

    console.log(myEE.eventNames());
    // Prints: [ 'foo', 'bar', Symbol(symbol) ] @@ -208,37 +208,37 @@
    req.get('Content-Type');
    // => "text/plain"

    req.get('content-type');
    // => "text/plain"

    req.get('Something');
    // => undefined

    Aliased as req.header().

    -

    Parameters

    • name: "set-cookie"

    Returns undefined | string[]

  • Parameters

    • name: string

    Returns undefined | string

  • getMaxListeners(): number
  • +

    Parameters

    • name: "set-cookie"

    Returns undefined | string[]

  • Parameters

    • name: string

    Returns undefined | string

  • getMaxListeners(): number
  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to {@link defaultMaxListeners}.

    since

    v1.0.0

    -

    Returns number

  • header(name: "set-cookie"): undefined | string[]
  • header(name: string): undefined | string
  • Parameters

    • name: "set-cookie"

    Returns undefined | string[]

  • Parameters

    • name: string

    Returns undefined | string

  • is(type: string | string[]): (null) | string | (false)
  • +

    Returns number

  • header(name: "set-cookie"): undefined | string[]
  • header(name: string): undefined | string
  • Parameters

    • name: "set-cookie"

    Returns undefined | string[]

  • Parameters

    • name: string

    Returns undefined | string

  • is(type: string | string[]): null | string | false
  • Check if the incoming request contains the "Content-Type" header field, and it contains the give mime type.

    Examples:

     // With Content-Type: text/html; charset=utf-8
    req.is('html');
    req.is('text/html');
    req.is('text/*');
    // => true

    // When Content-Type is application/json
    req.is('json');
    req.is('application/json');
    req.is('application/*');
    // => true

    req.is('html');
    // => false
    -

    Parameters

    • type: string | string[]

    Returns (null) | string | (false)

  • isPaused(): boolean
  • +

    Parameters

    • type: string | string[]

    Returns null | string | false

  • isPaused(): boolean
  • The readable.isPaused() method returns the current operating state of theReadable. This is used primarily by the mechanism that underlies thereadable.pipe() method. In most typical cases, there will be no reason to use this method directly.

    const readable = new stream.Readable();

    readable.isPaused(); // === false
    readable.pause();
    readable.isPaused(); // === true
    readable.resume();
    readable.isPaused(); // === false
    since

    v0.11.14

    -

    Returns boolean

  • listenerCount(eventName: string | symbol): number
  • +

    Returns boolean

  • listenerCount(eventName: string | symbol): number
  • Returns the number of listeners listening to the event named eventName.

    since

    v3.2.0

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

      -

    Returns number

  • listeners(eventName: string | symbol): Function[]
  • +

Returns number

  • listeners(eventName: string | symbol): Function[]
  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]
    since

    v0.1.26

    -

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • off(eventName: string | symbol, listener: ((...args: any[]) => void)): SessionRequest
  • +

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • off(eventName: string | symbol, listener: (...args: any[]) => void): SessionRequest
  • Alias for emitter.removeListener().

    since

    v10.0.0

    -

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: ((chunk: any) => void)
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: ((err: Error) => void)
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: ((chunk: any) => void)
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: ((err: Error) => void)
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • param(name: string, defaultValue?: any): string
  • deprecated

    since 4.11 Use either req.params, req.body or req.query, as applicable.

    +

    Parameters

    • eventName: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "close"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: (chunk: any) => void
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: (err: Error) => void
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "close"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: (chunk: any) => void
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: (err: Error) => void
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • param(name: string, defaultValue?: any): string
  • deprecated

    since 4.11 Use either req.params, req.body or req.query, as applicable.

    Return the value of param name when present or defaultValue.

    • Checks route placeholders, ex: /user/:id
    • @@ -248,7 +248,7 @@

      To utilize request bodies, req.body should be an object. This can be done by using the connect.bodyParser() middleware.

      -

    Parameters

    • name: string
    • Optional defaultValue: any

    Returns string

  • +

    Parameters

    • name: string
    • Optional defaultValue: any

    Returns string

  • The readable.pause() method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.

    @@ -256,7 +256,7 @@

    The readable.pause() method has no effect if there is a 'readable'event listener.

    since

    v0.9.4

    -

    Returns SessionRequest

  • pipe<T>(destination: T, options?: { end?: (false) | (true) }): T
  • Type Parameters

    • T extends WritableStream<T>

    Parameters

    • destination: T
    • Optional options: { end?: (false) | (true) }
      • Optional end?: (false) | (true)

    Returns T

  • prependListener(event: "close", listener: (() => void)): SessionRequest
  • prependListener(event: "data", listener: ((chunk: any) => void)): SessionRequest
  • prependListener(event: "end", listener: (() => void)): SessionRequest
  • prependListener(event: "error", listener: ((err: Error) => void)): SessionRequest
  • prependListener(event: "pause", listener: (() => void)): SessionRequest
  • prependListener(event: "readable", listener: (() => void)): SessionRequest
  • prependListener(event: "resume", listener: (() => void)): SessionRequest
  • prependListener(event: string | symbol, listener: ((...args: any[]) => void)): SessionRequest
  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: ((chunk: any) => void)
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: ((err: Error) => void)
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • prependOnceListener(event: "close", listener: (() => void)): SessionRequest
  • prependOnceListener(event: "data", listener: ((chunk: any) => void)): SessionRequest
  • prependOnceListener(event: "end", listener: (() => void)): SessionRequest
  • prependOnceListener(event: "error", listener: ((err: Error) => void)): SessionRequest
  • prependOnceListener(event: "pause", listener: (() => void)): SessionRequest
  • prependOnceListener(event: "readable", listener: (() => void)): SessionRequest
  • prependOnceListener(event: "resume", listener: (() => void)): SessionRequest
  • prependOnceListener(event: string | symbol, listener: ((...args: any[]) => void)): SessionRequest
  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: ((chunk: any) => void)
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: ((err: Error) => void)
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • push(chunk: any, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"): boolean
  • Parameters

    • chunk: any
    • Optional encoding: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"

    Returns boolean

  • range(size: number, options?: Options): undefined | Ranges | -1 | -2
  • +

    Returns SessionRequest

  • pipe<T>(destination: T, options?: { end?: false | true }): T
  • Type parameters

    • T: WritableStream<T>

    Parameters

    • destination: T
    • Optional options: { end?: false | true }
      • Optional end?: false | true

    Returns T

  • prependListener(event: "close", listener: () => void): SessionRequest
  • prependListener(event: "data", listener: (chunk: any) => void): SessionRequest
  • prependListener(event: "end", listener: () => void): SessionRequest
  • prependListener(event: "error", listener: (err: Error) => void): SessionRequest
  • prependListener(event: "pause", listener: () => void): SessionRequest
  • prependListener(event: "readable", listener: () => void): SessionRequest
  • prependListener(event: "resume", listener: () => void): SessionRequest
  • prependListener(event: string | symbol, listener: (...args: any[]) => void): SessionRequest
  • Parameters

    • event: "close"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: (chunk: any) => void
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: (err: Error) => void
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • prependOnceListener(event: "close", listener: () => void): SessionRequest
  • prependOnceListener(event: "data", listener: (chunk: any) => void): SessionRequest
  • prependOnceListener(event: "end", listener: () => void): SessionRequest
  • prependOnceListener(event: "error", listener: (err: Error) => void): SessionRequest
  • prependOnceListener(event: "pause", listener: () => void): SessionRequest
  • prependOnceListener(event: "readable", listener: () => void): SessionRequest
  • prependOnceListener(event: "resume", listener: () => void): SessionRequest
  • prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): SessionRequest
  • Parameters

    • event: "close"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: (chunk: any) => void
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: (err: Error) => void
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • push(chunk: any, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"): boolean
  • Parameters

    • chunk: any
    • Optional encoding: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"

    Returns boolean

  • range(size: number, options?: Options): undefined | Ranges | -1 | -2
  • Parse Range header field, capping to the given size.

    Unspecified ranges such as "0-" require knowledge of your resource length. In the case of a byte range this is of course the total number of bytes. @@ -265,16 +265,16 @@ See more ./types/range-parser/index.d.ts

    NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" should respond with 4 users when available, not 3.

    -

    Parameters

    • size: number
    • Optional options: Options

    Returns undefined | Ranges | -1 | -2

  • rawListeners(eventName: string | symbol): Function[]
  • +

    Parameters

    • size: number
    • Optional options: Options

    Returns undefined | Ranges | -1 | -2

  • rawListeners(eventName: string | symbol): Function[]
  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    const emitter = new EventEmitter();
    emitter.once('log', () => console.log('log once'));

    // Returns a new Array with a function `onceWrapper` which has a property
    // `listener` which contains the original listener bound above
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    logFnWrapper.listener();

    // Logs "log once" to the console and removes the listener
    logFnWrapper();

    emitter.on('log', () => console.log('log persistently'));
    // Will return a new Array with a single function bound by `.on()` above
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');
    since

    v9.4.0

    -

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • read(size?: number): any
  • -

    The readable.read() method reads data out of the internal buffer and -returns it. If no data is available to be read, null is returned. By default, -the data is returned as a Buffer object unless an encoding has been +

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • read(size?: number): any
  • +

    The readable.read() method pulls some data out of the internal buffer and +returns it. If no data available to be read, null is returned. By default, +the data will be returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.

    The optional size argument specifies a specific number of bytes to read. Ifsize bytes are not available to be read, null will be returned _unless_the stream has ended, in which @@ -308,14 +308,14 @@

    since

    v0.9.4

    Parameters

    • Optional size: number

      Optional argument to specify how much data to read.

      -

    Returns any

  • +

Returns any

  • Removes all listeners, or those of the specified eventName.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Returns a reference to the EventEmitter, so that calls can be chained.

    since

    v0.1.26

    -

    Parameters

    • Optional event: string | symbol

    Returns SessionRequest

  • removeListener(event: "close", listener: (() => void)): SessionRequest
  • removeListener(event: "data", listener: ((chunk: any) => void)): SessionRequest
  • removeListener(event: "end", listener: (() => void)): SessionRequest
  • removeListener(event: "error", listener: ((err: Error) => void)): SessionRequest
  • removeListener(event: "pause", listener: (() => void)): SessionRequest
  • removeListener(event: "readable", listener: (() => void)): SessionRequest
  • removeListener(event: "resume", listener: (() => void)): SessionRequest
  • removeListener(event: string | symbol, listener: ((...args: any[]) => void)): SessionRequest
  • Parameters

    • event: "close"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: ((chunk: any) => void)
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: ((err: Error) => void)
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • +

    Parameters

    • Optional event: string | symbol

    Returns SessionRequest

  • removeListener(event: "close", listener: () => void): SessionRequest
  • removeListener(event: "data", listener: (chunk: any) => void): SessionRequest
  • removeListener(event: "end", listener: () => void): SessionRequest
  • removeListener(event: "error", listener: (err: Error) => void): SessionRequest
  • removeListener(event: "pause", listener: () => void): SessionRequest
  • removeListener(event: "readable", listener: () => void): SessionRequest
  • removeListener(event: "resume", listener: () => void): SessionRequest
  • removeListener(event: string | symbol, listener: (...args: any[]) => void): SessionRequest
  • Parameters

    • event: "close"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "data"
    • listener: (chunk: any) => void
        • (chunk: any): void
        • Parameters

          • chunk: any

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "end"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "error"
    • listener: (err: Error) => void
        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns SessionRequest

  • Parameters

    • event: "pause"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "readable"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: "resume"
    • listener: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionRequest

  • The readable.resume() method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.

    The readable.resume() method can be used to fully consume the data from a @@ -324,7 +324,7 @@

    The readable.resume() method has no effect if there is a 'readable'event listener.

    since

    v0.9.4

    -

    Returns SessionRequest

  • +

    Returns SessionRequest

  • The readable.setEncoding() method sets the character encoding for data read from the Readable stream.

    By default, no encoding is assigned and stream data will be returned asBuffer objects. Setting an encoding causes the stream data @@ -339,17 +339,17 @@

    since

    v0.9.4

    Parameters

    • encoding: BufferEncoding

      The encoding to use.

      -

    Returns SessionRequest

  • +

Returns SessionRequest

  • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.

    Returns a reference to the EventEmitter, so that calls can be chained.

    since

    v0.3.5

    -

    Parameters

    • n: number

    Returns SessionRequest

  • +

    Parameters

    • n: number

    Returns SessionRequest

  • Calls message.socket.setTimeout(msecs, callback).

    since

    v0.5.9

    -

    Parameters

    • msecs: number
    • Optional callback: (() => void)
        • (): void
        • Returns void

    Returns SessionRequest

  • +

    Parameters

    • msecs: number
    • Optional callback: () => void
        • (): void
        • Returns void

    Returns SessionRequest

  • The readable.unpipe() method detaches a Writable stream previously attached using the pipe method.

    If the destination is not specified, then all pipes are detached.

    @@ -360,7 +360,7 @@
    since

    v0.9.4

    Parameters

    • Optional destination: WritableStream

      Optional specific stream to unpipe

      -

    Returns SessionRequest

  • unshift(chunk: any, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"): void
  • +

Returns SessionRequest

  • unshift(chunk: any, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"): void
  • Passing chunk as null signals the end of the stream (EOF) and behaves the same as readable.push(null), after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be @@ -373,7 +373,7 @@ has been emitted or a runtime error will be thrown.

    Developers using stream.unshift() often should consider switching to use of a Transform stream instead. See the API for stream implementers section for more information.

    -
    // Pull off a header delimited by \n\n.
    // Use unshift() if we get too much.
    // Call the callback with (error, header, stream).
    const { StringDecoder } = require('string_decoder');
    function parseHeader(stream, callback) {
    stream.on('error', callback);
    stream.on('readable', onReadable);
    const decoder = new StringDecoder('utf8');
    let header = '';
    function onReadable() {
    let chunk;
    while (null !== (chunk = stream.read())) {
    const str = decoder.write(chunk);
    if (str.includes('\n\n')) {
    // Found the header boundary.
    const split = str.split(/\n\n/);
    header += split.shift();
    const remaining = split.join('\n\n');
    const buf = Buffer.from(remaining, 'utf8');
    stream.removeListener('error', callback);
    // Remove the 'readable' listener before unshifting.
    stream.removeListener('readable', onReadable);
    if (buf.length)
    stream.unshift(buf);
    // Now the body of the message can be read from the stream.
    callback(null, header, stream);
    return;
    }
    // Still reading the header.
    header += str;
    }
    }
    } +
    // Pull off a header delimited by \n\n.
    // Use unshift() if we get too much.
    // Call the callback with (error, header, stream).
    const { StringDecoder } = require('string_decoder');
    function parseHeader(stream, callback) {
    stream.on('error', callback);
    stream.on('readable', onReadable);
    const decoder = new StringDecoder('utf8');
    let header = '';
    function onReadable() {
    let chunk;
    while (null !== (chunk = stream.read())) {
    const str = decoder.write(chunk);
    if (str.match(/\n\n/)) {
    // Found the header boundary.
    const split = str.split(/\n\n/);
    header += split.shift();
    const remaining = split.join('\n\n');
    const buf = Buffer.from(remaining, 'utf8');
    stream.removeListener('error', callback);
    // Remove the 'readable' listener before unshifting.
    stream.removeListener('readable', onReadable);
    if (buf.length)
    stream.unshift(buf);
    // Now the body of the message can be read from the stream.
    callback(null, header, stream);
    } else {
    // Still reading the header.
    header += str;
    }
    }
    }
    }

    Unlike push, stream.unshift(chunk) will not end the reading process by resetting the internal reading state of the stream. @@ -388,7 +388,7 @@ streams, chunk may be any JavaScript value.

  • Optional encoding: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex"

    Encoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.

    -

Returns void

  • +

Returns void

  • Prior to Node.js 0.10, streams did not implement the entire stream module API as it is currently defined. (See Compatibility for more information.)

    When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable diff --git a/docs/interfaces/framework_fastify.SessionRequest.html b/docs/interfaces/framework_fastify.SessionRequest.html index 81d9e2a5e..4e08599cd 100644 --- a/docs/interfaces/framework_fastify.SessionRequest.html +++ b/docs/interfaces/framework_fastify.SessionRequest.html @@ -1,4 +1,4 @@ -SessionRequest | supertokens-node

    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Hierarchy

    • FastifyRequest
      • SessionRequest

    Index

    Properties

    body: unknown
    connection: Socket
    headers: IncomingHttpHeaders
    hostname: string
    id: any
    ip: string
    ips?: string[]
    is404: boolean
    log: FastifyLoggerInstance
    method: string
    params: unknown
    protocol: "http" | "https"
    query: unknown
    raw: IncomingMessage
    req: IncomingMessage
    deprecated

    Use raw property

    -
    routerMethod: string
    routerPath: string
    socket: Socket
    url: string
    validationError?: Error & { validation: any; validationContext: string }
    +SessionRequest | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Hierarchy

    • FastifyRequest
      • SessionRequest

    Index

    Properties

    body: unknown
    connection: Socket
    headers: IncomingHttpHeaders
    hostname: string
    id: any
    ip: string
    ips?: string[]
    is404: boolean
    log: FastifyLoggerInstance
    method: string
    params: unknown
    protocol: "http" | "https"
    query: unknown
    raw: IncomingMessage
    req: IncomingMessage
    deprecated

    Use raw property

    +
    routerMethod: string
    routerPath: string
    socket: Socket
    url: string
    validationError?: Error & { validation: any; validationContext: string }

    in order for this to be used the user should ensure they have set the attachValidation option.

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Interface
    • Property
    • Class
    • Class with type parameter

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file diff --git a/docs/interfaces/framework_hapi.SessionRequest.html b/docs/interfaces/framework_hapi.SessionRequest.html index 30ae0e4f5..a5abcd2c2 100644 --- a/docs/interfaces/framework_hapi.SessionRequest.html +++ b/docs/interfaces/framework_hapi.SessionRequest.html @@ -1,4 +1,4 @@ -SessionRequest | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Hierarchy

    • Request
      • SessionRequest

    Index

    Properties

    app: RequestApplicationState
    +SessionRequest | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Hierarchy

    • Request
      • SessionRequest

    Index

    Properties

    app: RequestApplicationState

    Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. See docs

    auth: RequestAuth
    @@ -89,7 +89,7 @@
    server: Server

    Access: read only and the public server interface. The server object.

    -
    state: Dictionary<any>
    +
    state: Dictionary<any>

    An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition.

    url: URL

    The parsed request URI.

    @@ -100,7 +100,7 @@ (e.g. client disconnected or aborted early).

    Returns boolean

  • addListener<TArgs, Tcontext>(criteria: string | CriteriaObject, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • addListener<TArgs, Tcontext>(criteria: string | CriteriaObject, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • Subscribe a handler to an event. Same as podium.on().

    -

    Type Parameters

    • TArgs extends any[] = unknown[]

    • Tcontext extends object = SessionRequest

    Parameters

    • criteria: string | CriteriaObject
      +

      Type parameters

      Parameters

      • criteria: string | CriteriaObject

        The subscription criteria.

      • listener: Listener<Tcontext, TArgs>

        The handler method set to receive event updates. The function signature @@ -108,7 +108,7 @@

      • Optional context: Tcontext

        Optional object that binds to the listener handler.

      Returns SessionRequest

      A reference to the current emitter.

      -
    • Type Parameters

      Parameters

      • criteria: string | CriteriaObject
      • listener: Listener<Tcontext, TArgs>
      • Optional context: Tcontext

      Returns SessionRequest

  • emit(criteria: string | EmitCriteria, data?: any): Promise<void>
  • +
  • Type parameters

    Parameters

    • criteria: string | CriteriaObject
    • listener: Listener<Tcontext, TArgs>
    • Optional context: Tcontext

    Returns SessionRequest

  • emit(criteria: string | EmitCriteria, data?: any): Promise<void>
  • Emits an event update to all the subscribed listeners.

    Parameters

    • criteria: string | EmitCriteria

      The event update criteria.

      @@ -116,9 +116,9 @@

      The value emitted to the subscribers.

    Returns Promise<void>

    Promise that resolves when all events has been processed. Any errors will cause an immediate rejection.

    -
  • generateResponse(source: (null) | string | object, options?: { variety?: string; close?: any; marshal?: any; prepare?: any }): ResponseObject
  • +
  • generateResponse(source: null | string | object, options?: { variety?: string; close?: any; marshal?: any; prepare?: any }): ResponseObject
  • Returns a response which you can pass into the reply interface where:

    -

    Parameters

    • source: (null) | string | object
      +

      Parameters

      • source: null | string | object

        the value to set as the source of the reply interface, optional.

      • Optional options: { variety?: string; close?: any; marshal?: any; prepare?: any }

        options for the method, optional.

        @@ -142,7 +142,7 @@ See docs

  • on<TArgs, Tcontext>(criteria: string | CriteriaObject, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • on<TArgs, Tcontext>(criteria: string | CriteriaObject, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • Subscribe a handler to an event.

    -

    Type Parameters

    • TArgs extends any[] = unknown[]

    • Tcontext extends object = SessionRequest

    Parameters

    • criteria: string | CriteriaObject
      +

      Type parameters

      Parameters

      • criteria: string | CriteriaObject

        The subscription criteria.

      • listener: Listener<Tcontext, TArgs>

        The handler method set to receive event updates. The function signature @@ -150,10 +150,10 @@

      • Optional context: Tcontext

        Optional object that binds to the listener handler.

      Returns SessionRequest

      A reference to the current emitter.

      -
    • Type Parameters

      Parameters

      • criteria: string | CriteriaObject
      • listener: Listener<Tcontext, TArgs>
      • Optional context: Tcontext

      Returns SessionRequest

  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">): Promise<TArgs>
  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">): Promise<TArgs>
  • +
  • Type parameters

    Parameters

    • criteria: string | CriteriaObject
    • listener: Listener<Tcontext, TArgs>
    • Optional context: Tcontext

    Returns SessionRequest

  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">, listener: Listener<Tcontext, TArgs>, context?: Tcontext): SessionRequest
  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">): Promise<TArgs>
  • once<TArgs, Tcontext>(criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">): Promise<TArgs>
  • Same as podium.on() with the count option set to 1.

    Can also be called without an listener to wait for a single event.

    -

    Type Parameters

    • TArgs extends any[] = unknown[]

    • Tcontext extends object = SessionRequest

    Parameters

    • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">
      +

      Type parameters

      Parameters

      • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">

        The subscription criteria.

      • listener: Listener<Tcontext, TArgs>

        The handler method set to receive event updates. The function signature @@ -161,12 +161,12 @@

      • Optional context: Tcontext

        Optional object that binds to the listener handler.

      Returns SessionRequest

      A reference to the current emitter.

      -
    • Type Parameters

      Parameters

      • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">
      • listener: Listener<Tcontext, TArgs>
      • Optional context: Tcontext

      Returns SessionRequest

    • +
    • Type parameters

      Parameters

      • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">
      • listener: Listener<Tcontext, TArgs>
      • Optional context: Tcontext

      Returns SessionRequest

    • Wait for a single event. The count option is fixed to 1.

      -

      Type Parameters

      • TArgs extends any[] = unknown[]

      • Tcontext extends void = void

      Parameters

      • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">
        +

        Type parameters

        • TArgs: any[] = unknown[]

        • Tcontext: void = void

        Parameters

        • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">

          The subscription criteria.

        Returns Promise<TArgs>

        Promise with array of emitted parameters.

        -
      • Type Parameters

        • TArgs extends any[] = any[]

        • Tcontext extends void = void

        Parameters

        • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">

        Returns Promise<TArgs>

  • registerEvent(events: string | Podium | EventOptions | Event[]): void
  • +
  • Type parameters

    • TArgs: any[] = any[]

    • Tcontext: void = void

    Parameters

    • criteria: string | Pick<CriteriaObject, "name" | "channels" | "clone" | "filter" | "spread" | "tags">

    Returns Promise<TArgs>

  • registerEvent(events: string | Podium | EventOptions | Event[]): void
  • Register the specified events and their optional configuration. Events must be registered before they can be emitted or subscribed to. This is done to detect event name mispelling and invalid event activities.

    @@ -198,13 +198,13 @@

Returns void

void Can only be called from an 'onRequest' extension method. See docs

-
  • setUrl(url: string | URL, stripTrailingSlash?: (false) | (true)): void
  • +
  • setUrl(url: string | URL, stripTrailingSlash?: false | true): void
  • Changes the request URI before the router begins processing the request where: Can only be called from an 'onRequest' extension method.

    Parameters

    • url: string | URL

      the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL parse() method output.

      -
    • Optional stripTrailingSlash: (false) | (true)
      +
    • Optional stripTrailingSlash: false | true

      if true, strip the trailing slash from the path. Defaults to false.

    Returns void

    void See docs

    diff --git a/docs/interfaces/framework_koa.SessionContext.html b/docs/interfaces/framework_koa.SessionContext.html index 2014ed557..dda1f3c9f 100644 --- a/docs/interfaces/framework_koa.SessionContext.html +++ b/docs/interfaces/framework_koa.SessionContext.html @@ -1,4 +1,4 @@ -SessionContext | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Hierarchy

    • Context
      • SessionContext

    Index

    Properties

    URL: URL
    +SessionContext | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Hierarchy

    • Context
      • SessionContext

    Index

    Properties

    URL: URL

    Get WHATWG parsed URL object.

    accept: Accepts
    app: __module
    assert: typeof assert

    Similar to .throw(), adds assertion.

    @@ -71,7 +71,7 @@ Set query-string as an object.

    querystring: string

    Get/Set query string.

    -
    req: IncomingMessage
    request: Request
    res: ServerResponse
    respond?: (false) | (true)
    +
    req: IncomingMessage
    request: Request
    res: ServerResponse
    respond?: false | true

    To bypass Koa's built-in response handling, you may explicitly set ctx.respond = false;

    response: Response & { body: unknown }
    search: string

    Get the search string. Same as the querystring @@ -81,7 +81,7 @@

    secure: boolean

    Short-hand for:

    this.protocol == 'https'

    -
    socket: Socket
    +
    socket: Socket

    Return the request socket.

    stale: boolean

    Check if the request is stale, aka @@ -112,7 +112,7 @@

    Checks if the request is writable. Tests for the existence of the socket as node sometimes does not set it.

    -

    Methods

    • accepts(): string[]
    • accepts(...types: string[]): string | (false)
    • accepts(types: string[]): string | (false)
    • +

    Methods

    • accepts(): string[]
    • accepts(...types: string[]): string | false
    • accepts(types: string[]): string | false
    • Check if the given type(s) is acceptable, returning the best match when true, otherwise false, in which case you should respond with 406 "Not Acceptable".

      @@ -123,25 +123,25 @@

      Examples:

      // Accept: text/html
      this.accepts('html');
      // => "html"

      // Accept: text/*, application/json
      this.accepts('html');
      // => "html"
      this.accepts('text/html');
      // => "text/html"
      this.accepts('json', 'text');
      // => "json"
      this.accepts('application/json');
      // => "application/json"

      // Accept: text/*, application/json
      this.accepts('image/png');
      this.accepts('png');
      // => undefined

      // Accept: text/*;q=.5, application/json
      this.accepts(['html', 'json']);
      this.accepts('html', 'json');
      // => "json"
      -

      Returns string[]

    • Parameters

      • Rest ...types: string[]

      Returns string | (false)

    • Parameters

      • types: string[]

      Returns string | (false)

    • acceptsCharsets(): string[]
    • acceptsCharsets(...charsets: string[]): string | (false)
    • acceptsCharsets(charsets: string[]): string | (false)
    • +

      Returns string[]

    • Parameters

      • Rest ...types: string[]

      Returns string | false

    • Parameters

      • types: string[]

      Returns string | false

    • acceptsCharsets(): string[]
    • acceptsCharsets(...charsets: string[]): string | false
    • acceptsCharsets(charsets: string[]): string | false
    • Return accepted charsets or best fit based on charsets.

      Given Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5 an array sorted by quality is returned:

      ['utf-8', 'utf-7', 'iso-8859-1']
       
      -

      Returns string[]

    • Parameters

      • Rest ...charsets: string[]

      Returns string | (false)

    • Parameters

      • charsets: string[]

      Returns string | (false)

    • acceptsEncodings(): string[]
    • acceptsEncodings(...encodings: string[]): string | (false)
    • acceptsEncodings(encodings: string[]): string | (false)
    • +

      Returns string[]

    • Parameters

      • Rest ...charsets: string[]

      Returns string | false

    • Parameters

      • charsets: string[]

      Returns string | false

    • acceptsEncodings(): string[]
    • acceptsEncodings(...encodings: string[]): string | false
    • acceptsEncodings(encodings: string[]): string | false
    • Return accepted encodings or best fit based on encodings.

      Given Accept-Encoding: gzip, deflate an array sorted by quality is returned:

      ['gzip', 'deflate']
       
      -

      Returns string[]

    • Parameters

      • Rest ...encodings: string[]

      Returns string | (false)

    • Parameters

      • encodings: string[]

      Returns string | (false)

    • acceptsLanguages(): string[]
    • acceptsLanguages(...langs: string[]): string | (false)
    • acceptsLanguages(langs: string[]): string | (false)
    • +

      Returns string[]

    • Parameters

      • Rest ...encodings: string[]

      Returns string | false

    • Parameters

      • encodings: string[]

      Returns string | false

    • acceptsLanguages(): string[]
    • acceptsLanguages(...langs: string[]): string | false
    • acceptsLanguages(langs: string[]): string | false
    • Return accepted languages or best fit based on langs.

      Given Accept-Language: en;q=0.8, es, pt an array sorted by quality is returned:

      ['es', 'pt', 'en']
       
      -

      Returns string[]

    • Parameters

      • Rest ...langs: string[]

      Returns string | (false)

    • Parameters

      • langs: string[]

      Returns string | (false)

    • append(field: string, val: string | string[]): void
    • +

      Returns string[]

    • Parameters

      • Rest ...langs: string[]

      Returns string | false

    • Parameters

      • langs: string[]

      Returns string | false

    • append(field: string, val: string | string[]): void
    • Append additional header field with value val.

      Examples:

      this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
      this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
      this.append('Warning', '199 Miscellaneous warning'); @@ -162,7 +162,7 @@

      Parameters

      • field: string

      Returns string

    • inspect(): any
    • util.inspect() implementation, which just returns the JSON output.

      -

      Returns any

    • is(...types: string[]): (null) | string | (false)
    • is(types: string[]): (null) | string | (false)
    • +

      Returns any

    • is(...types: string[]): null | string | false
    • is(types: string[]): null | string | false
    • Check if the incoming request contains the "Content-Type" header field, and it contains any of the give mime types. If there is no request body, null is returned. @@ -171,7 +171,7 @@

      Examples:

      // With Content-Type: text/html; charset=utf-8
      this.is('html'); // => 'html'
      this.is('text/html'); // => 'text/html'
      this.is('text/*', 'application/json'); // => 'text/html'

      // When Content-Type is application/json
      this.is('json', 'urlencoded'); // => 'json'
      this.is('application/json'); // => 'application/json'
      this.is('html', 'application/*'); // => 'application/json'

      this.is('html'); // => false
      -

      Parameters

      • Rest ...types: string[]

      Returns (null) | string | (false)

    • Parameters

      • types: string[]

      Returns (null) | string | (false)

    • onerror(err: Error): void
    • +

      Parameters

      • Rest ...types: string[]

      Returns null | string | false

    • Parameters

      • types: string[]

      Returns null | string | false

    • onerror(err: Error): void
    • Default error handling.

      Parameters

      • err: Error

      Returns void

    • redirect(url: string, alt?: string): void
    • _mergeWithParent<ValueType>(childList: Readonly<Binding<ValueType>>[], parentList?: Readonly<Binding<ValueType>>[]): Readonly<Binding<ValueType>>[]
    • Type parameters

      • ValueType

      Parameters

      • childList: Readonly<Binding<ValueType>>[]
      • Optional parentList: Readonly<Binding<ValueType>>[]

      Returns Readonly<Binding<ValueType>>[]

    • Add a binding to the context. If a locked binding already exists with the same key, an error will be thrown.

      Parameters

      • binding: Binding<unknown>

        The configured binding to be added

        -

      Returns SessionContext

    • addListener(eventName: string | symbol, listener: ((...args: any[]) => void)): SessionContext
    • +

    Returns SessionContext

  • addListener(eventName: string | symbol, listener: (...args: any[]) => void): SessionContext
  • Alias for emitter.on(eventName, listener).

    since

    v0.1.26

    -

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionContext

  • bind<ValueType>(key: BindingAddress<ValueType>): Binding<ValueType>
  • +

    Parameters

    • eventName: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionContext

  • bind<ValueType>(key: BindingAddress<ValueType>): Binding<ValueType>
  • Create a binding with the given key in the context. If a locked binding already exists with the same key, an error will be thrown.

    -

    Type Parameters

    • ValueType = any

    Parameters

    • key: BindingAddress<ValueType>
      +

      Type parameters

      • ValueType = any

      Parameters

      • key: BindingAddress<ValueType>

        Binding key

      Returns Binding<ValueType>

  • close(): void
  • Close the context: clear observers, stop notifications, and remove event @@ -47,7 +47,7 @@ the given key in the context.

    For example, ctx.configure('controllers.MyController').to({x: 1}) will create binding controllers.MyController:$config with value {x: 1}.

    -

    Type Parameters

    • ConfigValueType = any

    Parameters

    • Optional key: string | BindingKey<unknown>
      +

      Type parameters

      • ConfigValueType = any

      Parameters

      • Optional key: string | BindingKey<unknown>

        The key for the binding to be configured

      Returns Binding<ConfigValueType>

  • contains(key: BindingAddress<unknown>): boolean
  • Check if a binding exists with the given key in the local context without @@ -56,7 +56,7 @@

    Binding key

Returns boolean

  • createView<T>(filter: BindingFilter, comparator?: BindingComparator, options?: Pick<ResolutionOptions, "optional" | "asProxyWithInterceptors">): ContextView<T>
  • Create a view of the context chain with the given binding filter

    -

    Type Parameters

    • T = unknown

    Parameters

    • filter: BindingFilter
      +

      Type parameters

      • T = unknown

      Parameters

      • filter: BindingFilter

        A function to match bindings

      • Optional comparator: BindingComparator

        A function to sort matched bindings

        @@ -67,7 +67,7 @@ as the prefix

        Parameters

        • Rest ...args: unknown[]

          Arguments for the debug

          -

        Returns void

  • emit(eventName: string | symbol, ...args: any[]): boolean
  • +

Returns void

  • emit(eventName: string | symbol, ...args: any[]): boolean
  • Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    @@ -80,11 +80,11 @@

    Error

Returns void

  • emitEvent<T>(type: string, event: T): void
  • A strongly-typed method to emit context events

    -

    Type Parameters

    • T extends ContextEvent

    Parameters

    • type: string
      +

      Type parameters

      • T: ContextEvent

      Parameters

      • type: string

        Event type

      • event: T

        Context event

        -

      Returns void

  • eventNames(): (string | symbol)[]
  • +

Returns void

  • eventNames(): (string | symbol)[]
  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    const EventEmitter = require('events');
    const myEE = new EventEmitter();
    myEE.on('foo', () => {});
    myEE.on('bar', () => {});

    const sym = Symbol('symbol');
    myEE.on(sym, () => {});

    console.log(myEE.eventNames());
    // Prints: [ 'foo', 'bar', Symbol(symbol) ] @@ -92,7 +92,7 @@
    since

    v6.0.0

    Returns (string | symbol)[]

  • find<ValueType>(pattern?: string | RegExp | BindingFilter): Readonly<Binding<ValueType>>[]
  • Find bindings using a key pattern or filter function

    -

    Type Parameters

    • ValueType = any

    Parameters

    • Optional pattern: string | RegExp | BindingFilter
      +

      Type parameters

      • ValueType = any

      Parameters

      • Optional pattern: string | RegExp | BindingFilter

        A filter function, a regexp or a wildcard pattern with optional * and ?. Find returns such bindings where the key matches the provided pattern.

        @@ -109,7 +109,7 @@

      Returns Readonly<Binding<ValueType>>[]

  • findByTag<ValueType>(tagFilter: string | RegExp | Record<string, any>): Readonly<Binding<ValueType>>[]
  • Find bindings using the tag filter. If the filter matches one of the binding tags, the binding is included.

    -

    Type Parameters

    • ValueType = any

    Parameters

    • tagFilter: string | RegExp | Record<string, any>
      +

      Type parameters

      • ValueType = any

      Parameters

      • tagFilter: string | RegExp | Record<string, any>

        A filter for tags. It can be in one of the following forms:

          @@ -125,7 +125,7 @@

      Returns Readonly<Binding<ValueType>>[]

  • findOrCreateBinding<T>(key: BindingAddress<T>, policy?: ALWAYS_CREATE | NEVER_CREATE | CREATE_IF_NOT_BOUND): Binding<T>
  • Find or create a binding for the given key

    -

    Type Parameters

    • T

    Parameters

    • key: BindingAddress<T>
      +

      Type parameters

      • T

      Parameters

      • key: BindingAddress<T>

        Binding address

      • Optional policy: ALWAYS_CREATE | NEVER_CREATE | CREATE_IF_NOT_BOUND

        Binding creation policy

        @@ -134,7 +134,7 @@ bound for the given key.

        example
        // get the value bound to "application.instance"
        const app = await ctx.get<Application>('application.instance');

        // get "rest" property from the value bound to "config"
        const config = await ctx.get<RestComponentConfig>('config#rest');

        // get "a" property of "numbers" property from the value bound to "data"
        ctx.bind('data').to({numbers: {a: 1, b: 2}, port: 3000});
        const a = await ctx.get<number>('data#numbers.a');
        -

        Type Parameters

        • ValueType

        Parameters

        • keyWithPath: BindingAddress<ValueType>
          +

          Type parameters

          • ValueType

          Parameters

          • keyWithPath: BindingAddress<ValueType>

            The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

          • Optional session: ResolutionSession
            @@ -146,31 +146,31 @@ of the bound value.

            example
            // get "rest" property from the value bound to "config"
            // use `undefined` when no config is provided
            const config = await ctx.get<RestComponentConfig>('config#rest', {
            optional: true
            });
            -

            Type Parameters

            • ValueType

            Parameters

            • keyWithPath: BindingAddress<ValueType>
              +

              Type parameters

              • ValueType

              Parameters

              • keyWithPath: BindingAddress<ValueType>

                The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

              • options: ResolutionOptions

                Options for resolution.

              Returns Promise<undefined | ValueType>

              A promise of the bound value, or a promise of undefined when the optional binding is not found.

              -
  • getBinding<ValueType>(key: BindingAddress<ValueType>): Binding<ValueType>
  • getBinding<ValueType>(key: BindingAddress<ValueType>, options?: { optional?: (false) | (true) }): undefined | Binding<ValueType>
  • +
  • getBinding<ValueType>(key: BindingAddress<ValueType>): Binding<ValueType>
  • getBinding<ValueType>(key: BindingAddress<ValueType>, options?: { optional?: false | true }): undefined | Binding<ValueType>
  • Look up a binding by key in the context and its ancestors. If no matching binding is found, an error will be thrown.

    -

    Type Parameters

    • ValueType = any

    Parameters

    • key: BindingAddress<ValueType>
      +

      Type parameters

      • ValueType = any

      Parameters

      • key: BindingAddress<ValueType>

        Binding key

      Returns Binding<ValueType>

    • Look up a binding by key in the context and its ancestors. If no matching binding is found and options.optional is not set to true, an error will be thrown.

      -

      Type Parameters

      • ValueType

      Parameters

      • key: BindingAddress<ValueType>
        +

        Type parameters

        • ValueType

        Parameters

        • key: BindingAddress<ValueType>

          Binding key

          -
        • Optional options: { optional?: (false) | (true) }
          +
        • Optional options: { optional?: false | true }

          Options to control if the binding is optional. If options.optional is set to true, the method will return undefined instead of throwing an error if the binding key is not found.

          -
          • Optional optional?: (false) | (true)

        Returns undefined | Binding<ValueType>

  • getConfig<ConfigValueType>(key: BindingAddress<unknown>, propertyPath?: string, resolutionOptions?: ResolutionOptions): Promise<undefined | ConfigValueType>
  • +
    • Optional optional?: false | true

Returns undefined | Binding<ValueType>

  • getConfig<ConfigValueType>(key: BindingAddress<unknown>, propertyPath?: string, resolutionOptions?: ResolutionOptions): Promise<undefined | ConfigValueType>
  • Resolve configuration for the binding by key

    -

    Type Parameters

    • ConfigValueType

    Parameters

    • key: BindingAddress<unknown>
      +

      Type parameters

      • ConfigValueType

      Parameters

      • key: BindingAddress<unknown>

        Binding key

      • Optional propertyPath: string

        Property path for the option. For example, x.y @@ -180,7 +180,7 @@

        Options for the resolution.

      Returns Promise<undefined | ConfigValueType>

  • getConfigAsValueOrPromise<ConfigValueType>(key: BindingAddress<unknown>, propertyPath?: string, resolutionOptions?: ResolutionOptions): ValueOrPromise<undefined | ConfigValueType>
  • Get the value or promise of configuration for a given binding by key

    -

    Type Parameters

    • ConfigValueType

    Parameters

    • key: BindingAddress<unknown>
      +

      Type parameters

      • ConfigValueType

      Parameters

      • key: BindingAddress<unknown>

        Binding key

      • Optional propertyPath: string

        Property path for the option. For example, x.y @@ -194,7 +194,7 @@

Returns ValueOrPromise<undefined | ConfigValueType>

  • getConfigSync<ConfigValueType>(key: BindingAddress<unknown>, propertyPath?: string, resolutionOptions?: ResolutionOptions): undefined | ConfigValueType
  • Resolve configuration synchronously for the binding by key

    -

    Type Parameters

    • ConfigValueType

    Parameters

    • key: BindingAddress<unknown>
      +

      Type parameters

      • ConfigValueType

      Parameters

      • key: BindingAddress<unknown>

        Binding key

      • Optional propertyPath: string

        Property path for the option. For example, x.y @@ -207,7 +207,7 @@ this method to supply its own namespace.

        example
        export class Application extends Context {
        super('application');
        }

        protected getDebugNamespace() {
        return 'loopback:context:application';
        }
        -

        Returns string

  • getMaxListeners(): number
  • +

    Returns string

  • getMaxListeners(): number
  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to {@link defaultMaxListeners}.

    since

    v1.0.0

    @@ -233,7 +233,7 @@ code.

    example
    // get the value bound to "application.instance"
    const app = ctx.getSync<Application>('application.instance');

    // get "rest" property from the value bound to "config"
    const config = await ctx.getSync<RestComponentConfig>('config#rest');
    -

Type Parameters

  • ValueType

Parameters

  • keyWithPath: BindingAddress<ValueType>
    +

    Type parameters

    • ValueType

    Parameters

    • keyWithPath: BindingAddress<ValueType>

      The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

    • Optional session: ResolutionSession
      @@ -247,7 +247,7 @@ code.

      example
      // get "rest" property from the value bound to "config"
      // use "undefined" when no config is provided
      const config = await ctx.getSync<RestComponentConfig>('config#rest', {
      optional: true
      });
      -

      Type Parameters

      • ValueType

      Parameters

      • keyWithPath: BindingAddress<ValueType>
        +

        Type parameters

        • ValueType

        Parameters

        • keyWithPath: BindingAddress<ValueType>

          The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

        • Optional options: ResolutionOptions
          @@ -259,7 +259,7 @@ of Binding#getValue(). Users should use get() or getSync() instead.

          example
          // get the value bound to "application.instance"
          ctx.getValueOrPromise<Application>('application.instance');

          // get "rest" property from the value bound to "config"
          ctx.getValueOrPromise<RestComponentConfig>('config#rest');

          // get "a" property of "numbers" property from the value bound to "data"
          ctx.bind('data').to({numbers: {a: 1, b: 2}, port: 3000});
          ctx.getValueOrPromise<number>('data#numbers.a');
          -
          internal

          Type Parameters

          • ValueType

          Parameters

          • keyWithPath: BindingAddress<ValueType>
            +
            internal

            Type parameters

            • ValueType

            Parameters

            • keyWithPath: BindingAddress<ValueType>

              The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

            • Optional optionsOrSession: ResolutionOptions | ResolutionSession
              @@ -283,34 +283,34 @@

              Check if this context is visible (same or ancestor) to the given one

              Parameters

              • ctx: Context

                Another context object

                -

              Returns boolean

            • listenerCount(eventName: string | symbol): number
            • +

            Returns boolean

          • listenerCount(eventName: string | symbol): number
          • Returns the number of listeners listening to the event named eventName.

            since

            v3.2.0

            Parameters

            • eventName: string | symbol

              The name of the event being listened for

              -

            Returns number

          • listeners(eventName: string | symbol): Function[]
          • +

          Returns number

        • listeners(eventName: string | symbol): Function[]
        • Returns a copy of the array of listeners for the event named eventName.

          server.on('connection', (stream) => {
          console.log('someone connected!');
          });
          console.log(util.inspect(server.listeners('connection')));
          // Prints: [ [Function] ]
          since

          v0.1.26

          -

          Parameters

          • eventName: string | symbol

          Returns Function[]

        • off(eventName: string | symbol, listener: ((...args: any[]) => void)): SessionContext
        • +

          Parameters

          • eventName: string | symbol

          Returns Function[]

        • off(eventName: string | symbol, listener: (...args: any[]) => void): SessionContext
        • Alias for emitter.removeListener().

          since

          v10.0.0

          -

          Parameters

          • eventName: string | symbol
          • listener: ((...args: any[]) => void)
              • (...args: any[]): void
              • Parameters

                • Rest ...args: any[]

                Returns void

          Returns SessionContext

        • on(eventName: "bind" | "unbind", listener: ContextEventListener): SessionContext
        • on(event: string | symbol, listener: ((...args: any[]) => void)): SessionContext
        • +

          Parameters

          • eventName: string | symbol
          • listener: (...args: any[]) => void
              • (...args: any[]): void
              • Parameters

                • Rest ...args: any[]

                Returns void

          Returns SessionContext

        • on(eventName: "bind" | "unbind", listener: ContextEventListener): SessionContext
        • on(event: string | symbol, listener: (...args: any[]) => void): SessionContext
        • The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.

          Parameters

          • eventName: "bind" | "unbind"

            The name of the event - always bind or unbind.

          • listener: ContextEventListener

            The listener function to call when the event is emitted.

            -

          Returns SessionContext

        • Parameters

          • event: string | symbol
          • listener: ((...args: any[]) => void)
              • (...args: any[]): void
              • Parameters

                • Rest ...args: any[]

                Returns void

          Returns SessionContext

        • once(eventName: "bind" | "unbind", listener: ContextEventListener): SessionContext
        • once(event: string | symbol, listener: ((...args: any[]) => void)): SessionContext
        • +

        Returns SessionContext

      • Parameters

        • event: string | symbol
        • listener: (...args: any[]) => void
            • (...args: any[]): void
            • Parameters

              • Rest ...args: any[]

              Returns void

        Returns SessionContext

      • once(eventName: "bind" | "unbind", listener: ContextEventListener): SessionContext
      • once(event: string | symbol, listener: (...args: any[]) => void): SessionContext
      • The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.

        Parameters

        • eventName: "bind" | "unbind"

          The name of the event - always bind or unbind.

        • listener: ContextEventListener

          The listener function to call when the event is emitted.

          -

        Returns SessionContext

      • Parameters

        • event: string | symbol
        • listener: ((...args: any[]) => void)
            • (...args: any[]): void
            • Parameters

              • Rest ...args: any[]

              Returns void

        Returns SessionContext

      • prependListener(eventName: string | symbol, listener: ((...args: any[]) => void)): SessionContext
      • +

      Returns SessionContext

    • Parameters

      • event: string | symbol
      • listener: (...args: any[]) => void
          • (...args: any[]): void
          • Parameters

            • Rest ...args: any[]

            Returns void

      Returns SessionContext

    • prependListener(eventName: string | symbol, listener: (...args: any[]) => void): SessionContext
    • Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple @@ -321,9 +321,9 @@

      since

      v6.0.0

      Parameters

      • eventName: string | symbol

        The name of the event.

        -
      • listener: ((...args: any[]) => void)
        +
      • listener: (...args: any[]) => void

        The callback function

        -
          • (...args: any[]): void
          • Parameters

            • Rest ...args: any[]

            Returns void

      Returns SessionContext

    • prependOnceListener(eventName: string | symbol, listener: ((...args: any[]) => void)): SessionContext
    • +
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionContext

  • prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): SessionContext
  • Adds a one-timelistener function for the event named eventName to the_beginning_ of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    }); @@ -332,22 +332,22 @@
    since

    v6.0.0

    Parameters

    • eventName: string | symbol

      The name of the event.

      -
    • listener: ((...args: any[]) => void)
      +
    • listener: (...args: any[]) => void

      The callback function

      -
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionContext

  • rawListeners(eventName: string | symbol): Function[]
  • +
      • (...args: any[]): void
      • Parameters

        • Rest ...args: any[]

        Returns void

Returns SessionContext

  • rawListeners(eventName: string | symbol): Function[]
  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    const emitter = new EventEmitter();
    emitter.once('log', () => console.log('log once'));

    // Returns a new Array with a function `onceWrapper` which has a property
    // `listener` which contains the original listener bound above
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    logFnWrapper.listener();

    // Logs "log once" to the console and removes the listener
    logFnWrapper();

    emitter.on('log', () => console.log('log persistently'));
    // Will return a new Array with a single function bound by `.on()` above
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');
    since

    v9.4.0

    -

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • +

    Parameters

    • eventName: string | symbol

    Returns Function[]

  • Removes all listeners, or those of the specified eventName.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Returns a reference to the EventEmitter, so that calls can be chained.

    since

    v0.1.26

    -

    Parameters

    • Optional event: string | symbol

    Returns SessionContext

  • removeListener(eventName: string | symbol, listener: ((...args: any[]) => void)): SessionContext
  • +

    Parameters

    • Optional event: string | symbol

    Returns SessionContext

  • removeListener(eventName: string | symbol, listener: (...args: any[]) => void): SessionContext
  • Removes the specified listener from the listener array for the event namedeventName.

    const callback = (stream) => {
    console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);
    @@ -372,7 +372,7 @@

    Returns a reference to the EventEmitter, so that calls can be chained.

    since

    v0.1.26

    -

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionContext

  • +

    Parameters

    • eventName: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns SessionContext

SessionClaimValidator: ({ claim: SessionClaim<any>; shouldRefetch: any } | {}) & { id: string; validate: any }
SessionInformation: { accessTokenPayload: any; expiry: number; sessionData: any; sessionHandle: string; timeCreated: number; userId: string }

Type declaration

  • accessTokenPayload: any
  • expiry: number
  • sessionData: any
  • sessionHandle: string
  • timeCreated: number
  • userId: string

Variables

Error: typeof default = SessionWrapper.Error

Functions

  • createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
  • Parameters

    • Optional payload: any
    • Optional validitySeconds: number
    • userContext: any = {}

    Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

  • createNewSession(res: any, userId: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise<SessionContainer>
  • fetchAndSetClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
  • getAllSessionHandlesForUser(userId: string, userContext?: any): Promise<string[]>
  • getClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, userContext?: any): Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>
  • Type Parameters

    • T

    Parameters

    • sessionHandle: string
    • claim: SessionClaim<T>
    • userContext: any = {}

    Returns Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>

  • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>
  • getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ issuer: string; jwks_uri: string; status: "OK" }>
  • getSessionInformation(sessionHandle: string, userContext?: any): Promise<undefined | SessionInformation>
  • init(config?: TypeInput): RecipeListFunction
  • mergeIntoAccessTokenPayload(sessionHandle: string, accessTokenPayloadUpdate: JSONObject, userContext?: any): Promise<boolean>
  • refreshSession(req: any, res: any, userContext?: any): Promise<SessionContainer>
  • removeClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
  • revokeAllSessionsForUser(userId: string, userContext?: any): Promise<string[]>
  • revokeMultipleSessions(sessionHandles: string[], userContext?: any): Promise<string[]>
  • revokeSession(sessionHandle: string, userContext?: any): Promise<boolean>
  • setClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, value: T, userContext?: any): Promise<boolean>
  • updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, userContext?: any): Promise<boolean>
  • updateSessionData(sessionHandle: string, newSessionData: any, userContext?: any): Promise<boolean>

Legend

  • Variable
  • Function
  • Function with type parameter
  • Type alias
  • Class
  • Class with type parameter
  • Interface

Settings

Theme

Generated using TypeDoc

\ No newline at end of file +
  • updateSessionData:function
    • updateSessionData(input: { newSessionData: any; sessionHandle: string; userContext: any }): Promise<boolean>
    • Parameters

      • input: { newSessionData: any; sessionHandle: string; userContext: any }
        • newSessionData: any
        • sessionHandle: string
        • userContext: any

      Returns Promise<boolean>

  • validateClaims:function
    • validateClaims(input: { accessTokenPayload: any; claimValidators: SessionClaimValidator[]; userContext: any; userId: string }): Promise<{ accessTokenPayloadUpdate?: any; invalidClaims: ClaimValidationError[] }>
  • validateClaimsInJWTPayload:function
    • validateClaimsInJWTPayload(input: { claimValidators: SessionClaimValidator[]; jwtPayload: JSONObject; userContext: any; userId: string }): Promise<{ invalidClaims: ClaimValidationError[]; status: "OK" }>
  • SessionClaimValidator: ({ claim: SessionClaim<any>; shouldRefetch: any } | {}) & { id: string; validate: any }
    SessionInformation: { accessTokenPayload: any; expiry: number; sessionData: any; sessionHandle: string; timeCreated: number; userId: string }

    Type declaration

    • accessTokenPayload: any
    • expiry: number
    • sessionData: any
    • sessionHandle: string
    • timeCreated: number
    • userId: string

    Variables

    Error: typeof default = SessionWrapper.Error

    Functions

    • createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>
    • Parameters

      • Optional payload: any
      • Optional validitySeconds: number
      • userContext: any = {}

      Returns Promise<{ jwt: string; status: "OK" } | { status: "UNSUPPORTED_ALGORITHM_ERROR" }>

    • createNewSession(req: any, res: any, userId: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise<SessionContainer>
    • fetchAndSetClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
    • getAllSessionHandlesForUser(userId: string, userContext?: any): Promise<string[]>
    • getClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, userContext?: any): Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>
    • Type parameters

      • T

      Parameters

      • sessionHandle: string
      • claim: SessionClaim<T>
      • userContext: any = {}

      Returns Promise<{ status: "SESSION_DOES_NOT_EXIST_ERROR" } | { status: "OK"; value: undefined | T }>

    • getJWKS(userContext?: any): Promise<{ keys: JsonWebKey[]; status: "OK" }>
    • getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ issuer: string; jwks_uri: string; status: "OK" }>
    • getSessionInformation(sessionHandle: string, userContext?: any): Promise<undefined | SessionInformation>
    • init(config?: TypeInput): RecipeListFunction
    • mergeIntoAccessTokenPayload(sessionHandle: string, accessTokenPayloadUpdate: JSONObject, userContext?: any): Promise<boolean>
    • refreshSession(req: any, res: any, userContext?: any): Promise<SessionContainer>
    • removeClaim(sessionHandle: string, claim: SessionClaim<any>, userContext?: any): Promise<boolean>
    • revokeAllSessionsForUser(userId: string, userContext?: any): Promise<string[]>
    • revokeMultipleSessions(sessionHandles: string[], userContext?: any): Promise<string[]>
    • revokeSession(sessionHandle: string, userContext?: any): Promise<boolean>
    • setClaimValue<T>(sessionHandle: string, claim: SessionClaim<T>, value: T, userContext?: any): Promise<boolean>
    • updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, userContext?: any): Promise<boolean>
    • updateSessionData(sessionHandle: string, newSessionData: any, userContext?: any): Promise<boolean>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file diff --git a/docs/modules/recipe_thirdparty.html b/docs/modules/recipe_thirdparty.html index 4e8ccab31..61ab4cf95 100644 --- a/docs/modules/recipe_thirdparty.html +++ b/docs/modules/recipe_thirdparty.html @@ -1 +1 @@ -recipe/thirdparty | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/thirdparty

    Index

    Type Aliases

    APIInterface: { appleRedirectHandlerPOST: undefined | ((input: { code: string; options: APIOptions; state: string; userContext: any }) => Promise<void>); authorisationUrlGET: undefined | ((input: { options: APIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>); signInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: APIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" } | GeneralErrorResponse>) }

    Type declaration

    • appleRedirectHandlerPOST: undefined | ((input: { code: string; options: APIOptions; state: string; userContext: any }) => Promise<void>)
    • authorisationUrlGET: undefined | ((input: { options: APIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>)
    • signInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: APIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" } | GeneralErrorResponse>)
    APIOptions: { appInfo: NormalisedAppinfo; config: TypeNormalisedInput; isInServerlessEnv: boolean; providers: TypeProvider[]; recipeId: string; recipeImplementation: RecipeInterface; req: BaseRequest; res: BaseResponse }

    Type declaration

    RecipeInterface: { getUserById: any; getUserByThirdPartyInfo: any; getUsersByEmail: any; signInUp: any }

    Type declaration

    • getUserById:function
      • getUserById(input: { userContext: any; userId: string }): Promise<undefined | User>
    • getUserByThirdPartyInfo:function
      • getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<undefined | User>
      • Parameters

        • input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<undefined | User>

    • getUsersByEmail:function
      • getUsersByEmail(input: { email: string; userContext: any }): Promise<User[]>
    • signInUp:function
      • signInUp(input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
      • Parameters

        • input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • email: string
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    TypeProvider: { id: string; isDefault?: boolean; get: any }

    Type declaration

    • id: string
    • Optional isDefault?: boolean
    • get:function
      • get(redirectURI: undefined | string, authCodeFromRequest: undefined | string, userContext: any): TypeProviderGetResponse
    User: { email: string; id: string; thirdParty: { id: string; userId: string }; timeJoined: number }

    Type declaration

    • email: string
    • id: string
    • thirdParty: { id: string; userId: string }
      • id: string
      • userId: string
    • timeJoined: number

    Variables

    Error: typeof default = Wrapper.Error

    Functions

    • Apple(config: TypeThirdPartyProviderAppleConfig): TypeProvider
    • Discord(config: TypeThirdPartyProviderDiscordConfig): TypeProvider
    • Facebook(config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Github(config: TypeThirdPartyProviderGithubConfig): TypeProvider
    • Google(config: TypeThirdPartyProviderGoogleConfig): TypeProvider
    • GoogleWorkspaces(config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • getUserById(userId: string, userContext?: any): Promise<undefined | User>
    • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
    • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
    • init(config: TypeInput): RecipeListFunction
    • signInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
    • Parameters

      • thirdPartyId: string
      • thirdPartyUserId: string
      • email: string
      • userContext: any = {}

      Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file +recipe/thirdparty | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/thirdparty

    Index

    Type aliases

    APIInterface: { appleRedirectHandlerPOST: undefined | ((input: { code: string; options: APIOptions; state: string; userContext: any }) => Promise<void>); authorisationUrlGET: undefined | ((input: { options: APIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>); signInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: APIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" } | GeneralErrorResponse>) }

    Type declaration

    • appleRedirectHandlerPOST: undefined | ((input: { code: string; options: APIOptions; state: string; userContext: any }) => Promise<void>)
    • authorisationUrlGET: undefined | ((input: { options: APIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>)
    • signInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: APIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" } | GeneralErrorResponse>)
    APIOptions: { appInfo: NormalisedAppinfo; config: TypeNormalisedInput; isInServerlessEnv: boolean; providers: TypeProvider[]; recipeId: string; recipeImplementation: RecipeInterface; req: BaseRequest; res: BaseResponse }

    Type declaration

    RecipeInterface: { getUserById: any; getUserByThirdPartyInfo: any; getUsersByEmail: any; signInUp: any }

    Type declaration

    • getUserById:function
      • getUserById(input: { userContext: any; userId: string }): Promise<undefined | User>
    • getUserByThirdPartyInfo:function
      • getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<undefined | User>
      • Parameters

        • input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<undefined | User>

    • getUsersByEmail:function
      • getUsersByEmail(input: { email: string; userContext: any }): Promise<User[]>
    • signInUp:function
      • signInUp(input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
      • Parameters

        • input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • email: string
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    TypeProvider: { id: string; isDefault?: boolean; get: any }

    Type declaration

    • id: string
    • Optional isDefault?: boolean
    • get:function
      • get(redirectURI: undefined | string, authCodeFromRequest: undefined | string, userContext: any): TypeProviderGetResponse
    User: { email: string; id: string; thirdParty: { id: string; userId: string }; timeJoined: number }

    Type declaration

    • email: string
    • id: string
    • thirdParty: { id: string; userId: string }
      • id: string
      • userId: string
    • timeJoined: number

    Variables

    Error: typeof default = Wrapper.Error

    Functions

    • Apple(config: TypeThirdPartyProviderAppleConfig): TypeProvider
    • Discord(config: TypeThirdPartyProviderDiscordConfig): TypeProvider
    • Facebook(config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Github(config: TypeThirdPartyProviderGithubConfig): TypeProvider
    • Google(config: TypeThirdPartyProviderGoogleConfig): TypeProvider
    • GoogleWorkspaces(config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • getUserById(userId: string, userContext?: any): Promise<undefined | User>
    • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
    • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
    • init(config: TypeInput): RecipeListFunction
    • signInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
    • Parameters

      • thirdPartyId: string
      • thirdPartyUserId: string
      • email: string
      • userContext: any = {}

      Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file diff --git a/docs/modules/recipe_thirdpartyemailpassword.html b/docs/modules/recipe_thirdpartyemailpassword.html index 23c01e1c8..36e7d8df9 100644 --- a/docs/modules/recipe_thirdpartyemailpassword.html +++ b/docs/modules/recipe_thirdpartyemailpassword.html @@ -1 +1 @@ -recipe/thirdpartyemailpassword | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/thirdpartyemailpassword

    Index

    References

    Re-exports TypeProvider

    Type Aliases

    APIInterface: { appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>); authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>); emailPasswordEmailExistsGET: undefined | ((input: { email: string; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>); emailPasswordSignInPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" } | GeneralErrorResponse>); emailPasswordSignUpPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } | GeneralErrorResponse>); generatePasswordResetTokenPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ status: "OK" } | GeneralErrorResponse>); passwordResetPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; token: string; userContext: any }) => Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } | GeneralErrorResponse>); thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>) }

    Type declaration

    • appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>)
    • authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>)
    • emailPasswordEmailExistsGET: undefined | ((input: { email: string; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>)
    • emailPasswordSignInPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" } | GeneralErrorResponse>)
    • emailPasswordSignUpPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } | GeneralErrorResponse>)
    • generatePasswordResetTokenPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ status: "OK" } | GeneralErrorResponse>)
    • passwordResetPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; token: string; userContext: any }) => Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } | GeneralErrorResponse>)
    • thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>)
    EmailPasswordAPIOptions: APIOptions
    RecipeInterface: { createResetPasswordToken: any; emailPasswordSignIn: any; emailPasswordSignUp: any; getUserById: any; getUserByThirdPartyInfo: any; getUsersByEmail: any; resetPasswordUsingToken: any; thirdPartySignInUp: any; updateEmailOrPassword: any }

    Type declaration

    • createResetPasswordToken:function
      • createResetPasswordToken(input: { userContext: any; userId: string }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
    • emailPasswordSignIn:function
      • emailPasswordSignIn(input: { email: string; password: string; userContext: any }): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
    • emailPasswordSignUp:function
      • emailPasswordSignUp(input: { email: string; password: string; userContext: any }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
    • getUserById:function
      • getUserById(input: { userContext: any; userId: string }): Promise<undefined | User>
    • getUserByThirdPartyInfo:function
      • getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<undefined | User>
    • getUsersByEmail:function
      • getUsersByEmail(input: { email: string; userContext: any }): Promise<User[]>
    • resetPasswordUsingToken:function
      • resetPasswordUsingToken(input: { newPassword: string; token: string; userContext: any }): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
      • Parameters

        • input: { newPassword: string; token: string; userContext: any }
          • newPassword: string
          • token: string
          • userContext: any

        Returns Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>

    • thirdPartySignInUp:function
      • thirdPartySignInUp(input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
      • Parameters

        • input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • email: string
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    • updateEmailOrPassword:function
      • updateEmailOrPassword(input: { email?: string; password?: string; userContext: any; userId: string }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" }>
      • Parameters

        • input: { email?: string; password?: string; userContext: any; userId: string }
          • Optional email?: string
          • Optional password?: string
          • userContext: any
          • userId: string

        Returns Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" }>

    ThirdPartyAPIOptions: APIOptions
    User: { email: string; id: string; thirdParty?: { id: string; userId: string }; timeJoined: number }

    Type declaration

    • email: string
    • id: string
    • Optional thirdParty?: { id: string; userId: string }
      • id: string
      • userId: string
    • timeJoined: number

    Variables

    Error: typeof default = Wrapper.Error

    Functions

    • Apple(config: TypeThirdPartyProviderAppleConfig): TypeProvider
    • Discord(config: TypeThirdPartyProviderDiscordConfig): TypeProvider
    • Facebook(config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Github(config: TypeThirdPartyProviderGithubConfig): TypeProvider
    • Google(config: TypeThirdPartyProviderGoogleConfig): TypeProvider
    • GoogleWorkspaces(config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • createResetPasswordToken(userId: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
    • emailPasswordSignIn(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
    • emailPasswordSignUp(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
    • getUserById(userId: string, userContext?: any): Promise<undefined | User>
    • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
    • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
    • init(config: TypeInput): RecipeListFunction
    • resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
    • sendEmail(input: TypeEmailPasswordPasswordResetEmailDeliveryInput & { userContext?: any }): Promise<void>
    • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
    • updateEmailOrPassword(input: { email?: string; password?: string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>
    • Parameters

      • input: { email?: string; password?: string; userContext?: any; userId: string }
        • Optional email?: string
        • Optional password?: string
        • Optional userContext?: any
        • userId: string

      Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file +recipe/thirdpartyemailpassword | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/thirdpartyemailpassword

    Index

    References

    Re-exports TypeProvider

    Type aliases

    APIInterface: { appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>); authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>); emailPasswordEmailExistsGET: undefined | ((input: { email: string; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>); emailPasswordSignInPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" } | GeneralErrorResponse>); emailPasswordSignUpPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } | GeneralErrorResponse>); generatePasswordResetTokenPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ status: "OK" } | GeneralErrorResponse>); passwordResetPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; token: string; userContext: any }) => Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } | GeneralErrorResponse>); thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>) }

    Type declaration

    • appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>)
    • authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>)
    • emailPasswordEmailExistsGET: undefined | ((input: { email: string; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>)
    • emailPasswordSignInPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" } | GeneralErrorResponse>)
    • emailPasswordSignUpPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ session: SessionContainer; status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } | GeneralErrorResponse>)
    • generatePasswordResetTokenPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; userContext: any }) => Promise<{ status: "OK" } | GeneralErrorResponse>)
    • passwordResetPOST: undefined | ((input: { formFields: { id: string; value: string }[]; options: EmailPasswordAPIOptions; token: string; userContext: any }) => Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } | GeneralErrorResponse>)
    • thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>)
    EmailPasswordAPIOptions: APIOptions
    RecipeInterface: { createResetPasswordToken: any; emailPasswordSignIn: any; emailPasswordSignUp: any; getUserById: any; getUserByThirdPartyInfo: any; getUsersByEmail: any; resetPasswordUsingToken: any; thirdPartySignInUp: any; updateEmailOrPassword: any }

    Type declaration

    • createResetPasswordToken:function
      • createResetPasswordToken(input: { userContext: any; userId: string }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
    • emailPasswordSignIn:function
      • emailPasswordSignIn(input: { email: string; password: string; userContext: any }): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
    • emailPasswordSignUp:function
      • emailPasswordSignUp(input: { email: string; password: string; userContext: any }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
    • getUserById:function
      • getUserById(input: { userContext: any; userId: string }): Promise<undefined | User>
    • getUserByThirdPartyInfo:function
      • getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<undefined | User>
    • getUsersByEmail:function
      • getUsersByEmail(input: { email: string; userContext: any }): Promise<User[]>
    • resetPasswordUsingToken:function
      • resetPasswordUsingToken(input: { newPassword: string; token: string; userContext: any }): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
      • Parameters

        • input: { newPassword: string; token: string; userContext: any }
          • newPassword: string
          • token: string
          • userContext: any

        Returns Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>

    • thirdPartySignInUp:function
      • thirdPartySignInUp(input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
      • Parameters

        • input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • email: string
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    • updateEmailOrPassword:function
      • updateEmailOrPassword(input: { email?: string; password?: string; userContext: any; userId: string }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" }>
      • Parameters

        • input: { email?: string; password?: string; userContext: any; userId: string }
          • Optional email?: string
          • Optional password?: string
          • userContext: any
          • userId: string

        Returns Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" }>

    ThirdPartyAPIOptions: APIOptions
    User: { email: string; id: string; thirdParty?: { id: string; userId: string }; timeJoined: number }

    Type declaration

    • email: string
    • id: string
    • Optional thirdParty?: { id: string; userId: string }
      • id: string
      • userId: string
    • timeJoined: number

    Variables

    Error: typeof default = Wrapper.Error

    Functions

    • Apple(config: TypeThirdPartyProviderAppleConfig): TypeProvider
    • Discord(config: TypeThirdPartyProviderDiscordConfig): TypeProvider
    • Facebook(config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Github(config: TypeThirdPartyProviderGithubConfig): TypeProvider
    • Google(config: TypeThirdPartyProviderGoogleConfig): TypeProvider
    • GoogleWorkspaces(config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • createResetPasswordToken(userId: string, userContext?: any): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>
    • emailPasswordSignIn(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>
    • emailPasswordSignUp(email: string, password: string, userContext?: any): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>
    • getUserById(userId: string, userContext?: any): Promise<undefined | User>
    • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | User>
    • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
    • init(config: TypeInput): RecipeListFunction
    • resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ status: "OK"; userId?: string } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" }>
    • sendEmail(input: TypeEmailPasswordPasswordResetEmailDeliveryInput & { userContext?: any }): Promise<void>
    • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
    • updateEmailOrPassword(input: { email?: string; password?: string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>
    • Parameters

      • input: { email?: string; password?: string; userContext?: any; userId: string }
        • Optional email?: string
        • Optional password?: string
        • Optional userContext?: any
        • userId: string

      Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file diff --git a/docs/modules/recipe_thirdpartypasswordless.html b/docs/modules/recipe_thirdpartypasswordless.html index 91ef0b57b..9112dcf5a 100644 --- a/docs/modules/recipe_thirdpartypasswordless.html +++ b/docs/modules/recipe_thirdpartypasswordless.html @@ -1 +1 @@ -recipe/thirdpartypasswordless | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/thirdpartypasswordless

    Index

    References

    Re-exports TypeProvider

    Type Aliases

    APIInterface: { appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>); authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>); consumeCodePOST: undefined | ((input: ({ deviceId: string; preAuthSessionId: string; userInputCode: string } | { linkCode: string; preAuthSessionId: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" }>); createCodePOST: undefined | ((input: ({ email: string } | { phoneNumber: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ deviceId: string; flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; preAuthSessionId: string; status: "OK" } | GeneralErrorResponse>); passwordlessUserEmailExistsGET: undefined | ((input: { email: string; options: PasswordlessAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>); passwordlessUserPhoneNumberExistsGET: undefined | ((input: { options: PasswordlessAPIOptions; phoneNumber: string; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>); resendCodePOST: undefined | ((input: { deviceId: string; preAuthSessionId: string } & { options: PasswordlessAPIOptions; userContext: any }) => Promise<GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" | "OK" }>); thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>) }

    Type declaration

    • appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>)
    • authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>)
    • consumeCodePOST: undefined | ((input: ({ deviceId: string; preAuthSessionId: string; userInputCode: string } | { linkCode: string; preAuthSessionId: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" }>)
    • createCodePOST: undefined | ((input: ({ email: string } | { phoneNumber: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ deviceId: string; flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; preAuthSessionId: string; status: "OK" } | GeneralErrorResponse>)
    • passwordlessUserEmailExistsGET: undefined | ((input: { email: string; options: PasswordlessAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>)
    • passwordlessUserPhoneNumberExistsGET: undefined | ((input: { options: PasswordlessAPIOptions; phoneNumber: string; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>)
    • resendCodePOST: undefined | ((input: { deviceId: string; preAuthSessionId: string } & { options: PasswordlessAPIOptions; userContext: any }) => Promise<GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" | "OK" }>)
    • thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>)
    PasswordlessAPIOptions: APIOptions
    RecipeInterface: { consumeCode: any; createCode: any; createNewCodeForDevice: any; getUserById: any; getUserByPhoneNumber: any; getUserByThirdPartyInfo: any; getUsersByEmail: any; listCodesByDeviceId: any; listCodesByEmail: any; listCodesByPhoneNumber: any; listCodesByPreAuthSessionId: any; revokeAllCodes: any; revokeCode: any; thirdPartySignInUp: any; updatePasswordlessUser: any }

    Type declaration

    • consumeCode:function
      • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
      • Parameters

        • input: { deviceId: string; preAuthSessionId: string; userContext: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext: any }

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

    • createCode:function
      • createCode(input: { email: string } & { userContext: any; userInputCode?: string } | { phoneNumber: string } & { userContext: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
      • Parameters

        • input: { email: string } & { userContext: any; userInputCode?: string } | { phoneNumber: string } & { userContext: any; userInputCode?: string }

        Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

    • createNewCodeForDevice:function
      • createNewCodeForDevice(input: { deviceId: string; userContext: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
      • Parameters

        • input: { deviceId: string; userContext: any; userInputCode?: string }
          • deviceId: string
          • userContext: any
          • Optional userInputCode?: string

        Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

    • getUserById:function
      • getUserById(input: { userContext: any; userId: string }): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
      • Parameters

        • input: { userContext: any; userId: string }
          • userContext: any
          • userId: string

        Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

    • getUserByPhoneNumber:function
      • getUserByPhoneNumber(input: { phoneNumber: string; userContext: any }): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
      • Parameters

        • input: { phoneNumber: string; userContext: any }
          • phoneNumber: string
          • userContext: any

        Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

    • getUserByThirdPartyInfo:function
      • getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
      • Parameters

        • input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

    • getUsersByEmail:function
      • getUsersByEmail(input: { email: string; userContext: any }): Promise<User[]>
    • listCodesByDeviceId:function
      • listCodesByDeviceId(input: { deviceId: string; userContext: any }): Promise<undefined | DeviceType>
    • listCodesByEmail:function
      • listCodesByEmail(input: { email: string; userContext: any }): Promise<DeviceType[]>
    • listCodesByPhoneNumber:function
      • listCodesByPhoneNumber(input: { phoneNumber: string; userContext: any }): Promise<DeviceType[]>
    • listCodesByPreAuthSessionId:function
      • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext: any }): Promise<undefined | DeviceType>
    • revokeAllCodes:function
      • revokeAllCodes(input: { email: string; userContext: any } | { phoneNumber: string; userContext: any }): Promise<{ status: "OK" }>
    • revokeCode:function
      • revokeCode(input: { codeId: string; userContext: any }): Promise<{ status: "OK" }>
    • thirdPartySignInUp:function
      • thirdPartySignInUp(input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
      • Parameters

        • input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • email: string
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    • updatePasswordlessUser:function
      • updatePasswordlessUser(input: { email?: string | (null); phoneNumber?: string | (null); userContext: any; userId: string }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
      • Parameters

        • input: { email?: string | (null); phoneNumber?: string | (null); userContext: any; userId: string }
          • Optional email?: string | (null)
          • Optional phoneNumber?: string | (null)
          • userContext: any
          • userId: string

        Returns Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

    ThirdPartyAPIOptions: APIOptions
    User: ({ email?: string; phoneNumber?: string } | { email: string; thirdParty: { id: string; userId: string } }) & { id: string; timeJoined: number }

    Variables

    Error: typeof default = Wrapper.Error

    Functions

    • Apple(config: TypeThirdPartyProviderAppleConfig): TypeProvider
    • Discord(config: TypeThirdPartyProviderDiscordConfig): TypeProvider
    • Facebook(config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Github(config: TypeThirdPartyProviderGithubConfig): TypeProvider
    • Google(config: TypeThirdPartyProviderGoogleConfig): TypeProvider
    • GoogleWorkspaces(config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
    • Parameters

      • input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }

      Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

    • createCode(input: { email: string } & { userContext?: any; userInputCode?: string } | { phoneNumber: string } & { userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
    • Parameters

      • input: { email: string } & { userContext?: any; userInputCode?: string } | { phoneNumber: string } & { userContext?: any; userInputCode?: string }

      Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

    • createMagicLink(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<string>
    • createNewCodeForDevice(input: { deviceId: string; userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
    • Parameters

      • input: { deviceId: string; userContext?: any; userInputCode?: string }
        • deviceId: string
        • Optional userContext?: any
        • Optional userInputCode?: string

      Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

    • getUserById(userId: string, userContext?: any): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
    • Parameters

      • userId: string
      • userContext: any = {}

      Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

    • getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
    • Parameters

      • input: { phoneNumber: string; userContext?: any }
        • phoneNumber: string
        • Optional userContext?: any

      Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

    • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>
    • Parameters

      • thirdPartyId: string
      • thirdPartyUserId: string
      • userContext: any = {}

      Returns Promise<undefined | { email?: string; phoneNumber?: string } & { id: string; timeJoined: number } | { email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number }>

    • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
    • init(config: TypeInput): RecipeListFunction
    • listCodesByDeviceId(input: { deviceId: string; userContext?: any }): Promise<undefined | DeviceType>
    • listCodesByEmail(input: { email: string; userContext?: any }): Promise<DeviceType[]>
    • listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<DeviceType[]>
    • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext?: any }): Promise<undefined | DeviceType>
    • passwordlessSignInUp(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: string; user: User }>
    • revokeAllCodes(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ status: "OK" }>
    • revokeCode(input: { codeId: string; userContext?: any }): Promise<{ status: "OK" }>
    • sendEmail(input: TypePasswordlessEmailDeliveryInput & { userContext?: any }): Promise<void>
    • sendSms(input: TypePasswordlessSmsDeliveryInput & { userContext?: any }): Promise<void>
    • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
    • updatePasswordlessUser(input: { email?: (null) | string; phoneNumber?: (null) | string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
    • Parameters

      • input: { email?: (null) | string; phoneNumber?: (null) | string; userContext?: any; userId: string }
        • Optional email?: (null) | string
        • Optional phoneNumber?: (null) | string
        • Optional userContext?: any
        • userId: string

      Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file +recipe/thirdpartypasswordless | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/thirdpartypasswordless

    Index

    References

    Re-exports TypeProvider

    Type aliases

    APIInterface: { appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>); authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>); consumeCodePOST: undefined | ((input: ({ deviceId: string; preAuthSessionId: string; userInputCode: string } | { linkCode: string; preAuthSessionId: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" }>); createCodePOST: undefined | ((input: ({ email: string } | { phoneNumber: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ deviceId: string; flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; preAuthSessionId: string; status: "OK" } | GeneralErrorResponse>); passwordlessUserEmailExistsGET: undefined | ((input: { email: string; options: PasswordlessAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>); passwordlessUserPhoneNumberExistsGET: undefined | ((input: { options: PasswordlessAPIOptions; phoneNumber: string; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>); resendCodePOST: undefined | ((input: { deviceId: string; preAuthSessionId: string } & { options: PasswordlessAPIOptions; userContext: any }) => Promise<GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" | "OK" }>); thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>) }

    Type declaration

    • appleRedirectHandlerPOST: undefined | ((input: { code: string; options: ThirdPartyAPIOptions; state: string; userContext: any }) => Promise<void>)
    • authorisationUrlGET: undefined | ((input: { options: ThirdPartyAPIOptions; provider: TypeProvider; userContext: any }) => Promise<{ status: "OK"; url: string } | GeneralErrorResponse>)
    • consumeCodePOST: undefined | ((input: ({ deviceId: string; preAuthSessionId: string; userInputCode: string } | { linkCode: string; preAuthSessionId: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" }>)
    • createCodePOST: undefined | ((input: ({ email: string } | { phoneNumber: string }) & { options: PasswordlessAPIOptions; userContext: any }) => Promise<{ deviceId: string; flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; preAuthSessionId: string; status: "OK" } | GeneralErrorResponse>)
    • passwordlessUserEmailExistsGET: undefined | ((input: { email: string; options: PasswordlessAPIOptions; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>)
    • passwordlessUserPhoneNumberExistsGET: undefined | ((input: { options: PasswordlessAPIOptions; phoneNumber: string; userContext: any }) => Promise<{ exists: boolean; status: "OK" } | GeneralErrorResponse>)
    • resendCodePOST: undefined | ((input: { deviceId: string; preAuthSessionId: string } & { options: PasswordlessAPIOptions; userContext: any }) => Promise<GeneralErrorResponse | { status: "RESTART_FLOW_ERROR" | "OK" }>)
    • thirdPartySignInUpPOST: undefined | ((input: { authCodeResponse?: any; clientId?: string; code: string; options: ThirdPartyAPIOptions; provider: TypeProvider; redirectURI: string; userContext: any }) => Promise<{ authCodeResponse: any; createdNewUser: boolean; session: SessionContainer; status: "OK"; user: User } | GeneralErrorResponse | { status: "NO_EMAIL_GIVEN_BY_PROVIDER" }>)
    PasswordlessAPIOptions: APIOptions
    RecipeInterface: { consumeCode: any; createCode: any; createNewCodeForDevice: any; getUserById: any; getUserByPhoneNumber: any; getUserByThirdPartyInfo: any; getUsersByEmail: any; listCodesByDeviceId: any; listCodesByEmail: any; listCodesByPhoneNumber: any; listCodesByPreAuthSessionId: any; revokeAllCodes: any; revokeCode: any; thirdPartySignInUp: any; updatePasswordlessUser: any }

    Type declaration

    • consumeCode:function
      • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
      • Parameters

        • input: { deviceId: string; preAuthSessionId: string; userContext: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext: any }

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

    • createCode:function
      • createCode(input: ({ email: string } & { userContext: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext: any; userInputCode?: string })): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
      • Parameters

        • input: ({ email: string } & { userContext: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext: any; userInputCode?: string })

        Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

    • createNewCodeForDevice:function
      • createNewCodeForDevice(input: { deviceId: string; userContext: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
      • Parameters

        • input: { deviceId: string; userContext: any; userInputCode?: string }
          • deviceId: string
          • userContext: any
          • Optional userInputCode?: string

        Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

    • getUserById:function
      • getUserById(input: { userContext: any; userId: string }): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
      • Parameters

        • input: { userContext: any; userId: string }
          • userContext: any
          • userId: string

        Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

    • getUserByPhoneNumber:function
      • getUserByPhoneNumber(input: { phoneNumber: string; userContext: any }): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
      • Parameters

        • input: { phoneNumber: string; userContext: any }
          • phoneNumber: string
          • userContext: any

        Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

    • getUserByThirdPartyInfo:function
      • getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
      • Parameters

        • input: { thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

    • getUsersByEmail:function
      • getUsersByEmail(input: { email: string; userContext: any }): Promise<User[]>
    • listCodesByDeviceId:function
      • listCodesByDeviceId(input: { deviceId: string; userContext: any }): Promise<undefined | DeviceType>
    • listCodesByEmail:function
      • listCodesByEmail(input: { email: string; userContext: any }): Promise<DeviceType[]>
    • listCodesByPhoneNumber:function
      • listCodesByPhoneNumber(input: { phoneNumber: string; userContext: any }): Promise<DeviceType[]>
    • listCodesByPreAuthSessionId:function
      • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext: any }): Promise<undefined | DeviceType>
    • revokeAllCodes:function
      • revokeAllCodes(input: { email: string; userContext: any } | { phoneNumber: string; userContext: any }): Promise<{ status: "OK" }>
    • revokeCode:function
      • revokeCode(input: { codeId: string; userContext: any }): Promise<{ status: "OK" }>
    • thirdPartySignInUp:function
      • thirdPartySignInUp(input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
      • Parameters

        • input: { email: string; thirdPartyId: string; thirdPartyUserId: string; userContext: any }
          • email: string
          • thirdPartyId: string
          • thirdPartyUserId: string
          • userContext: any

        Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User }>

    • updatePasswordlessUser:function
      • updatePasswordlessUser(input: { email?: string | null; phoneNumber?: string | null; userContext: any; userId: string }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
      • Parameters

        • input: { email?: string | null; phoneNumber?: string | null; userContext: any; userId: string }
          • Optional email?: string | null
          • Optional phoneNumber?: string | null
          • userContext: any
          • userId: string

        Returns Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

    ThirdPartyAPIOptions: APIOptions
    User: ({ email?: string; phoneNumber?: string } | { email: string; thirdParty: { id: string; userId: string } }) & { id: string; timeJoined: number }

    Variables

    Error: typeof default = Wrapper.Error

    Functions

    • Apple(config: TypeThirdPartyProviderAppleConfig): TypeProvider
    • Discord(config: TypeThirdPartyProviderDiscordConfig): TypeProvider
    • Facebook(config: TypeThirdPartyProviderFacebookConfig): TypeProvider
    • Github(config: TypeThirdPartyProviderGithubConfig): TypeProvider
    • Google(config: TypeThirdPartyProviderGoogleConfig): TypeProvider
    • GoogleWorkspaces(config: TypeThirdPartyProviderGoogleWorkspacesConfig): TypeProvider
    • consumeCode(input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>
    • Parameters

      • input: { deviceId: string; preAuthSessionId: string; userContext?: any; userInputCode: string } | { linkCode: string; preAuthSessionId: string; userContext?: any }

      Returns Promise<{ createdNewUser: boolean; status: "OK"; user: User } | { failedCodeInputAttemptCount: number; maximumCodeInputAttempts: number; status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR" } | { status: "RESTART_FLOW_ERROR" }>

    • createCode(input: ({ email: string } & { userContext?: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext?: any; userInputCode?: string })): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>
    • Parameters

      • input: ({ email: string } & { userContext?: any; userInputCode?: string }) | ({ phoneNumber: string } & { userContext?: any; userInputCode?: string })

      Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string }>

    • createMagicLink(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<string>
    • createNewCodeForDevice(input: { deviceId: string; userContext?: any; userInputCode?: string }): Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>
    • Parameters

      • input: { deviceId: string; userContext?: any; userInputCode?: string }
        • deviceId: string
        • Optional userContext?: any
        • Optional userInputCode?: string

      Returns Promise<{ codeId: string; codeLifetime: number; deviceId: string; linkCode: string; preAuthSessionId: string; status: "OK"; timeCreated: number; userInputCode: string } | { status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR" }>

    • getUserById(userId: string, userContext?: any): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
    • Parameters

      • userId: string
      • userContext: any = {}

      Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

    • getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
    • Parameters

      • input: { phoneNumber: string; userContext?: any }
        • phoneNumber: string
        • Optional userContext?: any

      Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

    • getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>
    • Parameters

      • thirdPartyId: string
      • thirdPartyUserId: string
      • userContext: any = {}

      Returns Promise<undefined | ({ email?: string; phoneNumber?: string } & { id: string; timeJoined: number }) | ({ email: string; thirdParty: { id: string; userId: string } } & { id: string; timeJoined: number })>

    • getUsersByEmail(email: string, userContext?: any): Promise<User[]>
    • init(config: TypeInput): RecipeListFunction
    • listCodesByDeviceId(input: { deviceId: string; userContext?: any }): Promise<undefined | DeviceType>
    • listCodesByEmail(input: { email: string; userContext?: any }): Promise<DeviceType[]>
    • listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise<DeviceType[]>
    • listCodesByPreAuthSessionId(input: { preAuthSessionId: string; userContext?: any }): Promise<undefined | DeviceType>
    • passwordlessSignInUp(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ createdNewUser: boolean; status: string; user: User }>
    • revokeAllCodes(input: { email: string; userContext?: any } | { phoneNumber: string; userContext?: any }): Promise<{ status: "OK" }>
    • revokeCode(input: { codeId: string; userContext?: any }): Promise<{ status: "OK" }>
    • sendEmail(input: TypePasswordlessEmailDeliveryInput & { userContext?: any }): Promise<void>
    • sendSms(input: TypePasswordlessSmsDeliveryInput & { userContext?: any }): Promise<void>
    • thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ createdNewUser: boolean; status: "OK"; user: User }>
    • updatePasswordlessUser(input: { email?: null | string; phoneNumber?: null | string; userContext?: any; userId: string }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>
    • Parameters

      • input: { email?: null | string; phoneNumber?: null | string; userContext?: any; userId: string }
        • Optional email?: null | string
        • Optional phoneNumber?: null | string
        • Optional userContext?: any
        • userId: string

      Returns Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file diff --git a/docs/modules/recipe_usermetadata.html b/docs/modules/recipe_usermetadata.html index 7e284399d..cc8555df9 100644 --- a/docs/modules/recipe_usermetadata.html +++ b/docs/modules/recipe_usermetadata.html @@ -1,4 +1,4 @@ -recipe/usermetadata | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/usermetadata

    Index

    Type Aliases

    RecipeInterface: { clearUserMetadata: any; getUserMetadata: any; updateUserMetadata: any }

    Type declaration

    • clearUserMetadata:function
      • clearUserMetadata(input: { userContext: any; userId: string }): Promise<{ status: "OK" }>
    • getUserMetadata:function
      • getUserMetadata(input: { userContext: any; userId: string }): Promise<{ metadata: any; status: "OK" }>
    • updateUserMetadata:function
      • updateUserMetadata(input: { metadataUpdate: JSONObject; userContext: any; userId: string }): Promise<{ metadata: JSONObject; status: "OK" }>
      • +recipe/usermetadata | supertokens-node
        Options
        All
        • Public
        • Public/Protected
        • All
        Menu

        Module recipe/usermetadata

        Index

        Type aliases

        RecipeInterface: { clearUserMetadata: any; getUserMetadata: any; updateUserMetadata: any }

        Type declaration

        • clearUserMetadata:function
          • clearUserMetadata(input: { userContext: any; userId: string }): Promise<{ status: "OK" }>
        • getUserMetadata:function
          • getUserMetadata(input: { userContext: any; userId: string }): Promise<{ metadata: any; status: "OK" }>
        • updateUserMetadata:function
          • updateUserMetadata(input: { metadataUpdate: JSONObject; userContext: any; userId: string }): Promise<{ metadata: JSONObject; status: "OK" }>
          • Updates the metadata object of the user by doing a shallow merge of the stored and the update JSONs and removing properties set to null on the root level of the update object. e.g.:

            @@ -7,4 +7,4 @@
          • update: { "notifications": { "sms": true }, "todos": null }
          • result: { "preferences": { "theme":"dark" }, "notifications": { "sms": true } }
          -

        Parameters

        • input: { metadataUpdate: JSONObject; userContext: any; userId: string }
          • metadataUpdate: JSONObject
          • userContext: any
          • userId: string

        Returns Promise<{ metadata: JSONObject; status: "OK" }>

    Functions

    • clearUserMetadata(userId: string, userContext?: any): Promise<{ status: "OK" }>
    • getUserMetadata(userId: string, userContext?: any): Promise<{ metadata: any; status: "OK" }>
    • init(config?: TypeInput): RecipeListFunction
    • updateUserMetadata(userId: string, metadataUpdate: JSONObject, userContext?: any): Promise<{ metadata: JSONObject; status: "OK" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file +

    Parameters

    • input: { metadataUpdate: JSONObject; userContext: any; userId: string }
      • metadataUpdate: JSONObject
      • userContext: any
      • userId: string

    Returns Promise<{ metadata: JSONObject; status: "OK" }>

    Functions

    • clearUserMetadata(userId: string, userContext?: any): Promise<{ status: "OK" }>
    • getUserMetadata(userId: string, userContext?: any): Promise<{ metadata: any; status: "OK" }>
    • init(config?: TypeInput): RecipeListFunction
    • updateUserMetadata(userId: string, metadataUpdate: JSONObject, userContext?: any): Promise<{ metadata: JSONObject; status: "OK" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file diff --git a/docs/modules/recipe_userroles.html b/docs/modules/recipe_userroles.html index 47cb5fc42..17f8d49f5 100644 --- a/docs/modules/recipe_userroles.html +++ b/docs/modules/recipe_userroles.html @@ -1 +1 @@ -recipe/userroles | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/userroles

    Index

    Type Aliases

    RecipeInterface: { addRoleToUser: any; createNewRoleOrAddPermissions: any; deleteRole: any; getAllRoles: any; getPermissionsForRole: any; getRolesForUser: any; getRolesThatHavePermission: any; getUsersThatHaveRole: any; removePermissionsFromRole: any; removeUserRole: any }

    Type declaration

    • addRoleToUser:function
      • addRoleToUser(input: { role: string; userContext: any; userId: string }): Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any; userId: string }
          • role: string
          • userContext: any
          • userId: string

        Returns Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • createNewRoleOrAddPermissions:function
      • createNewRoleOrAddPermissions(input: { permissions: string[]; role: string; userContext: any }): Promise<{ createdNewRole: boolean; status: "OK" }>
      • Parameters

        • input: { permissions: string[]; role: string; userContext: any }
          • permissions: string[]
          • role: string
          • userContext: any

        Returns Promise<{ createdNewRole: boolean; status: "OK" }>

    • deleteRole:function
      • deleteRole(input: { role: string; userContext: any }): Promise<{ didRoleExist: boolean; status: "OK" }>
      • Parameters

        • input: { role: string; userContext: any }
          • role: string
          • userContext: any

        Returns Promise<{ didRoleExist: boolean; status: "OK" }>

    • getAllRoles:function
      • getAllRoles(input: { userContext: any }): Promise<{ roles: string[]; status: "OK" }>
    • getPermissionsForRole:function
      • getPermissionsForRole(input: { role: string; userContext: any }): Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any }
          • role: string
          • userContext: any

        Returns Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • getRolesForUser:function
      • getRolesForUser(input: { userContext: any; userId: string }): Promise<{ roles: string[]; status: "OK" }>
      • Parameters

        • input: { userContext: any; userId: string }
          • userContext: any
          • userId: string

        Returns Promise<{ roles: string[]; status: "OK" }>

    • getRolesThatHavePermission:function
      • getRolesThatHavePermission(input: { permission: string; userContext: any }): Promise<{ roles: string[]; status: "OK" }>
      • Parameters

        • input: { permission: string; userContext: any }
          • permission: string
          • userContext: any

        Returns Promise<{ roles: string[]; status: "OK" }>

    • getUsersThatHaveRole:function
      • getUsersThatHaveRole(input: { role: string; userContext: any }): Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any }
          • role: string
          • userContext: any

        Returns Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>

    • removePermissionsFromRole:function
      • removePermissionsFromRole(input: { permissions: string[]; role: string; userContext: any }): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { permissions: string[]; role: string; userContext: any }
          • permissions: string[]
          • role: string
          • userContext: any

        Returns Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>

    • removeUserRole:function
      • removeUserRole(input: { role: string; userContext: any; userId: string }): Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any; userId: string }
          • role: string
          • userContext: any
          • userId: string

        Returns Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    Variables

    PermissionClaim: PermissionClaimClass = ...
    UserRoleClaim: UserRoleClaimClass = ...

    Functions

    • addRoleToUser(userId: string, role: string, userContext?: any): Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
    • Parameters

      • userId: string
      • role: string
      • Optional userContext: any

      Returns Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • createNewRoleOrAddPermissions(role: string, permissions: string[], userContext?: any): Promise<{ createdNewRole: boolean; status: "OK" }>
    • deleteRole(role: string, userContext?: any): Promise<{ didRoleExist: boolean; status: "OK" }>
    • getAllRoles(userContext?: any): Promise<{ roles: string[]; status: "OK" }>
    • getPermissionsForRole(role: string, userContext?: any): Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
    • Parameters

      • role: string
      • Optional userContext: any

      Returns Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • getRolesForUser(userId: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
    • getRolesThatHavePermission(permission: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
    • getUsersThatHaveRole(role: string, userContext?: any): Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>
    • init(config?: TypeInput): RecipeListFunction
    • removePermissionsFromRole(role: string, permissions: string[], userContext?: any): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>
    • removeUserRole(userId: string, role: string, userContext?: any): Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
    • Parameters

      • userId: string
      • role: string
      • Optional userContext: any

      Returns Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file +recipe/userroles | supertokens-node
    Options
    All
    • Public
    • Public/Protected
    • All
    Menu

    Module recipe/userroles

    Index

    Type aliases

    RecipeInterface: { addRoleToUser: any; createNewRoleOrAddPermissions: any; deleteRole: any; getAllRoles: any; getPermissionsForRole: any; getRolesForUser: any; getRolesThatHavePermission: any; getUsersThatHaveRole: any; removePermissionsFromRole: any; removeUserRole: any }

    Type declaration

    • addRoleToUser:function
      • addRoleToUser(input: { role: string; userContext: any; userId: string }): Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any; userId: string }
          • role: string
          • userContext: any
          • userId: string

        Returns Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • createNewRoleOrAddPermissions:function
      • createNewRoleOrAddPermissions(input: { permissions: string[]; role: string; userContext: any }): Promise<{ createdNewRole: boolean; status: "OK" }>
      • Parameters

        • input: { permissions: string[]; role: string; userContext: any }
          • permissions: string[]
          • role: string
          • userContext: any

        Returns Promise<{ createdNewRole: boolean; status: "OK" }>

    • deleteRole:function
      • deleteRole(input: { role: string; userContext: any }): Promise<{ didRoleExist: boolean; status: "OK" }>
      • Parameters

        • input: { role: string; userContext: any }
          • role: string
          • userContext: any

        Returns Promise<{ didRoleExist: boolean; status: "OK" }>

    • getAllRoles:function
      • getAllRoles(input: { userContext: any }): Promise<{ roles: string[]; status: "OK" }>
    • getPermissionsForRole:function
      • getPermissionsForRole(input: { role: string; userContext: any }): Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any }
          • role: string
          • userContext: any

        Returns Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • getRolesForUser:function
      • getRolesForUser(input: { userContext: any; userId: string }): Promise<{ roles: string[]; status: "OK" }>
      • Parameters

        • input: { userContext: any; userId: string }
          • userContext: any
          • userId: string

        Returns Promise<{ roles: string[]; status: "OK" }>

    • getRolesThatHavePermission:function
      • getRolesThatHavePermission(input: { permission: string; userContext: any }): Promise<{ roles: string[]; status: "OK" }>
      • Parameters

        • input: { permission: string; userContext: any }
          • permission: string
          • userContext: any

        Returns Promise<{ roles: string[]; status: "OK" }>

    • getUsersThatHaveRole:function
      • getUsersThatHaveRole(input: { role: string; userContext: any }): Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any }
          • role: string
          • userContext: any

        Returns Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>

    • removePermissionsFromRole:function
      • removePermissionsFromRole(input: { permissions: string[]; role: string; userContext: any }): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { permissions: string[]; role: string; userContext: any }
          • permissions: string[]
          • role: string
          • userContext: any

        Returns Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>

    • removeUserRole:function
      • removeUserRole(input: { role: string; userContext: any; userId: string }): Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
      • Parameters

        • input: { role: string; userContext: any; userId: string }
          • role: string
          • userContext: any
          • userId: string

        Returns Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    Variables

    PermissionClaim: PermissionClaimClass = ...
    UserRoleClaim: UserRoleClaimClass = ...

    Functions

    • addRoleToUser(userId: string, role: string, userContext?: any): Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
    • Parameters

      • userId: string
      • role: string
      • Optional userContext: any

      Returns Promise<{ didUserAlreadyHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • createNewRoleOrAddPermissions(role: string, permissions: string[], userContext?: any): Promise<{ createdNewRole: boolean; status: "OK" }>
    • deleteRole(role: string, userContext?: any): Promise<{ didRoleExist: boolean; status: "OK" }>
    • getAllRoles(userContext?: any): Promise<{ roles: string[]; status: "OK" }>
    • getPermissionsForRole(role: string, userContext?: any): Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
    • Parameters

      • role: string
      • Optional userContext: any

      Returns Promise<{ permissions: string[]; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    • getRolesForUser(userId: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
    • getRolesThatHavePermission(permission: string, userContext?: any): Promise<{ roles: string[]; status: "OK" }>
    • getUsersThatHaveRole(role: string, userContext?: any): Promise<{ status: "OK"; users: string[] } | { status: "UNKNOWN_ROLE_ERROR" }>
    • init(config?: TypeInput): RecipeListFunction
    • removePermissionsFromRole(role: string, permissions: string[], userContext?: any): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR" }>
    • removeUserRole(userId: string, role: string, userContext?: any): Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>
    • Parameters

      • userId: string
      • role: string
      • Optional userContext: any

      Returns Promise<{ didUserHaveRole: boolean; status: "OK" } | { status: "UNKNOWN_ROLE_ERROR" }>

    Legend

    • Variable
    • Function
    • Function with type parameter
    • Type alias
    • Class
    • Class with type parameter
    • Interface

    Settings

    Theme

    Generated using TypeDoc

    \ No newline at end of file diff --git a/frontendDriverInterfaceSupported.json b/frontendDriverInterfaceSupported.json index a449dce2a..d84874259 100644 --- a/frontendDriverInterfaceSupported.json +++ b/frontendDriverInterfaceSupported.json @@ -1,4 +1,4 @@ { "_comment": "contains a list of frontend-driver interfaces branch names that this core supports", - "versions": ["1.15"] + "versions": ["1.16"] } diff --git a/lib/build/constants.d.ts b/lib/build/constants.d.ts index 112aa652a..e961ba82d 100644 --- a/lib/build/constants.d.ts +++ b/lib/build/constants.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck export declare const HEADER_RID = "rid"; export declare const HEADER_FDI = "fdi-version"; diff --git a/lib/build/constants.js b/lib/build/constants.js index 85edcd22e..ad8a0d0a6 100644 --- a/lib/build/constants.js +++ b/lib/build/constants.js @@ -14,5 +14,6 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.HEADER_FDI = exports.HEADER_RID = void 0; exports.HEADER_RID = "rid"; exports.HEADER_FDI = "fdi-version"; diff --git a/lib/build/error.d.ts b/lib/build/error.d.ts index 41083aef0..e41c53794 100644 --- a/lib/build/error.d.ts +++ b/lib/build/error.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export default class SuperTokensError extends Error { private static errMagic; static BAD_INPUT_ERROR: "BAD_INPUT_ERROR"; @@ -6,18 +5,14 @@ export default class SuperTokensError extends Error { payload: any; fromRecipe: string | undefined; private errMagic; - constructor( - options: - | { - message: string; - payload?: any; - type: string; - } - | { - message: string; - type: "BAD_INPUT_ERROR"; - payload: undefined; - } - ); + constructor(options: { + message: string; + payload?: any; + type: string; + } | { + message: string; + type: "BAD_INPUT_ERROR"; + payload: undefined; + }); static isErrorFromSuperTokens(obj: any): obj is SuperTokensError; } diff --git a/lib/build/framework/awsLambda/framework.d.ts b/lib/build/framework/awsLambda/framework.d.ts index f07716627..1264410e8 100644 --- a/lib/build/framework/awsLambda/framework.d.ts +++ b/lib/build/framework/awsLambda/framework.d.ts @@ -1,11 +1,4 @@ -// @ts-nocheck -import type { - APIGatewayProxyEventV2, - APIGatewayProxyEvent, - APIGatewayProxyResult, - APIGatewayProxyStructuredResultV2, - Handler, -} from "aws-lambda"; +import type { APIGatewayProxyEventV2, APIGatewayProxyEvent, APIGatewayProxyResult, APIGatewayProxyStructuredResultV2, Handler } from "aws-lambda"; import { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; import { BaseResponse } from "../response"; @@ -57,24 +50,14 @@ export declare class AWSResponse extends BaseResponse { constructor(event: SupertokensLambdaEvent | SupertokensLambdaEventV2); sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; - setCookie: ( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" - ) => void; + removeHeader: (key: string) => void; + setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; /** * @param {number} statusCode */ setStatusCode: (statusCode: number) => void; sendJSONResponse: (content: any) => void; - sendResponse: ( - response?: APIGatewayProxyResult | APIGatewayProxyStructuredResultV2 | undefined - ) => APIGatewayProxyResult | APIGatewayProxyStructuredResultV2; + sendResponse: (response?: APIGatewayProxyResult | APIGatewayProxyStructuredResultV2 | undefined) => APIGatewayProxyResult | APIGatewayProxyStructuredResultV2; } export interface SessionEventV2 extends SupertokensLambdaEventV2 { session?: SessionContainerInterface; @@ -82,7 +65,7 @@ export interface SessionEventV2 extends SupertokensLambdaEventV2 { export interface SessionEvent extends SupertokensLambdaEvent { session?: SessionContainerInterface; } -export declare const middleware: (handler?: Handler | undefined) => Handler; +export declare const middleware: (handler?: Handler | undefined) => Handler; export interface AWSFramework extends Framework { middleware: (handler?: Handler) => Handler; } diff --git a/lib/build/framework/awsLambda/framework.js b/lib/build/framework/awsLambda/framework.js index 0ecc14e2f..b2d1374d6 100644 --- a/lib/build/framework/awsLambda/framework.js +++ b/lib/build/framework/awsLambda/framework.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.AWSWrapper = exports.middleware = exports.AWSResponse = exports.AWSRequest = void 0; const utils_1 = require("../../utils"); const request_1 = require("../request"); const response_1 = require("../response"); @@ -41,20 +20,20 @@ const querystring_1 = require("querystring"); class AWSRequest extends request_1.BaseRequest { constructor(event) { super(); - this.getFormData = () => - __awaiter(this, void 0, void 0, function* () { - if (this.parsedUrlEncodedFormData === undefined) { - if (this.event.body === null || this.event.body === undefined) { + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + if (this.parsedUrlEncodedFormData === undefined) { + if (this.event.body === null || this.event.body === undefined) { + this.parsedUrlEncodedFormData = {}; + } + else { + this.parsedUrlEncodedFormData = querystring_1.parse(this.event.body); + if (this.parsedUrlEncodedFormData === undefined) { this.parsedUrlEncodedFormData = {}; - } else { - this.parsedUrlEncodedFormData = querystring_1.parse(this.event.body); - if (this.parsedUrlEncodedFormData === undefined) { - this.parsedUrlEncodedFormData = {}; - } } } - return this.parsedUrlEncodedFormData; - }); + } + return this.parsedUrlEncodedFormData; + }); this.getKeyValueFromQuery = (key) => { if (this.event.queryStringParameters === undefined || this.event.queryStringParameters === null) { return undefined; @@ -65,20 +44,20 @@ class AWSRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => - __awaiter(this, void 0, void 0, function* () { - if (this.parsedJSONBody === undefined) { - if (this.event.body === null || this.event.body === undefined) { + this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { + if (this.parsedJSONBody === undefined) { + if (this.event.body === null || this.event.body === undefined) { + this.parsedJSONBody = {}; + } + else { + this.parsedJSONBody = JSON.parse(this.event.body); + if (this.parsedJSONBody === undefined) { this.parsedJSONBody = {}; - } else { - this.parsedJSONBody = JSON.parse(this.event.body); - if (this.parsedJSONBody === undefined) { - this.parsedJSONBody = {}; - } } } - return this.parsedJSONBody; - }); + } + return this.parsedJSONBody; + }); this.getMethod = () => { let rawMethod = this.event.httpMethod; if (rawMethod !== undefined) { @@ -88,20 +67,15 @@ class AWSRequest extends request_1.BaseRequest { }; this.getCookieValue = (key) => { let cookies = this.event.cookies; - if ( - (this.event.headers === undefined || this.event.headers === null) && - (cookies === undefined || cookies === null) - ) { + if ((this.event.headers === undefined || this.event.headers === null) && + (cookies === undefined || cookies === null)) { return undefined; } let value = utils_2.getCookieValueFromHeaders(this.event.headers, key); if (value === undefined && cookies !== undefined && cookies !== null) { - value = utils_2.getCookieValueFromHeaders( - { - cookie: cookies.join(";"), - }, - key - ); + value = utils_2.getCookieValueFromHeaders({ + cookie: cookies.join(";"), + }, key); } return value; }; @@ -146,17 +120,11 @@ class AWSResponse extends response_1.BaseResponse { allowDuplicateKey, }); }; + this.removeHeader = (key) => { + this.event.supertokens.response.headers = this.event.supertokens.response.headers.filter((header) => header.key.toLowerCase() !== key.toLowerCase()); + }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - let serialisedCookie = utils_2.serializeCookieValue( - key, - value, - domain, - secure, - httpOnly, - expires, - path, - sameSite - ); + let serialisedCookie = utils_2.serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite); this.event.supertokens.response.cookies.push(serialisedCookie); }; /** @@ -171,7 +139,7 @@ class AWSResponse extends response_1.BaseResponse { this.sendJSONResponse = (content) => { if (!this.responseSet) { this.content = JSON.stringify(content); - this.setHeader("Context-Type", "application/json", false); + this.setHeader("Content-Type", "application/json", false); this.responseSet = true; } }; @@ -204,7 +172,8 @@ class AWSResponse extends response_1.BaseResponse { if (supertokensHeaders[i].allowDuplicateKey && currentValue !== undefined) { let newValue = `${currentValue}, ${supertokensHeaders[i].value}`; headers[supertokensHeaders[i].key] = newValue; - } else { + } + else { headers[supertokensHeaders[i].key] = supertokensHeaders[i].value; } } @@ -214,28 +183,26 @@ class AWSResponse extends response_1.BaseResponse { cookies = []; } cookies.push(...supertokensCookies); - let result = Object.assign(Object.assign({}, response), { cookies, body, statusCode, headers }); + let result = Object.assign(Object.assign({}, response), { cookies, + body, + statusCode, + headers }); return result; - } else { + } + else { let multiValueHeaders = response.multiValueHeaders; if (multiValueHeaders === undefined) { multiValueHeaders = {}; } let headsersInMultiValueHeaders = Object.keys(multiValueHeaders); - let cookieHeader = headsersInMultiValueHeaders.find( - (h) => h.toLowerCase() === constants_1.COOKIE_HEADER.toLowerCase() - ); + let cookieHeader = headsersInMultiValueHeaders.find((h) => h.toLowerCase() === constants_1.COOKIE_HEADER.toLowerCase()); if (cookieHeader === undefined) { multiValueHeaders[constants_1.COOKIE_HEADER] = supertokensCookies; - } else { + } + else { multiValueHeaders[cookieHeader].push(...supertokensCookies); } - let result = Object.assign(Object.assign({}, response), { - multiValueHeaders, - body: body, - statusCode: statusCode, - headers, - }); + let result = Object.assign(Object.assign({}, response), { multiValueHeaders, body: body, statusCode: statusCode, headers }); return result; } }; @@ -254,39 +221,40 @@ class AWSResponse extends response_1.BaseResponse { } } exports.AWSResponse = AWSResponse; -exports.middleware = (handler) => { - return (event, context, callback) => - __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new AWSRequest(event); - let response = new AWSResponse(event); - try { - let result = yield supertokens.middleware(request, response); - if (result) { - return response.sendResponse(); - } - if (handler !== undefined) { - let handlerResult = yield handler(event, context, callback); - return response.sendResponse(handlerResult); - } - /** - * it reaches this point only if the API route was not exposed by - * the SDK and user didn't provide a handler - */ - response.setStatusCode(404); - response.sendJSONResponse({ - error: `The middleware couldn't serve the API path ${request.getOriginalURL()}, method: ${request.getMethod()}. If this is an unexpected behaviour, please create an issue here: https://github.com/supertokens/supertokens-node/issues`, - }); +const middleware = (handler) => { + return (event, context, callback) => __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new AWSRequest(event); + let response = new AWSResponse(event); + try { + let result = yield supertokens.middleware(request, response); + if (result) { return response.sendResponse(); - } catch (err) { - yield supertokens.errorHandler(err, request, response); - if (response.responseSet) { - return response.sendResponse(); - } - throw err; } - }); + if (handler !== undefined) { + let handlerResult = yield handler(event, context, callback); + return response.sendResponse(handlerResult); + } + /** + * it reaches this point only if the API route was not exposed by + * the SDK and user didn't provide a handler + */ + response.setStatusCode(404); + response.sendJSONResponse({ + error: `The middleware couldn't serve the API path ${request.getOriginalURL()}, method: ${request.getMethod()}. If this is an unexpected behaviour, please create an issue here: https://github.com/supertokens/supertokens-node/issues`, + }); + return response.sendResponse(); + } + catch (err) { + yield supertokens.errorHandler(err, request, response); + if (response.responseSet) { + return response.sendResponse(); + } + throw err; + } + }); }; +exports.middleware = middleware; exports.AWSWrapper = { middleware: exports.middleware, wrapRequest: (unwrapped) => { diff --git a/lib/build/framework/awsLambda/index.d.ts b/lib/build/framework/awsLambda/index.d.ts index 1028174f0..b69a4cee2 100644 --- a/lib/build/framework/awsLambda/index.d.ts +++ b/lib/build/framework/awsLambda/index.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck export type { SessionEvent, SessionEventV2 } from "./framework"; -export declare const middleware: ( - handler?: import("aws-lambda").Handler | undefined -) => import("aws-lambda").Handler; +export declare const middleware: (handler?: import("aws-lambda").Handler | undefined) => import("aws-lambda").Handler; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/awsLambda/index.js b/lib/build/framework/awsLambda/index.js index 8313b5030..9e86669f5 100644 --- a/lib/build/framework/awsLambda/index.js +++ b/lib/build/framework/awsLambda/index.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapResponse = exports.wrapRequest = exports.middleware = void 0; const framework_1 = require("./framework"); exports.middleware = framework_1.AWSWrapper.middleware; exports.wrapRequest = framework_1.AWSWrapper.wrapRequest; diff --git a/lib/build/framework/constants.d.ts b/lib/build/framework/constants.d.ts index eb751247f..831d39575 100644 --- a/lib/build/framework/constants.d.ts +++ b/lib/build/framework/constants.d.ts @@ -1,2 +1 @@ -// @ts-nocheck export declare const COOKIE_HEADER = "Set-Cookie"; diff --git a/lib/build/framework/constants.js b/lib/build/framework/constants.js index d3728e594..8a7a8ea6c 100644 --- a/lib/build/framework/constants.js +++ b/lib/build/framework/constants.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.COOKIE_HEADER = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/framework/express/framework.d.ts b/lib/build/framework/express/framework.d.ts index ba1865f51..2fc4da709 100644 --- a/lib/build/framework/express/framework.d.ts +++ b/lib/build/framework/express/framework.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import type { Request, Response, NextFunction } from "express"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; @@ -24,16 +23,8 @@ export declare class ExpressResponse extends BaseResponse { constructor(response: Response); sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; - setCookie: ( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" - ) => void; + removeHeader: (key: string) => void; + setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; /** * @param {number} statusCode */ diff --git a/lib/build/framework/express/framework.js b/lib/build/framework/express/framework.js index c7445c338..0f9ba525a 100644 --- a/lib/build/framework/express/framework.js +++ b/lib/build/framework/express/framework.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExpressWrapper = exports.errorHandler = exports.middleware = exports.ExpressResponse = exports.ExpressRequest = void 0; const utils_1 = require("../../utils"); const request_1 = require("../request"); const response_1 = require("../response"); @@ -53,14 +32,13 @@ const supertokens_1 = require("../../supertokens"); class ExpressRequest extends request_1.BaseRequest { constructor(request) { super(); - this.getFormData = () => - __awaiter(this, void 0, void 0, function* () { - if (!this.formDataParserChecked) { - yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -71,14 +49,13 @@ class ExpressRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => - __awaiter(this, void 0, void 0, function* () { - if (!this.parserChecked) { - yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); - this.parserChecked = true; - } - return this.request.body; - }); + this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { + if (!this.parserChecked) { + yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); + this.parserChecked = true; + } + return this.request.body; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -117,18 +94,11 @@ class ExpressResponse extends response_1.BaseResponse { this.setHeader = (key, value, allowDuplicateKey) => { utils_2.setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; + this.removeHeader = (key) => { + this.response.removeHeader(key); + }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - utils_2.setCookieForServerResponse( - this.response, - key, - value, - domain, - secure, - httpOnly, - expires, - path, - sameSite - ); + utils_2.setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); }; /** * @param {number} statusCode @@ -149,44 +119,48 @@ class ExpressResponse extends response_1.BaseResponse { } } exports.ExpressResponse = ExpressResponse; -exports.middleware = () => { - return (req, res, next) => - __awaiter(void 0, void 0, void 0, function* () { - let supertokens; - const request = new ExpressRequest(req); - const response = new ExpressResponse(res); - try { - supertokens = supertokens_1.default.getInstanceOrThrowError(); - const result = yield supertokens.middleware(request, response); - if (!result) { - return next(); +const middleware = () => { + return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { + let supertokens; + const request = new ExpressRequest(req); + const response = new ExpressResponse(res); + try { + supertokens = supertokens_1.default.getInstanceOrThrowError(); + const result = yield supertokens.middleware(request, response); + if (!result) { + return next(); + } + } + catch (err) { + if (supertokens) { + try { + yield supertokens.errorHandler(err, request, response); } - } catch (err) { - if (supertokens) { - try { - yield supertokens.errorHandler(err, request, response); - } catch (_a) { - next(err); - } - } else { + catch (_a) { next(err); } } - }); -}; -exports.errorHandler = () => { - return (err, req, res, next) => - __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new ExpressRequest(req); - let response = new ExpressResponse(res); - try { - yield supertokens.errorHandler(err, request, response); - } catch (err) { - return next(err); + else { + next(err); } - }); + } + }); +}; +exports.middleware = middleware; +const errorHandler = () => { + return (err, req, res, next) => __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new ExpressRequest(req); + let response = new ExpressResponse(res); + try { + yield supertokens.errorHandler(err, request, response); + } + catch (err) { + return next(err); + } + }); }; +exports.errorHandler = errorHandler; exports.ExpressWrapper = { middleware: exports.middleware, errorHandler: exports.errorHandler, diff --git a/lib/build/framework/express/index.d.ts b/lib/build/framework/express/index.d.ts index 9bf873aa2..cc2b67499 100644 --- a/lib/build/framework/express/index.d.ts +++ b/lib/build/framework/express/index.d.ts @@ -1,15 +1,6 @@ -// @ts-nocheck +/// export type { SessionRequest } from "./framework"; -export declare const middleware: () => ( - req: import("express").Request, - res: import("express").Response, - next: import("express").NextFunction -) => Promise; -export declare const errorHandler: () => ( - err: any, - req: import("express").Request, - res: import("express").Response, - next: import("express").NextFunction -) => Promise; +export declare const middleware: () => (req: import("express").Request, res: import("express").Response, next: import("express").NextFunction) => Promise; +export declare const errorHandler: () => (err: any, req: import("express").Request, res: import("express").Response, next: import("express").NextFunction) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/express/index.js b/lib/build/framework/express/index.js index 61772f629..238165935 100644 --- a/lib/build/framework/express/index.js +++ b/lib/build/framework/express/index.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapResponse = exports.wrapRequest = exports.errorHandler = exports.middleware = void 0; const framework_1 = require("./framework"); exports.middleware = framework_1.ExpressWrapper.middleware; exports.errorHandler = framework_1.ExpressWrapper.errorHandler; diff --git a/lib/build/framework/fastify/framework.d.ts b/lib/build/framework/fastify/framework.d.ts index a57cc3efa..5041488c2 100644 --- a/lib/build/framework/fastify/framework.d.ts +++ b/lib/build/framework/fastify/framework.d.ts @@ -1,5 +1,3 @@ -// @ts-nocheck -/// import type { FastifyRequest as OriginalFastifyRequest, FastifyReply, FastifyPluginCallback } from "fastify"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; @@ -23,16 +21,8 @@ export declare class FastifyResponse extends BaseResponse { constructor(response: FastifyReply); sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; - setCookie: ( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" - ) => void; + removeHeader: (key: string) => void; + setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; /** * @param {number} statusCode */ @@ -49,19 +39,5 @@ export interface FasitfyFramework extends Framework { plugin: FastifyPluginCallback; errorHandler: () => (err: any, req: OriginalFastifyRequest, res: FastifyReply) => Promise; } -export declare const errorHandler: () => ( - err: any, - req: OriginalFastifyRequest< - import("fastify/types/route").RouteGenericInterface, - import("http").Server, - import("http").IncomingMessage - >, - res: FastifyReply< - import("http").Server, - import("http").IncomingMessage, - import("http").ServerResponse, - import("fastify/types/route").RouteGenericInterface, - unknown - > -) => Promise; +export declare const errorHandler: () => (err: any, req: OriginalFastifyRequest, res: FastifyReply) => Promise; export declare const FastifyWrapper: FasitfyFramework; diff --git a/lib/build/framework/fastify/framework.js b/lib/build/framework/fastify/framework.js index 1fb0c5dd5..16172309b 100644 --- a/lib/build/framework/fastify/framework.js +++ b/lib/build/framework/fastify/framework.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.FastifyWrapper = exports.errorHandler = exports.FastifyResponse = exports.FastifyRequest = void 0; const utils_1 = require("../../utils"); const request_1 = require("../request"); const response_1 = require("../response"); @@ -54,10 +33,9 @@ const constants_1 = require("../constants"); class FastifyRequest extends request_1.BaseRequest { constructor(request) { super(); - this.getFormData = () => - __awaiter(this, void 0, void 0, function* () { - return this.request.body; // NOTE: ask user to add require('fastify-formbody') - }); + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + return this.request.body; // NOTE: ask user to add require('fastify-formbody') + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -68,10 +46,9 @@ class FastifyRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => - __awaiter(this, void 0, void 0, function* () { - return this.request.body; - }); + this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { + return this.request.body; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -105,27 +82,24 @@ class FastifyResponse extends response_1.BaseResponse { // we have the this.response.header for compatibility with nextJS if (existingValue === undefined) { this.response.header(key, value); - } else if (allowDuplicateKey) { + } + else if (allowDuplicateKey) { this.response.header(key, existingValue + ", " + value); - } else { + } + else { // we overwrite the current one with the new one this.response.header(key, value); } - } catch (err) { + } + catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; + this.removeHeader = (key) => { + this.response.removeHeader(key); + }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - let serialisedCookie = utils_2.serializeCookieValue( - key, - value, - domain, - secure, - httpOnly, - expires, - path, - sameSite - ); + let serialisedCookie = utils_2.serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite); /** * lets say if current value is undefined, prev -> undefined * @@ -188,30 +162,29 @@ class FastifyResponse extends response_1.BaseResponse { } exports.FastifyResponse = FastifyResponse; function plugin(fastify, _, done) { - fastify.addHook("preHandler", (req, reply) => - __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new FastifyRequest(req); - let response = new FastifyResponse(reply); - try { - yield supertokens.middleware(request, response); - } catch (err) { - yield supertokens.errorHandler(err, request, response); - } - }) - ); + fastify.addHook("preHandler", (req, reply) => __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new FastifyRequest(req); + let response = new FastifyResponse(reply); + try { + yield supertokens.middleware(request, response); + } + catch (err) { + yield supertokens.errorHandler(err, request, response); + } + })); done(); } plugin[Symbol.for("skip-override")] = true; -exports.errorHandler = () => { - return (err, req, res) => - __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new FastifyRequest(req); - let response = new FastifyResponse(res); - yield supertokens.errorHandler(err, request, response); - }); +const errorHandler = () => { + return (err, req, res) => __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new FastifyRequest(req); + let response = new FastifyResponse(res); + yield supertokens.errorHandler(err, request, response); + }); }; +exports.errorHandler = errorHandler; exports.FastifyWrapper = { plugin, errorHandler: exports.errorHandler, diff --git a/lib/build/framework/fastify/index.d.ts b/lib/build/framework/fastify/index.d.ts index 3cca3a1a2..0737a9984 100644 --- a/lib/build/framework/fastify/index.d.ts +++ b/lib/build/framework/fastify/index.d.ts @@ -1,21 +1,6 @@ -// @ts-nocheck /// export type { SessionRequest } from "./framework"; export declare const plugin: import("fastify").FastifyPluginCallback, import("http").Server>; -export declare const errorHandler: () => ( - err: any, - req: import("fastify").FastifyRequest< - import("fastify/types/route").RouteGenericInterface, - import("http").Server, - import("http").IncomingMessage - >, - res: import("fastify").FastifyReply< - import("http").Server, - import("http").IncomingMessage, - import("http").ServerResponse, - import("fastify/types/route").RouteGenericInterface, - unknown - > -) => Promise; +export declare const errorHandler: () => (err: any, req: import("fastify").FastifyRequest, res: import("fastify").FastifyReply) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/fastify/index.js b/lib/build/framework/fastify/index.js index c202276ac..3b855ed7e 100644 --- a/lib/build/framework/fastify/index.js +++ b/lib/build/framework/fastify/index.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapResponse = exports.wrapRequest = exports.errorHandler = exports.plugin = void 0; const framework_1 = require("./framework"); exports.plugin = framework_1.FastifyWrapper.plugin; exports.errorHandler = framework_1.FastifyWrapper.errorHandler; diff --git a/lib/build/framework/hapi/framework.d.ts b/lib/build/framework/hapi/framework.d.ts index a49deac96..80034d219 100644 --- a/lib/build/framework/hapi/framework.d.ts +++ b/lib/build/framework/hapi/framework.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import type { Request, ResponseToolkit, Plugin, ResponseObject } from "@hapi/hapi"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; @@ -17,7 +16,7 @@ export declare class HapiRequest extends BaseRequest { getOriginalURL: () => string; } export interface ExtendedResponseToolkit extends ResponseToolkit { - lazyHeaderBindings: (h: ResponseToolkit, key: string, value: string, allowDuplicateKey: boolean) => void; + lazyHeaderBindings: (h: ResponseToolkit, key: string, value: string | undefined, allowDuplicateKey: boolean) => void; } export declare class HapiResponse extends BaseResponse { private response; @@ -28,16 +27,8 @@ export declare class HapiResponse extends BaseResponse { constructor(response: ExtendedResponseToolkit); sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; - setCookie: ( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" - ) => void; + removeHeader: (key: string) => void; + setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; /** * @param {number} statusCode */ diff --git a/lib/build/framework/hapi/framework.js b/lib/build/framework/hapi/framework.js index 65167d3ae..942ae8d5a 100644 --- a/lib/build/framework/hapi/framework.js +++ b/lib/build/framework/hapi/framework.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.HapiWrapper = exports.HapiResponse = exports.HapiRequest = void 0; const utils_1 = require("../../utils"); const request_1 = require("../request"); const response_1 = require("../response"); @@ -53,10 +32,9 @@ const supertokens_1 = require("../../supertokens"); class HapiRequest extends request_1.BaseRequest { constructor(request) { super(); - this.getFormData = () => - __awaiter(this, void 0, void 0, function* () { - return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; - }); + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -67,10 +45,9 @@ class HapiRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => - __awaiter(this, void 0, void 0, function* () { - return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; - }); + this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { + return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -102,10 +79,14 @@ class HapiResponse extends response_1.BaseResponse { this.setHeader = (key, value, allowDuplicateKey) => { try { this.response.lazyHeaderBindings(this.response, key, value, allowDuplicateKey); - } catch (err) { + } + catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; + this.removeHeader = (key) => { + this.response.lazyHeaderBindings(this.response, key, undefined, false); + }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { let now = Date.now(); if (expires > now) { @@ -117,7 +98,8 @@ class HapiResponse extends response_1.BaseResponse { ttl: expires - now, isSameSite: sameSite === "lax" ? "Lax" : sameSite === "none" ? "None" : "Strict", }); - } else { + } + else { this.response.unstate(key); } }; @@ -159,52 +141,56 @@ const plugin = { register: function (server, _) { return __awaiter(this, void 0, void 0, function* () { let supertokens = supertokens_1.default.getInstanceOrThrowError(); - server.ext("onPreHandler", (req, h) => - __awaiter(this, void 0, void 0, function* () { - let request = new HapiRequest(req); - let response = new HapiResponse(h); - let result = yield supertokens.middleware(request, response); - if (!result) { - return h.continue; - } - return response.sendResponse(); - }) - ); - server.ext("onPreResponse", (request, h) => - __awaiter(this, void 0, void 0, function* () { - (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { - if (request.response.isBoom) { - request.response.output.headers[key] = value; - } else { - request.response.header(key, value, { append: allowDuplicateKey }); - } - }); + server.ext("onPreHandler", (req, h) => __awaiter(this, void 0, void 0, function* () { + let request = new HapiRequest(req); + let response = new HapiResponse(h); + let result = yield supertokens.middleware(request, response); + if (!result) { + return h.continue; + } + return response.sendResponse(); + })); + server.ext("onPreResponse", (request, h) => __awaiter(this, void 0, void 0, function* () { + (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { if (request.response.isBoom) { - let err = request.response.data || request.response; - let req = new HapiRequest(request); - let res = new HapiResponse(h); - if (err !== undefined && err !== null) { - try { - yield supertokens.errorHandler(err, req, res); - if (res.responseSet) { - let resObj = res.sendResponse(true); - (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { - resObj.header(key, value, { append: allowDuplicateKey }); - }); - return resObj.takeover(); - } - return h.continue; - } catch (e) { - return h.continue; + request.response.output.headers[key] = value; + } + else { + request.response.header(key, value, { append: allowDuplicateKey }); + } + }); + if (request.response.isBoom) { + let err = request.response.data || request.response; + let req = new HapiRequest(request); + let res = new HapiResponse(h); + if (err !== undefined && err !== null) { + try { + yield supertokens.errorHandler(err, req, res); + if (res.responseSet) { + let resObj = res.sendResponse(true); + (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { + resObj.header(key, value, { append: allowDuplicateKey }); + }); + return resObj.takeover(); } + return h.continue; + } + catch (e) { + return h.continue; } } - return h.continue; - }) - ); + } + return h.continue; + })); server.decorate("toolkit", "lazyHeaderBindings", function (h, key, value, allowDuplicateKey) { - h.request.app.lazyHeaders = h.request.app.lazyHeaders || []; - h.request.app.lazyHeaders.push({ key, value, allowDuplicateKey }); + const anyApp = h.request.app; + anyApp.lazyHeaders = anyApp.lazyHeaders || []; + if (value === undefined) { + anyApp.lazyHeaders = anyApp.lazyHeaders.filter((header) => header.key.toLowerCase() !== key.toLowerCase()); + } + else { + anyApp.lazyHeaders.push({ key, value, allowDuplicateKey }); + } }); let supportedRoutes = []; let routeMethodSet = new Set(); diff --git a/lib/build/framework/hapi/index.d.ts b/lib/build/framework/hapi/index.d.ts index ea293f69b..fb09d5b15 100644 --- a/lib/build/framework/hapi/index.d.ts +++ b/lib/build/framework/hapi/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export type { SessionRequest } from "./framework"; export declare const plugin: import("@hapi/hapi").Plugin<{}>; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; diff --git a/lib/build/framework/hapi/index.js b/lib/build/framework/hapi/index.js index 9e8e95a69..5aed04807 100644 --- a/lib/build/framework/hapi/index.js +++ b/lib/build/framework/hapi/index.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapResponse = exports.wrapRequest = exports.plugin = void 0; const framework_1 = require("./framework"); exports.plugin = framework_1.HapiWrapper.plugin; exports.wrapRequest = framework_1.HapiWrapper.wrapRequest; diff --git a/lib/build/framework/index.d.ts b/lib/build/framework/index.d.ts index 8fd8891ce..cd0ab5dcd 100644 --- a/lib/build/framework/index.d.ts +++ b/lib/build/framework/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export { BaseRequest } from "./request"; export { BaseResponse } from "./response"; import * as expressFramework from "./express"; diff --git a/lib/build/framework/index.js b/lib/build/framework/index.js index de9aa84e2..51941df72 100644 --- a/lib/build/framework/index.js +++ b/lib/build/framework/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.awsLambda = exports.koa = exports.loopback = exports.hapi = exports.fastify = exports.express = exports.BaseResponse = exports.BaseRequest = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -15,9 +16,9 @@ Object.defineProperty(exports, "__esModule", { value: true }); * under the License. */ var request_1 = require("./request"); -exports.BaseRequest = request_1.BaseRequest; +Object.defineProperty(exports, "BaseRequest", { enumerable: true, get: function () { return request_1.BaseRequest; } }); var response_1 = require("./response"); -exports.BaseResponse = response_1.BaseResponse; +Object.defineProperty(exports, "BaseResponse", { enumerable: true, get: function () { return response_1.BaseResponse; } }); const expressFramework = require("./express"); const fastifyFramework = require("./fastify"); const hapiFramework = require("./hapi"); diff --git a/lib/build/framework/koa/framework.d.ts b/lib/build/framework/koa/framework.d.ts index 36fa51dec..01c4fc110 100644 --- a/lib/build/framework/koa/framework.d.ts +++ b/lib/build/framework/koa/framework.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import type { Context, Next } from "koa"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; @@ -25,16 +24,8 @@ export declare class KoaResponse extends BaseResponse { constructor(ctx: Context); sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; - setCookie: ( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" - ) => void; + removeHeader: (key: string) => void; + setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; /** * @param {number} statusCode */ diff --git a/lib/build/framework/koa/framework.js b/lib/build/framework/koa/framework.js index 94d4b1ae1..d333c3642 100644 --- a/lib/build/framework/koa/framework.js +++ b/lib/build/framework/koa/framework.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.KoaWrapper = exports.middleware = exports.KoaResponse = exports.KoaRequest = void 0; const utils_1 = require("../../utils"); const request_1 = require("../request"); const response_1 = require("../response"); @@ -54,13 +33,12 @@ const supertokens_1 = require("../../supertokens"); class KoaRequest extends request_1.BaseRequest { constructor(ctx) { super(); - this.getFormData = () => - __awaiter(this, void 0, void 0, function* () { - if (this.parsedUrlEncodedFormData === undefined) { - this.parsedUrlEncodedFormData = yield parseURLEncodedFormData(this.ctx); - } - return this.parsedUrlEncodedFormData; - }); + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + if (this.parsedUrlEncodedFormData === undefined) { + this.parsedUrlEncodedFormData = yield parseURLEncodedFormData(this.ctx); + } + return this.parsedUrlEncodedFormData; + }); this.getKeyValueFromQuery = (key) => { if (this.ctx.query === undefined) { return undefined; @@ -71,13 +49,12 @@ class KoaRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => - __awaiter(this, void 0, void 0, function* () { - if (this.parsedJSONBody === undefined) { - this.parsedJSONBody = yield parseJSONBodyFromRequest(this.ctx); - } - return this.parsedJSONBody === undefined ? {} : this.parsedJSONBody; - }); + this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { + if (this.parsedJSONBody === undefined) { + this.parsedJSONBody = yield parseJSONBodyFromRequest(this.ctx); + } + return this.parsedJSONBody === undefined ? {} : this.parsedJSONBody; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.ctx.request.method); }; @@ -131,16 +108,22 @@ class KoaResponse extends response_1.BaseResponse { let existingValue = existingHeaders[key.toLowerCase()]; if (existingValue === undefined) { this.ctx.set(key, value); - } else if (allowDuplicateKey) { + } + else if (allowDuplicateKey) { this.ctx.set(key, existingValue + ", " + value); - } else { + } + else { // we overwrite the current one with the new one this.ctx.set(key, value); } - } catch (err) { + } + catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; + this.removeHeader = (key) => { + this.ctx.remove(key); + }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { this.ctx.cookies.set(key, value, { secure, @@ -171,22 +154,23 @@ class KoaResponse extends response_1.BaseResponse { } } exports.KoaResponse = KoaResponse; -exports.middleware = () => { - return (ctx, next) => - __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new KoaRequest(ctx); - let response = new KoaResponse(ctx); - try { - let result = yield supertokens.middleware(request, response); - if (!result) { - return yield next(); - } - } catch (err) { - return yield supertokens.errorHandler(err, request, response); +const middleware = () => { + return (ctx, next) => __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new KoaRequest(ctx); + let response = new KoaResponse(ctx); + try { + let result = yield supertokens.middleware(request, response); + if (!result) { + return yield next(); } - }); + } + catch (err) { + return yield supertokens.errorHandler(err, request, response); + } + }); }; +exports.middleware = middleware; exports.KoaWrapper = { middleware: exports.middleware, wrapRequest: (unwrapped) => { diff --git a/lib/build/framework/koa/index.d.ts b/lib/build/framework/koa/index.d.ts index 1d6395964..928863a7e 100644 --- a/lib/build/framework/koa/index.d.ts +++ b/lib/build/framework/koa/index.d.ts @@ -1,4 +1,4 @@ -// @ts-nocheck +/// export type { SessionContext } from "./framework"; export declare const middleware: () => (ctx: import("koa").Context, next: import("koa").Next) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; diff --git a/lib/build/framework/koa/index.js b/lib/build/framework/koa/index.js index 29516c72e..4f7150a4f 100644 --- a/lib/build/framework/koa/index.js +++ b/lib/build/framework/koa/index.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapResponse = exports.wrapRequest = exports.middleware = void 0; const framework_1 = require("./framework"); exports.middleware = framework_1.KoaWrapper.middleware; exports.wrapRequest = framework_1.KoaWrapper.wrapRequest; diff --git a/lib/build/framework/loopback/framework.d.ts b/lib/build/framework/loopback/framework.d.ts index ae474aa56..c62de7950 100644 --- a/lib/build/framework/loopback/framework.d.ts +++ b/lib/build/framework/loopback/framework.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import type { MiddlewareContext, Response, Middleware } from "@loopback/rest"; import { SessionContainerInterface } from "../../recipe/session/types"; import { HTTPMethod } from "../../types"; @@ -24,16 +23,8 @@ export declare class LoopbackResponse extends BaseResponse { constructor(ctx: MiddlewareContext); sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; - setCookie: ( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" - ) => void; + removeHeader: (key: string) => void; + setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; setStatusCode: (statusCode: number) => void; sendJSONResponse: (content: any) => void; } diff --git a/lib/build/framework/loopback/framework.js b/lib/build/framework/loopback/framework.js index cf86a8544..7379a7d37 100644 --- a/lib/build/framework/loopback/framework.js +++ b/lib/build/framework/loopback/framework.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoopbackWrapper = exports.middleware = exports.LoopbackResponse = exports.LoopbackRequest = void 0; const utils_1 = require("../../utils"); const request_1 = require("../request"); const response_1 = require("../response"); @@ -53,14 +32,13 @@ const supertokens_1 = require("../../supertokens"); class LoopbackRequest extends request_1.BaseRequest { constructor(ctx) { super(); - this.getFormData = () => - __awaiter(this, void 0, void 0, function* () { - if (!this.formDataParserChecked) { - yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -71,14 +49,13 @@ class LoopbackRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => - __awaiter(this, void 0, void 0, function* () { - if (!this.parserChecked) { - yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); - this.parserChecked = true; - } - return this.request.body; - }); + this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { + if (!this.parserChecked) { + yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); + this.parserChecked = true; + } + return this.request.body; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -110,18 +87,11 @@ class LoopbackResponse extends response_1.BaseResponse { this.setHeader = (key, value, allowDuplicateKey) => { utils_2.setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; + this.removeHeader = (key) => { + this.response.removeHeader(key); + }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - utils_2.setCookieForServerResponse( - this.response, - key, - value, - domain, - secure, - httpOnly, - expires, - path, - sameSite - ); + utils_2.setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); }; this.setStatusCode = (statusCode) => { if (!this.response.writableEnded) { @@ -139,21 +109,22 @@ class LoopbackResponse extends response_1.BaseResponse { } } exports.LoopbackResponse = LoopbackResponse; -exports.middleware = (ctx, next) => - __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new LoopbackRequest(ctx); - let response = new LoopbackResponse(ctx); - try { - let result = yield supertokens.middleware(request, response); - if (!result) { - return yield next(); - } - return; - } catch (err) { - return yield supertokens.errorHandler(err, request, response); +const middleware = (ctx, next) => __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new LoopbackRequest(ctx); + let response = new LoopbackResponse(ctx); + try { + let result = yield supertokens.middleware(request, response); + if (!result) { + return yield next(); } - }); + return; + } + catch (err) { + return yield supertokens.errorHandler(err, request, response); + } +}); +exports.middleware = middleware; exports.LoopbackWrapper = { middleware: exports.middleware, wrapRequest: (unwrapped) => { diff --git a/lib/build/framework/loopback/index.d.ts b/lib/build/framework/loopback/index.d.ts index 4074a2fd5..89ccde4f4 100644 --- a/lib/build/framework/loopback/index.d.ts +++ b/lib/build/framework/loopback/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export type { SessionContext } from "./framework"; export declare const middleware: import("@loopback/rest").Middleware; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; diff --git a/lib/build/framework/loopback/index.js b/lib/build/framework/loopback/index.js index e256494a9..ae5cb6ad4 100644 --- a/lib/build/framework/loopback/index.js +++ b/lib/build/framework/loopback/index.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapResponse = exports.wrapRequest = exports.middleware = void 0; const framework_1 = require("./framework"); exports.middleware = framework_1.LoopbackWrapper.middleware; exports.wrapRequest = framework_1.LoopbackWrapper.wrapRequest; diff --git a/lib/build/framework/request.d.ts b/lib/build/framework/request.d.ts index 17513cb35..a79bc1471 100644 --- a/lib/build/framework/request.d.ts +++ b/lib/build/framework/request.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { HTTPMethod } from "../types"; export declare abstract class BaseRequest { wrapperUsed: boolean; diff --git a/lib/build/framework/request.js b/lib/build/framework/request.js index b9a06bd23..d3d8773e6 100644 --- a/lib/build/framework/request.js +++ b/lib/build/framework/request.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseRequest = void 0; class BaseRequest { constructor() { this.wrapperUsed = true; diff --git a/lib/build/framework/response.d.ts b/lib/build/framework/response.d.ts index f09730a92..e12c992b2 100644 --- a/lib/build/framework/response.d.ts +++ b/lib/build/framework/response.d.ts @@ -1,19 +1,10 @@ -// @ts-nocheck export declare abstract class BaseResponse { wrapperUsed: boolean; original: any; constructor(); abstract setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; - abstract setCookie: ( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" - ) => void; + abstract removeHeader: (key: string) => void; + abstract setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; abstract setStatusCode: (statusCode: number) => void; abstract sendJSONResponse: (content: any) => void; abstract sendHTMLResponse: (html: string) => void; diff --git a/lib/build/framework/response.js b/lib/build/framework/response.js index de4701343..d634020ad 100644 --- a/lib/build/framework/response.js +++ b/lib/build/framework/response.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseResponse = void 0; class BaseResponse { constructor() { this.wrapperUsed = true; diff --git a/lib/build/framework/types.d.ts b/lib/build/framework/types.d.ts index f685b5e0a..392cc0142 100644 --- a/lib/build/framework/types.d.ts +++ b/lib/build/framework/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export declare type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda"; import { BaseRequest, BaseResponse } from "."; export declare let SchemaFramework: { diff --git a/lib/build/framework/types.js b/lib/build/framework/types.js index e3e7797ed..282217eef 100644 --- a/lib/build/framework/types.js +++ b/lib/build/framework/types.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.SchemaFramework = void 0; exports.SchemaFramework = { type: "string", enum: ["express", "fastify", "hapi", "loopback", "koa", "awsLambda"], diff --git a/lib/build/framework/utils.d.ts b/lib/build/framework/utils.d.ts index c9e1a80c1..a123f2507 100644 --- a/lib/build/framework/utils.d.ts +++ b/lib/build/framework/utils.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /// import type { Request, Response } from "express"; import type { IncomingMessage } from "http"; @@ -9,23 +8,13 @@ export declare function getCookieValueFromHeaders(headers: any, key: string): st export declare function getCookieValueFromIncomingMessage(request: IncomingMessage, key: string): string | undefined; export declare function getHeaderValueFromIncomingMessage(request: IncomingMessage, key: string): string | undefined; export declare function normalizeHeaderValue(value: string | string[] | undefined): string | undefined; -export declare function assertThatBodyParserHasBeenUsedForExpressLikeRequest( - method: HTTPMethod, - request: (Request | NextApiRequest) & { - __supertokensFromNextJS?: true; - } -): Promise; -export declare function assertFormDataBodyParserHasBeenUsedForExpressLikeRequest( - request: (Request | NextApiRequest) & { - __supertokensFromNextJS?: true; - } -): Promise; -export declare function setHeaderForExpressLikeResponse( - res: Response, - key: string, - value: string, - allowDuplicateKey: boolean -): void; +export declare function assertThatBodyParserHasBeenUsedForExpressLikeRequest(method: HTTPMethod, request: (Request | NextApiRequest) & { + __supertokensFromNextJS?: true; +}): Promise; +export declare function assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(request: (Request | NextApiRequest) & { + __supertokensFromNextJS?: true; +}): Promise; +export declare function setHeaderForExpressLikeResponse(res: Response, key: string, value: string, allowDuplicateKey: boolean): void; /** * * @param res @@ -37,29 +26,6 @@ export declare function setHeaderForExpressLikeResponse( * @param expires * @param path */ -export declare function setCookieForServerResponse( - res: ServerResponse, - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" -): ServerResponse; -export declare function getCookieValueToSetInHeader( - prev: string | string[] | undefined, - val: string | string[], - key: string -): string | string[]; -export declare function serializeCookieValue( - key: string, - value: string, - domain: string | undefined, - secure: boolean, - httpOnly: boolean, - expires: number, - path: string, - sameSite: "strict" | "lax" | "none" -): string; +export declare function setCookieForServerResponse(res: ServerResponse, key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none"): ServerResponse; +export declare function getCookieValueToSetInHeader(prev: string | string[] | undefined, val: string | string[], key: string): string | string[]; +export declare function serializeCookieValue(key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none"): string; diff --git a/lib/build/framework/utils.js b/lib/build/framework/utils.js index 159e2d2b4..d7ca91bd3 100644 --- a/lib/build/framework/utils.js +++ b/lib/build/framework/utils.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.serializeCookieValue = exports.getCookieValueToSetInHeader = exports.setCookieForServerResponse = exports.setHeaderForExpressLikeResponse = exports.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest = exports.assertThatBodyParserHasBeenUsedForExpressLikeRequest = exports.normalizeHeaderValue = exports.getHeaderValueFromIncomingMessage = exports.getCookieValueFromIncomingMessage = exports.getCookieValueFromHeaders = void 0; const cookie_1 = require("cookie"); const body_parser_1 = require("body-parser"); const http_1 = require("http"); @@ -98,7 +77,8 @@ function JSONCookie(str) { } try { return JSON.parse(str.slice(2)); - } catch (err) { + } + catch (err) { return undefined; } } @@ -129,21 +109,22 @@ function assertThatBodyParserHasBeenUsedForExpressLikeRequest(method, request) { if (typeof request.body === "string") { try { request.body = JSON.parse(request.body); - } catch (err) { + } + catch (err) { if (request.body === "") { request.body = {}; - } else { + } + else { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, message: "API input error: Please make sure to pass a valid JSON input in the request body", }); } } - } else if ( - request.body === undefined || + } + else if (request.body === undefined || Buffer.isBuffer(request.body) || - Object.keys(request.body).length === 0 - ) { + Object.keys(request.body).length === 0) { // parsing it again to make sure that the request is parsed atleast once by a json parser let jsonParser = body_parser_1.json(); let err = yield new Promise((resolve) => { @@ -179,7 +160,8 @@ function assertThatBodyParserHasBeenUsedForExpressLikeRequest(method, request) { }); } } - } else if (method === "delete" || method === "get") { + } + else if (method === "delete" || method === "get") { if (request.query === undefined) { let parser = body_parser_1.urlencoded({ extended: true }); let err = yield new Promise((resolve) => parser(request, new http_1.ServerResponse(request), resolve)); @@ -240,24 +222,30 @@ function setHeaderForExpressLikeResponse(res, key, value, allowDuplicateKey) { if (existingValue === undefined) { if (res.header !== undefined) { res.header(key, value); - } else { + } + else { res.setHeader(key, value); } - } else if (allowDuplicateKey) { + } + else if (allowDuplicateKey) { if (res.header !== undefined) { res.header(key, existingValue + ", " + value); - } else { + } + else { res.setHeader(key, existingValue + ", " + value); } - } else { + } + else { // we overwrite the current one with the new one if (res.header !== undefined) { res.header(key, value); - } else { + } + else { res.setHeader(key, value); } } - } catch (err) { + } + catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } } @@ -274,12 +262,7 @@ exports.setHeaderForExpressLikeResponse = setHeaderForExpressLikeResponse; * @param path */ function setCookieForServerResponse(res, key, value, domain, secure, httpOnly, expires, path, sameSite) { - return appendToServerResponse( - res, - constants_1.COOKIE_HEADER, - serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite), - key - ); + return appendToServerResponse(res, constants_1.COOKIE_HEADER, serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite), key); } exports.setCookieForServerResponse = setCookieForServerResponse; /** @@ -311,7 +294,8 @@ function getCookieValueToSetInHeader(prev, val, key) { } } prev = removedDuplicate; - } else { + } + else { if (prev.startsWith(key)) { prev = undefined; } diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index 2868b27a1..798130e35 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; import { User } from "./types"; @@ -29,43 +28,28 @@ export default class SuperTokensWrapper { externalUserId: string; externalUserIdInfo?: string; force?: boolean; - }): Promise< - | { - status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; - } - | { - status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; - doesSuperTokensUserIdExist: boolean; - doesExternalUserIdExist: boolean; - } - >; - static getUserForRecipeId( - userId: string, - recipeId: string - ): Promise<{ + }): Promise<{ + status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; + } | { + status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; + doesSuperTokensUserIdExist: boolean; + doesExternalUserIdExist: boolean; + }>; + static getUserForRecipeId(userId: string, recipeId: string): Promise<{ user: import("./recipe/accountlinking/types").RecipeLevelUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; + recipe: "emailpassword" | "thirdparty" | "passwordless" | "thirdpartyemailpassword" | "thirdpartypasswordless" | undefined; }>; static getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; - }): Promise< - | { - status: "OK"; - superTokensUserId: string; - externalUserId: string; - externalUserIdInfo: string | undefined; - } - | { - status: "UNKNOWN_MAPPING_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + superTokensUserId: string; + externalUserId: string; + externalUserIdInfo: string | undefined; + } | { + status: "UNKNOWN_MAPPING_ERROR"; + }>; static deleteUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; @@ -84,11 +68,7 @@ export default class SuperTokensWrapper { static getUser(userId: string, userContext?: any): Promise; static listUsersByAccountInfo(info: AccountInfo, userContext?: any): Promise; static getUserByAccountInfo(info: AccountInfoWithRecipeId, userContext?: any): Promise; - static deleteUser( - userId: string, - removeAllLinkedAccounts?: boolean, - userContext?: any - ): Promise<{ + static deleteUser(userId: string, removeAllLinkedAccounts?: boolean, userContext?: any): Promise<{ status: "OK"; }>; } diff --git a/lib/build/index.js b/lib/build/index.js index f7a35dd5c..d5ddbddf2 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.Error = exports.getUserForRecipeId = exports.getUserByAccountInfo = exports.listUsersByAccountInfo = exports.getUser = exports.updateOrDeleteUserIdMappingInfo = exports.deleteUserIdMapping = exports.getUserIdMapping = exports.createUserIdMapping = exports.deleteUser = exports.getUsersNewestFirst = exports.getUsersOldestFirst = exports.getUserCount = exports.getAllCORSHeaders = exports.init = void 0; const supertokens_1 = require("./supertokens"); const error_1 = require("./error"); const recipe_1 = require("./recipe/accountlinking/recipe"); @@ -57,18 +36,10 @@ class SuperTokensWrapper { return supertokens_1.default.getInstanceOrThrowError().getUserCount(includeRecipeIds); } static getUsersOldestFirst(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getUsers( - Object.assign(Object.assign({ timeJoinedOrder: "ASC" }, input), { userContext: undefined }) - ); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsers(Object.assign(Object.assign({ timeJoinedOrder: "ASC" }, input), { userContext: undefined })); } static getUsersNewestFirst(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getUsers( - Object.assign(Object.assign({ timeJoinedOrder: "DESC" }, input), { userContext: undefined }) - ); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsers(Object.assign(Object.assign({ timeJoinedOrder: "DESC" }, input), { userContext: undefined })); } static createUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().createUserIdMapping(input); diff --git a/lib/build/ingredients/emaildelivery/index.d.ts b/lib/build/ingredients/emaildelivery/index.d.ts index bfa1e8fd9..d5e16f685 100644 --- a/lib/build/ingredients/emaildelivery/index.d.ts +++ b/lib/build/ingredients/emaildelivery/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeInputWithService, EmailDeliveryInterface } from "./types"; export default class EmailDelivery { ingredientInterfaceImpl: EmailDeliveryInterface; diff --git a/lib/build/ingredients/emaildelivery/services/smtp.d.ts b/lib/build/ingredients/emaildelivery/services/smtp.d.ts index 43a3c5437..a9c836077 100644 --- a/lib/build/ingredients/emaildelivery/services/smtp.d.ts +++ b/lib/build/ingredients/emaildelivery/services/smtp.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export interface SMTPServiceConfig { host: string; @@ -22,11 +21,9 @@ export declare type TypeInputSendRawEmail = GetContentResult & { }; export declare type ServiceInterface = { sendRawEmail: (input: TypeInputSendRawEmail) => Promise; - getContent: ( - input: T & { - userContext: any; - } - ) => Promise; + getContent: (input: T & { + userContext: any; + }) => Promise; }; export declare type TypeInput = { smtpSettings: SMTPServiceConfig; diff --git a/lib/build/ingredients/emaildelivery/types.d.ts b/lib/build/ingredients/emaildelivery/types.d.ts index 494e9f4cd..60ed3c5dd 100644 --- a/lib/build/ingredients/emaildelivery/types.d.ts +++ b/lib/build/ingredients/emaildelivery/types.d.ts @@ -1,26 +1,17 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export declare type EmailDeliveryInterface = { - sendEmail: ( - input: T & { - userContext: any; - } - ) => Promise; + sendEmail: (input: T & { + userContext: any; + }) => Promise; }; /** * config class parameter when parent Recipe create a new EmailDeliveryIngredient object via constructor */ export interface TypeInput { service?: EmailDeliveryInterface; - override?: ( - originalImplementation: EmailDeliveryInterface, - builder: OverrideableBuilder> - ) => EmailDeliveryInterface; + override?: (originalImplementation: EmailDeliveryInterface, builder: OverrideableBuilder>) => EmailDeliveryInterface; } export interface TypeInputWithService { service: EmailDeliveryInterface; - override?: ( - originalImplementation: EmailDeliveryInterface, - builder: OverrideableBuilder> - ) => EmailDeliveryInterface; + override?: (originalImplementation: EmailDeliveryInterface, builder: OverrideableBuilder>) => EmailDeliveryInterface; } diff --git a/lib/build/ingredients/smsdelivery/index.d.ts b/lib/build/ingredients/smsdelivery/index.d.ts index 80e9f60a6..e04656804 100644 --- a/lib/build/ingredients/smsdelivery/index.d.ts +++ b/lib/build/ingredients/smsdelivery/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeInputWithService, SmsDeliveryInterface } from "./types"; export default class SmsDelivery { ingredientInterfaceImpl: SmsDeliveryInterface; diff --git a/lib/build/ingredients/smsdelivery/services/supertokens.d.ts b/lib/build/ingredients/smsdelivery/services/supertokens.d.ts index 1196903bb..16a0f1990 100644 --- a/lib/build/ingredients/smsdelivery/services/supertokens.d.ts +++ b/lib/build/ingredients/smsdelivery/services/supertokens.d.ts @@ -1,2 +1 @@ -// @ts-nocheck export declare const SUPERTOKENS_SMS_SERVICE_URL = "https://api.supertokens.com/0/services/sms"; diff --git a/lib/build/ingredients/smsdelivery/services/supertokens.js b/lib/build/ingredients/smsdelivery/services/supertokens.js index 094cb3d44..2689f25fb 100644 --- a/lib/build/ingredients/smsdelivery/services/supertokens.js +++ b/lib/build/ingredients/smsdelivery/services/supertokens.js @@ -14,4 +14,5 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.SUPERTOKENS_SMS_SERVICE_URL = void 0; exports.SUPERTOKENS_SMS_SERVICE_URL = "https://api.supertokens.com/0/services/sms"; diff --git a/lib/build/ingredients/smsdelivery/services/twilio.d.ts b/lib/build/ingredients/smsdelivery/services/twilio.d.ts index 25f19db7e..c912ca866 100644 --- a/lib/build/ingredients/smsdelivery/services/twilio.d.ts +++ b/lib/build/ingredients/smsdelivery/services/twilio.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import * as Twilio from "twilio"; /** @@ -9,40 +8,33 @@ import * as Twilio from "twilio"; * if none of "from" and "messagingServiceSid" is passed, error * should be thrown. */ -export declare type TwilioServiceConfig = - | { - accountSid: string; - authToken: string; - from: string; - opts?: Twilio.Twilio.TwilioClientOptions; - } - | { - accountSid: string; - authToken: string; - messagingServiceSid: string; - opts?: Twilio.Twilio.TwilioClientOptions; - }; +export declare type TwilioServiceConfig = { + accountSid: string; + authToken: string; + from: string; + opts?: Twilio.Twilio.TwilioClientOptions; +} | { + accountSid: string; + authToken: string; + messagingServiceSid: string; + opts?: Twilio.Twilio.TwilioClientOptions; +}; export interface GetContentResult { body: string; toPhoneNumber: string; } export declare type TypeInputSendRawSms = GetContentResult & { userContext: any; -} & ( - | { - from: string; - } - | { - messagingServiceSid: string; - } - ); +} & ({ + from: string; +} | { + messagingServiceSid: string; +}); export declare type ServiceInterface = { sendRawSms: (input: TypeInputSendRawSms) => Promise; - getContent: ( - input: T & { - userContext: any; - } - ) => Promise; + getContent: (input: T & { + userContext: any; + }) => Promise; }; export declare type TypeInput = { twilioSettings: TwilioServiceConfig; diff --git a/lib/build/ingredients/smsdelivery/services/twilio.js b/lib/build/ingredients/smsdelivery/services/twilio.js index 6e42adbab..05b97a999 100644 --- a/lib/build/ingredients/smsdelivery/services/twilio.js +++ b/lib/build/ingredients/smsdelivery/services/twilio.js @@ -1,13 +1,11 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.normaliseUserInputConfig = void 0; function normaliseUserInputConfig(input) { let from = "from" in input.twilioSettings ? input.twilioSettings.from : undefined; - let messagingServiceSid = - "messagingServiceSid" in input.twilioSettings ? input.twilioSettings.messagingServiceSid : undefined; - if ( - (from === undefined && messagingServiceSid === undefined) || - (from !== undefined && messagingServiceSid !== undefined) - ) { + let messagingServiceSid = "messagingServiceSid" in input.twilioSettings ? input.twilioSettings.messagingServiceSid : undefined; + if ((from === undefined && messagingServiceSid === undefined) || + (from !== undefined && messagingServiceSid !== undefined)) { throw Error(`Please pass exactly one of "from" and "messagingServiceSid" config for twilioSettings.`); } return input; diff --git a/lib/build/ingredients/smsdelivery/types.d.ts b/lib/build/ingredients/smsdelivery/types.d.ts index f45dc8f2a..2c658feff 100644 --- a/lib/build/ingredients/smsdelivery/types.d.ts +++ b/lib/build/ingredients/smsdelivery/types.d.ts @@ -1,26 +1,17 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export declare type SmsDeliveryInterface = { - sendSms: ( - input: T & { - userContext: any; - } - ) => Promise; + sendSms: (input: T & { + userContext: any; + }) => Promise; }; /** * config class parameter when parent Recipe create a new SmsDeliveryIngredient object via constructor */ export interface TypeInput { service?: SmsDeliveryInterface; - override?: ( - originalImplementation: SmsDeliveryInterface, - builder: OverrideableBuilder> - ) => SmsDeliveryInterface; + override?: (originalImplementation: SmsDeliveryInterface, builder: OverrideableBuilder>) => SmsDeliveryInterface; } export interface TypeInputWithService { service: SmsDeliveryInterface; - override?: ( - originalImplementation: SmsDeliveryInterface, - builder: OverrideableBuilder> - ) => SmsDeliveryInterface; + override?: (originalImplementation: SmsDeliveryInterface, builder: OverrideableBuilder>) => SmsDeliveryInterface; } diff --git a/lib/build/logger.d.ts b/lib/build/logger.d.ts index 1a3a6aef6..3edf34fdc 100644 --- a/lib/build/logger.d.ts +++ b/lib/build/logger.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck declare function logDebugMessage(message: string): void; export { logDebugMessage }; diff --git a/lib/build/logger.js b/lib/build/logger.js index 510a2cad8..885ace0d6 100644 --- a/lib/build/logger.js +++ b/lib/build/logger.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.logDebugMessage = void 0; const debug_1 = require("debug"); const version_1 = require("./version"); const SUPERTOKENS_DEBUG_NAMESPACE = "com.supertokens"; @@ -23,11 +24,7 @@ const SUPERTOKENS_DEBUG_NAMESPACE = "com.supertokens"; */ function logDebugMessage(message) { if (debug_1.default.enabled(SUPERTOKENS_DEBUG_NAMESPACE)) { - debug_1.default(SUPERTOKENS_DEBUG_NAMESPACE)( - `{t: "${new Date().toISOString()}", message: \"${message}\", file: \"${getFileLocation()}\" sdkVer: "${ - version_1.version - }"}` - ); + debug_1.default(SUPERTOKENS_DEBUG_NAMESPACE)(`{t: "${new Date().toISOString()}", message: \"${message}\", file: \"${getFileLocation()}\" sdkVer: "${version_1.version}"}`); console.log(); } } diff --git a/lib/build/nextjs.d.ts b/lib/build/nextjs.d.ts index 195a81422..d9474bda9 100644 --- a/lib/build/nextjs.d.ts +++ b/lib/build/nextjs.d.ts @@ -1,9 +1,4 @@ -// @ts-nocheck export default class NextJS { - static superTokensNextWrapper( - middleware: (next: (middlewareError?: any) => void) => Promise, - request: any, - response: any - ): Promise; + static superTokensNextWrapper(middleware: (next: (middlewareError?: any) => void) => Promise, request: any, response: any): Promise; } export declare let superTokensNextWrapper: typeof NextJS.superTokensNextWrapper; diff --git a/lib/build/nextjs.js b/lib/build/nextjs.js index ee4696402..ac3313c21 100644 --- a/lib/build/nextjs.js +++ b/lib/build/nextjs.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.superTokensNextWrapper = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -64,28 +43,27 @@ function next(request, response, resolve, reject) { class NextJS { static superTokensNextWrapper(middleware, request, response) { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => - __awaiter(this, void 0, void 0, function* () { - request.__supertokensFromNextJS = true; - try { - let callbackCalled = false; - const result = yield middleware((err) => { - callbackCalled = true; - next(request, response, resolve, reject)(err); - }); - if (!callbackCalled && !response.finished && !response.headersSent) { - return resolve(result); - } - } catch (err) { - yield express_1.errorHandler()(err, request, response, (errorHandlerError) => { - if (errorHandlerError !== undefined) { - return reject(errorHandlerError); - } - // do nothing, error handler does not resolve the promise. - }); + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + request.__supertokensFromNextJS = true; + try { + let callbackCalled = false; + const result = yield middleware((err) => { + callbackCalled = true; + next(request, response, resolve, reject)(err); + }); + if (!callbackCalled && !response.finished && !response.headersSent) { + return resolve(result); } - }) - ); + } + catch (err) { + yield express_1.errorHandler()(err, request, response, (errorHandlerError) => { + if (errorHandlerError !== undefined) { + return reject(errorHandlerError); + } + // do nothing, error handler does not resolve the promise. + }); + } + })); }); } } diff --git a/lib/build/normalisedURLDomain.d.ts b/lib/build/normalisedURLDomain.d.ts index b75c15d4b..a5ad011c6 100644 --- a/lib/build/normalisedURLDomain.d.ts +++ b/lib/build/normalisedURLDomain.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export default class NormalisedURLDomain { private value; constructor(url: string); diff --git a/lib/build/normalisedURLDomain.js b/lib/build/normalisedURLDomain.js index e4a69f7f8..2bc9d05aa 100644 --- a/lib/build/normalisedURLDomain.js +++ b/lib/build/normalisedURLDomain.js @@ -35,14 +35,17 @@ function normaliseURLDomainOrThrowError(input, ignoreProtocol = false) { if (ignoreProtocol) { if (urlObj.hostname.startsWith("localhost") || utils_1.isAnIpAddress(urlObj.hostname)) { input = "http://" + urlObj.host; - } else { + } + else { input = "https://" + urlObj.host; } - } else { + } + else { input = urlObj.protocol + "//" + urlObj.host; } return input; - } catch (err) {} + } + catch (err) { } // not a valid URL if (input.startsWith("/")) { throw Error("Please provide a valid domain name"); @@ -52,17 +55,16 @@ function normaliseURLDomainOrThrowError(input, ignoreProtocol = false) { } // If the input contains a . it means they have given a domain name. // So we try assuming that they have given a domain name - if ( - (input.indexOf(".") !== -1 || input.startsWith("localhost")) && + if ((input.indexOf(".") !== -1 || input.startsWith("localhost")) && !input.startsWith("http://") && - !input.startsWith("https://") - ) { + !input.startsWith("https://")) { input = "https://" + input; // at this point, it should be a valid URL. So we test that before doing a recursive call try { new url_1.URL(input); return normaliseURLDomainOrThrowError(input, true); - } catch (err) {} + } + catch (err) { } } throw Error("Please provide a valid domain name"); } diff --git a/lib/build/normalisedURLPath.d.ts b/lib/build/normalisedURLPath.d.ts index db7787bb4..41e4ee331 100644 --- a/lib/build/normalisedURLPath.d.ts +++ b/lib/build/normalisedURLPath.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export default class NormalisedURLPath { private value; constructor(url: string); diff --git a/lib/build/normalisedURLPath.js b/lib/build/normalisedURLPath.js index c254d8349..3c724145f 100644 --- a/lib/build/normalisedURLPath.js +++ b/lib/build/normalisedURLPath.js @@ -48,15 +48,14 @@ function normaliseURLPathOrThrowError(input) { return input.substr(0, input.length - 1); } return input; - } catch (err) {} + } + catch (err) { } // not a valid URL // If the input contains a . it means they have given a domain name. // So we try assuming that they have given a domain name + path - if ( - (domainGiven(input) || input.startsWith("localhost")) && + if ((domainGiven(input) || input.startsWith("localhost")) && !input.startsWith("http://") && - !input.startsWith("https://") - ) { + !input.startsWith("https://")) { input = "http://" + input; return normaliseURLPathOrThrowError(input); } @@ -68,7 +67,8 @@ function normaliseURLPathOrThrowError(input) { // test that we can convert this to prevent an infinite loop new url_1.URL("http://example.com" + input); return normaliseURLPathOrThrowError("http://example.com" + input); - } catch (err) { + } + catch (err) { throw Error("Please provide a valid URL path"); } } @@ -80,10 +80,12 @@ function domainGiven(input) { try { let url = new url_1.URL(input); return url.hostname.indexOf(".") !== -1; - } catch (ignored) {} + } + catch (ignored) { } try { let url = new url_1.URL("http://" + input); return url.hostname.indexOf(".") !== -1; - } catch (ignored) {} + } + catch (ignored) { } return false; } diff --git a/lib/build/postSuperTokensInitCallbacks.d.ts b/lib/build/postSuperTokensInitCallbacks.d.ts index 6eef30adb..7a16d1e20 100644 --- a/lib/build/postSuperTokensInitCallbacks.d.ts +++ b/lib/build/postSuperTokensInitCallbacks.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export declare class PostSuperTokensInitCallbacks { static postInitCallbacks: (() => void)[]; static addPostInitCallback(cb: () => void): void; diff --git a/lib/build/postSuperTokensInitCallbacks.js b/lib/build/postSuperTokensInitCallbacks.js index 8a4b10406..a58af9157 100644 --- a/lib/build/postSuperTokensInitCallbacks.js +++ b/lib/build/postSuperTokensInitCallbacks.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.PostSuperTokensInitCallbacks = void 0; class PostSuperTokensInitCallbacks { static addPostInitCallback(cb) { PostSuperTokensInitCallbacks.postInitCallbacks.push(cb); diff --git a/lib/build/processState.d.ts b/lib/build/processState.d.ts index aa2d9a2a8..cfbe2e5ed 100644 --- a/lib/build/processState.d.ts +++ b/lib/build/processState.d.ts @@ -1,9 +1,8 @@ -// @ts-nocheck export declare enum PROCESS_STATE { CALLING_SERVICE_IN_VERIFY = 0, CALLING_SERVICE_IN_GET_HANDSHAKE_INFO = 1, CALLING_SERVICE_IN_GET_API_VERSION = 2, - CALLING_SERVICE_IN_REQUEST_HELPER = 3, + CALLING_SERVICE_IN_REQUEST_HELPER = 3 } export declare class ProcessState { history: PROCESS_STATE[]; diff --git a/lib/build/processState.js b/lib/build/processState.js index 76a6ccc76..8df0d20df 100644 --- a/lib/build/processState.js +++ b/lib/build/processState.js @@ -13,46 +13,24 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProcessState = exports.PROCESS_STATE = void 0; var PROCESS_STATE; (function (PROCESS_STATE) { - PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_VERIFY"] = 0)] = "CALLING_SERVICE_IN_VERIFY"; - PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"] = 1)] = - "CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"; - PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_GET_API_VERSION"] = 2)] = "CALLING_SERVICE_IN_GET_API_VERSION"; - PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_REQUEST_HELPER"] = 3)] = "CALLING_SERVICE_IN_REQUEST_HELPER"; -})((PROCESS_STATE = exports.PROCESS_STATE || (exports.PROCESS_STATE = {}))); + PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_VERIFY"] = 0] = "CALLING_SERVICE_IN_VERIFY"; + PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"] = 1] = "CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"; + PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_GET_API_VERSION"] = 2] = "CALLING_SERVICE_IN_GET_API_VERSION"; + PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_REQUEST_HELPER"] = 3] = "CALLING_SERVICE_IN_REQUEST_HELPER"; +})(PROCESS_STATE = exports.PROCESS_STATE || (exports.PROCESS_STATE = {})); class ProcessState { constructor() { this.history = []; @@ -72,26 +50,27 @@ class ProcessState { this.reset = () => { this.history = []; }; - this.waitForEvent = (state, timeInMS = 7000) => - __awaiter(this, void 0, void 0, function* () { - let startTime = Date.now(); - return new Promise((resolve) => { - let actualThis = this; - function tryAndGet() { - let result = actualThis.getEventByLastEventByName(state); - if (result === undefined) { - if (Date.now() - startTime > timeInMS) { - resolve(undefined); - } else { - setTimeout(tryAndGet, 1000); - } - } else { - resolve(result); + this.waitForEvent = (state, timeInMS = 7000) => __awaiter(this, void 0, void 0, function* () { + let startTime = Date.now(); + return new Promise((resolve) => { + let actualThis = this; + function tryAndGet() { + let result = actualThis.getEventByLastEventByName(state); + if (result === undefined) { + if (Date.now() - startTime > timeInMS) { + resolve(undefined); + } + else { + setTimeout(tryAndGet, 1000); } } - tryAndGet(); - }); + else { + resolve(result); + } + } + tryAndGet(); }); + }); } static getInstance() { if (ProcessState.instance === undefined) { diff --git a/lib/build/querier.d.ts b/lib/build/querier.d.ts index 791b32e0a..378421357 100644 --- a/lib/build/querier.d.ts +++ b/lib/build/querier.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import NormalisedURLDomain from "./normalisedURLDomain"; import NormalisedURLPath from "./normalisedURLPath"; export declare class Querier { @@ -15,13 +14,10 @@ export declare class Querier { static reset(): void; getHostsAliveForTesting: () => Set; static getNewInstanceOrThrowError(rIdToCore?: string): Querier; - static init( - hosts?: { - domain: NormalisedURLDomain; - basePath: NormalisedURLPath; - }[], - apiKey?: string - ): void; + static init(hosts?: { + domain: NormalisedURLDomain; + basePath: NormalisedURLPath; + }[], apiKey?: string): void; sendPostRequest: (path: NormalisedURLPath, body: any) => Promise; sendDeleteRequest: (path: NormalisedURLPath, body: any) => Promise; sendGetRequest: (path: NormalisedURLPath, params: any) => Promise; diff --git a/lib/build/querier.js b/lib/build/querier.js index c43215a3d..afc0b3c1b 100644 --- a/lib/build/querier.js +++ b/lib/build/querier.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.Querier = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -54,44 +33,31 @@ class Querier { // we have rIdToCore so that recipes can force change the rId sent to core. This is a hack until the core is able // to support multiple rIds per API constructor(hosts, rIdToCore) { - this.getAPIVersion = () => - __awaiter(this, void 0, void 0, function* () { - var _a; - if (Querier.apiVersion !== undefined) { - return Querier.apiVersion; - } - processState_1.ProcessState.getInstance().addState( - processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_API_VERSION - ); - let response = yield this.sendRequestHelper( - new normalisedURLPath_1.default("/apiversion"), - "GET", - (url) => { - let headers = {}; - if (Querier.apiKey !== undefined) { - headers = { - "api-key": Querier.apiKey, - }; - } - return axios_1.default.get(url, { - headers, - }); - }, - ((_a = this.__hosts) === null || _a === void 0 ? void 0 : _a.length) || 0 - ); - let cdiSupportedByServer = response.versions; - let supportedVersion = utils_1.getLargestVersionFromIntersection( - cdiSupportedByServer, - version_1.cdiSupported - ); - if (supportedVersion === undefined) { - throw Error( - "The running SuperTokens core version is not compatible with this NodeJS SDK. Please visit https://supertokens.io/docs/community/compatibility to find the right versions" - ); - } - Querier.apiVersion = supportedVersion; + this.getAPIVersion = () => __awaiter(this, void 0, void 0, function* () { + var _a; + if (Querier.apiVersion !== undefined) { return Querier.apiVersion; - }); + } + processState_1.ProcessState.getInstance().addState(processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_API_VERSION); + let response = yield this.sendRequestHelper(new normalisedURLPath_1.default("/apiversion"), "GET", (url) => { + let headers = {}; + if (Querier.apiKey !== undefined) { + headers = { + "api-key": Querier.apiKey, + }; + } + return axios_1.default.get(url, { + headers, + }); + }, ((_a = this.__hosts) === null || _a === void 0 ? void 0 : _a.length) || 0); + let cdiSupportedByServer = response.versions; + let supportedVersion = utils_1.getLargestVersionFromIntersection(cdiSupportedByServer, version_1.cdiSupported); + if (supportedVersion === undefined) { + throw Error("The running SuperTokens core version is not compatible with this NodeJS SDK. Please visit https://supertokens.io/docs/community/compatibility to find the right versions"); + } + Querier.apiVersion = supportedVersion; + return Querier.apiVersion; + }); this.getHostsAliveForTesting = () => { if (process.env.TEST_MODE !== "testing") { throw Error("calling testing function in non testing env"); @@ -99,171 +65,128 @@ class Querier { return Querier.hostsAliveForTesting; }; // path should start with "/" - this.sendPostRequest = (path, body) => - __awaiter(this, void 0, void 0, function* () { - var _b; - return this.sendRequestHelper( - path, - "POST", - (url) => - __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { - "cdi-version": apiVersion, - "content-type": "application/json; charset=utf-8", - }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default({ - method: "POST", - url, - data: body, - headers, - }); - }), - ((_b = this.__hosts) === null || _b === void 0 ? void 0 : _b.length) || 0 - ); - }); + this.sendPostRequest = (path, body) => __awaiter(this, void 0, void 0, function* () { + var _b; + return this.sendRequestHelper(path, "POST", (url) => __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { + "cdi-version": apiVersion, + "content-type": "application/json; charset=utf-8", + }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default({ + method: "POST", + url, + data: body, + headers, + }); + }), ((_b = this.__hosts) === null || _b === void 0 ? void 0 : _b.length) || 0); + }); // path should start with "/" - this.sendDeleteRequest = (path, body) => - __awaiter(this, void 0, void 0, function* () { - var _c; - return this.sendRequestHelper( - path, - "DELETE", - (url) => - __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { "cdi-version": apiVersion }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { - "api-key": Querier.apiKey, - "content-type": "application/json; charset=utf-8", - }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default({ - method: "DELETE", - url, - data: body, - headers, - }); - }), - ((_c = this.__hosts) === null || _c === void 0 ? void 0 : _c.length) || 0 - ); - }); + this.sendDeleteRequest = (path, body) => __awaiter(this, void 0, void 0, function* () { + var _c; + return this.sendRequestHelper(path, "DELETE", (url) => __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { "cdi-version": apiVersion }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey, "content-type": "application/json; charset=utf-8" }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default({ + method: "DELETE", + url, + data: body, + headers, + }); + }), ((_c = this.__hosts) === null || _c === void 0 ? void 0 : _c.length) || 0); + }); // path should start with "/" - this.sendGetRequest = (path, params) => - __awaiter(this, void 0, void 0, function* () { - var _d; - return this.sendRequestHelper( - path, - "GET", - (url) => - __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { "cdi-version": apiVersion }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default.get(url, { - params, - headers, - }); - }), - ((_d = this.__hosts) === null || _d === void 0 ? void 0 : _d.length) || 0 - ); - }); + this.sendGetRequest = (path, params) => __awaiter(this, void 0, void 0, function* () { + var _d; + return this.sendRequestHelper(path, "GET", (url) => __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { "cdi-version": apiVersion }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default.get(url, { + params, + headers, + }); + }), ((_d = this.__hosts) === null || _d === void 0 ? void 0 : _d.length) || 0); + }); // path should start with "/" - this.sendPutRequest = (path, body) => - __awaiter(this, void 0, void 0, function* () { - var _e; - return this.sendRequestHelper( - path, - "PUT", - (url) => - __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { - "cdi-version": apiVersion, - "content-type": "application/json; charset=utf-8", - }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default({ - method: "PUT", - url, - data: body, - headers, - }); - }), - ((_e = this.__hosts) === null || _e === void 0 ? void 0 : _e.length) || 0 - ); - }); + this.sendPutRequest = (path, body) => __awaiter(this, void 0, void 0, function* () { + var _e; + return this.sendRequestHelper(path, "PUT", (url) => __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { "cdi-version": apiVersion, "content-type": "application/json; charset=utf-8" }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default({ + method: "PUT", + url, + data: body, + headers, + }); + }), ((_e = this.__hosts) === null || _e === void 0 ? void 0 : _e.length) || 0); + }); // path should start with "/" - this.sendRequestHelper = (path, method, axiosFunction, numberOfTries) => - __awaiter(this, void 0, void 0, function* () { - if (this.__hosts === undefined) { - throw Error( - "No SuperTokens core available to query. Please pass supertokens > connectionURI to the init function, or override all the functions of the recipe you are using." - ); + this.sendRequestHelper = (path, method, axiosFunction, numberOfTries) => __awaiter(this, void 0, void 0, function* () { + if (this.__hosts === undefined) { + throw Error("No SuperTokens core available to query. Please pass supertokens > connectionURI to the init function, or override all the functions of the recipe you are using."); + } + if (numberOfTries === 0) { + throw Error("No SuperTokens core available to query"); + } + let currentDomain = this.__hosts[Querier.lastTriedIndex].domain.getAsStringDangerous(); + let currentBasePath = this.__hosts[Querier.lastTriedIndex].basePath.getAsStringDangerous(); + Querier.lastTriedIndex++; + Querier.lastTriedIndex = Querier.lastTriedIndex % this.__hosts.length; + try { + processState_1.ProcessState.getInstance().addState(processState_1.PROCESS_STATE.CALLING_SERVICE_IN_REQUEST_HELPER); + let response = yield axiosFunction(currentDomain + currentBasePath + path.getAsStringDangerous()); + if (process.env.TEST_MODE === "testing") { + Querier.hostsAliveForTesting.add(currentDomain + currentBasePath); + } + if (response.status !== 200) { + throw response; } - if (numberOfTries === 0) { - throw Error("No SuperTokens core available to query"); + return response.data; + } + catch (err) { + if (err.message !== undefined && err.message.includes("ECONNREFUSED")) { + return yield this.sendRequestHelper(path, method, axiosFunction, numberOfTries - 1); + } + if (err.response !== undefined && err.response.status !== undefined && err.response.data !== undefined) { + throw new Error("SuperTokens core threw an error for a " + + method + + " request to path: '" + + path.getAsStringDangerous() + + "' with status code: " + + err.response.status + + " and message: " + + err.response.data); } - let currentDomain = this.__hosts[Querier.lastTriedIndex].domain.getAsStringDangerous(); - let currentBasePath = this.__hosts[Querier.lastTriedIndex].basePath.getAsStringDangerous(); - Querier.lastTriedIndex++; - Querier.lastTriedIndex = Querier.lastTriedIndex % this.__hosts.length; - try { - processState_1.ProcessState.getInstance().addState( - processState_1.PROCESS_STATE.CALLING_SERVICE_IN_REQUEST_HELPER - ); - let response = yield axiosFunction(currentDomain + currentBasePath + path.getAsStringDangerous()); - if (process.env.TEST_MODE === "testing") { - Querier.hostsAliveForTesting.add(currentDomain + currentBasePath); - } - if (response.status !== 200) { - throw response; - } - return response.data; - } catch (err) { - if (err.message !== undefined && err.message.includes("ECONNREFUSED")) { - return yield this.sendRequestHelper(path, method, axiosFunction, numberOfTries - 1); - } - if ( - err.response !== undefined && - err.response.status !== undefined && - err.response.data !== undefined - ) { - throw new Error( - "SuperTokens core threw an error for a " + - method + - " request to path: '" + - path.getAsStringDangerous() + - "' with status code: " + - err.response.status + - " and message: " + - err.response.data - ); - } else { - throw err; - } + else { + throw err; } - }); + } + }); this.__hosts = hosts; this.rIdToCore = rIdToCore; } diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 9dc6815df..e10968cc4 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,189 +1,96 @@ -// @ts-nocheck import { SessionContainer } from "../session"; import Recipe from "./recipe"; import type { AccountInfoAndEmailWithRecipeId, RecipeInterface, RecipeLevelUser } from "./types"; import type { User } from "../../types"; export default class Wrapper { static init: typeof Recipe.init; - static getRecipeUserIdsForPrimaryUserIds( - primaryUserIds: string[], - userContext?: any - ): Promise<{ + static getRecipeUserIdsForPrimaryUserIds(primaryUserIds: string[], userContext?: any): Promise<{ [primaryUserId: string]: string[]; }>; - static getPrimaryUserIdsforRecipeUserIds( - recipeUserIds: string[], - userContext?: any - ): Promise<{ + static getPrimaryUserIdsforRecipeUserIds(recipeUserIds: string[], userContext?: any): Promise<{ [recipeUserId: string]: string | null; }>; - static addNewRecipeUserIdWithoutPrimaryUserId( - recipeUserId: string, - recipeId: string, - timeJoined: number, - userContext?: any - ): Promise<{ + static addNewRecipeUserIdWithoutPrimaryUserId(recipeUserId: string, recipeId: string, timeJoined: number, userContext?: any): Promise<{ status: "OK"; createdNewEntry: boolean; }>; - static canCreatePrimaryUserId( - recipeUserId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - } - | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; - static createPrimaryUser( - recipeUserId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - user: User; - } - | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; - static canLinkAccounts( - recipeUserId: string, - primaryUserId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } - | { - status: "ACCOUNTS_ALREADY_LINKED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; - static linkAccounts( - recipeUserId: string, - primaryUserId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNTS_ALREADY_LINKED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; - static unlinkAccounts( - recipeUserId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - wasRecipeUserDeleted: boolean; - } - | { - status: "NO_PRIMARY_USER_FOUND"; - } - >; - static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId( - recipeUserId: string, - userContext?: any - ): Promise; + static canCreatePrimaryUserId(recipeUserId: string, userContext?: any): Promise<{ + status: "OK"; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; + static createPrimaryUser(recipeUserId: string, userContext?: any): Promise<{ + status: "OK"; + user: User; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; + static canLinkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any): Promise<{ + status: "OK"; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; + static linkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any): Promise<{ + status: "OK"; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; + static unlinkAccounts(recipeUserId: string, userContext?: any): Promise<{ + status: "OK"; + wasRecipeUserDeleted: boolean; + } | { + status: "NO_PRIMARY_USER_FOUND"; + }>; + static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId(recipeUserId: string, userContext?: any): Promise; static isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any): Promise; - static doPostSignUpAccountLinkingOperations( - info: AccountInfoAndEmailWithRecipeId, - infoVerified: boolean, - recipeUserId: string, - userContext: any - ): Promise; - static accountLinkPostSignInViaSession( - session: SessionContainer, - info: AccountInfoAndEmailWithRecipeId, - infoVerified: boolean, - userContext: any - ): Promise< - | { - createRecipeUser: true; - updateVerificationClaim: boolean; - } - | ({ - createRecipeUser: false; - } & { - accountsLinked: true; - updateVerificationClaim: boolean; - }) - | ({ - createRecipeUser: false; - } & { - accountsLinked: false; - reason: - | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" - | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" - | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; - }) - | ({ - createRecipeUser: false; - } & { - accountsLinked: false; - reason: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - }) - >; - static createPrimaryUserIdOrLinkAccounts( - recipeUserId: string, - session: SessionContainer | undefined, - userContext?: any - ): Promise; + static doPostSignUpAccountLinkingOperations(info: AccountInfoAndEmailWithRecipeId, infoVerified: boolean, recipeUserId: string, userContext: any): Promise; + static accountLinkPostSignInViaSession(session: SessionContainer, info: AccountInfoAndEmailWithRecipeId, infoVerified: boolean, userContext: any): Promise<{ + createRecipeUser: true; + updateVerificationClaim: boolean; + } | ({ + createRecipeUser: false; + } & ({ + accountsLinked: true; + updateVerificationClaim: boolean; + } | { + accountsLinked: false; + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + } | { + accountsLinked: false; + reason: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + }))>; + static createPrimaryUserIdOrLinkAccounts(recipeUserId: string, session: SessionContainer | undefined, userContext?: any): Promise; static onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any): Promise; - static shouldDoAutomaticAccountLinking( - newAccountInfo: AccountInfoAndEmailWithRecipeId, - user: User | undefined, - session: SessionContainer | undefined, - userContext?: any - ): Promise< - | { - shouldAutomaticallyLink: false; - } - | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - } - >; - static getIdentitiesForUser( - user: User - ): { + static shouldDoAutomaticAccountLinking(newAccountInfo: AccountInfoAndEmailWithRecipeId, user: User | undefined, session: SessionContainer | undefined, userContext?: any): Promise<{ + shouldAutomaticallyLink: false; + } | { + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + }>; + static getIdentitiesForUser(user: User): { verified: { emails: string[]; phoneNumbers: string[]; @@ -202,11 +109,7 @@ export default class Wrapper { }; }; static fetchFromAccountToLinkTable(recipeUserId: string, userContext?: any): Promise; - static storeIntoAccountToLinkTable( - recipeUserId: string, - primaryUserId: string, - userContext?: any - ): Promise<{ + static storeIntoAccountToLinkTable(recipeUserId: string, primaryUserId: string, userContext?: any): Promise<{ status: "OK"; }>; } diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index a46dc88d6..dde211c37 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -13,70 +13,43 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.storeIntoAccountToLinkTable = exports.fetchFromAccountToLinkTable = exports.getIdentitiesForUser = exports.shouldDoAutomaticAccountLinking = exports.onAccountLinked = exports.createPrimaryUserIdOrLinkAccounts = exports.accountLinkPostSignInViaSession = exports.doPostSignUpAccountLinkingOperations = exports.isSignUpAllowed = exports.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = exports.unlinkAccounts = exports.linkAccounts = exports.canLinkAccounts = exports.createPrimaryUser = exports.canCreatePrimaryUserId = exports.addNewRecipeUserIdWithoutPrimaryUserId = exports.getPrimaryUserIdsforRecipeUserIds = exports.getRecipeUserIdsForPrimaryUserIds = exports.init = void 0; const recipe_1 = require("./recipe"); class Wrapper { static getRecipeUserIdsForPrimaryUserIds(primaryUserIds, userContext) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getRecipeUserIdsForPrimaryUserIds({ - primaryUserIds, - userContext: userContext === undefined ? {} : userContext, - }); + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getRecipeUserIdsForPrimaryUserIds({ + primaryUserIds, + userContext: userContext === undefined ? {} : userContext, + }); }); } static getPrimaryUserIdsforRecipeUserIds(recipeUserIds, userContext) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ - recipeUserIds, - userContext: userContext === undefined ? {} : userContext, - }); + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ + recipeUserIds, + userContext: userContext === undefined ? {} : userContext, + }); }); } static addNewRecipeUserIdWithoutPrimaryUserId(recipeUserId, recipeId, timeJoined, userContext) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.addNewRecipeUserIdWithoutPrimaryUserId({ - recipeUserId, - recipeId, - timeJoined, - userContext: userContext === undefined ? {} : userContext, - }); + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.addNewRecipeUserIdWithoutPrimaryUserId({ + recipeUserId, + recipeId, + timeJoined, + userContext: userContext === undefined ? {} : userContext, + }); }); } static canCreatePrimaryUserId(recipeUserId, userContext) { @@ -169,17 +142,13 @@ class Wrapper { static onAccountLinked(user, newAccountInfo, userContext) { return __awaiter(this, void 0, void 0, function* () { userContext = userContext === undefined ? {} : userContext; - return yield recipe_1.default - .getInstanceOrThrowError() - .config.onAccountLinked(user, newAccountInfo, userContext); + return yield recipe_1.default.getInstanceOrThrowError().config.onAccountLinked(user, newAccountInfo, userContext); }); } static shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext) { return __awaiter(this, void 0, void 0, function* () { userContext = userContext === undefined ? {} : userContext; - return yield recipe_1.default - .getInstanceOrThrowError() - .config.shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext); + return yield recipe_1.default.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext); }); } static getIdentitiesForUser(user) { @@ -188,17 +157,20 @@ class Wrapper { static fetchFromAccountToLinkTable(recipeUserId, userContext) { return __awaiter(this, void 0, void 0, function* () { userContext = userContext === undefined ? {} : userContext; - return yield recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.fetchFromAccountToLinkTable({ + recipeUserId, + userContext, + }); }); } static storeIntoAccountToLinkTable(recipeUserId, primaryUserId, userContext) { return __awaiter(this, void 0, void 0, function* () { userContext = userContext === undefined ? {} : userContext; - return yield recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.storeIntoAccountToLinkTable({ recipeUserId, primaryUserId, userContext }); + return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.storeIntoAccountToLinkTable({ + recipeUserId, + primaryUserId, + userContext, + }); }); } } diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 94357d75f..a29475081 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; @@ -15,19 +14,11 @@ export default class Recipe extends RecipeModule { static init(config: TypeInput): RecipeListFunction; static getInstanceOrThrowError(): Recipe; getAPIsHandled(): APIHandled[]; - handleAPIRequest( - _id: string, - _req: BaseRequest, - _response: BaseResponse, - _path: normalisedURLPath, - _method: HTTPMethod - ): Promise; + handleAPIRequest(_id: string, _req: BaseRequest, _response: BaseResponse, _path: normalisedURLPath, _method: HTTPMethod): Promise; handleError(error: error, _request: BaseRequest, _response: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; - getIdentitiesForUser: ( - user: User - ) => { + getIdentitiesForUser: (user: User) => { verified: { emails: string[]; phoneNumbers: string[]; @@ -45,76 +36,42 @@ export default class Recipe extends RecipeModule { }[]; }; }; - isSignUpAllowed: ({ - info, - userContext, - }: { + isSignUpAllowed: ({ info, userContext, }: { info: AccountInfoAndEmailWithRecipeId; userContext: any; }) => Promise; - doPostSignUpAccountLinkingOperations: ({ - info, - infoVerified, - recipeUserId, - userContext, - }: { + doPostSignUpAccountLinkingOperations: ({ info, infoVerified, recipeUserId, userContext, }: { info: AccountInfoAndEmailWithRecipeId; infoVerified: boolean; recipeUserId: string; userContext: any; }) => Promise; - accountLinkPostSignInViaSession: ({ - session, - info, - infoVerified, - userContext, - }: { + accountLinkPostSignInViaSession: ({ session, info, infoVerified, userContext, }: { session: SessionContainer; info: AccountInfoAndEmailWithRecipeId; infoVerified: boolean; userContext: any; - }) => Promise< - | { - createRecipeUser: true; - updateVerificationClaim: boolean; - } - | ({ - createRecipeUser: false; - } & { - accountsLinked: true; - updateVerificationClaim: boolean; - }) - | ({ - createRecipeUser: false; - } & { - accountsLinked: false; - reason: - | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" - | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" - | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; - }) - | ({ - createRecipeUser: false; - } & { - accountsLinked: false; - reason: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - }) - >; - getPrimaryUserIdThatCanBeLinkedToRecipeUserId: ({ - recipeUserId, - userContext, - }: { + }) => Promise<{ + createRecipeUser: true; + updateVerificationClaim: boolean; + } | ({ + createRecipeUser: false; + } & ({ + accountsLinked: true; + updateVerificationClaim: boolean; + } | { + accountsLinked: false; + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + } | { + accountsLinked: false; + reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + }))>; + getPrimaryUserIdThatCanBeLinkedToRecipeUserId: ({ recipeUserId, userContext, }: { recipeUserId: string; userContext: any; }) => Promise; - createPrimaryUserIdOrLinkAccounts: ({ - recipeUserId, - session, - userContext, - }: { + createPrimaryUserIdOrLinkAccounts: ({ recipeUserId, session, userContext, }: { recipeUserId: string; session: SessionContainer | undefined; userContext: any; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index d7a7515e1..8829edbcc 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); const utils_1 = require("./utils"); @@ -73,244 +51,160 @@ class Recipe extends recipeModule_1.default { if (loginMethod.email !== undefined) { if (loginMethod.verified) { identities.verified.emails.push(loginMethod.email); - } else { + } + else { identities.unverified.emails.push(loginMethod.email); } } if (loginMethod.phoneNumber !== undefined) { if (loginMethod.verified) { identities.verified.phoneNumbers.push(loginMethod.phoneNumber); - } else { + } + else { identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); } } if (loginMethod.thirdParty !== undefined) { if (loginMethod.verified) { identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); - } else { + } + else { identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); } } } return identities; }; - this.isSignUpAllowed = ({ info, userContext }) => - __awaiter(this, void 0, void 0, function* () { - let identifier; - if (info.email !== undefined) { - identifier = { - email: info.email, - }; - } else if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, - }; - } else { - throw Error("this error should never be thrown"); - } - let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, - userContext, - }); - if (users === undefined || users.length === 0) { - return true; - } - let primaryUser = users.find((u) => u.isPrimaryUser); - if (primaryUser === undefined) { - return true; - } - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, - primaryUser, - undefined, - userContext - ); - let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink - ? shouldDoAccountLinking.shouldRequireVerification - : false; - if (!shouldRequireVerification) { - return true; - } - let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); - if (info.email !== undefined) { - return identitiesForPrimaryUser.verified.emails.includes(info.email); - } - if (info.phoneNumber !== undefined) { - return identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber); - } - throw Error("it should never reach here"); + this.isSignUpAllowed = ({ info, userContext, }) => __awaiter(this, void 0, void 0, function* () { + let identifier; + if (info.email !== undefined) { + identifier = { + email: info.email, + }; + } + else if (info.phoneNumber !== undefined) { + identifier = { + phoneNumber: info.phoneNumber, + }; + } + else { + throw Error("this error should never be thrown"); + } + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: identifier, + userContext, }); - this.doPostSignUpAccountLinkingOperations = ({ info, infoVerified, recipeUserId, userContext }) => - __awaiter(this, void 0, void 0, function* () { - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, - undefined, - undefined, - userContext - ); - if ( - shouldDoAccountLinking.shouldAutomaticallyLink && - shouldDoAccountLinking.shouldRequireVerification - ) { - if (!infoVerified) { - return recipeUserId; - } - } - let canCreatePrimaryUserId = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId, - userContext, - }); - if (canCreatePrimaryUserId) { - let user = yield this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId, - userContext, - }); - if (user.status !== "OK") { - throw Error("should never come here. Error from createPrimaryUser: " + user.status); - } - return user.user.id; - } - let identifier; - if (info.email !== undefined) { - identifier = { - email: info.email, - }; - } else if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, - }; - } else { - throw Error("this error should never be thrown"); - } - let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, - userContext, - }); - if (users === undefined || users.length === 0) { - throw Error("this error should never be thrown"); - } - let primaryUser = users.find((u) => u.isPrimaryUser); - if (primaryUser === undefined) { - throw Error("this error should never be thrown"); - } - shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, - primaryUser, - undefined, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + if (users === undefined || users.length === 0) { + return true; + } + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser === undefined) { + return true; + } + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(info, primaryUser, undefined, userContext); + let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink + ? shouldDoAccountLinking.shouldRequireVerification + : false; + if (!shouldRequireVerification) { + return true; + } + let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); + if (info.email !== undefined) { + return identitiesForPrimaryUser.verified.emails.includes(info.email); + } + if (info.phoneNumber !== undefined) { + return identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber); + } + throw Error("it should never reach here"); + }); + this.doPostSignUpAccountLinkingOperations = ({ info, infoVerified, recipeUserId, userContext, }) => __awaiter(this, void 0, void 0, function* () { + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(info, undefined, undefined, userContext); + if (shouldDoAccountLinking.shouldAutomaticallyLink && shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { return recipeUserId; } - let result = yield this.recipeInterfaceImpl.linkAccounts({ + } + let canCreatePrimaryUserId = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId, + userContext, + }); + if (canCreatePrimaryUserId) { + let user = yield this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId, - primaryUserId: primaryUser.id, userContext, }); - if (result.status !== "OK") { - throw Error("this error status shouldn't not be thrown. Error" + result.status); + if (user.status !== "OK") { + throw Error("should never come here. Error from createPrimaryUser: " + user.status); } - return primaryUser.id; + return user.user.id; + } + let identifier; + if (info.email !== undefined) { + identifier = { + email: info.email, + }; + } + else if (info.phoneNumber !== undefined) { + identifier = { + phoneNumber: info.phoneNumber, + }; + } + else { + throw Error("this error should never be thrown"); + } + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: identifier, + userContext, }); - this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => - __awaiter(this, void 0, void 0, function* () { - let userId = session.getUserId(); - let user = yield this.recipeInterfaceImpl.getUser({ - userId, - userContext, - }); - if (user === undefined) { - throw Error("this should not be thrown"); + if (users === undefined || users.length === 0) { + throw Error("this error should never be thrown"); + } + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser === undefined) { + throw Error("this error should never be thrown"); + } + shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(info, primaryUser, undefined, userContext); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } + let result = yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId, + primaryUserId: primaryUser.id, + userContext, + }); + if (result.status !== "OK") { + throw Error("this error status shouldn't not be thrown. Error" + result.status); + } + return primaryUser.id; + }); + this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext, }) => __awaiter(this, void 0, void 0, function* () { + let userId = session.getUserId(); + let user = yield this.recipeInterfaceImpl.getUser({ + userId, + userContext, + }); + if (user === undefined) { + throw Error("this should not be thrown"); + } + /** + * checking if the user with existing session + * is a primary user or not + */ + if (!user.isPrimaryUser) { + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(info, undefined, session, userContext); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + }; } - /** - * checking if the user with existing session - * is a primary user or not - */ - if (!user.isPrimaryUser) { - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, - undefined, - session, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - }; - } - let recipeId = user.loginMethods[0].recipeId; - let recipeUser = yield __1.getUserForRecipeId(user.id, recipeId); - if (recipeUser.user === undefined) { - throw Error( - "This error should never be thrown. Check for bug in `getUserForRecipeId` function" - ); - } - shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - recipeUser.user, - undefined, - session, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - }; - } - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!user.loginMethods[0].verified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } - } - /** - * checking if primary user can be created for the existing recipe user - */ - let canCreatePrimaryUser = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId: user.id, - userContext, - }); - if (canCreatePrimaryUser.status !== "OK") { - return { - createRecipeUser: false, - accountsLinked: false, - reason: canCreatePrimaryUser.status, - primaryUserId: canCreatePrimaryUser.primaryUserId, - }; - } - /** - * creating primary user for the recipe user - */ - let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId: user.id, - userContext, - }); - if (createPrimaryUserResult.status !== "OK") { - return { - createRecipeUser: false, - accountsLinked: false, - reason: createPrimaryUserResult.status, - primaryUserId: createPrimaryUserResult.primaryUserId, - }; - } - user = createPrimaryUserResult.user; + let recipeId = user.loginMethods[0].recipeId; + let recipeUser = yield __1.getUserForRecipeId(user.id, recipeId); + if (recipeUser.user === undefined) { + throw Error("This error should never be thrown. Check for bug in `getUserForRecipeId` function"); } - /** - * checking if account linking is allowed for given primary user - * and new login info - */ - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, - user, - session, - userContext - ); + shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(recipeUser.user, undefined, session, userContext); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return { createRecipeUser: false, @@ -318,295 +212,335 @@ class Recipe extends recipeModule_1.default { reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!user.loginMethods[0].verified) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; + } + } /** - * checking if a recipe user already exists for the given - * login info + * checking if primary user can be created for the existing recipe user */ - let recipeInfo; - if (info.recipeId === "emailpassword" && info.email !== undefined) { - recipeInfo = { - recipeId: "emailpassword", - email: info.email, - }; - } else if (info.recipeId === "thirdparty" && info.thirdParty !== undefined) { - recipeInfo = { - recipeId: "thirdparty", - thirdpartyId: info.thirdParty.id, - thirdpartyUserId: info.thirdParty.userId, - }; - } else if (info.recipeId === "passwordless" && info.email !== undefined) { - recipeInfo = { - recipeId: "passwordless", - email: info.email, - }; - } else if (info.recipeId === "passwordless" && info.phoneNumber !== undefined) { - recipeInfo = { - recipeId: "passwordless", - phoneNumber: info.phoneNumber, - }; - } else { - throw Error("this error should never be thrown"); - } - let recipeUser = yield this.recipeInterfaceImpl.getUserByAccountInfo({ - info: recipeInfo, + let canCreatePrimaryUser = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId: user.id, userContext, }); - if (recipeUser === undefined) { - /** - * if recipe user doesn't exists, we check if - * any of the identifying info associated with - * the primary user equals to the identifying info - * of the given input. If so, return createRecipeUser - * as true to let the recipe know that a recipe user needs - * to be created and set updateVerificationClaim to false - * so the recipe will call back this function when the - * recipe user is created - */ - let identitiesForPrimaryUser = this.getIdentitiesForUser(user); - if (info.email !== undefined) { - let result = - identitiesForPrimaryUser.verified.emails.includes(info.email) || - identitiesForPrimaryUser.unverified.emails.includes(info.email); - if (result) { - return { - createRecipeUser: true, - updateVerificationClaim: false, - }; - } - } - if (info.phoneNumber !== undefined) { - let result = - identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || - identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); - if (result) { - return { - createRecipeUser: true, - updateVerificationClaim: false, - }; - } - } - /** - * checking if there already exists any other primary - * user which is associated with the identifying info - * for the given input - */ - let existingRecipeUserForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: recipeInfo, - userContext, - }); - if (existingRecipeUserForInputInfo !== undefined) { - let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); - if (primaryUserIfExists !== undefined) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: primaryUserIfExists.id, - }; - } - } - /** - * if the existing info is not verified, we do want - * to create a recipe user but don't want recipe - * to again callback this function for any further - * linking part. Instead, we want the recipe to - * update the session claim so it can be known that - * the new account needs to be verified. so, return - * createRecipeUser as true to let the recipe know - * that a recipe user needs to be created and set - * updateVerificationClaim to true so the recipe will - * not call back this function and update the session - * claim instead - */ - if (!infoVerified) { - if (shouldDoAccountLinking.shouldRequireVerification) { - return { - createRecipeUser: true, - updateVerificationClaim: true, - }; - } - } + if (canCreatePrimaryUser.status !== "OK") { return { - createRecipeUser: true, - updateVerificationClaim: false, + createRecipeUser: false, + accountsLinked: false, + reason: canCreatePrimaryUser.status, + primaryUserId: canCreatePrimaryUser.primaryUserId, }; } /** - * checking if th primary user (associated with session) - * and recipe user (associated with login info) can be - * linked + * creating primary user for the recipe user */ - let canLinkAccounts = yield this.recipeInterfaceImpl.canLinkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, + let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: user.id, userContext, }); - if (canLinkAccounts.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { - return { - createRecipeUser: false, - accountsLinked: true, - updateVerificationClaim: false, - }; - } - if (canLinkAccounts.status !== "OK") { + if (createPrimaryUserResult.status !== "OK") { return { createRecipeUser: false, accountsLinked: false, - reason: canLinkAccounts.status, - primaryUserId: canLinkAccounts.primaryUserId, + reason: createPrimaryUserResult.status, + primaryUserId: createPrimaryUserResult.primaryUserId, }; } + user = createPrimaryUserResult.user; + } + /** + * checking if account linking is allowed for given primary user + * and new login info + */ + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(info, user, session, userContext); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + }; + } + /** + * checking if a recipe user already exists for the given + * login info + */ + let recipeInfo; + if (info.recipeId === "emailpassword" && info.email !== undefined) { + recipeInfo = { + recipeId: "emailpassword", + email: info.email, + }; + } + else if (info.recipeId === "thirdparty" && info.thirdParty !== undefined) { + recipeInfo = { + recipeId: "thirdparty", + thirdpartyId: info.thirdParty.id, + thirdpartyUserId: info.thirdParty.userId, + }; + } + else if (info.recipeId === "passwordless" && info.email !== undefined) { + recipeInfo = { + recipeId: "passwordless", + email: info.email, + }; + } + else if (info.recipeId === "passwordless" && info.phoneNumber !== undefined) { + recipeInfo = { + recipeId: "passwordless", + phoneNumber: info.phoneNumber, + }; + } + else { + throw Error("this error should never be thrown"); + } + let recipeUser = yield this.recipeInterfaceImpl.getUserByAccountInfo({ + info: recipeInfo, + userContext, + }); + if (recipeUser === undefined) { + /** + * if recipe user doesn't exists, we check if + * any of the identifying info associated with + * the primary user equals to the identifying info + * of the given input. If so, return createRecipeUser + * as true to let the recipe know that a recipe user needs + * to be created and set updateVerificationClaim to false + * so the recipe will call back this function when the + * recipe user is created + */ let identitiesForPrimaryUser = this.getIdentitiesForUser(user); - let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; if (info.email !== undefined) { - recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = - identitiesForPrimaryUser.verified.emails.includes(info.email) || + let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || identitiesForPrimaryUser.unverified.emails.includes(info.email); + if (result) { + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } } - if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { - recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = - identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || + if (info.phoneNumber !== undefined) { + let result = identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); - } - if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { - /** - * TODO: let's Ly belongs to P1 such that Ly equal to Lx. - * if LY verified, mark Lx as verified. If Lx is verfied, - * then mark all Ly as verified - */ - } else { - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } + if (result) { + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; } } - yield this.recipeInterfaceImpl.linkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, + /** + * checking if there already exists any other primary + * user which is associated with the identifying info + * for the given input + */ + let existingRecipeUserForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: recipeInfo, userContext, }); + if (existingRecipeUserForInputInfo !== undefined) { + let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); + if (primaryUserIfExists !== undefined) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUserIfExists.id, + }; + } + } + /** + * if the existing info is not verified, we do want + * to create a recipe user but don't want recipe + * to again callback this function for any further + * linking part. Instead, we want the recipe to + * update the session claim so it can be known that + * the new account needs to be verified. so, return + * createRecipeUser as true to let the recipe know + * that a recipe user needs to be created and set + * updateVerificationClaim to true so the recipe will + * not call back this function and update the session + * claim instead + */ + if (!infoVerified) { + if (shouldDoAccountLinking.shouldRequireVerification) { + return { + createRecipeUser: true, + updateVerificationClaim: true, + }; + } + } + return { + createRecipeUser: true, + updateVerificationClaim: false, + }; + } + /** + * checking if th primary user (associated with session) + * and recipe user (associated with login info) can be + * linked + */ + let canLinkAccounts = yield this.recipeInterfaceImpl.canLinkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); + if (canLinkAccounts.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { return { createRecipeUser: false, accountsLinked: true, - updateVerificationClaim: true, + updateVerificationClaim: false, + }; + } + if (canLinkAccounts.status !== "OK") { + return { + createRecipeUser: false, + accountsLinked: false, + reason: canLinkAccounts.status, + primaryUserId: canLinkAccounts.primaryUserId, + }; + } + let identitiesForPrimaryUser = this.getIdentitiesForUser(user); + let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; + if (info.email !== undefined) { + recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = + identitiesForPrimaryUser.verified.emails.includes(info.email) || + identitiesForPrimaryUser.unverified.emails.includes(info.email); + } + if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { + recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = + identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || + identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + } + if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { + /** + * TODO: let's Ly belongs to P1 such that Ly equal to Lx. + * if LY verified, mark Lx as verified. If Lx is verfied, + * then mark all Ly as verified + */ + } + else { + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; + } + } + } + yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUser.id, + primaryUserId: user.id, + userContext, + }); + return { + createRecipeUser: false, + accountsLinked: true, + updateVerificationClaim: true, + }; + }); + this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId = ({ recipeUserId, userContext, }) => __awaiter(this, void 0, void 0, function* () { + let user = yield __1.getUser(recipeUserId, userContext); + if (user === undefined) { + return undefined; + } + if (user.isPrimaryUser) { + return user; + } + let pUser = yield this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); + if (pUser !== undefined && pUser.isPrimaryUser) { + return pUser; + } + let identifier; + let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array + if (loginMethodInfo.email !== undefined) { + identifier = { + email: loginMethodInfo.email, + }; + } + else if (loginMethodInfo.phoneNumber !== undefined) { + identifier = { + phoneNumber: loginMethodInfo.phoneNumber, }; + } + else { + throw Error("this error should never be thrown"); + } + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: identifier, + userContext, + }); + if (users === undefined || users.length === 0) { + return undefined; + } + return users.find((u) => u.isPrimaryUser); + }); + this.createPrimaryUserIdOrLinkAccounts = ({ recipeUserId, session, userContext, }) => __awaiter(this, void 0, void 0, function* () { + let primaryUser = yield this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ + recipeUserId, + userContext, }); - this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId = ({ recipeUserId, userContext }) => - __awaiter(this, void 0, void 0, function* () { + if (primaryUser === undefined) { let user = yield __1.getUser(recipeUserId, userContext); - if (user === undefined) { - return undefined; - } - if (user.isPrimaryUser) { - return user; - } - let pUser = yield this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); - if (pUser !== undefined && pUser.isPrimaryUser) { - return pUser; - } - let identifier; - let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array - if (loginMethodInfo.email !== undefined) { - identifier = { - email: loginMethodInfo.email, - }; - } else if (loginMethodInfo.phoneNumber !== undefined) { - identifier = { - phoneNumber: loginMethodInfo.phoneNumber, - }; - } else { + if (user === undefined || user.isPrimaryUser) { throw Error("this error should never be thrown"); } - let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, - userContext, - }); - if (users === undefined || users.length === 0) { - return undefined; + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(Object.assign({}, user.loginMethods[0]), undefined, session, userContext); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { + yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: recipeUserId, + userContext, + }); + // TODO: remove session claim } - return users.find((u) => u.isPrimaryUser); - }); - this.createPrimaryUserIdOrLinkAccounts = ({ recipeUserId, session, userContext }) => - __awaiter(this, void 0, void 0, function* () { - let primaryUser = yield this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ - recipeUserId, - userContext, - }); - if (primaryUser === undefined) { + } + else { + /** + * recipeUser already linked with primaryUser + */ + let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); + if (recipeUser === undefined) { let user = yield __1.getUser(recipeUserId, userContext); if (user === undefined || user.isPrimaryUser) { throw Error("this error should never be thrown"); } - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - Object.assign({}, user.loginMethods[0]), - undefined, - session, - userContext - ); + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(Object.assign({}, user.loginMethods[0]), primaryUser, session, userContext); if (shouldDoAccountLinking.shouldAutomaticallyLink) { - yield this.recipeInterfaceImpl.createPrimaryUser({ + let linkAccountsResult = yield this.recipeInterfaceImpl.linkAccounts({ recipeUserId: recipeUserId, + primaryUserId: primaryUser.id, userContext, }); - // TODO: remove session claim - } - } else { - /** - * recipeUser already linked with primaryUser - */ - let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); - if (recipeUser === undefined) { - let user = yield __1.getUser(recipeUserId, userContext); - if (user === undefined || user.isPrimaryUser) { - throw Error("this error should never be thrown"); - } - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - Object.assign({}, user.loginMethods[0]), - primaryUser, - session, - userContext - ); - if (shouldDoAccountLinking.shouldAutomaticallyLink) { - let linkAccountsResult = yield this.recipeInterfaceImpl.linkAccounts({ - recipeUserId: recipeUserId, - primaryUserId: primaryUser.id, - userContext, - }); - if (linkAccountsResult.status === "OK") { - // TODO: remove session claim if session claim exists - // else create a new session - } + if (linkAccountsResult.status === "OK") { + // TODO: remove session claim if session claim exists + // else create a new session } } } - }); + } + }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config)); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } } static init(config) { return (appInfo) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe( - Recipe.RECIPE_ID, - appInfo, - config, - {}, - { - emailDelivery: undefined, - } - ); + Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, config, {}, { + emailDelivery: undefined, + }); return Recipe.instance; - } else { + } + else { throw new Error("AccountLinking recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.d.ts b/lib/build/recipe/accountlinking/recipeImplementation.d.ts index 7e4369ba3..9b5e6e73e 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.d.ts +++ b/lib/build/recipe/accountlinking/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface, TypeNormalisedInput } from "./types"; import { Querier } from "../../querier"; export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 8c9036891..9abd26ea5 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -13,66 +13,38 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); const session_1 = require("../session"); const __1 = require("../.."); function getRecipeImplementation(querier, config) { return { - getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { + getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds, }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/users"), - { - primaryUserIds: primaryUserIds.join(","), - } - ); + let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { + primaryUserIds: primaryUserIds.join(","), + }); return result.userIdMapping; }); }, - getPrimaryUserIdsforRecipeUserIds: function ({ recipeUserIds }) { + getPrimaryUserIdsforRecipeUserIds: function ({ recipeUserIds, }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/users"), - { - recipeUserIds: recipeUserIds.join(","), - } - ); + let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { + recipeUserIds: recipeUserIds.join(","), + }); return result.userIdMapping; }); }, - addNewRecipeUserIdWithoutPrimaryUserId: function ({ recipeUserId, recipeId, timeJoined }) { + addNewRecipeUserIdWithoutPrimaryUserId: function ({ recipeUserId, recipeId, timeJoined, }) { return __awaiter(this, void 0, void 0, function* () { return querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user"), { recipeUserId, @@ -81,7 +53,7 @@ function getRecipeImplementation(querier, config) { }); }); }, - getUsers: function ({ timeJoinedOrder, limit, paginationToken, includeRecipeIds }) { + getUsers: function ({ timeJoinedOrder, limit, paginationToken, includeRecipeIds, }) { return __awaiter(this, void 0, void 0, function* () { let includeRecipeIdsStr = undefined; if (includeRecipeIds !== undefined) { @@ -99,7 +71,7 @@ function getRecipeImplementation(querier, config) { }; }); }, - canCreatePrimaryUserId: function ({ recipeUserId, userContext }) { + canCreatePrimaryUserId: function ({ recipeUserId, userContext, }) { return __awaiter(this, void 0, void 0, function* () { /** * getting map of recipeUserIds to primaryUserIds @@ -183,8 +155,7 @@ function getRecipeImplementation(querier, config) { return { status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", primaryUserId: primaryUser.id, - description: - "Account info related to recipe user is already linked with another primary user id", + description: "Account info related to recipe user is already linked with another primary user id", }; } /** @@ -196,7 +167,7 @@ function getRecipeImplementation(querier, config) { }; }); }, - createPrimaryUser: function ({ recipeUserId, userContext }) { + createPrimaryUser: function ({ recipeUserId, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ recipeUserId, @@ -205,19 +176,16 @@ function getRecipeImplementation(querier, config) { if (canCreatePrimaryUser.status !== "OK") { return canCreatePrimaryUser; } - let primaryUser = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), - { - recipeUserId, - } - ); + let primaryUser = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), { + recipeUserId, + }); if (!primaryUser.user.isPrimaryUser) { throw Error("creating primaryUser for recipeUser failed in core"); } return primaryUser; }); }, - canLinkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { + canLinkAccounts: function ({ recipeUserId, primaryUserId, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let primaryUser = yield this.getUser({ userId: primaryUserId, @@ -252,16 +220,14 @@ function getRecipeImplementation(querier, config) { return { status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", description: "recipeUserId already associated with another primaryUserId", - primaryUserId: recipeUser.id, + primaryUserId: recipeUser.id, // this is actually the primary user ID cause isPrimaryUser is true }; } let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ recipeUserId, userContext, }); - if ( - canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - ) { + if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { if (canCreatePrimaryUser.primaryUserId === primaryUserId) { return { status: "ACCOUNTS_ALREADY_LINKED_ERROR", @@ -289,7 +255,7 @@ function getRecipeImplementation(querier, config) { }; }); }, - linkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { + linkAccounts: function ({ recipeUserId, primaryUserId, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let canLinkAccountsResult = yield this.canLinkAccounts({ recipeUserId, @@ -299,13 +265,10 @@ function getRecipeImplementation(querier, config) { if (canLinkAccountsResult.status !== "OK") { return canLinkAccountsResult; } - let accountsLinkingResult = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), - { - recipeUserId, - primaryUserId, - } - ); + let accountsLinkingResult = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), { + recipeUserId, + primaryUserId, + }); if (accountsLinkingResult.status === "OK") { yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); let user = yield this.getUser({ @@ -319,21 +282,19 @@ function getRecipeImplementation(querier, config) { if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = yield __1.getUserForRecipeId( - loginMethodInfo.recipeUserId, - loginMethodInfo.recipeId - ); + let recipeUser = yield __1.getUserForRecipeId(loginMethodInfo.recipeUserId, loginMethodInfo.recipeId); if (recipeUser.user === undefined) { throw Error("this error should never be thrown"); } yield config.onAccountLinked(user, recipeUser.user, userContext); - } else { + } + else { throw Error(`error thrown from core while linking accounts: ${accountsLinkingResult.status}`); } return accountsLinkingResult; }); }, - unlinkAccounts: function ({ recipeUserId, userContext }) { + unlinkAccounts: function ({ recipeUserId, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsforRecipeUserIds({ recipeUserIds: [recipeUserId], @@ -369,16 +330,14 @@ function getRecipeImplementation(querier, config) { }; } } - let accountsUnlinkingResult = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/unlink"), - { - recipeUserId, - primaryUserId, - } - ); + let accountsUnlinkingResult = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/unlink"), { + recipeUserId, + primaryUserId, + }); if (accountsUnlinkingResult.status === "OK") { yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); - } else { + } + else { throw Error(`error thrown from core while unlinking accounts: ${accountsUnlinkingResult.status}`); } return { @@ -389,12 +348,9 @@ function getRecipeImplementation(querier, config) { }, getUser: function ({ userId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user"), - { - userId, - } - ); + let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user"), { + userId, + }); if (result.status === "OK") { return result.user; } @@ -403,10 +359,7 @@ function getRecipeImplementation(querier, config) { }, listUsersByAccountInfo: function ({ info }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/users/accountinfo"), - Object.assign({}, info) - ); + let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users/accountinfo"), Object.assign({}, info)); if (result.status === "OK") { return result.users; } @@ -415,17 +368,14 @@ function getRecipeImplementation(querier, config) { }, getUserByAccountInfo: function ({ info }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/users/accountinfo"), - Object.assign({}, info) - ); + let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users/accountinfo"), Object.assign({}, info)); if (result.status === "OK") { return result.users[0]; } return undefined; }); }, - deleteUser: function ({ userId, removeAllLinkedAccounts, userContext }) { + deleteUser: function ({ userId, removeAllLinkedAccounts, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let user = yield this.getUser({ userId, userContext }); if (user === undefined) { @@ -439,7 +389,8 @@ function getRecipeImplementation(querier, config) { */ if (removeAllLinkedAccounts) { recipeUsersToRemove = user.loginMethods; - } else { + } + else { recipeUsersToRemove = user.loginMethods.filter((u) => u.recipeUserId === userId); } for (let i = 0; i < recipeUsersToRemove.length; i++) { @@ -458,26 +409,20 @@ function getRecipeImplementation(querier, config) { }; }); }, - fetchFromAccountToLinkTable: function ({ recipeUserId }) { + fetchFromAccountToLinkTable: function ({ recipeUserId, }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), - { - recipeUserId, - } - ); + let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), { + recipeUserId, + }); return result.user; }); }, - storeIntoAccountToLinkTable: function ({ recipeUserId, primaryUserId }) { + storeIntoAccountToLinkTable: function ({ recipeUserId, primaryUserId, }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), - { - recipeUserId, - primaryUserId, - } - ); + let result = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), { + recipeUserId, + primaryUserId, + }); return result; }); }, diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 1553c6a05..85466f51b 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -1,51 +1,28 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import type { User } from "../../types"; import { SessionContainer } from "../session"; export declare type TypeInput = { onAccountLinked?: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - shouldDoAutomaticAccountLinking?: ( - newAccountInfo: AccountInfoAndEmailWithRecipeId, - user: User | undefined, - session: SessionContainer | undefined, - userContext: any - ) => Promise< - | { - shouldAutomaticallyLink: false; - } - | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - } - >; + shouldDoAutomaticAccountLinking?: (newAccountInfo: AccountInfoAndEmailWithRecipeId, user: User | undefined, session: SessionContainer | undefined, userContext: any) => Promise<{ + shouldAutomaticallyLink: false; + } | { + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + }>; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; }; }; export declare type TypeNormalisedInput = { onAccountLinked: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - shouldDoAutomaticAccountLinking: ( - newAccountInfo: AccountInfoAndEmailWithRecipeId, - user: User | undefined, - session: SessionContainer | undefined, - userContext: any - ) => Promise< - | { - shouldAutomaticallyLink: false; - } - | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - } - >; + shouldDoAutomaticAccountLinking: (newAccountInfo: AccountInfoAndEmailWithRecipeId, user: User | undefined, session: SessionContainer | undefined, userContext: any) => Promise<{ + shouldAutomaticallyLink: false; + } | { + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + }>; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; }; }; export declare type RecipeInterface = { @@ -83,95 +60,81 @@ export declare type RecipeInterface = { canCreatePrimaryUserId: (input: { recipeUserId: string; userContext: any; - }) => Promise< - | { - status: "OK"; - } - | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; + }) => Promise<{ + status: "OK"; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; createPrimaryUser: (input: { recipeUserId: string; userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - } - | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; + }) => Promise<{ + status: "OK"; + user: User; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; canLinkAccounts: (input: { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise< - | { - status: "OK"; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } - | { - status: "ACCOUNTS_ALREADY_LINKED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; + }) => Promise<{ + status: "OK"; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; linkAccounts: (input: { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise< - | { - status: "OK"; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNTS_ALREADY_LINKED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - >; + }) => Promise<{ + status: "OK"; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNTS_ALREADY_LINKED_ERROR"; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + }>; unlinkAccounts: (input: { recipeUserId: string; userContext: any; - }) => Promise< - | { - status: "OK"; - wasRecipeUserDeleted: boolean; - } - | { - status: "NO_PRIMARY_USER_FOUND"; - } - >; - getUser: (input: { userId: string; userContext: any }) => Promise; - listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; - getUserByAccountInfo: (input: { info: AccountInfoWithRecipeId; userContext: any }) => Promise; + }) => Promise<{ + status: "OK"; + wasRecipeUserDeleted: boolean; + } | { + status: "NO_PRIMARY_USER_FOUND"; + }>; + getUser: (input: { + userId: string; + userContext: any; + }) => Promise; + listUsersByAccountInfo: (input: { + info: AccountInfo; + userContext: any; + }) => Promise; + getUserByAccountInfo: (input: { + info: AccountInfoWithRecipeId; + userContext: any; + }) => Promise; deleteUser: (input: { userId: string; removeAllLinkedAccounts: boolean; @@ -179,7 +142,10 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; - fetchFromAccountToLinkTable: (input: { recipeUserId: string; userContext: any }) => Promise; + fetchFromAccountToLinkTable: (input: { + recipeUserId: string; + userContext: any; + }) => Promise; storeIntoAccountToLinkTable: (input: { recipeUserId: string; primaryUserId: string; @@ -209,28 +175,22 @@ export declare type AccountInfoAndEmailWithRecipeId = { userId: string; }; }; -export declare type AccountInfo = - | { - email: string; - } - | { - thirdpartyId: string; - thirdpartyUserId: string; - } - | { - phoneNumber: string; - }; -export declare type AccountInfoWithRecipeId = - | { - recipeId: "emailpassword" | "passwordless"; - email: string; - } - | { - recipeId: "thirdparty"; - thirdpartyId: string; - thirdpartyUserId: string; - } - | { - recipeId: "passwordless"; - phoneNumber: string; - }; +export declare type AccountInfo = { + email: string; +} | { + thirdpartyId: string; + thirdpartyUserId: string; +} | { + phoneNumber: string; +}; +export declare type AccountInfoWithRecipeId = { + recipeId: "emailpassword" | "passwordless"; + email: string; +} | { + recipeId: "thirdparty"; + thirdpartyId: string; + thirdpartyUserId: string; +} | { + recipeId: "passwordless"; + phoneNumber: string; +}; diff --git a/lib/build/recipe/accountlinking/utils.d.ts b/lib/build/recipe/accountlinking/utils.d.ts index 687c0db39..2ab72230d 100644 --- a/lib/build/recipe/accountlinking/utils.d.ts +++ b/lib/build/recipe/accountlinking/utils.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import type { NormalisedAppinfo } from "../../types"; import type { TypeInput, TypeNormalisedInput } from "./types"; export declare function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/accountlinking/utils.js b/lib/build/recipe/accountlinking/utils.js index 632652d47..8c40669d7 100644 --- a/lib/build/recipe/accountlinking/utils.js +++ b/lib/build/recipe/accountlinking/utils.js @@ -13,40 +13,19 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormaliseUserInput = void 0; function defaultOnAccountLinked(_user, _newAccountInfo, _userContext) { - return __awaiter(this, void 0, void 0, function* () {}); + return __awaiter(this, void 0, void 0, function* () { }); } function defaultShouldDoAutomaticAccountLinking(_newAccountInfo, _user, _session, _userContext) { return __awaiter(this, void 0, void 0, function* () { @@ -57,8 +36,7 @@ function defaultShouldDoAutomaticAccountLinking(_newAccountInfo, _user, _session } function validateAndNormaliseUserInput(_, config) { let onAccountLinked = config.onAccountLinked || defaultOnAccountLinked; - let shouldDoAutomaticAccountLinking = - config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; + let shouldDoAutomaticAccountLinking = config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; let override = Object.assign({ functions: (originalImplementation) => originalImplementation }, config.override); return { override, diff --git a/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts b/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts index ccb15887b..b387e87ad 100644 --- a/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts +++ b/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts @@ -1,7 +1,2 @@ -// @ts-nocheck import { APIFunction, APIInterface, APIOptions } from "../types"; -export default function apiKeyProtector( - apiImplementation: APIInterface, - options: APIOptions, - apiFunction: APIFunction -): Promise; +export default function apiKeyProtector(apiImplementation: APIInterface, options: APIOptions, apiFunction: APIFunction): Promise; diff --git a/lib/build/recipe/dashboard/api/apiKeyProtector.js b/lib/build/recipe/dashboard/api/apiKeyProtector.js index 14f446112..6d0c9fc0e 100644 --- a/lib/build/recipe/dashboard/api/apiKeyProtector.js +++ b/lib/build/recipe/dashboard/api/apiKeyProtector.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. * diff --git a/lib/build/recipe/dashboard/api/dashboard.d.ts b/lib/build/recipe/dashboard/api/dashboard.d.ts index f6bd1a1bf..3d609d83f 100644 --- a/lib/build/recipe/dashboard/api/dashboard.d.ts +++ b/lib/build/recipe/dashboard/api/dashboard.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export default function dashboard(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/dashboard/api/dashboard.js b/lib/build/recipe/dashboard/api/dashboard.js index 5d61bede0..e07eebec9 100644 --- a/lib/build/recipe/dashboard/api/dashboard.js +++ b/lib/build/recipe/dashboard/api/dashboard.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); function dashboard(apiImplementation, options) { diff --git a/lib/build/recipe/dashboard/api/implementation.d.ts b/lib/build/recipe/dashboard/api/implementation.d.ts index 0218549fa..75c1214f2 100644 --- a/lib/build/recipe/dashboard/api/implementation.d.ts +++ b/lib/build/recipe/dashboard/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/dashboard/api/implementation.js b/lib/build/recipe/dashboard/api/implementation.js index 88e75453c..bc1c3ea5a 100644 --- a/lib/build/recipe/dashboard/api/implementation.js +++ b/lib/build/recipe/dashboard/api/implementation.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLDomain_1 = require("../../../normalisedURLDomain"); const normalisedURLPath_1 = require("../../../normalisedURLPath"); @@ -56,8 +34,7 @@ function getAPIImplementation() { const bundleBasePathString = yield input.options.recipeImplementation.getDashboardBundleLocation({ userContext: input.userContext, }); - const bundleDomain = - new normalisedURLDomain_1.default(bundleBasePathString).getAsStringDangerous() + + const bundleDomain = new normalisedURLDomain_1.default(bundleBasePathString).getAsStringDangerous() + new normalisedURLPath_1.default(bundleBasePathString).getAsStringDangerous(); let connectionURI = ""; const superTokensInstance = supertokens_1.default.getInstanceOrThrowError(); @@ -71,8 +48,8 @@ function getAPIImplementation() { diff --git a/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts b/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts index c184332e6..11588ff0e 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userDelete.js b/lib/build/recipe/dashboard/api/userdetails/userDelete.js index 5691be06e..e02ab01c3 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userDelete.js +++ b/lib/build/recipe/dashboard/api/userdetails/userDelete.js @@ -1,55 +1,33 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userDelete = void 0; const error_1 = require("../../../../error"); const __1 = require("../../../.."); -exports.userDelete = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - let removeAllLinkedAccountsQueryValue = options.req.getKeyValueFromQuery("removeAllLinkedAccounts"); - if (removeAllLinkedAccountsQueryValue !== undefined) { - removeAllLinkedAccountsQueryValue = removeAllLinkedAccountsQueryValue.trim().toLowerCase(); - } - const removeAllLinkedAccounts = - removeAllLinkedAccountsQueryValue === undefined ? undefined : removeAllLinkedAccountsQueryValue === "true"; - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - yield __1.deleteUser(userId, removeAllLinkedAccounts); - return { - status: "OK", - }; - }); +const userDelete = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + let removeAllLinkedAccountsQueryValue = options.req.getKeyValueFromQuery("removeAllLinkedAccounts"); + if (removeAllLinkedAccountsQueryValue !== undefined) { + removeAllLinkedAccountsQueryValue = removeAllLinkedAccountsQueryValue.trim().toLowerCase(); + } + const removeAllLinkedAccounts = removeAllLinkedAccountsQueryValue === undefined ? undefined : removeAllLinkedAccountsQueryValue === "true"; + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + yield __1.deleteUser(userId, removeAllLinkedAccounts); + return { + status: "OK", + }; +}); +exports.userDelete = userDelete; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts index ba6da64a6..d996548af 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIFunction } from "../../types"; export declare const userEmailverifyGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js index 1c2714f31..bb9b2cc19 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js @@ -1,59 +1,39 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userEmailverifyGet = void 0; const error_1 = require("../../../../error"); const recipe_1 = require("../../../emailverification/recipe"); const emailverification_1 = require("../../../emailverification"); -exports.userEmailverifyGet = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const req = options.req; - const userId = req.getKeyValueFromQuery("userId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - try { - recipe_1.default.getInstanceOrThrowError(); - } catch (e) { - return { - status: "FEATURE_NOT_ENABLED_ERROR", - }; - } - const response = yield emailverification_1.default.isEmailVerified(userId); +const userEmailverifyGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const req = options.req; + const userId = req.getKeyValueFromQuery("userId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + try { + recipe_1.default.getInstanceOrThrowError(); + } + catch (e) { return { - status: "OK", - isVerified: response, + status: "FEATURE_NOT_ENABLED_ERROR", }; - }); + } + const response = yield emailverification_1.default.isEmailVerified(userId); + return { + status: "OK", + isVerified: response, + }; +}); +exports.userEmailverifyGet = userEmailverifyGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts index 055c3cb89..a5df12097 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js index 3d13785e9..85268ceb2 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js @@ -1,71 +1,51 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userEmailVerifyPut = void 0; const error_1 = require("../../../../error"); const emailverification_1 = require("../../../emailverification"); -exports.userEmailVerifyPut = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const verified = requestBody.verified; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (verified === undefined || typeof verified !== "boolean") { - throw new error_1.default({ - message: "Required parameter 'verified' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); +const userEmailVerifyPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const verified = requestBody.verified; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (verified === undefined || typeof verified !== "boolean") { + throw new error_1.default({ + message: "Required parameter 'verified' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (verified) { + const tokenResponse = yield emailverification_1.default.createEmailVerificationToken(userId); + if (tokenResponse.status === "EMAIL_ALREADY_VERIFIED_ERROR") { + return { + status: "OK", + }; } - if (verified) { - const tokenResponse = yield emailverification_1.default.createEmailVerificationToken(userId); - if (tokenResponse.status === "EMAIL_ALREADY_VERIFIED_ERROR") { - return { - status: "OK", - }; - } - const verifyResponse = yield emailverification_1.default.verifyEmailUsingToken(tokenResponse.token); - if (verifyResponse.status === "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR") { - // This should never happen because we consume the token immediately after creating it - throw new Error("Should not come here"); - } - } else { - yield emailverification_1.default.unverifyEmail(userId); + const verifyResponse = yield emailverification_1.default.verifyEmailUsingToken(tokenResponse.token); + if (verifyResponse.status === "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR") { + // This should never happen because we consume the token immediately after creating it + throw new Error("Should not come here"); } - return { - status: "OK", - }; - }); + } + else { + yield emailverification_1.default.unverifyEmail(userId); + } + return { + status: "OK", + }; +}); +exports.userEmailVerifyPut = userEmailVerifyPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts index 50b925c62..5d114cb61 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK" | "EMAIL_ALREADY_VERIFIED_ERROR"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js index bd46798a9..baf6ef8c2 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js @@ -1,74 +1,53 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userEmailVerifyTokenPost = void 0; const error_1 = require("../../../../error"); const emailverification_1 = require("../../../emailverification"); const recipe_1 = require("../../../emailverification/recipe"); const utils_1 = require("../../../emailverification/utils"); -exports.userEmailVerifyTokenPost = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - let emailResponse = yield recipe_1.default.getInstanceOrThrowError().getEmailForUserId(userId, {}); - if (emailResponse.status !== "OK") { - throw new Error("Should never come here"); - } - let emailVerificationToken = yield emailverification_1.default.createEmailVerificationToken(userId); - if (emailVerificationToken.status === "EMAIL_ALREADY_VERIFIED_ERROR") { - return { - status: "EMAIL_ALREADY_VERIFIED_ERROR", - }; - } - let emailVerifyLink = utils_1.getEmailVerifyLink({ - appInfo: options.appInfo, - token: emailVerificationToken.token, - recipeId: recipe_1.default.RECIPE_ID, - }); - yield emailverification_1.default.sendEmail({ - type: "EMAIL_VERIFICATION", - user: { - id: userId, - email: emailResponse.email, - }, - emailVerifyLink, +const userEmailVerifyTokenPost = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, }); + } + let emailResponse = yield recipe_1.default.getInstanceOrThrowError().getEmailForUserId(userId, {}); + if (emailResponse.status !== "OK") { + throw new Error("Should never come here"); + } + let emailVerificationToken = yield emailverification_1.default.createEmailVerificationToken(userId); + if (emailVerificationToken.status === "EMAIL_ALREADY_VERIFIED_ERROR") { return { - status: "OK", + status: "EMAIL_ALREADY_VERIFIED_ERROR", }; + } + let emailVerifyLink = utils_1.getEmailVerifyLink({ + appInfo: options.appInfo, + token: emailVerificationToken.token, + recipeId: recipe_1.default.RECIPE_ID, + }); + yield emailverification_1.default.sendEmail({ + type: "EMAIL_VERIFICATION", + user: { + id: userId, + email: emailResponse.email, + }, + emailVerifyLink, }); + return { + status: "OK", + }; +}); +exports.userEmailVerifyTokenPost = userEmailVerifyTokenPost; diff --git a/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts index dd04c1ee3..95e0ac4b8 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIFunction } from "../../types"; export declare const userGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userGet.js b/lib/build/recipe/dashboard/api/userdetails/userGet.js index 7c8d28606..c2dda8971 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userGet.js @@ -1,90 +1,69 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userGet = void 0; const error_1 = require("../../../../error"); const utils_1 = require("../../utils"); const recipe_1 = require("../../../usermetadata/recipe"); const usermetadata_1 = require("../../../usermetadata"); -exports.userGet = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - const recipeId = options.req.getKeyValueFromQuery("recipeId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (recipeId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'recipeId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (!utils_1.isValidRecipeId(recipeId)) { - throw new error_1.default({ - message: "Invalid recipe id", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - let user = (yield utils_1.getUserForRecipeId(userId, recipeId)).user; - if (user === undefined) { - return { - status: "NO_USER_FOUND_ERROR", - }; - } - try { - recipe_1.default.getInstanceOrThrowError(); - } catch (_) { - user = Object.assign(Object.assign({}, user), { - firstName: "FEATURE_NOT_ENABLED", - lastName: "FEATURE_NOT_ENABLED", - }); - return { - status: "OK", - recipeId: recipeId, - user, - }; - } - const userMetaData = yield usermetadata_1.default.getUserMetadata(userId); - const { first_name, last_name } = userMetaData.metadata; - user = Object.assign(Object.assign({}, user), { - firstName: first_name === undefined ? "" : first_name, - lastName: last_name === undefined ? "" : last_name, +const userGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + const recipeId = options.req.getKeyValueFromQuery("recipeId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, }); + } + if (recipeId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'recipeId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (!utils_1.isValidRecipeId(recipeId)) { + throw new error_1.default({ + message: "Invalid recipe id", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (!utils_1.isRecipeInitialised(recipeId)) { + return { + status: "RECIPE_NOT_INITIALISED", + }; + } + let user = (yield utils_1.getUserForRecipeId(userId, recipeId)).user; + if (user === undefined) { + return { + status: "NO_USER_FOUND_ERROR", + }; + } + try { + recipe_1.default.getInstanceOrThrowError(); + } + catch (_) { + user = Object.assign(Object.assign({}, user), { firstName: "FEATURE_NOT_ENABLED", lastName: "FEATURE_NOT_ENABLED" }); return { status: "OK", recipeId: recipeId, user, }; - }); + } + const userMetaData = yield usermetadata_1.default.getUserMetadata(userId); + const { first_name, last_name } = userMetaData.metadata; + user = Object.assign(Object.assign({}, user), { firstName: first_name === undefined ? "" : first_name, lastName: last_name === undefined ? "" : last_name }); + return { + status: "OK", + recipeId: recipeId, + user, + }; +}); +exports.userGet = userGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts index f2ba7687d..d5f6f5c8d 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIFunction } from "../../types"; export declare const userMetaDataGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js index 41499681a..8554da725 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js @@ -1,58 +1,38 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userMetaDataGet = void 0; const error_1 = require("../../../../error"); const recipe_1 = require("../../../usermetadata/recipe"); const usermetadata_1 = require("../../../usermetadata"); -exports.userMetaDataGet = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - try { - recipe_1.default.getInstanceOrThrowError(); - } catch (e) { - return { - status: "FEATURE_NOT_ENABLED_ERROR", - }; - } - const metaDataResponse = usermetadata_1.default.getUserMetadata(userId); +const userMetaDataGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + try { + recipe_1.default.getInstanceOrThrowError(); + } + catch (e) { return { - status: "OK", - data: (yield metaDataResponse).metadata, + status: "FEATURE_NOT_ENABLED_ERROR", }; - }); + } + const metaDataResponse = usermetadata_1.default.getUserMetadata(userId); + return { + status: "OK", + data: (yield metaDataResponse).metadata, + }; +}); +exports.userMetaDataGet = userMetaDataGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts index 0bbbe8a65..84c9ada1b 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js index 4adbf605c..d3e7c8206 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js @@ -1,90 +1,70 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userMetadataPut = void 0; const recipe_1 = require("../../../usermetadata/recipe"); const usermetadata_1 = require("../../../usermetadata"); const error_1 = require("../../../../error"); -exports.userMetadataPut = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const data = requestBody.data; - // This is to throw an error early in case the recipe has not been initialised - recipe_1.default.getInstanceOrThrowError(); - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); +const userMetadataPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const data = requestBody.data; + // This is to throw an error early in case the recipe has not been initialised + recipe_1.default.getInstanceOrThrowError(); + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (data === undefined || typeof data !== "string") { + throw new error_1.default({ + message: "Required parameter 'data' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + // Make sure that data is a valid JSON, this will throw + try { + let parsedData = JSON.parse(data); + if (typeof parsedData !== "object") { + throw new Error(); } - if (data === undefined || typeof data !== "string") { - throw new error_1.default({ - message: "Required parameter 'data' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); + if (Array.isArray(parsedData)) { + throw new Error(); } - // Make sure that data is a valid JSON, this will throw - try { - let parsedData = JSON.parse(data); - if (typeof parsedData !== "object") { - throw new Error(); - } - if (Array.isArray(parsedData)) { - throw new Error(); - } - if (parsedData === null) { - throw new Error(); - } - } catch (e) { - throw new error_1.default({ - message: "'data' must be a valid JSON body", - type: error_1.default.BAD_INPUT_ERROR, - }); + if (parsedData === null) { + throw new Error(); } - /** - * This API is meant to set the user metadata of a user. We delete the existing data - * before updating it because we want to make sure that shallow merging does not result - * in the data being incorrect - * - * For example if the old data is {test: "test", test2: "test2"} and the user wants to delete - * test2 from the data simply calling updateUserMetadata with {test: "test"} would not remove - * test2 because of shallow merging. - * - * Removing first ensures that the final data is exactly what the user wanted it to be - */ - yield usermetadata_1.default.clearUserMetadata(userId); - yield usermetadata_1.default.updateUserMetadata(userId, JSON.parse(data)); - return { - status: "OK", - }; - }); + } + catch (e) { + throw new error_1.default({ + message: "'data' must be a valid JSON body", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + /** + * This API is meant to set the user metadata of a user. We delete the existing data + * before updating it because we want to make sure that shallow merging does not result + * in the data being incorrect + * + * For example if the old data is {test: "test", test2: "test2"} and the user wants to delete + * test2 from the data simply calling updateUserMetadata with {test: "test"} would not remove + * test2 because of shallow merging. + * + * Removing first ensures that the final data is exactly what the user wanted it to be + */ + yield usermetadata_1.default.clearUserMetadata(userId); + yield usermetadata_1.default.updateUserMetadata(userId, JSON.parse(data)); + return { + status: "OK", + }; +}); +exports.userMetadataPut = userMetadataPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts index 83b8371fe..ef18b9292 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts @@ -1,15 +1,11 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; -declare type Response = - | { - status: "OK"; - } - | { - status: "PROVIDE_RECIPE_USER_ID_AS_USER_ID_ERROR"; - } - | { - status: "INVALID_PASSWORD_ERROR"; - error: string; - }; +declare type Response = { + status: "OK"; +} | { + status: "PROVIDE_RECIPE_USER_ID_AS_USER_ID_ERROR"; +} | { + status: "INVALID_PASSWORD_ERROR"; + error: string; +}; export declare const userPasswordPut: (_: APIInterface, options: APIOptions) => Promise; export {}; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js index f64e1d86c..1a437f65d 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js @@ -1,105 +1,57 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userPasswordPut = void 0; const error_1 = require("../../../../error"); const recipe_1 = require("../../../emailpassword/recipe"); const emailpassword_1 = require("../../../emailpassword"); const recipe_2 = require("../../../thirdpartyemailpassword/recipe"); const thirdpartyemailpassword_1 = require("../../../thirdpartyemailpassword"); const constants_1 = require("../../../emailpassword/constants"); -exports.userPasswordPut = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const email = requestBody.email; - const newPassword = requestBody.newPassword; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (newPassword === undefined || typeof newPassword !== "string") { - throw new error_1.default({ - message: "Required parameter 'newPassword' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - let recipeToUse; +const userPasswordPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const email = requestBody.email; + const newPassword = requestBody.newPassword; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (newPassword === undefined || typeof newPassword !== "string") { + throw new error_1.default({ + message: "Required parameter 'newPassword' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + let recipeToUse; + try { + recipe_1.default.getInstanceOrThrowError(); + recipeToUse = "emailpassword"; + } + catch (_) { } + if (recipeToUse === undefined) { try { - recipe_1.default.getInstanceOrThrowError(); - recipeToUse = "emailpassword"; - } catch (_) {} - if (recipeToUse === undefined) { - try { - recipe_2.default.getInstanceOrThrowError(); - recipeToUse = "thirdpartyemailpassword"; - } catch (_) {} + recipe_2.default.getInstanceOrThrowError(); + recipeToUse = "thirdpartyemailpassword"; } - if (recipeToUse === undefined) { - // This means that neither emailpassword or thirdpartyemailpassword is initialised - throw new Error("Should never come here"); - } - if (recipeToUse === "emailpassword") { - let passwordFormFields = recipe_1.default - .getInstanceOrThrowError() - .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); - let passwordValidationError = yield passwordFormFields[0].validate(newPassword); - if (passwordValidationError !== undefined) { - return { - status: "INVALID_PASSWORD_ERROR", - error: passwordValidationError, - }; - } - const passwordResetToken = yield emailpassword_1.default.createResetPasswordToken(userId, email); - if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { - // Techincally it can but its an edge case so we assume that it wont - throw new Error("Should never come here"); - } - const passwordResetResponse = yield emailpassword_1.default.resetPasswordUsingToken( - passwordResetToken.token, - newPassword - ); - if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { - throw new Error("Should never come here"); - } - return { - status: "OK", - }; - } - let passwordFormFields = recipe_2.default - .getInstanceOrThrowError() - .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); + catch (_) { } + } + if (recipeToUse === undefined) { + // This means that neither emailpassword or thirdpartyemailpassword is initialised + throw new Error("Should never come here"); + } + if (recipeToUse === "emailpassword") { + let passwordFormFields = recipe_1.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); let passwordValidationError = yield passwordFormFields[0].validate(newPassword); if (passwordValidationError !== undefined) { return { @@ -107,19 +59,38 @@ exports.userPasswordPut = (_, options) => error: passwordValidationError, }; } - const passwordResetToken = yield thirdpartyemailpassword_1.default.createResetPasswordToken(userId, email); + const passwordResetToken = yield emailpassword_1.default.createResetPasswordToken(userId, email); if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { // Techincally it can but its an edge case so we assume that it wont throw new Error("Should never come here"); } - const passwordResetResponse = yield thirdpartyemailpassword_1.default.resetPasswordUsingToken( - passwordResetToken.token, - newPassword - ); + const passwordResetResponse = yield emailpassword_1.default.resetPasswordUsingToken(passwordResetToken.token, newPassword); if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { throw new Error("Should never come here"); } return { status: "OK", }; - }); + } + let passwordFormFields = recipe_2.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); + let passwordValidationError = yield passwordFormFields[0].validate(newPassword); + if (passwordValidationError !== undefined) { + return { + status: "INVALID_PASSWORD_ERROR", + error: passwordValidationError, + }; + } + const passwordResetToken = yield thirdpartyemailpassword_1.default.createResetPasswordToken(userId, email); + if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { + // Techincally it can but its an edge case so we assume that it wont + throw new Error("Should never come here"); + } + const passwordResetResponse = yield thirdpartyemailpassword_1.default.resetPasswordUsingToken(passwordResetToken.token, newPassword); + if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { + throw new Error("Should never come here"); + } + return { + status: "OK", + }; +}); +exports.userPasswordPut = userPasswordPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts index ba250bb3d..4b1c52571 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts @@ -1,22 +1,16 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; -declare type Response = - | { - status: "OK"; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - | { - status: "INVALID_EMAIL_ERROR"; - error: string; - } - | { - status: "PHONE_ALREADY_EXISTS_ERROR"; - } - | { - status: "INVALID_PHONE_ERROR"; - error: string; - }; +declare type Response = { + status: "OK"; +} | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; +} | { + status: "INVALID_EMAIL_ERROR"; + error: string; +} | { + status: "PHONE_ALREADY_EXISTS_ERROR"; +} | { + status: "INVALID_PHONE_ERROR"; + error: string; +}; export declare const userPut: (_: APIInterface, options: APIOptions) => Promise; export {}; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPut.js b/lib/build/recipe/dashboard/api/userdetails/userPut.js index 8e05c0889..6f82fd1ae 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userPut.js @@ -1,39 +1,18 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userPut = void 0; const error_1 = require("../../../../error"); const recipe_1 = require("../../../emailpassword/recipe"); -const recipe_2 = require("../../../emailpassword/recipe"); +const recipe_2 = require("../../../thirdpartyemailpassword/recipe"); const recipe_3 = require("../../../passwordless/recipe"); const recipe_4 = require("../../../thirdpartypasswordless/recipe"); const emailpassword_1 = require("../../../emailpassword"); @@ -45,314 +24,313 @@ const recipe_5 = require("../../../usermetadata/recipe"); const usermetadata_1 = require("../../../usermetadata"); const constants_1 = require("../../../emailpassword/constants"); const utils_2 = require("../../../passwordless/utils"); -const updateEmailForRecipeId = (recipeId, userId, email) => - __awaiter(void 0, void 0, void 0, function* () { - if (recipeId === "emailpassword") { - let emailFormFields = recipe_1.default - .getInstanceOrThrowError() - .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); - let validationError = yield emailFormFields[0].validate(email); - if (validationError !== undefined) { - return { - status: "INVALID_EMAIL_ERROR", - error: validationError, - }; - } - const emailUpdateResponse = yield emailpassword_1.default.updateEmailOrPassword({ - userId, - email, - }); - if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } +const updateEmailForRecipeId = (recipeId, userId, email) => __awaiter(void 0, void 0, void 0, function* () { + if (recipeId === "emailpassword") { + let emailFormFields = recipe_1.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); + let validationError = yield emailFormFields[0].validate(email); + if (validationError !== undefined) { return { - status: "OK", + status: "INVALID_EMAIL_ERROR", + error: validationError, }; } - if (recipeId === "thirdpartyemailpassword") { - let emailFormFields = recipe_2.default - .getInstanceOrThrowError() - .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); - let validationError = yield emailFormFields[0].validate(email); - if (validationError !== undefined) { - return { - status: "INVALID_EMAIL_ERROR", - error: validationError, - }; - } - const emailUpdateResponse = yield thirdpartyemailpassword_1.default.updateEmailOrPassword({ - userId, - email, - }); - if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } - if (emailUpdateResponse.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } + const emailUpdateResponse = yield emailpassword_1.default.updateEmailOrPassword({ + userId, + email, + }); + if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { return { - status: "OK", + status: "EMAIL_ALREADY_EXISTS_ERROR", }; } - if (recipeId === "passwordless") { - let isValidEmail = true; - let validationError = ""; - const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; - if (passwordlessConfig.contactMethod === "PHONE") { - const validationResult = yield utils_2.defaultValidateEmail(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; - } - } else { - const validationResult = yield passwordlessConfig.validateEmailAddress(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; - } - } - if (!isValidEmail) { - return { - status: "INVALID_EMAIL_ERROR", - error: validationError, - }; - } - const updateResult = yield passwordless_1.default.updateUser({ - userId, - email, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } - if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } + return { + status: "OK", + }; + } + if (recipeId === "thirdpartyemailpassword") { + let emailFormFields = recipe_2.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); + let validationError = yield emailFormFields[0].validate(email); + if (validationError !== undefined) { return { - status: "OK", + status: "INVALID_EMAIL_ERROR", + error: validationError, }; } - if (recipeId === "thirdpartypasswordless") { - let isValidEmail = true; - let validationError = ""; - const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; - if (passwordlessConfig.contactMethod === "PHONE") { - const validationResult = yield utils_2.defaultValidateEmail(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; - } - } else { - const validationResult = yield passwordlessConfig.validateEmailAddress(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; - } - } - if (!isValidEmail) { - return { - status: "INVALID_EMAIL_ERROR", - error: validationError, - }; - } - const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ - userId, - email, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } - if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } + const emailUpdateResponse = yield thirdpartyemailpassword_1.default.updateEmailOrPassword({ + userId, + email, + }); + if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { return { - status: "OK", + status: "EMAIL_ALREADY_EXISTS_ERROR", }; } - /** - * If it comes here then the user is a third party user in which case the UI should not have allowed this - */ - throw new Error("Should never come here"); - }); -const updatePhoneForRecipeId = (recipeId, userId, phone) => - __awaiter(void 0, void 0, void 0, function* () { - if (recipeId === "passwordless") { - let isValidPhone = true; - let validationError = ""; - const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; - if (passwordlessConfig.contactMethod === "EMAIL") { - const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; - } - } else { - const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; - } - } - if (!isValidPhone) { - return { - status: "INVALID_PHONE_ERROR", - error: validationError, - }; - } - const updateResult = yield passwordless_1.default.updateUser({ - userId, - phoneNumber: phone, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); + if (emailUpdateResponse.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); + } + return { + status: "OK", + }; + } + if (recipeId === "passwordless") { + let isValidEmail = true; + let validationError = ""; + const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; + if (passwordlessConfig.contactMethod === "PHONE") { + const validationResult = yield utils_2.defaultValidateEmail(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; } - if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { - return { - status: "PHONE_ALREADY_EXISTS_ERROR", - }; + } + else { + const validationResult = yield passwordlessConfig.validateEmailAddress(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; } + } + if (!isValidEmail) { return { - status: "OK", + status: "INVALID_EMAIL_ERROR", + error: validationError, }; } - if (recipeId === "thirdpartypasswordless") { - let isValidPhone = true; - let validationError = ""; - const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; - if (passwordlessConfig.contactMethod === "EMAIL") { - const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; - } - } else { - const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; - } - } - if (!isValidPhone) { - return { - status: "INVALID_PHONE_ERROR", - error: validationError, - }; - } - const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ - userId, - phoneNumber: phone, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } - if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { - return { - status: "PHONE_ALREADY_EXISTS_ERROR", - }; - } + const updateResult = yield passwordless_1.default.updateUser({ + userId, + email, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); + } + if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { return { - status: "OK", + status: "EMAIL_ALREADY_EXISTS_ERROR", }; } - /** - * If it comes here then the user is a not a passwordless user in which case the UI should not have allowed this - */ - throw new Error("Should never come here"); - }); -exports.userPut = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const recipeId = requestBody.recipeId; - const firstName = requestBody.firstName; - const lastName = requestBody.lastName; - const email = requestBody.email; - const phone = requestBody.phone; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); + return { + status: "OK", + }; + } + if (recipeId === "thirdpartypasswordless") { + let isValidEmail = true; + let validationError = ""; + const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; + if (passwordlessConfig.contactMethod === "PHONE") { + const validationResult = yield utils_2.defaultValidateEmail(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; + } } - if (recipeId === undefined || typeof recipeId !== "string") { - throw new error_1.default({ - message: "Required parameter 'recipeId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); + else { + const validationResult = yield passwordlessConfig.validateEmailAddress(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; + } } - if (!utils_1.isValidRecipeId(recipeId)) { - throw new error_1.default({ - message: "Invalid recipe id", - type: error_1.default.BAD_INPUT_ERROR, - }); + if (!isValidEmail) { + return { + status: "INVALID_EMAIL_ERROR", + error: validationError, + }; } - if (firstName === undefined || typeof firstName !== "string") { - throw new error_1.default({ - message: "Required parameter 'firstName' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); + const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ + userId, + email, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); } - if (lastName === undefined || typeof lastName !== "string") { - throw new error_1.default({ - message: "Required parameter 'lastName' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); + if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { + return { + status: "EMAIL_ALREADY_EXISTS_ERROR", + }; } - if (email === undefined || typeof email !== "string") { - throw new error_1.default({ - message: "Required parameter 'email' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); + return { + status: "OK", + }; + } + /** + * If it comes here then the user is a third party user in which case the UI should not have allowed this + */ + throw new Error("Should never come here"); +}); +const updatePhoneForRecipeId = (recipeId, userId, phone) => __awaiter(void 0, void 0, void 0, function* () { + if (recipeId === "passwordless") { + let isValidPhone = true; + let validationError = ""; + const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; + if (passwordlessConfig.contactMethod === "EMAIL") { + const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; + } } - if (phone === undefined || typeof phone !== "string") { - throw new error_1.default({ - message: "Required parameter 'phone' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); + else { + const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; + } } - let userResponse = yield utils_1.getUserForRecipeId(userId, recipeId); - if (userResponse.user === undefined || userResponse.recipe === undefined) { + if (!isValidPhone) { + return { + status: "INVALID_PHONE_ERROR", + error: validationError, + }; + } + const updateResult = yield passwordless_1.default.updateUser({ + userId, + phoneNumber: phone, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { throw new Error("Should never come here"); } - if (firstName.trim() !== "" || lastName.trim() !== "") { - let isRecipeInitialised = false; - try { - recipe_5.default.getInstanceOrThrowError(); - isRecipeInitialised = true; - } catch (_) { - // no op - } - if (isRecipeInitialised) { - let metaDataUpdate = {}; - if (firstName.trim() !== "") { - metaDataUpdate["first_name"] = firstName.trim(); - } - if (lastName.trim() !== "") { - metaDataUpdate["last_name"] = lastName.trim(); - } - yield usermetadata_1.default.updateUserMetadata(userId, metaDataUpdate); - } + if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { + return { + status: "PHONE_ALREADY_EXISTS_ERROR", + }; } - if (email.trim() !== "") { - const emailUpdateResponse = yield updateEmailForRecipeId(userResponse.recipe, userId, email.trim()); - if (emailUpdateResponse.status !== "OK") { - return emailUpdateResponse; + return { + status: "OK", + }; + } + if (recipeId === "thirdpartypasswordless") { + let isValidPhone = true; + let validationError = ""; + const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; + if (passwordlessConfig.contactMethod === "EMAIL") { + const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; } } - if (phone.trim() !== "") { - const phoneUpdateResponse = yield updatePhoneForRecipeId(userResponse.recipe, userId, phone.trim()); - if (phoneUpdateResponse.status !== "OK") { - return phoneUpdateResponse; + else { + const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; } } + if (!isValidPhone) { + return { + status: "INVALID_PHONE_ERROR", + error: validationError, + }; + } + const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ + userId, + phoneNumber: phone, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); + } + if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { + return { + status: "PHONE_ALREADY_EXISTS_ERROR", + }; + } return { status: "OK", }; - }); + } + /** + * If it comes here then the user is a not a passwordless user in which case the UI should not have allowed this + */ + throw new Error("Should never come here"); +}); +const userPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const recipeId = requestBody.recipeId; + const firstName = requestBody.firstName; + const lastName = requestBody.lastName; + const email = requestBody.email; + const phone = requestBody.phone; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (recipeId === undefined || typeof recipeId !== "string") { + throw new error_1.default({ + message: "Required parameter 'recipeId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (!utils_1.isValidRecipeId(recipeId)) { + throw new error_1.default({ + message: "Invalid recipe id", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (firstName === undefined || typeof firstName !== "string") { + throw new error_1.default({ + message: "Required parameter 'firstName' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (lastName === undefined || typeof lastName !== "string") { + throw new error_1.default({ + message: "Required parameter 'lastName' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (email === undefined || typeof email !== "string") { + throw new error_1.default({ + message: "Required parameter 'email' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (phone === undefined || typeof phone !== "string") { + throw new error_1.default({ + message: "Required parameter 'phone' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + let userResponse = yield utils_1.getUserForRecipeId(userId, recipeId); + if (userResponse.user === undefined || userResponse.recipe === undefined) { + throw new Error("Should never come here"); + } + if (firstName.trim() !== "" || lastName.trim() !== "") { + let isRecipeInitialised = false; + try { + recipe_5.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { + // no op + } + if (isRecipeInitialised) { + let metaDataUpdate = {}; + if (firstName.trim() !== "") { + metaDataUpdate["first_name"] = firstName.trim(); + } + if (lastName.trim() !== "") { + metaDataUpdate["last_name"] = lastName.trim(); + } + yield usermetadata_1.default.updateUserMetadata(userId, metaDataUpdate); + } + } + if (email.trim() !== "") { + const emailUpdateResponse = yield updateEmailForRecipeId(userResponse.recipe, userId, email.trim()); + if (emailUpdateResponse.status !== "OK") { + return emailUpdateResponse; + } + } + if (phone.trim() !== "") { + const phoneUpdateResponse = yield updatePhoneForRecipeId(userResponse.recipe, userId, phone.trim()); + if (phoneUpdateResponse.status !== "OK") { + return phoneUpdateResponse; + } + } + return { + status: "OK", + }; +}); +exports.userPut = userPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts index 34a18f080..535a23b27 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIFunction } from "../../types"; export declare const userSessionsGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js index 52dfb7143..e85bc1516 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js @@ -1,70 +1,46 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.userSessionsGet = void 0; +const error_1 = require("../../../../error"); +const session_1 = require("../../../session"); +const userSessionsGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + const response = yield session_1.default.getAllSessionHandlesForUser(userId); + let sessions = []; + let sessionInfoPromises = []; + for (let i = 0; i < response.length; i++) { + sessionInfoPromises.push(new Promise((res, rej) => __awaiter(void 0, void 0, void 0, function* () { + try { + const sessionResponse = yield session_1.default.getSessionInformation(response[i]); + if (sessionResponse !== undefined) { + sessions[i] = sessionResponse; } + res(); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + catch (e) { + rej(e); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + }))); + } + yield Promise.all(sessionInfoPromises); + return { + status: "OK", + sessions, }; -Object.defineProperty(exports, "__esModule", { value: true }); -const error_1 = require("../../../../error"); -const session_1 = require("../../../session"); -exports.userSessionsGet = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - const response = yield session_1.default.getAllSessionHandlesForUser(userId); - let sessions = []; - let sessionInfoPromises = []; - for (let i = 0; i < response.length; i++) { - sessionInfoPromises.push( - new Promise((res, rej) => - __awaiter(void 0, void 0, void 0, function* () { - try { - const sessionResponse = yield session_1.default.getSessionInformation(response[i]); - if (sessionResponse !== undefined) { - sessions[i] = sessionResponse; - } - res(); - } catch (e) { - rej(e); - } - }) - ) - ); - } - yield Promise.all(sessionInfoPromises); - return { - status: "OK", - sessions, - }; - }); +}); +exports.userSessionsGet = userSessionsGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts index 2a5a7eeb7..68aa2a281 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js index 22153cb9f..1c9f0ed45 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js @@ -1,50 +1,29 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.userSessionsPost = void 0; const error_1 = require("../../../../error"); const session_1 = require("../../../session"); -exports.userSessionsPost = (_, options) => - __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const sessionHandles = requestBody.sessionHandles; - if (sessionHandles === undefined || !Array.isArray(sessionHandles)) { - throw new error_1.default({ - message: "Required parameter 'sessionHandles' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - yield session_1.default.revokeMultipleSessions(sessionHandles); - return { - status: "OK", - }; - }); +const userSessionsPost = (_, options) => __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const sessionHandles = requestBody.sessionHandles; + if (sessionHandles === undefined || !Array.isArray(sessionHandles)) { + throw new error_1.default({ + message: "Required parameter 'sessionHandles' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + yield session_1.default.revokeMultipleSessions(sessionHandles); + return { + status: "OK", + }; +}); +exports.userSessionsPost = userSessionsPost; diff --git a/lib/build/recipe/dashboard/api/usersCountGet.d.ts b/lib/build/recipe/dashboard/api/usersCountGet.d.ts index 9291de948..9546bd205 100644 --- a/lib/build/recipe/dashboard/api/usersCountGet.d.ts +++ b/lib/build/recipe/dashboard/api/usersCountGet.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/usersCountGet.js b/lib/build/recipe/dashboard/api/usersCountGet.js index 56eff2000..224cc81f4 100644 --- a/lib/build/recipe/dashboard/api/usersCountGet.js +++ b/lib/build/recipe/dashboard/api/usersCountGet.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_1 = require("../../../supertokens"); function usersCountGet(_, __) { diff --git a/lib/build/recipe/dashboard/api/usersGet.d.ts b/lib/build/recipe/dashboard/api/usersGet.d.ts index ec90a7275..b53967462 100644 --- a/lib/build/recipe/dashboard/api/usersGet.d.ts +++ b/lib/build/recipe/dashboard/api/usersGet.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../types"; import { RecipeLevelUser } from "../../accountlinking/types"; declare type User = { diff --git a/lib/build/recipe/dashboard/api/usersGet.js b/lib/build/recipe/dashboard/api/usersGet.js index cbc3a9044..f000ea5bf 100644 --- a/lib/build/recipe/dashboard/api/usersGet.js +++ b/lib/build/recipe/dashboard/api/usersGet.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../../../error"); const __1 = require("../../.."); @@ -56,20 +34,20 @@ function usersGet(_, options) { }); } let paginationToken = options.req.getKeyValueFromQuery("paginationToken"); - let usersResponse = - timeJoinedOrder === "DESC" - ? yield __1.getUsersNewestFirst({ - limit: parseInt(limit), - paginationToken, - }) - : yield __1.getUsersOldestFirst({ - limit: parseInt(limit), - paginationToken, - }); + let usersResponse = timeJoinedOrder === "DESC" + ? yield __1.getUsersNewestFirst({ + limit: parseInt(limit), + paginationToken, + }) + : yield __1.getUsersOldestFirst({ + limit: parseInt(limit), + paginationToken, + }); // If the UserMetaData recipe has been initialised, fetch first and last name try { recipe_1.default.getInstanceOrThrowError(); - } catch (e) { + } + catch (e) { // Recipe has not been initialised, return without first name and last name return { status: "OK", @@ -81,25 +59,18 @@ function usersGet(_, options) { let metaDataFetchPromises = []; for (let i = 0; i < usersResponse.users.length; i++) { const userObj = usersResponse.users[i]; - metaDataFetchPromises.push( - () => - new Promise((resolve, reject) => - __awaiter(this, void 0, void 0, function* () { - try { - const userMetaDataResponse = yield usermetadata_1.default.getUserMetadata(userObj.id); - const { first_name, last_name } = userMetaDataResponse.metadata; - updatedUsersArray[i] = Object.assign(Object.assign({}, userObj), { - firstName: first_name, - lastName: last_name, - }); - resolve(true); - } catch (e) { - // Something went wrong when fetching user meta data - reject(e); - } - }) - ) - ); + metaDataFetchPromises.push(() => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + try { + const userMetaDataResponse = yield usermetadata_1.default.getUserMetadata(userObj.id); + const { first_name, last_name } = userMetaDataResponse.metadata; + updatedUsersArray[i] = Object.assign(Object.assign({}, userObj), { firstName: first_name, lastName: last_name }); + resolve(true); + } + catch (e) { + // Something went wrong when fetching user meta data + reject(e); + } + }))); } let promiseArrayStartPosition = 0; let batchSize = 5; diff --git a/lib/build/recipe/dashboard/api/validateKey.d.ts b/lib/build/recipe/dashboard/api/validateKey.d.ts index 39fa8c2a0..7e393f9e4 100644 --- a/lib/build/recipe/dashboard/api/validateKey.d.ts +++ b/lib/build/recipe/dashboard/api/validateKey.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export default function validateKey(_: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/dashboard/api/validateKey.js b/lib/build/recipe/dashboard/api/validateKey.js index f805ab857..3662e6fb4 100644 --- a/lib/build/recipe/dashboard/api/validateKey.js +++ b/lib/build/recipe/dashboard/api/validateKey.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../utils"); @@ -56,7 +34,8 @@ function validateKey(_, options) { }); if (!shouldAllowAccess) { utils_2.sendUnauthorisedAccess(options.res); - } else { + } + else { options.res.sendJSONResponse({ status: "OK", }); diff --git a/lib/build/recipe/dashboard/constants.d.ts b/lib/build/recipe/dashboard/constants.d.ts index 5862ffc64..147eeee45 100644 --- a/lib/build/recipe/dashboard/constants.d.ts +++ b/lib/build/recipe/dashboard/constants.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export declare const DASHBOARD_API = "/dashboard"; export declare const VALIDATE_KEY_API = "/api/key/validate"; export declare const USERS_LIST_GET_API = "/api/users"; diff --git a/lib/build/recipe/dashboard/constants.js b/lib/build/recipe/dashboard/constants.js index c5d4bda83..c340ac76f 100644 --- a/lib/build/recipe/dashboard/constants.js +++ b/lib/build/recipe/dashboard/constants.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.USER_EMAIL_VERIFY_TOKEN_API = exports.USER_PASSWORD_API = exports.USER_SESSIONS_API = exports.USER_METADATA_API = exports.USER_EMAIL_VERIFY_API = exports.USER_API = exports.USERS_COUNT_API = exports.USERS_LIST_GET_API = exports.VALIDATE_KEY_API = exports.DASHBOARD_API = void 0; exports.DASHBOARD_API = "/dashboard"; exports.VALIDATE_KEY_API = "/api/key/validate"; exports.USERS_LIST_GET_API = "/api/users"; diff --git a/lib/build/recipe/dashboard/index.d.ts b/lib/build/recipe/dashboard/index.d.ts index 3fc17a34f..8a3e59113 100644 --- a/lib/build/recipe/dashboard/index.d.ts +++ b/lib/build/recipe/dashboard/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import Recipe from "./recipe"; import { RecipeInterface, APIOptions, APIInterface } from "./types"; export default class Wrapper { diff --git a/lib/build/recipe/dashboard/index.js b/lib/build/recipe/dashboard/index.js index 6928aaf8b..3689ebcb7 100644 --- a/lib/build/recipe/dashboard/index.js +++ b/lib/build/recipe/dashboard/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.init = void 0; /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -15,7 +16,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); * under the License. */ const recipe_1 = require("./recipe"); -class Wrapper {} +class Wrapper { +} exports.default = Wrapper; Wrapper.init = recipe_1.default.init; exports.init = Wrapper.init; diff --git a/lib/build/recipe/dashboard/recipe.d.ts b/lib/build/recipe/dashboard/recipe.d.ts index 6e29b8d50..03fb0827b 100644 --- a/lib/build/recipe/dashboard/recipe.d.ts +++ b/lib/build/recipe/dashboard/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction } from "../../types"; import { APIInterface, RecipeInterface, TypeInput, TypeNormalisedInput } from "./types"; @@ -17,13 +16,7 @@ export default class Recipe extends RecipeModule { static init(config: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - __: NormalisedURLPath, - ___: HTTPMethod - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, __: NormalisedURLPath, ___: HTTPMethod) => Promise; handleError: (err: error, _: BaseRequest, __: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is error; diff --git a/lib/build/recipe/dashboard/recipe.js b/lib/build/recipe/dashboard/recipe.js index b433b8b1e..642834c79 100644 --- a/lib/build/recipe/dashboard/recipe.js +++ b/lib/build/recipe/dashboard/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_js_override_1 = require("supertokens-js-override"); const recipeModule_1 = require("../../recipeModule"); @@ -84,76 +62,81 @@ class Recipe extends recipeModule_1.default { */ return []; }; - this.handleAPIRequest = (id, req, res, __, ___) => - __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - isInServerlessEnv: this.isInServerlessEnv, - appInfo: this.getAppInfo(), - }; - // For these APIs we dont need API key validation - if (id === constants_1.DASHBOARD_API) { - return yield dashboard_1.default(this.apiImpl, options); + this.handleAPIRequest = (id, req, res, __, ___) => __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + isInServerlessEnv: this.isInServerlessEnv, + appInfo: this.getAppInfo(), + }; + // For these APIs we dont need API key validation + if (id === constants_1.DASHBOARD_API) { + return yield dashboard_1.default(this.apiImpl, options); + } + if (id === constants_1.VALIDATE_KEY_API) { + return yield validateKey_1.default(this.apiImpl, options); + } + // Do API key validation for the remaining APIs + let apiFunction; + if (id === constants_1.USERS_LIST_GET_API) { + apiFunction = usersGet_1.default; + } + else if (id === constants_1.USERS_COUNT_API) { + apiFunction = usersCountGet_1.default; + } + else if (id === constants_1.USER_API) { + if (req.getMethod() === "get") { + apiFunction = userGet_1.userGet; + } + if (req.getMethod() === "delete") { + apiFunction = userDelete_1.userDelete; + } + if (req.getMethod() === "put") { + apiFunction = userPut_1.userPut; } - if (id === constants_1.VALIDATE_KEY_API) { - return yield validateKey_1.default(this.apiImpl, options); + } + else if (id === constants_1.USER_EMAIL_VERIFY_API) { + if (req.getMethod() === "get") { + apiFunction = userEmailVerifyGet_1.userEmailverifyGet; + } + if (req.getMethod() === "put") { + apiFunction = userEmailVerifyPut_1.userEmailVerifyPut; } - // Do API key validation for the remaining APIs - let apiFunction; - if (id === constants_1.USERS_LIST_GET_API) { - apiFunction = usersGet_1.default; - } else if (id === constants_1.USERS_COUNT_API) { - apiFunction = usersCountGet_1.default; - } else if (id === constants_1.USER_API) { - if (req.getMethod() === "get") { - apiFunction = userGet_1.userGet; - } - if (req.getMethod() === "delete") { - apiFunction = userDelete_1.userDelete; - } - if (req.getMethod() === "put") { - apiFunction = userPut_1.userPut; - } - } else if (id === constants_1.USER_EMAIL_VERIFY_API) { - if (req.getMethod() === "get") { - apiFunction = userEmailVerifyGet_1.userEmailverifyGet; - } - if (req.getMethod() === "put") { - apiFunction = userEmailVerifyPut_1.userEmailVerifyPut; - } - } else if (id === constants_1.USER_METADATA_API) { - if (req.getMethod() === "get") { - apiFunction = userMetadataGet_1.userMetaDataGet; - } - if (req.getMethod() === "put") { - apiFunction = userMetadataPut_1.userMetadataPut; - } - } else if (id === constants_1.USER_SESSIONS_API) { - if (req.getMethod() === "get") { - apiFunction = userSessionsGet_1.userSessionsGet; - } - if (req.getMethod() === "post") { - apiFunction = userSessionsPost_1.userSessionsPost; - } - } else if (id === constants_1.USER_PASSWORD_API) { - apiFunction = userPasswordPut_1.userPasswordPut; - } else if (id === constants_1.USER_EMAIL_VERIFY_TOKEN_API) { - apiFunction = userEmailVerifyTokenPost_1.userEmailVerifyTokenPost; + } + else if (id === constants_1.USER_METADATA_API) { + if (req.getMethod() === "get") { + apiFunction = userMetadataGet_1.userMetaDataGet; } - // If the id doesnt match any APIs return false - if (apiFunction === undefined) { - return false; + if (req.getMethod() === "put") { + apiFunction = userMetadataPut_1.userMetadataPut; } - return yield apiKeyProtector_1.default(this.apiImpl, options, apiFunction); - }); - this.handleError = (err, _, __) => - __awaiter(this, void 0, void 0, function* () { - throw err; - }); + } + else if (id === constants_1.USER_SESSIONS_API) { + if (req.getMethod() === "get") { + apiFunction = userSessionsGet_1.userSessionsGet; + } + if (req.getMethod() === "post") { + apiFunction = userSessionsPost_1.userSessionsPost; + } + } + else if (id === constants_1.USER_PASSWORD_API) { + apiFunction = userPasswordPut_1.userPasswordPut; + } + else if (id === constants_1.USER_EMAIL_VERIFY_TOKEN_API) { + apiFunction = userEmailVerifyTokenPost_1.userEmailVerifyTokenPost; + } + // If the id doesnt match any APIs return false + if (apiFunction === undefined) { + return false; + } + return yield apiKeyProtector_1.default(this.apiImpl, options, apiFunction); + }); + this.handleError = (err, _, __) => __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; @@ -161,9 +144,7 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; this.returnAPIIdIfCanHandleRequest = (path, method) => { - const dashboardBundlePath = this.getAppInfo().apiBasePath.appendPath( - new normalisedURLPath_1.default(constants_1.DASHBOARD_API) - ); + const dashboardBundlePath = this.getAppInfo().apiBasePath.appendPath(new normalisedURLPath_1.default(constants_1.DASHBOARD_API)); if (utils_1.isApiPath(path, this.getAppInfo())) { return utils_1.getApiIdIfMatched(path, method); } @@ -194,10 +175,9 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } else { - throw new Error( - "Emailverification recipe has already been initialised. Please check your code for bugs." - ); + } + else { + throw new Error("Emailverification recipe has already been initialised. Please check your code for bugs."); } }; } diff --git a/lib/build/recipe/dashboard/recipeImplementation.d.ts b/lib/build/recipe/dashboard/recipeImplementation.d.ts index 881866f94..e18ef71f4 100644 --- a/lib/build/recipe/dashboard/recipeImplementation.d.ts +++ b/lib/build/recipe/dashboard/recipeImplementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { RecipeInterface } from "./types"; export default function getRecipeImplementation(): RecipeInterface; diff --git a/lib/build/recipe/dashboard/recipeImplementation.js b/lib/build/recipe/dashboard/recipeImplementation.js index 6f231cd85..2a3de05e4 100644 --- a/lib/build/recipe/dashboard/recipeImplementation.js +++ b/lib/build/recipe/dashboard/recipeImplementation.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const version_1 = require("../../version"); function getRecipeImplementation() { @@ -57,10 +35,7 @@ function getRecipeImplementation() { return __awaiter(this, void 0, void 0, function* () { let apiKeyHeaderValue = input.req.getHeaderValue("authorization"); // We receieve the api key as `Bearer API_KEY`, this retrieves just the key - apiKeyHeaderValue = - apiKeyHeaderValue === null || apiKeyHeaderValue === void 0 - ? void 0 - : apiKeyHeaderValue.split(" ")[1]; + apiKeyHeaderValue = apiKeyHeaderValue === null || apiKeyHeaderValue === void 0 ? void 0 : apiKeyHeaderValue.split(" ")[1]; if (apiKeyHeaderValue === undefined) { return false; } diff --git a/lib/build/recipe/dashboard/types.d.ts b/lib/build/recipe/dashboard/types.d.ts index 0ef772c19..a6f931af7 100644 --- a/lib/build/recipe/dashboard/types.d.ts +++ b/lib/build/recipe/dashboard/types.d.ts @@ -1,30 +1,29 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import { BaseRequest, BaseResponse } from "../../framework"; import { NormalisedAppinfo } from "../../types"; export declare type TypeInput = { apiKey: string; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { apiKey: string; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getDashboardBundleLocation(input: { userContext: any }): Promise; - shouldAllowAccess(input: { req: BaseRequest; config: TypeNormalisedInput; userContext: any }): Promise; + getDashboardBundleLocation(input: { + userContext: any; + }): Promise; + shouldAllowAccess(input: { + req: BaseRequest; + config: TypeNormalisedInput; + userContext: any; + }): Promise; }; export declare type APIOptions = { recipeImplementation: RecipeInterface; @@ -36,7 +35,10 @@ export declare type APIOptions = { appInfo: NormalisedAppinfo; }; export declare type APIInterface = { - dashboardGET: undefined | ((input: { options: APIOptions; userContext: any }) => Promise); + dashboardGET: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise); }; export declare type APIFunction = (apiImplementation: APIInterface, options: APIOptions) => Promise; export declare type RecipeIdForUser = "emailpassword" | "thirdparty" | "passwordless"; diff --git a/lib/build/recipe/dashboard/utils.d.ts b/lib/build/recipe/dashboard/utils.d.ts index 0fc5eb763..d6b04c353 100644 --- a/lib/build/recipe/dashboard/utils.d.ts +++ b/lib/build/recipe/dashboard/utils.d.ts @@ -1,30 +1,14 @@ -// @ts-nocheck import { BaseResponse } from "../../framework"; import NormalisedURLPath from "../../normalisedURLPath"; import { HTTPMethod, NormalisedAppinfo } from "../../types"; -import { - EmailPasswordUser, - PasswordlessUser, - RecipeIdForUser, - ThirdPartyUser, - TypeInput, - TypeNormalisedInput, -} from "./types"; +import { EmailPasswordUser, PasswordlessUser, RecipeIdForUser, ThirdPartyUser, TypeInput, TypeNormalisedInput } from "./types"; export declare function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput; export declare function isApiPath(path: NormalisedURLPath, appInfo: NormalisedAppinfo): boolean; export declare function getApiIdIfMatched(path: NormalisedURLPath, method: HTTPMethod): string | undefined; export declare function sendUnauthorisedAccess(res: BaseResponse): void; export declare function isValidRecipeId(recipeId: string): recipeId is RecipeIdForUser; -export declare function getUserForRecipeId( - userId: string, - recipeId: string -): Promise<{ +export declare function getUserForRecipeId(userId: string, recipeId: string): Promise<{ user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; + recipe: "emailpassword" | "thirdparty" | "passwordless" | "thirdpartyemailpassword" | "thirdpartypasswordless" | undefined; }>; +export declare function isRecipeInitialised(recipeId: RecipeIdForUser): boolean; diff --git a/lib/build/recipe/dashboard/utils.js b/lib/build/recipe/dashboard/utils.js index 7020add55..1b910f47a 100644 --- a/lib/build/recipe/dashboard/utils.js +++ b/lib/build/recipe/dashboard/utils.js @@ -13,53 +13,31 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.isRecipeInitialised = exports.getUserForRecipeId = exports.isValidRecipeId = exports.sendUnauthorisedAccess = exports.getApiIdIfMatched = exports.isApiPath = exports.validateAndNormaliseUserInput = void 0; const normalisedURLPath_1 = require("../../normalisedURLPath"); const utils_1 = require("../../utils"); const constants_1 = require("./constants"); const __1 = require("../.."); +const recipe_1 = require("../emailpassword/recipe"); +const recipe_2 = require("../thirdparty/recipe"); +const recipe_3 = require("../passwordless/recipe"); +const recipe_4 = require("../thirdpartyemailpassword/recipe"); +const recipe_5 = require("../thirdpartypasswordless/recipe"); function validateAndNormaliseUserInput(config) { if (config.apiKey.trim().length === 0) { throw new Error("apiKey provided to Dashboard recipe cannot be empty"); } - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); return { apiKey: config.apiKey, override, @@ -67,9 +45,7 @@ function validateAndNormaliseUserInput(config) { } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function isApiPath(path, appInfo) { - const dashboardRecipeBasePath = appInfo.apiBasePath.appendPath( - new normalisedURLPath_1.default(constants_1.DASHBOARD_API) - ); + const dashboardRecipeBasePath = appInfo.apiBasePath.appendPath(new normalisedURLPath_1.default(constants_1.DASHBOARD_API)); if (!path.startsWith(dashboardRecipeBasePath)) { return false; } @@ -147,3 +123,57 @@ function getUserForRecipeId(userId, recipeId) { }); } exports.getUserForRecipeId = getUserForRecipeId; +function isRecipeInitialised(recipeId) { + let isRecipeInitialised = false; + if (recipeId === "emailpassword") { + try { + recipe_1.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { } + if (!isRecipeInitialised) { + try { + recipe_4.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { } + } + } + else if (recipeId === "passwordless") { + try { + recipe_3.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { } + if (!isRecipeInitialised) { + try { + recipe_5.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { } + } + } + else if (recipeId === "thirdparty") { + try { + recipe_2.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { } + if (!isRecipeInitialised) { + try { + recipe_4.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { } + } + if (!isRecipeInitialised) { + try { + recipe_5.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } + catch (_) { } + } + } + return isRecipeInitialised; +} +exports.isRecipeInitialised = isRecipeInitialised; diff --git a/lib/build/recipe/emailpassword/api/emailExists.d.ts b/lib/build/recipe/emailpassword/api/emailExists.d.ts index 74f301a87..e0f0ae4d8 100644 --- a/lib/build/recipe/emailpassword/api/emailExists.d.ts +++ b/lib/build/recipe/emailpassword/api/emailExists.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function emailExists(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/emailExists.js b/lib/build/recipe/emailpassword/api/emailExists.js index 74a1abcbd..d6a7de7e3 100644 --- a/lib/build/recipe/emailpassword/api/emailExists.js +++ b/lib/build/recipe/emailpassword/api/emailExists.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); diff --git a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts index 866cf3c64..02820a357 100644 --- a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts +++ b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts @@ -1,6 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; -export default function generatePasswordResetToken( - apiImplementation: APIInterface, - options: APIOptions -): Promise; +export default function generatePasswordResetToken(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js index 3fa0fad07..d4e88af7a 100644 --- a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js +++ b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -55,10 +33,7 @@ function generatePasswordResetToken(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError( - options.config.resetPasswordUsingTokenFeature.formFieldsForGenerateTokenForm, - (yield options.req.getJSONBody()).formFields - ); + let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.resetPasswordUsingTokenFeature.formFieldsForGenerateTokenForm, (yield options.req.getJSONBody()).formFields); let result = yield apiImplementation.generatePasswordResetTokenPOST({ formFields, options, diff --git a/lib/build/recipe/emailpassword/api/implementation.d.ts b/lib/build/recipe/emailpassword/api/implementation.d.ts index 402db9918..a1619b2fd 100644 --- a/lib/build/recipe/emailpassword/api/implementation.d.ts +++ b/lib/build/recipe/emailpassword/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index dd82895e8..f52e53f5a 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const session_1 = require("../../session"); @@ -44,7 +22,7 @@ function getAPIImplementation() { }; }); }, - emailExistsGET: function ({ email, options, userContext }) { + emailExistsGET: function ({ email, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let user = yield options.recipeImplementation.getUserByEmail({ email, userContext }); return { @@ -53,7 +31,7 @@ function getAPIImplementation() { }; }); }, - generatePasswordResetTokenPOST: function ({ formFields, options, userContext }) { + generatePasswordResetTokenPOST: function ({ formFields, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let user = yield options.recipeImplementation.getUserByEmail({ email, userContext }); @@ -73,8 +51,7 @@ function getAPIImplementation() { status: "OK", }; } - let passwordResetLink = - options.appInfo.websiteDomain.getAsStringDangerous() + + let passwordResetLink = options.appInfo.websiteDomain.getAsStringDangerous() + options.appInfo.websiteBasePath.getAsStringDangerous() + "/reset-password?token=" + response.token + @@ -92,7 +69,7 @@ function getAPIImplementation() { }; }); }, - passwordResetPOST: function ({ formFields, token, options, userContext }) { + passwordResetPOST: function ({ formFields, token, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let newPassword = formFields.filter((f) => f.id === "password")[0].value; let response = yield options.recipeImplementation.resetPasswordUsingToken({ @@ -103,7 +80,7 @@ function getAPIImplementation() { return response; }); }, - signInPOST: function ({ formFields, options, userContext }) { + signInPOST: function ({ formFields, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; @@ -112,14 +89,7 @@ function getAPIImplementation() { return response; } let user = response.user; - let session = yield session_1.default.createNewSession( - options.res, - user.id, - user.recipeUserId, - {}, - {}, - userContext - ); + let session = yield session_1.default.createNewSession(options.req, options.res, user.id, user.recipeUserId, {}, {}, userContext); return { status: "OK", session, @@ -127,7 +97,7 @@ function getAPIImplementation() { }; }); }, - signUpPOST: function ({ formFields, options, userContext }) { + signUpPOST: function ({ formFields, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; @@ -136,20 +106,13 @@ function getAPIImplementation() { return response; } let user = response.user; - let session = yield session_1.default.createNewSession( - options.res, - user.id, - user.recipeUserId, - {}, - {}, - userContext - ); + let session = yield session_1.default.createNewSession(options.req, options.res, user.id, user.recipeUserId, {}, {}, userContext); return { status: "OK", session, user, createdNewUser: true, - createdNewRecipeUser: true, + createdNewRecipeUser: true, // TODO }; }); }, diff --git a/lib/build/recipe/emailpassword/api/passwordReset.d.ts b/lib/build/recipe/emailpassword/api/passwordReset.d.ts index 4b5e6641c..b3eff0ec7 100644 --- a/lib/build/recipe/emailpassword/api/passwordReset.d.ts +++ b/lib/build/recipe/emailpassword/api/passwordReset.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function passwordReset(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/passwordReset.js b/lib/build/recipe/emailpassword/api/passwordReset.js index 4c29fffe4..7e0e3a849 100644 --- a/lib/build/recipe/emailpassword/api/passwordReset.js +++ b/lib/build/recipe/emailpassword/api/passwordReset.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -56,10 +34,7 @@ function passwordReset(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError( - options.config.resetPasswordUsingTokenFeature.formFieldsForPasswordResetForm, - (yield options.req.getJSONBody()).formFields - ); + let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.resetPasswordUsingTokenFeature.formFieldsForPasswordResetForm, (yield options.req.getJSONBody()).formFields); let token = (yield options.req.getJSONBody()).token; if (token === undefined) { throw new error_1.default({ @@ -79,14 +54,11 @@ function passwordReset(apiImplementation, options) { options, userContext: utils_3.makeDefaultUserContextFromAPI(options.req), }); - utils_1.send200Response( - options.res, - result.status === "OK" - ? { - status: "OK", - } - : result - ); + utils_1.send200Response(options.res, result.status === "OK" + ? { + status: "OK", + } + : result); return true; }); } diff --git a/lib/build/recipe/emailpassword/api/signin.d.ts b/lib/build/recipe/emailpassword/api/signin.d.ts index 6ca49c1fc..73c69f7c8 100644 --- a/lib/build/recipe/emailpassword/api/signin.d.ts +++ b/lib/build/recipe/emailpassword/api/signin.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signInAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/signin.js b/lib/build/recipe/emailpassword/api/signin.js index 971c51911..039b3beda 100644 --- a/lib/build/recipe/emailpassword/api/signin.js +++ b/lib/build/recipe/emailpassword/api/signin.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -55,10 +33,7 @@ function signInAPI(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError( - options.config.signInFeature.formFields, - (yield options.req.getJSONBody()).formFields - ); + let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.signInFeature.formFields, (yield options.req.getJSONBody()).formFields); let result = yield apiImplementation.signInPOST({ formFields, options, @@ -69,7 +44,8 @@ function signInAPI(apiImplementation, options) { status: "OK", user: result.user, }); - } else { + } + else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/emailpassword/api/signup.d.ts b/lib/build/recipe/emailpassword/api/signup.d.ts index bd1fa2e88..939be43a2 100644 --- a/lib/build/recipe/emailpassword/api/signup.d.ts +++ b/lib/build/recipe/emailpassword/api/signup.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signUpAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/signup.js b/lib/build/recipe/emailpassword/api/signup.js index 9587e868a..bb21d0b1a 100644 --- a/lib/build/recipe/emailpassword/api/signup.js +++ b/lib/build/recipe/emailpassword/api/signup.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -56,10 +34,7 @@ function signUpAPI(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError( - options.config.signUpFeature.formFields, - (yield options.req.getJSONBody()).formFields - ); + let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.signUpFeature.formFields, (yield options.req.getJSONBody()).formFields); let result = yield apiImplementation.signUpPOST({ formFields, options, @@ -70,9 +45,11 @@ function signUpAPI(apiImplementation, options) { status: "OK", user: result.user, }); - } else if (result.status === "GENERAL_ERROR") { + } + else if (result.status === "GENERAL_ERROR") { utils_1.send200Response(options.res, result); - } else { + } + else { throw new error_1.default({ type: error_1.default.FIELD_ERROR, payload: [ diff --git a/lib/build/recipe/emailpassword/api/utils.d.ts b/lib/build/recipe/emailpassword/api/utils.d.ts index 5579f71cc..d028348e5 100644 --- a/lib/build/recipe/emailpassword/api/utils.d.ts +++ b/lib/build/recipe/emailpassword/api/utils.d.ts @@ -1,11 +1,5 @@ -// @ts-nocheck import { NormalisedFormField } from "../types"; -export declare function validateFormFieldsOrThrowError( - configFormFields: NormalisedFormField[], - formFieldsRaw: any -): Promise< - { - id: string; - value: string; - }[] ->; +export declare function validateFormFieldsOrThrowError(configFormFields: NormalisedFormField[], formFieldsRaw: any): Promise<{ + id: string; + value: string; +}[]>; diff --git a/lib/build/recipe/emailpassword/api/utils.js b/lib/build/recipe/emailpassword/api/utils.js index 1d9784a5b..5622399ac 100644 --- a/lib/build/recipe/emailpassword/api/utils.js +++ b/lib/build/recipe/emailpassword/api/utils.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateFormFieldsOrThrowError = void 0; const error_1 = require("../error"); const constants_1 = require("../constants"); function validateFormFieldsOrThrowError(configFormFields, formFieldsRaw) { @@ -91,7 +70,8 @@ function validateFormOrThrowError(inputs, configFormFields) { error: "Field is not optional", id: field.id, }); - } else { + } + else { // Otherwise, use validate function. const error = yield field.validate(input.value); // If error, add it. diff --git a/lib/build/recipe/emailpassword/constants.d.ts b/lib/build/recipe/emailpassword/constants.d.ts index 9b58b697a..98af9478d 100644 --- a/lib/build/recipe/emailpassword/constants.d.ts +++ b/lib/build/recipe/emailpassword/constants.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export declare const FORM_FIELD_PASSWORD_ID = "password"; export declare const FORM_FIELD_EMAIL_ID = "email"; export declare const SIGN_UP_API = "/signup"; diff --git a/lib/build/recipe/emailpassword/constants.js b/lib/build/recipe/emailpassword/constants.js index 5a9dad752..465baa718 100644 --- a/lib/build/recipe/emailpassword/constants.js +++ b/lib/build/recipe/emailpassword/constants.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.SIGNUP_EMAIL_EXISTS_API = exports.PASSWORD_RESET_API = exports.GENERATE_PASSWORD_RESET_TOKEN_API = exports.SIGN_IN_API = exports.SIGN_UP_API = exports.FORM_FIELD_EMAIL_ID = exports.FORM_FIELD_PASSWORD_ID = void 0; exports.FORM_FIELD_PASSWORD_ID = "password"; exports.FORM_FIELD_EMAIL_ID = "email"; exports.SIGN_UP_API = "/signup"; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 31b3d1fd8..249521031 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,28 +1,15 @@ -// @ts-nocheck import { TypeEmailPasswordEmailDeliveryInput, User, RecipeInterface } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService - implements EmailDeliveryInterface { +export default class BackwardCompatibilityService implements EmailDeliveryInterface { private recipeInterfaceImpl; private isInServerlessEnv; private appInfo; private resetPasswordUsingTokenFeature; - constructor( - recipeInterfaceImpl: RecipeInterface, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - resetPasswordUsingTokenFeature?: { - createAndSendCustomEmail?: ( - user: User, - passwordResetURLWithToken: string, - userContext: any - ) => Promise; - } - ); - sendEmail: ( - input: import("../../../types").TypeEmailPasswordPasswordResetEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + constructor(recipeInterfaceImpl: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, resetPasswordUsingTokenFeature?: { + createAndSendCustomEmail?: (user: User, passwordResetURLWithToken: string, userContext: any) => Promise; + }); + sendEmail: (input: TypeEmailPasswordEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js index 69a1f3f81..13cf2bdcc 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -1,79 +1,55 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const passwordResetFunctions_1 = require("../../../passwordResetFunctions"); class BackwardCompatibilityService { constructor(recipeInterfaceImpl, appInfo, isInServerlessEnv, resetPasswordUsingTokenFeature) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - let user = yield this.recipeInterfaceImpl.getUserById({ - userId: input.user.recipeUserId, - userContext: input.userContext, - }); - if (user === undefined) { - throw Error("this should never come here"); - } - try { - if (!this.isInServerlessEnv) { - this.resetPasswordUsingTokenFeature - .createAndSendCustomEmail(user, input.passwordResetLink, input.userContext) - .catch((_) => {}); - } else { - // see https://github.com/supertokens/supertokens-node/pull/135 - yield this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( - user, - input.passwordResetLink, - input.userContext - ); - } - } catch (_) {} + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + let user = yield this.recipeInterfaceImpl.getUserById({ + userId: input.user.recipeUserId, + userContext: input.userContext, }); + if (user === undefined) { + throw Error("this should never come here"); + } + // we add this here cause the user may have overridden the sendEmail function + // to change the input email and if we don't do this, the input email + // will get reset by the getUserById call above. + user.email = input.user.email; + try { + if (!this.isInServerlessEnv) { + this.resetPasswordUsingTokenFeature + .createAndSendCustomEmail(user, input.passwordResetLink, input.userContext) + .catch((_) => { }); + } + else { + // see https://github.com/supertokens/supertokens-node/pull/135 + yield this.resetPasswordUsingTokenFeature.createAndSendCustomEmail(user, input.passwordResetLink, input.userContext); + } + } + catch (_) { } + }); this.recipeInterfaceImpl = recipeInterfaceImpl; this.isInServerlessEnv = isInServerlessEnv; this.appInfo = appInfo; { - let inputCreateAndSendCustomEmail = - resetPasswordUsingTokenFeature === null || resetPasswordUsingTokenFeature === void 0 - ? void 0 - : resetPasswordUsingTokenFeature.createAndSendCustomEmail; + let inputCreateAndSendCustomEmail = resetPasswordUsingTokenFeature === null || resetPasswordUsingTokenFeature === void 0 ? void 0 : resetPasswordUsingTokenFeature.createAndSendCustomEmail; this.resetPasswordUsingTokenFeature = inputCreateAndSendCustomEmail !== undefined ? { - createAndSendCustomEmail: inputCreateAndSendCustomEmail, - } + createAndSendCustomEmail: inputCreateAndSendCustomEmail, + } : { - createAndSendCustomEmail: passwordResetFunctions_1.createAndSendCustomEmail(this.appInfo), - }; + createAndSendCustomEmail: passwordResetFunctions_1.createAndSendCustomEmail(this.appInfo), + }; } } } diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts index 4de04d983..dd2ef062c 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/index.js index fc7c1fa88..a3d9c24c8 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/index.js @@ -14,5 +14,6 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPService = void 0; const smtp_1 = require("./smtp"); exports.SMTPService = smtp_1.default; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts index e2a97045f..d6b78e973 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts @@ -1,13 +1,10 @@ -// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { TypeEmailPasswordEmailDeliveryInput } from "../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; export default class SMTPService implements EmailDeliveryInterface { serviceImpl: ServiceInterface; constructor(config: TypeInput); - sendEmail: ( - input: import("../../../types").TypeEmailPasswordPasswordResetEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + sendEmail: (input: TypeEmailPasswordEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js index 2975b7375..a91e9c1e1 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js @@ -1,48 +1,23 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = require("supertokens-js-override"); const serviceImplementation_1 = require("./serviceImplementation"); class SMTPService { constructor(config) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - yield this.serviceImpl.sendRawEmail( - Object.assign(Object.assign({}, content), { userContext: input.userContext }) - ); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + yield this.serviceImpl.sendRawEmail(Object.assign(Object.assign({}, content), { userContext: input.userContext })); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -52,9 +27,7 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default( - serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) - ); + let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts index 34240509a..403345e85 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import { TypeEmailPasswordPasswordResetEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; -export default function getPasswordResetEmailContent( - input: TypeEmailPasswordPasswordResetEmailDeliveryInput -): GetContentResult; +export default function getPasswordResetEmailContent(input: TypeEmailPasswordPasswordResetEmailDeliveryInput): GetContentResult; export declare function getPasswordResetEmailHTML(appName: string, email: string, resetLink: string): string; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js index 58896b307..76e4ffed9 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getPasswordResetEmailHTML = void 0; const supertokens_1 = require("../../../../../supertokens"); function getPasswordResetEmailContent(input) { let supertokens = supertokens_1.default.getInstanceOrThrowError(); @@ -499,13 +500,6 @@ function getPasswordResetEmailHTML(appName, email, resetLink) { text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts index 95fdbda32..8336455b9 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts @@ -1,11 +1,7 @@ -// @ts-nocheck import { TypeEmailPasswordEmailDeliveryInput } from "../../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation( - transporter: Transporter, - from: { - name: string; - email: string; - } -): ServiceInterface; +export declare function getServiceImplementation(transporter: Transporter, from: { + name: string; + email: string; +}): ServiceInterface; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js index 0ab93d789..b966408b8 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getServiceImplementation = void 0; const passwordReset_1 = require("../passwordReset"); function getServiceImplementation(transporter, from) { return { @@ -57,7 +36,8 @@ function getServiceImplementation(transporter, from) { subject: input.subject, html: input.body, }); - } else { + } + else { yield transporter.sendMail({ from: `${from.name} <${from.email}>`, to: input.toEmail, diff --git a/lib/build/recipe/emailpassword/error.d.ts b/lib/build/recipe/emailpassword/error.d.ts index d4dc2cf9b..a96613142 100644 --- a/lib/build/recipe/emailpassword/error.d.ts +++ b/lib/build/recipe/emailpassword/error.d.ts @@ -1,20 +1,15 @@ -// @ts-nocheck import STError from "../../error"; export default class SessionError extends STError { static FIELD_ERROR: "FIELD_ERROR"; - constructor( - options: - | { - type: "FIELD_ERROR"; - payload: { - id: string; - error: string; - }[]; - message: string; - } - | { - type: "BAD_INPUT_ERROR"; - message: string; - } - ); + constructor(options: { + type: "FIELD_ERROR"; + payload: { + id: string; + error: string; + }[]; + message: string; + } | { + type: "BAD_INPUT_ERROR"; + message: string; + }); } diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index b56deadee..7e7915eb3 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -1,36 +1,21 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIOptions, APIInterface, TypeEmailPasswordEmailDeliveryInput } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static signUp( - email: string, - password: string, - userContext?: any - ): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - >; - static signIn( - email: string, - password: string, - userContext?: any - ): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - >; + static signUp(email: string, password: string, userContext?: any): Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + }>; + static signIn(email: string, password: string, userContext?: any): Promise<{ + status: "OK"; + user: User; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + }>; static getUserById(userId: string, userContext?: any): Promise; static getUserByEmail(email: string, userContext?: any): Promise; /** @@ -44,33 +29,19 @@ export default class Wrapper { * * And we want to allow primaryUserId being passed in. */ - static createResetPasswordToken( - userId: string, - email: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "UNKNOWN_USER_ID_ERROR"; - } - >; - static resetPasswordUsingToken( - token: string, - newPassword: string, - userContext?: any - ): Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + static createResetPasswordToken(userId: string, email: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "UNKNOWN_USER_ID_ERROR"; + }>; + static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ + status: "OK"; + email: string; + userId: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; static updateEmailOrPassword(input: { userId: string; email?: string; @@ -79,11 +50,9 @@ export default class Wrapper { }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; }>; - static sendEmail( - input: TypeEmailPasswordEmailDeliveryInput & { - userContext?: any; - } - ): Promise; + static sendEmail(input: TypeEmailPasswordEmailDeliveryInput & { + userContext?: any; + }): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/emailpassword/index.js b/lib/build/recipe/emailpassword/index.js index c430e0567..14d12280c 100644 --- a/lib/build/recipe/emailpassword/index.js +++ b/lib/build/recipe/emailpassword/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.sendEmail = exports.updateEmailOrPassword = exports.resetPasswordUsingToken = exports.createResetPasswordToken = exports.getUserByEmail = exports.getUserById = exports.signIn = exports.signUp = exports.Error = exports.init = void 0; const recipe_1 = require("./recipe"); const error_1 = require("./error"); class Wrapper { @@ -100,16 +79,12 @@ class Wrapper { }); } static updateEmailOrPassword(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); } static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { let recipeInstance = recipe_1.default.getInstanceOrThrowError(); - return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail( - Object.assign({ userContext: {} }, input) - ); + return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } } diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index 56b10c948..2169ad4d9 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -1,6 +1,3 @@ -// @ts-nocheck import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function createAndSendCustomEmail( - appInfo: NormalisedAppinfo -): (user: User, passwordResetURLWithToken: string) => Promise; +export declare function createAndSendCustomEmail(appInfo: NormalisedAppinfo): (user: User, passwordResetURLWithToken: string) => Promise; diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.js b/lib/build/recipe/emailpassword/passwordResetFunctions.js index 0bd55b876..48312c9da 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.js +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.js @@ -13,87 +13,62 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.createAndSendCustomEmail = void 0; const axios_1 = require("axios"); const logger_1 = require("../../logger"); function createAndSendCustomEmail(appInfo) { - return (user, passwordResetURLWithToken) => - __awaiter(this, void 0, void 0, function* () { - // related issue: https://github.com/supertokens/supertokens-node/issues/38 - if (process.env.TEST_MODE === "testing") { - return; - } - try { - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.io/0/st/auth/password/reset", - data: { - email: user.email, - appName: appInfo.appName, - passwordResetURL: passwordResetURLWithToken, - }, - headers: { - "api-version": 0, - }, - }); - logger_1.logDebugMessage(`Password reset email sent to ${user.email}`); - } catch (error) { - logger_1.logDebugMessage("Error sending password reset email"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } - } else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + return (user, passwordResetURLWithToken) => __awaiter(this, void 0, void 0, function* () { + // related issue: https://github.com/supertokens/supertokens-node/issues/38 + if (process.env.TEST_MODE === "testing") { + return; + } + try { + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.io/0/st/auth/password/reset", + data: { + email: user.email, + appName: appInfo.appName, + passwordResetURL: passwordResetURLWithToken, + }, + headers: { + "api-version": 0, + }, + }); + logger_1.logDebugMessage(`Password reset email sent to ${user.email}`); + } + catch (error) { + logger_1.logDebugMessage("Error sending password reset email"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage( - JSON.stringify( - { - email: user.email, - appName: appInfo.appName, - passwordResetURL: passwordResetURLWithToken, - }, - null, - 2 - ) - ); + else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + } + else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); } - }); + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage(JSON.stringify({ + email: user.email, + appName: appInfo.appName, + passwordResetURL: passwordResetURLWithToken, + }, null, 2)); + } + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; diff --git a/lib/build/recipe/emailpassword/recipe.d.ts b/lib/build/recipe/emailpassword/recipe.d.ts index f2bd86c2c..1592f333d 100644 --- a/lib/build/recipe/emailpassword/recipe.d.ts +++ b/lib/build/recipe/emailpassword/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface } from "./types"; import { NormalisedAppinfo, APIHandled, HTTPMethod, RecipeListFunction } from "../../types"; @@ -16,26 +15,14 @@ export default class Recipe extends RecipeModule { apiImpl: APIInterface; isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput | undefined, - ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput | undefined, ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + }); static getInstanceOrThrowError(): Recipe; static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - _path: NormalisedURLPath, - _method: HTTPMethod - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _path: NormalisedURLPath, _method: HTTPMethod) => Promise; handleError: (err: STError, _request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/emailpassword/recipe.js b/lib/build/recipe/emailpassword/recipe.js index 9dc18f245..d60ed5bac 100644 --- a/lib/build/recipe/emailpassword/recipe.js +++ b/lib/build/recipe/emailpassword/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -83,9 +61,7 @@ class Recipe extends recipeModule_1.default { }, { method: "post", - pathWithoutApiBasePath: new normalisedURLPath_1.default( - constants_1.GENERATE_PASSWORD_RESET_TOKEN_API - ), + pathWithoutApiBasePath: new normalisedURLPath_1.default(constants_1.GENERATE_PASSWORD_RESET_TOKEN_API), id: constants_1.GENERATE_PASSWORD_RESET_TOKEN_API, disabled: this.apiImpl.generatePasswordResetTokenPOST === undefined, }, @@ -103,46 +79,50 @@ class Recipe extends recipeModule_1.default { }, ]; }; - this.handleAPIRequest = (id, req, res, _path, _method) => - __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - emailDelivery: this.emailDelivery, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.SIGN_UP_API) { - return yield signup_1.default(this.apiImpl, options); - } else if (id === constants_1.SIGN_IN_API) { - return yield signin_1.default(this.apiImpl, options); - } else if (id === constants_1.GENERATE_PASSWORD_RESET_TOKEN_API) { - return yield generatePasswordResetToken_1.default(this.apiImpl, options); - } else if (id === constants_1.PASSWORD_RESET_API) { - return yield passwordReset_1.default(this.apiImpl, options); - } else if (id === constants_1.SIGNUP_EMAIL_EXISTS_API) { - return yield emailExists_1.default(this.apiImpl, options); + this.handleAPIRequest = (id, req, res, _path, _method) => __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + emailDelivery: this.emailDelivery, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.SIGN_UP_API) { + return yield signup_1.default(this.apiImpl, options); + } + else if (id === constants_1.SIGN_IN_API) { + return yield signin_1.default(this.apiImpl, options); + } + else if (id === constants_1.GENERATE_PASSWORD_RESET_TOKEN_API) { + return yield generatePasswordResetToken_1.default(this.apiImpl, options); + } + else if (id === constants_1.PASSWORD_RESET_API) { + return yield passwordReset_1.default(this.apiImpl, options); + } + else if (id === constants_1.SIGNUP_EMAIL_EXISTS_API) { + return yield emailExists_1.default(this.apiImpl, options); + } + return false; + }); + this.handleError = (err, _request, response) => __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + if (err.type === error_1.default.FIELD_ERROR) { + return utils_2.send200Response(response, { + status: "FIELD_ERROR", + formFields: err.payload, + }); } - return false; - }); - this.handleError = (err, _request, response) => - __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - if (err.type === error_1.default.FIELD_ERROR) { - return utils_2.send200Response(response, { - status: "FIELD_ERROR", - formFields: err.payload, - }); - } else { - throw err; - } - } else { + else { throw err; } - }); + } + else { + throw err; + } + }); this.getAllCORSHeaders = () => { return []; }; @@ -150,25 +130,22 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; // extra instance functions below............... - this.getEmailForUserId = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo !== undefined) { - return { - status: "OK", - email: userInfo.email, - }; - } + this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo !== undefined) { return { - status: "UNKNOWN_USER_ID_ERROR", + status: "OK", + email: userInfo.email, }; - }); + } + return { + status: "UNKNOWN_USER_ID_ERROR", + }; + }); this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -181,9 +158,7 @@ class Recipe extends recipeModule_1.default { */ this.emailDelivery = ingredients.emailDelivery === undefined - ? new emaildelivery_1.default( - this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) - ) + ? new emaildelivery_1.default(this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv)) : ingredients.emailDelivery; postSuperTokensInitCallbacks_1.PostSuperTokensInitCallbacks.addPostInitCallback(() => { const emailVerificationRecipe = recipe_1.default.getInstance(); @@ -205,7 +180,8 @@ class Recipe extends recipeModule_1.default { emailDelivery: undefined, }); return Recipe.instance; - } else { + } + else { throw new Error("Emailpassword recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/emailpassword/recipeImplementation.d.ts b/lib/build/recipe/emailpassword/recipeImplementation.d.ts index 86bf78a27..8a3a26d7c 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.d.ts +++ b/lib/build/recipe/emailpassword/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/emailpassword/recipeImplementation.js b/lib/build/recipe/emailpassword/recipeImplementation.js index 307ac1e64..b222492f0 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -1,40 +1,18 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); function getRecipeInterface(querier) { return { - signUp: function ({ email, password }) { + signUp: function ({ email, password, }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signup"), { email, @@ -42,14 +20,15 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return response; - } else { + } + else { return { status: "EMAIL_ALREADY_EXISTS_ERROR", }; } }); }, - signIn: function ({ email, password }) { + signIn: function ({ email, password, }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signin"), { email, @@ -57,7 +36,8 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return response; - } else { + } + else { return { status: "WRONG_CREDENTIALS_ERROR", }; @@ -71,7 +51,8 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } else { + } + else { return undefined; } }); @@ -83,41 +64,37 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } else { + } + else { return undefined; } }); }, - createResetPasswordToken: function ({ userId }) { + createResetPasswordToken: function ({ userId, }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/user/password/reset/token"), - { - userId, - } - ); + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/password/reset/token"), { + userId, + }); if (response.status === "OK") { return { status: "OK", token: response.token, }; - } else { + } + else { return { status: "UNKNOWN_USER_ID_ERROR", }; } }); }, - resetPasswordUsingToken: function ({ token, newPassword }) { + resetPasswordUsingToken: function ({ token, newPassword, }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/user/password/reset"), - { - method: "token", - token, - newPassword, - } - ); + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/password/reset"), { + method: "token", + token, + newPassword, + }); return response; }); }, @@ -132,11 +109,13 @@ function getRecipeInterface(querier) { return { status: "OK", }; - } else if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { + } + else if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return { status: "EMAIL_ALREADY_EXISTS_ERROR", }; - } else { + } + else { return { status: "UNKNOWN_USER_ID_ERROR", }; diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index f4c3d4ef5..28eb67257 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -1,26 +1,16 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { - TypeInput as EmailDeliveryTypeInput, - TypeInputWithService as EmailDeliveryTypeInputWithService, -} from "../../ingredients/emaildelivery/types"; +import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; import { GeneralErrorResponse, NormalisedAppinfo } from "../../types"; export declare type TypeNormalisedInput = { signUpFeature: TypeNormalisedInputSignUp; signInFeature: TypeNormalisedInputSignIn; - getEmailDeliveryConfig: ( - recipeImpl: RecipeInterface, - isInServerlessEnv: boolean - ) => EmailDeliveryTypeInputWithService; + getEmailDeliveryConfig: (recipeImpl: RecipeInterface, isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; resetPasswordUsingTokenFeature: TypeNormalisedInputResetPasswordUsingTokenFeature; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -68,10 +58,7 @@ export declare type TypeInput = { emailDelivery?: EmailDeliveryTypeInput; resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -80,30 +67,30 @@ export declare type RecipeInterface = { email: string; password: string; userContext: any; - }): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + }>; signIn(input: { email: string; password: string; userContext: any; - }): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - >; - getUserById(input: { userId: string; userContext: any }): Promise; - getUserByEmail(input: { email: string; userContext: any }): Promise; + }): Promise<{ + status: "OK"; + user: User; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + }>; + getUserById(input: { + userId: string; + userContext: any; + }): Promise; + getUserByEmail(input: { + email: string; + userContext: any; + }): Promise; /** * We do not make email optional here cause we want to * allow passing in primaryUserId. If we make email optional, @@ -119,29 +106,23 @@ export declare type RecipeInterface = { userId: string; email: string; userContext: any; - }): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "UNKNOWN_USER_ID_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + token: string; + } | { + status: "UNKNOWN_USER_ID_ERROR"; + }>; resetPasswordUsingToken(input: { token: string; newPassword: string; userContext: any; - }): Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + email: string; + userId: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; updateEmailOrPassword(input: { userId: string; email?: string; @@ -162,143 +143,104 @@ export declare type APIOptions = { emailDelivery: EmailDeliveryIngredient; }; export declare type APIInterface = { - emailExistsGET: - | undefined - | ((input: { - email: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >); - generatePasswordResetTokenPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - } - | { - status: "PASSWORD_RESET_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); - passwordResetPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - | GeneralErrorResponse - >); - signInPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - | GeneralErrorResponse - >); - signUpPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewUser: boolean; - session: SessionContainerInterface; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); - linkAccountToExistingAccountPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); + emailExistsGET: undefined | ((input: { + email: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + } | GeneralErrorResponse>); + generatePasswordResetTokenPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + } | { + status: "PASSWORD_RESET_NOT_ALLOWED"; + reason: string; + } | GeneralErrorResponse>); + passwordResetPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + email: string; + userId: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } | GeneralErrorResponse>); + signInPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + session: SessionContainerInterface; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + } | GeneralErrorResponse>); + signUpPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewUser: boolean; + session: SessionContainerInterface; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } | GeneralErrorResponse>); + linkAccountToExistingAccountPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } | GeneralErrorResponse>); }; export declare type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; diff --git a/lib/build/recipe/emailpassword/utils.d.ts b/lib/build/recipe/emailpassword/utils.d.ts index c48cdc96d..21051df4b 100644 --- a/lib/build/recipe/emailpassword/utils.d.ts +++ b/lib/build/recipe/emailpassword/utils.d.ts @@ -1,23 +1,7 @@ -// @ts-nocheck import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput, NormalisedFormField, TypeInputFormField } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function validateAndNormaliseUserInput( - recipeInstance: Recipe, - appInfo: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; export declare function normaliseSignUpFormFields(formFields?: TypeInputFormField[]): NormalisedFormField[]; -export declare function defaultPasswordValidator( - value: any -): Promise< - | "Development bug: Please make sure the password field yields a string" - | "Password must contain at least 8 characters, including a number" - | "Password's length must be lesser than 100 characters" - | "Password must contain at least one alphabet" - | "Password must contain at least one number" - | undefined ->; -export declare function defaultEmailValidator( - value: any -): Promise<"Development bug: Please make sure the email field yields a string" | "Email is invalid" | undefined>; +export declare function defaultPasswordValidator(value: any): Promise<"Development bug: Please make sure the password field yields a string" | "Password must contain at least 8 characters, including a number" | "Password's length must be lesser than 100 characters" | "Password must contain at least one alphabet" | "Password must contain at least one number" | undefined>; +export declare function defaultEmailValidator(value: any): Promise<"Development bug: Please make sure the email field yields a string" | "Email is invalid" | undefined>; diff --git a/lib/build/recipe/emailpassword/utils.js b/lib/build/recipe/emailpassword/utils.js index 880c657c4..53f175c63 100644 --- a/lib/build/recipe/emailpassword/utils.js +++ b/lib/build/recipe/emailpassword/utils.js @@ -13,61 +13,27 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultEmailValidator = exports.defaultPasswordValidator = exports.normaliseSignUpFormFields = exports.validateAndNormaliseUserInput = void 0; const constants_1 = require("./constants"); const backwardCompatibility_1 = require("./emaildelivery/services/backwardCompatibility"); function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { - let signUpFeature = validateAndNormaliseSignupConfig( - recipeInstance, - appInfo, - config === undefined ? undefined : config.signUpFeature - ); + let signUpFeature = validateAndNormaliseSignupConfig(recipeInstance, appInfo, config === undefined ? undefined : config.signUpFeature); let signInFeature = validateAndNormaliseSignInConfig(recipeInstance, appInfo, signUpFeature); let resetPasswordUsingTokenFeature = validateAndNormaliseResetPasswordUsingTokenConfig(signUpFeature); - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); function getEmailDeliveryConfig(recipeImpl, isInServerlessEnv) { var _a; - let emailService = - (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 - ? void 0 - : _a.service; + let emailService = (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; /** * following code is for backward compatibility. * if user has not passed emailDelivery config, we @@ -76,14 +42,9 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { * createAndSendCustomEmail implementation which calls our supertokens API */ if (emailService === undefined) { - emailService = new backwardCompatibility_1.default( - recipeImpl, - appInfo, - isInServerlessEnv, - config === null || config === void 0 ? void 0 : config.resetPasswordUsingTokenFeature - ); + emailService = new backwardCompatibility_1.default(recipeImpl, appInfo, isInServerlessEnv, config === null || config === void 0 ? void 0 : config.resetPasswordUsingTokenFeature); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -95,8 +56,7 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService, - }); + service: emailService }); } return { signUpFeature, @@ -111,21 +71,21 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(signUpConfig) { let formFieldsForPasswordResetForm = signUpConfig.formFields .filter((filter) => filter.id === constants_1.FORM_FIELD_PASSWORD_ID) .map((field) => { - return { - id: field.id, - validate: field.validate, - optional: false, - }; - }); + return { + id: field.id, + validate: field.validate, + optional: false, + }; + }); let formFieldsForGenerateTokenForm = signUpConfig.formFields .filter((filter) => filter.id === constants_1.FORM_FIELD_EMAIL_ID) .map((field) => { - return { - id: field.id, - validate: field.validate, - optional: false, - }; - }); + return { + id: field.id, + validate: field.validate, + optional: false, + }; + }); return { formFieldsForPasswordResetForm, formFieldsForGenerateTokenForm, @@ -133,18 +93,15 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(signUpConfig) { } function normaliseSignInFormFields(formFields) { return formFields - .filter( - (filter) => - filter.id === constants_1.FORM_FIELD_EMAIL_ID || filter.id === constants_1.FORM_FIELD_PASSWORD_ID - ) + .filter((filter) => filter.id === constants_1.FORM_FIELD_EMAIL_ID || filter.id === constants_1.FORM_FIELD_PASSWORD_ID) .map((field) => { - return { - id: field.id, - // see issue: https://github.com/supertokens/supertokens-node/issues/36 - validate: field.id === constants_1.FORM_FIELD_EMAIL_ID ? field.validate : defaultValidator, - optional: false, - }; - }); + return { + id: field.id, + // see issue: https://github.com/supertokens/supertokens-node/issues/36 + validate: field.id === constants_1.FORM_FIELD_EMAIL_ID ? field.validate : defaultValidator, + optional: false, + }; + }); } function validateAndNormaliseSignInConfig(_, __, signUpConfig) { let formFields = normaliseSignInFormFields(signUpConfig.formFields); @@ -162,13 +119,15 @@ function normaliseSignUpFormFields(formFields) { validate: field.validate === undefined ? defaultPasswordValidator : field.validate, optional: false, }); - } else if (field.id === constants_1.FORM_FIELD_EMAIL_ID) { + } + else if (field.id === constants_1.FORM_FIELD_EMAIL_ID) { normalisedFormFields.push({ id: field.id, validate: field.validate === undefined ? defaultEmailValidator : field.validate, optional: false, }); - } else { + } + else { normalisedFormFields.push({ id: field.id, validate: field.validate === undefined ? defaultValidator : field.validate, @@ -239,11 +198,7 @@ function defaultEmailValidator(value) { if (typeof value !== "string") { return "Development bug: Please make sure the email field yields a string"; } - if ( - value.match( - /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ - ) === null - ) { + if (value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/) === null) { return "Email is invalid"; } return undefined; diff --git a/lib/build/recipe/emailverification/api/emailVerify.d.ts b/lib/build/recipe/emailverification/api/emailVerify.d.ts index bd6b5b6c4..3504f8e34 100644 --- a/lib/build/recipe/emailverification/api/emailVerify.d.ts +++ b/lib/build/recipe/emailverification/api/emailVerify.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function emailVerify(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailverification/api/emailVerify.js b/lib/build/recipe/emailverification/api/emailVerify.js index f413ecf7e..857481ee0 100644 --- a/lib/build/recipe/emailverification/api/emailVerify.js +++ b/lib/build/recipe/emailverification/api/emailVerify.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); @@ -71,12 +49,7 @@ function emailVerify(apiImplementation, options) { message: "The email verification token must be a string", }); } - const session = yield session_1.default.getSession( - options.req, - options.res, - { overrideGlobalClaimValidators: () => [], sessionRequired: false }, - userContext - ); + const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [], sessionRequired: false }, userContext); let response = yield apiImplementation.verifyEmailPOST({ token, options, @@ -85,19 +58,16 @@ function emailVerify(apiImplementation, options) { }); if (response.status === "OK") { result = { status: "OK" }; - } else { + } + else { result = response; } - } else { + } + else { if (apiImplementation.isEmailVerifiedGET === undefined) { return false; } - const session = yield session_1.default.getSession( - options.req, - options.res, - { overrideGlobalClaimValidators: () => [] }, - userContext - ); + const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [] }, userContext); result = yield apiImplementation.isEmailVerifiedGET({ options, session: session, diff --git a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts index 0bea1d2c2..d321fa1a9 100644 --- a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts +++ b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts @@ -1,6 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; -export default function generateEmailVerifyToken( - apiImplementation: APIInterface, - options: APIOptions -): Promise; +export default function generateEmailVerifyToken(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js index 13da2cee0..acad3d3a3 100644 --- a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js +++ b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); @@ -55,12 +33,7 @@ function generateEmailVerifyToken(apiImplementation, options) { return false; } const userContext = utils_2.makeDefaultUserContextFromAPI(options.req); - const session = yield session_1.default.getSession( - options.req, - options.res, - { overrideGlobalClaimValidators: () => [] }, - userContext - ); + const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [] }, userContext); const result = yield apiImplementation.generateEmailVerifyTokenPOST({ options, session: session, diff --git a/lib/build/recipe/emailverification/api/implementation.d.ts b/lib/build/recipe/emailverification/api/implementation.d.ts index dd40e7025..b3c21a436 100644 --- a/lib/build/recipe/emailverification/api/implementation.d.ts +++ b/lib/build/recipe/emailverification/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../"; export default function getAPIInterface(): APIInterface; diff --git a/lib/build/recipe/emailverification/api/implementation.js b/lib/build/recipe/emailverification/api/implementation.js index 4714a8010..d7830fcd1 100644 --- a/lib/build/recipe/emailverification/api/implementation.js +++ b/lib/build/recipe/emailverification/api/implementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const recipe_1 = require("../recipe"); @@ -38,13 +16,14 @@ const error_1 = require("../../session/error"); const utils_1 = require("../utils"); function getAPIInterface() { return { - verifyEmailPOST: function ({ token, options, session, userContext }) { + verifyEmailPOST: function ({ token, options, session, userContext, }) { return __awaiter(this, void 0, void 0, function* () { const res = yield options.recipeImplementation.verifyEmailUsingToken({ token, userContext }); if (res.status === "OK" && session !== undefined) { try { yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); - } catch (err) { + } + catch (err) { // This should never happen, since we've just set the status above. if (err.message === "UNKNOWN_USER_ID") { throw new error_1.default({ @@ -58,14 +37,15 @@ function getAPIInterface() { return res; }); }, - isEmailVerifiedGET: function ({ userContext, session }) { + isEmailVerifiedGET: function ({ userContext, session, }) { return __awaiter(this, void 0, void 0, function* () { if (session === undefined) { throw new Error("Session is undefined. Should not come here."); } try { yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); - } catch (err) { + } + catch (err) { if (err.message === "UNKNOWN_USER_ID") { throw new error_1.default({ type: error_1.default.UNAUTHORISED, @@ -74,10 +54,7 @@ function getAPIInterface() { } throw err; } - const isVerified = yield session.getClaimValue( - emailVerificationClaim_1.EmailVerificationClaim, - userContext - ); + const isVerified = yield session.getClaimValue(emailVerificationClaim_1.EmailVerificationClaim, userContext); if (isVerified === undefined) { throw new Error("Should never come here: EmailVerificationClaim failed to set value"); } @@ -87,23 +64,20 @@ function getAPIInterface() { }; }); }, - generateEmailVerifyTokenPOST: function ({ options, userContext, session }) { + generateEmailVerifyTokenPOST: function ({ options, userContext, session, }) { return __awaiter(this, void 0, void 0, function* () { if (session === undefined) { throw new Error("Session is undefined. Should not come here."); } const userId = session.getUserId(); - const emailInfo = yield recipe_1.default - .getInstanceOrThrowError() - .getEmailForUserId(userId, userContext); + const emailInfo = yield recipe_1.default.getInstanceOrThrowError().getEmailForUserId(userId, userContext); if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { - logger_1.logDebugMessage( - `Email verification email not sent to user ${userId} because it doesn't have an email address.` - ); + logger_1.logDebugMessage(`Email verification email not sent to user ${userId} because it doesn't have an email address.`); return { status: "EMAIL_ALREADY_VERIFIED_ERROR", }; - } else if (emailInfo.status === "OK") { + } + else if (emailInfo.status === "OK") { let response = yield options.recipeImplementation.createEmailVerificationToken({ userId, email: emailInfo.email, @@ -114,14 +88,9 @@ function getAPIInterface() { // this can happen if the email was verified in another browser // and this session is still outdated - and the user has not // called the get email verification API yet. - yield session.fetchAndSetClaim( - emailVerificationClaim_1.EmailVerificationClaim, - userContext - ); + yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); } - logger_1.logDebugMessage( - `Email verification email not sent to ${emailInfo.email} because it is already verified.` - ); + logger_1.logDebugMessage(`Email verification email not sent to ${emailInfo.email} because it is already verified.`); return response; } if ((yield session.getClaimValue(emailVerificationClaim_1.EmailVerificationClaim)) !== false) { @@ -148,11 +117,9 @@ function getAPIInterface() { return { status: "OK", }; - } else { - throw new error_1.default({ - type: error_1.default.UNAUTHORISED, - message: "Unknown User ID provided", - }); + } + else { + throw new error_1.default({ type: error_1.default.UNAUTHORISED, message: "Unknown User ID provided" }); } }); }, diff --git a/lib/build/recipe/emailverification/constants.d.ts b/lib/build/recipe/emailverification/constants.d.ts index 7d50fa860..ebc1e0937 100644 --- a/lib/build/recipe/emailverification/constants.d.ts +++ b/lib/build/recipe/emailverification/constants.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck export declare const GENERATE_EMAIL_VERIFY_TOKEN_API = "/user/email/verify/token"; export declare const EMAIL_VERIFY_API = "/user/email/verify"; diff --git a/lib/build/recipe/emailverification/constants.js b/lib/build/recipe/emailverification/constants.js index a77400c05..b40f50dbc 100644 --- a/lib/build/recipe/emailverification/constants.js +++ b/lib/build/recipe/emailverification/constants.js @@ -14,5 +14,6 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.EMAIL_VERIFY_API = exports.GENERATE_EMAIL_VERIFY_TOKEN_API = void 0; exports.GENERATE_EMAIL_VERIFY_TOKEN_API = "/user/email/verify/token"; exports.EMAIL_VERIFY_API = "/user/email/verify"; diff --git a/lib/build/recipe/emailverification/emailVerificationClaim.d.ts b/lib/build/recipe/emailverification/emailVerificationClaim.d.ts index d29302506..87d3bf0b7 100644 --- a/lib/build/recipe/emailverification/emailVerificationClaim.d.ts +++ b/lib/build/recipe/emailverification/emailVerificationClaim.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BooleanClaim } from "../session/claims"; import { SessionClaimValidator } from "../session"; /** diff --git a/lib/build/recipe/emailverification/emailVerificationClaim.js b/lib/build/recipe/emailverification/emailVerificationClaim.js index 9108502fb..26dcfff5a 100644 --- a/lib/build/recipe/emailverification/emailVerificationClaim.js +++ b/lib/build/recipe/emailverification/emailVerificationClaim.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.EmailVerificationClaim = exports.EmailVerificationClaimClass = void 0; const recipe_1 = require("./recipe"); const claims_1 = require("../session/claims"); /** @@ -45,36 +24,27 @@ class EmailVerificationClaimClass extends claims_1.BooleanClaim { const recipe = recipe_1.default.getInstanceOrThrowError(); let emailInfo = yield recipe.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { - return recipe.recipeInterfaceImpl.isEmailVerified({ - userId, - email: emailInfo.email, - userContext, - }); - } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + return recipe.recipeInterfaceImpl.isEmailVerified({ userId, email: emailInfo.email, userContext }); + } + else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { // We consider people without email addresses as validated return true; - } else { + } + else { throw new Error("UNKNOWN_USER_ID"); } }); }, defaultMaxAgeInSeconds: 300, }); - this.validators = Object.assign(Object.assign({}, this.validators), { - isVerified: (refetchTimeOnFalseInSeconds = 10, maxAgeInSeconds = 300) => - Object.assign(Object.assign({}, this.validators.hasValue(true, maxAgeInSeconds)), { - shouldRefetch: (payload, userContext) => { - const value = this.getValueFromPayload(payload, userContext); - return ( - value === undefined || - this.getLastRefetchTime(payload, userContext) < Date.now() - maxAgeInSeconds * 1000 || - (value === false && - this.getLastRefetchTime(payload, userContext) < - Date.now() - refetchTimeOnFalseInSeconds * 1000) - ); - }, - }), - }); + this.validators = Object.assign(Object.assign({}, this.validators), { isVerified: (refetchTimeOnFalseInSeconds = 10, maxAgeInSeconds = 300) => (Object.assign(Object.assign({}, this.validators.hasValue(true, maxAgeInSeconds)), { shouldRefetch: (payload, userContext) => { + const value = this.getValueFromPayload(payload, userContext); + return (value === undefined || + this.getLastRefetchTime(payload, userContext) < Date.now() - maxAgeInSeconds * 1000 || + (value === false && + this.getLastRefetchTime(payload, userContext) < + Date.now() - refetchTimeOnFalseInSeconds * 1000)); + } })) }); } } exports.EmailVerificationClaimClass = EmailVerificationClaimClass; diff --git a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts index f09fbc85b..e13e29369 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts @@ -1,6 +1,3 @@ -// @ts-nocheck import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function createAndSendCustomEmail( - appInfo: NormalisedAppinfo -): (user: User, emailVerifyURLWithToken: string) => Promise; +export declare function createAndSendCustomEmail(appInfo: NormalisedAppinfo): (user: User, emailVerifyURLWithToken: string) => Promise; diff --git a/lib/build/recipe/emailverification/emailVerificationFunctions.js b/lib/build/recipe/emailverification/emailVerificationFunctions.js index 0a79efd04..1bcce679c 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.js +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.js @@ -13,86 +13,61 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.createAndSendCustomEmail = void 0; const axios_1 = require("axios"); const logger_1 = require("../../logger"); function createAndSendCustomEmail(appInfo) { - return (user, emailVerifyURLWithToken) => - __awaiter(this, void 0, void 0, function* () { - if (process.env.TEST_MODE === "testing") { - return; - } - try { - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.io/0/st/auth/email/verify", - data: { - email: user.email, - appName: appInfo.appName, - emailVerifyURL: emailVerifyURLWithToken, - }, - headers: { - "api-version": 0, - }, - }); - logger_1.logDebugMessage(`Email sent to ${user.email}`); - } catch (error) { - logger_1.logDebugMessage("Error sending verification email"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } - } else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + return (user, emailVerifyURLWithToken) => __awaiter(this, void 0, void 0, function* () { + if (process.env.TEST_MODE === "testing") { + return; + } + try { + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.io/0/st/auth/email/verify", + data: { + email: user.email, + appName: appInfo.appName, + emailVerifyURL: emailVerifyURLWithToken, + }, + headers: { + "api-version": 0, + }, + }); + logger_1.logDebugMessage(`Email sent to ${user.email}`); + } + catch (error) { + logger_1.logDebugMessage("Error sending verification email"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage( - JSON.stringify( - { - email: user.email, - appName: appInfo.appName, - emailVerifyURL: emailVerifyURLWithToken, - }, - null, - 2 - ) - ); + else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + } + else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); } - }); + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage(JSON.stringify({ + email: user.email, + appName: appInfo.appName, + emailVerifyURL: emailVerifyURLWithToken, + }, null, 2)); + } + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts index 6a681f11d..1ab8e9294 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,24 +1,12 @@ -// @ts-nocheck import { TypeEmailVerificationEmailDeliveryInput, User } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService - implements EmailDeliveryInterface { +export default class BackwardCompatibilityService implements EmailDeliveryInterface { private appInfo; private isInServerlessEnv; private createAndSendCustomEmail; - constructor( - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - createAndSendCustomEmail?: ( - user: User, - emailVerificationURLWithToken: string, - userContext: any - ) => Promise - ); - sendEmail: ( - input: TypeEmailVerificationEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + constructor(appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, createAndSendCustomEmail?: (user: User, emailVerificationURLWithToken: string, userContext: any) => Promise); + sendEmail: (input: TypeEmailVerificationEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js index 67e5311b1..dd2ba732b 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js @@ -1,54 +1,29 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const emailVerificationFunctions_1 = require("../../../emailVerificationFunctions"); class BackwardCompatibilityService { constructor(appInfo, isInServerlessEnv, createAndSendCustomEmail) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - try { - if (!this.isInServerlessEnv) { - this.createAndSendCustomEmail( - input.user, - input.emailVerifyLink, - input.userContext - ).catch((_) => {}); - } else { - // see https://github.com/supertokens/supertokens-node/pull/135 - yield this.createAndSendCustomEmail(input.user, input.emailVerifyLink, input.userContext); - } - } catch (_) {} - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + try { + if (!this.isInServerlessEnv) { + this.createAndSendCustomEmail(input.user, input.emailVerifyLink, input.userContext).catch((_) => { }); + } + else { + // see https://github.com/supertokens/supertokens-node/pull/135 + yield this.createAndSendCustomEmail(input.user, input.emailVerifyLink, input.userContext); + } + } + catch (_) { } + }); this.appInfo = appInfo; this.isInServerlessEnv = isInServerlessEnv; this.createAndSendCustomEmail = diff --git a/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts index 4de04d983..dd2ef062c 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/index.js b/lib/build/recipe/emailverification/emaildelivery/services/index.js index fc7c1fa88..a3d9c24c8 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/index.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/index.js @@ -14,5 +14,6 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPService = void 0; const smtp_1 = require("./smtp"); exports.SMTPService = smtp_1.default; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts index c28581ed2..521c97ea6 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; export default function getEmailVerifyEmailContent(input: TypeEmailVerificationEmailDeliveryInput): GetContentResult; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js index a89ab822e..818ad1522 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getEmailVerifyEmailHTML = void 0; const supertokens_1 = require("../../../../../supertokens"); function getEmailVerifyEmailContent(input) { let supertokens = supertokens_1.default.getInstanceOrThrowError(); @@ -499,13 +500,6 @@ function getEmailVerifyEmailHTML(appName, email, verificationLink) { text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts index c3030da4e..28d36d828 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts @@ -1,13 +1,10 @@ -// @ts-nocheck import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; export default class SMTPService implements EmailDeliveryInterface { serviceImpl: ServiceInterface; constructor(config: TypeInput); - sendEmail: ( - input: TypeEmailVerificationEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + sendEmail: (input: TypeEmailVerificationEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js index 2975b7375..a91e9c1e1 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js @@ -1,48 +1,23 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = require("supertokens-js-override"); const serviceImplementation_1 = require("./serviceImplementation"); class SMTPService { constructor(config) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - yield this.serviceImpl.sendRawEmail( - Object.assign(Object.assign({}, content), { userContext: input.userContext }) - ); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + yield this.serviceImpl.sendRawEmail(Object.assign(Object.assign({}, content), { userContext: input.userContext })); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -52,9 +27,7 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default( - serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) - ); + let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts index 3f668725f..01ad49a79 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts @@ -1,11 +1,7 @@ -// @ts-nocheck import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation( - transporter: Transporter, - from: { - name: string; - email: string; - } -): ServiceInterface; +export declare function getServiceImplementation(transporter: Transporter, from: { + name: string; + email: string; +}): ServiceInterface; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js index a5a21bf87..431d3adb8 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getServiceImplementation = void 0; const emailVerify_1 = require("./emailVerify"); function getServiceImplementation(transporter, from) { return { @@ -57,7 +36,8 @@ function getServiceImplementation(transporter, from) { subject: input.subject, html: input.body, }); - } else { + } + else { yield transporter.sendMail({ from: `${from.name} <${from.email}>`, to: input.toEmail, diff --git a/lib/build/recipe/emailverification/error.d.ts b/lib/build/recipe/emailverification/error.d.ts index 486758b61..71d57623f 100644 --- a/lib/build/recipe/emailverification/error.d.ts +++ b/lib/build/recipe/emailverification/error.d.ts @@ -1,5 +1,7 @@ -// @ts-nocheck import STError from "../../error"; export default class SessionError extends STError { - constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); + constructor(options: { + type: "BAD_INPUT_ERROR"; + message: string; + }); } diff --git a/lib/build/recipe/emailverification/index.d.ts b/lib/build/recipe/emailverification/index.d.ts index 9262ec6ec..dc3e5bdb8 100644 --- a/lib/build/recipe/emailverification/index.d.ts +++ b/lib/build/recipe/emailverification/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, APIOptions, APIInterface, User, TypeEmailVerificationEmailDeliveryInput } from "./types"; @@ -6,51 +5,28 @@ export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; static EmailVerificationClaim: import("./emailVerificationClaim").EmailVerificationClaimClass; - static createEmailVerificationToken( - userId: string, - email?: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - } - >; - static verifyEmailUsingToken( - token: string, - userContext?: any - ): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - >; + static createEmailVerificationToken(userId: string, email?: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + }>; + static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + }>; static isEmailVerified(userId: string, email?: string, userContext?: any): Promise; - static revokeEmailVerificationTokens( - userId: string, - email?: string, - userContext?: any - ): Promise<{ + static revokeEmailVerificationTokens(userId: string, email?: string, userContext?: any): Promise<{ status: string; }>; - static unverifyEmail( - userId: string, - email?: string, - userContext?: any - ): Promise<{ + static unverifyEmail(userId: string, email?: string, userContext?: any): Promise<{ status: string; }>; - static sendEmail( - input: TypeEmailVerificationEmailDeliveryInput & { - userContext?: any; - } - ): Promise; + static sendEmail(input: TypeEmailVerificationEmailDeliveryInput & { + userContext?: any; + }): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/emailverification/index.js b/lib/build/recipe/emailverification/index.js index 74f75371e..b1b2bf1c2 100644 --- a/lib/build/recipe/emailverification/index.js +++ b/lib/build/recipe/emailverification/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.EmailVerificationClaim = exports.sendEmail = exports.unverifyEmail = exports.revokeEmailVerificationTokens = exports.isEmailVerified = exports.verifyEmailUsingToken = exports.createEmailVerificationToken = exports.Error = exports.init = void 0; const recipe_1 = require("./recipe"); const error_1 = require("./error"); const emailVerificationClaim_1 = require("./emailVerificationClaim"); @@ -56,11 +35,13 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } + else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { return { status: "EMAIL_ALREADY_VERIFIED_ERROR", }; - } else { + } + else { throw new global.Error("Unknown User ID provided without email"); } } @@ -86,9 +67,11 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } + else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { return true; - } else { + } + else { throw new global.Error("Unknown User ID provided without email"); } } @@ -109,14 +92,16 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } + else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { // This only happens for phone based passwordless users (or if the user added a custom getEmailForUserId) // We can return OK here, since there is no way to create an email verification token // if getEmailForUserId returns EMAIL_DOES_NOT_EXIST_ERROR. return { status: "OK", }; - } else { + } + else { throw new global.Error("Unknown User ID provided without email"); } } @@ -134,12 +119,14 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } + else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { // Here we are returning OK since that's how it used to work, but a later call to isVerified will still return true return { status: "OK", }; - } else { + } + else { throw new global.Error("Unknown User ID provided without email"); } } @@ -153,9 +140,7 @@ class Wrapper { static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { let recipeInstance = recipe_1.default.getInstanceOrThrowError(); - return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail( - Object.assign({ userContext: {} }, input) - ); + return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } } @@ -172,4 +157,4 @@ exports.revokeEmailVerificationTokens = Wrapper.revokeEmailVerificationTokens; exports.unverifyEmail = Wrapper.unverifyEmail; exports.sendEmail = Wrapper.sendEmail; var emailVerificationClaim_2 = require("./emailVerificationClaim"); -exports.EmailVerificationClaim = emailVerificationClaim_2.EmailVerificationClaim; +Object.defineProperty(exports, "EmailVerificationClaim", { enumerable: true, get: function () { return emailVerificationClaim_2.EmailVerificationClaim; } }); diff --git a/lib/build/recipe/emailverification/recipe.d.ts b/lib/build/recipe/emailverification/recipe.d.ts index 6cb431f31..e5db23be4 100644 --- a/lib/build/recipe/emailverification/recipe.d.ts +++ b/lib/build/recipe/emailverification/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, GetEmailForUserIdFunc } from "./types"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; @@ -16,27 +15,15 @@ export default class Recipe extends RecipeModule { isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; getEmailForUserIdFuncsFromOtherRecipes: GetEmailForUserIdFunc[]; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + }); static getInstanceOrThrowError(): Recipe; static getInstance(): Recipe | undefined; static init(config: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - _: NormalisedURLPath, - __: HTTPMethod - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _: NormalisedURLPath, __: HTTPMethod) => Promise; handleError: (err: STError, _: BaseRequest, __: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/emailverification/recipe.js b/lib/build/recipe/emailverification/recipe.js index 32e01ebab..32dcc817b 100644 --- a/lib/build/recipe/emailverification/recipe.js +++ b/lib/build/recipe/emailverification/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -69,9 +47,7 @@ class Recipe extends recipeModule_1.default { return [ { method: "post", - pathWithoutApiBasePath: new normalisedURLPath_1.default( - constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API - ), + pathWithoutApiBasePath: new normalisedURLPath_1.default(constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API), id: constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API, disabled: this.apiImpl.generateEmailVerifyTokenPOST === undefined, }, @@ -89,61 +65,57 @@ class Recipe extends recipeModule_1.default { }, ]; }; - this.handleAPIRequest = (id, req, res, _, __) => - __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - emailDelivery: this.emailDelivery, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API) { - return yield generateEmailVerifyToken_1.default(this.apiImpl, options); - } else { - return yield emailVerify_1.default(this.apiImpl, options); - } - }); - this.handleError = (err, _, __) => - __awaiter(this, void 0, void 0, function* () { - throw err; - }); + this.handleAPIRequest = (id, req, res, _, __) => __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + emailDelivery: this.emailDelivery, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API) { + return yield generateEmailVerifyToken_1.default(this.apiImpl, options); + } + else { + return yield emailVerify_1.default(this.apiImpl, options); + } + }); + this.handleError = (err, _, __) => __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; this.isErrorFromThisRecipe = (err) => { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; - this.getEmailForUserId = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - if (this.config.getEmailForUserId !== undefined) { - const userRes = yield this.config.getEmailForUserId(userId, userContext); - if (userRes.status !== "UNKNOWN_USER_ID_ERROR") { - return userRes; - } + this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + if (this.config.getEmailForUserId !== undefined) { + const userRes = yield this.config.getEmailForUserId(userId, userContext); + if (userRes.status !== "UNKNOWN_USER_ID_ERROR") { + return userRes; } - for (const getEmailForUserId of this.getEmailForUserIdFuncsFromOtherRecipes) { - const res = yield getEmailForUserId(userId, userContext); - if (res.status !== "UNKNOWN_USER_ID_ERROR") { - return res; - } + } + for (const getEmailForUserId of this.getEmailForUserIdFuncsFromOtherRecipes) { + const res = yield getEmailForUserId(userId, userContext); + if (res.status !== "UNKNOWN_USER_ID_ERROR") { + return res; } - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - }); + } + return { + status: "UNKNOWN_USER_ID_ERROR", + }; + }); this.addGetEmailForUserIdFunc = (func) => { this.getEmailForUserIdFuncsFromOtherRecipes.push(func); }; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -175,22 +147,15 @@ class Recipe extends recipeModule_1.default { emailDelivery: undefined, }); postSuperTokensInitCallbacks_1.PostSuperTokensInitCallbacks.addPostInitCallback(() => { - recipe_1.default - .getInstanceOrThrowError() - .addClaimFromOtherRecipe(emailVerificationClaim_1.EmailVerificationClaim); + recipe_1.default.getInstanceOrThrowError().addClaimFromOtherRecipe(emailVerificationClaim_1.EmailVerificationClaim); if (config.mode === "REQUIRED") { - recipe_1.default - .getInstanceOrThrowError() - .addClaimValidatorFromOtherRecipe( - emailVerificationClaim_1.EmailVerificationClaim.validators.isVerified() - ); + recipe_1.default.getInstanceOrThrowError().addClaimValidatorFromOtherRecipe(emailVerificationClaim_1.EmailVerificationClaim.validators.isVerified()); } }); return Recipe.instance; - } else { - throw new Error( - "Emailverification recipe has already been initialised. Please check your code for bugs." - ); + } + else { + throw new Error("Emailverification recipe has already been initialised. Please check your code for bugs."); } }; } diff --git a/lib/build/recipe/emailverification/recipeImplementation.d.ts b/lib/build/recipe/emailverification/recipeImplementation.d.ts index 6a2182ed3..d6ed6101f 100644 --- a/lib/build/recipe/emailverification/recipeImplementation.d.ts +++ b/lib/build/recipe/emailverification/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "./"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/emailverification/recipeImplementation.js b/lib/build/recipe/emailverification/recipeImplementation.js index a5baedfae..f7ddb1ed8 100644 --- a/lib/build/recipe/emailverification/recipeImplementation.js +++ b/lib/build/recipe/emailverification/recipeImplementation.js @@ -1,69 +1,42 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); function getRecipeInterface(querier) { return { - createEmailVerificationToken: function ({ userId, email }) { + createEmailVerificationToken: function ({ userId, email, }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/user/email/verify/token"), - { - userId, - email, - } - ); + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/email/verify/token"), { + userId, + email, + }); if (response.status === "OK") { return { status: "OK", token: response.token, }; - } else { + } + else { return { status: "EMAIL_ALREADY_VERIFIED_ERROR", }; } }); }, - verifyEmailUsingToken: function ({ token }) { + verifyEmailUsingToken: function ({ token, }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/user/email/verify"), - { - method: "token", - token, - } - ); + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/email/verify"), { + method: "token", + token, + }); if (response.status === "OK") { return { status: "OK", @@ -72,7 +45,8 @@ function getRecipeInterface(querier) { email: response.email, }, }; - } else { + } + else { return { status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR", }; @@ -81,25 +55,19 @@ function getRecipeInterface(querier) { }, isEmailVerified: function ({ userId, email }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/user/email/verify"), - { - userId, - email, - } - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user/email/verify"), { + userId, + email, + }); return response.isVerified; }); }, revokeEmailVerificationTokens: function (input) { return __awaiter(this, void 0, void 0, function* () { - yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/user/email/verify/token/remove"), - { - userId: input.userId, - email: input.email, - } - ); + yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/email/verify/token/remove"), { + userId: input.userId, + email: input.email, + }); return { status: "OK" }; }); }, diff --git a/lib/build/recipe/emailverification/types.d.ts b/lib/build/recipe/emailverification/types.d.ts index 27bb17bd3..48b6d100f 100644 --- a/lib/build/recipe/emailverification/types.d.ts +++ b/lib/build/recipe/emailverification/types.d.ts @@ -1,62 +1,38 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; -import { - TypeInput as EmailDeliveryTypeInput, - TypeInputWithService as EmailDeliveryTypeInputWithService, -} from "../../ingredients/emaildelivery/types"; +import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; import { GeneralErrorResponse, NormalisedAppinfo } from "../../types"; import { SessionContainerInterface } from "../session/types"; export declare type TypeInput = { mode: "REQUIRED" | "OPTIONAL"; emailDelivery?: EmailDeliveryTypeInput; - getEmailForUserId?: ( - userId: string, - userContext: any - ) => Promise< - | { - status: "OK"; - email: string; - } - | { - status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; - } - >; + getEmailForUserId?: (userId: string, userContext: any) => Promise<{ + status: "OK"; + email: string; + } | { + status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; + }>; /** * @deprecated Please use emailDelivery config instead */ createAndSendCustomEmail?: (user: User, emailVerificationURLWithToken: string, userContext: any) => Promise; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { mode: "REQUIRED" | "OPTIONAL"; - getEmailDeliveryConfig: ( - isInServerlessEnv: boolean - ) => EmailDeliveryTypeInputWithService; - getEmailForUserId?: ( - userId: string, - userContext: any - ) => Promise< - | { - status: "OK"; - email: string; - } - | { - status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; - } - >; + getEmailDeliveryConfig: (isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; + getEmailForUserId?: (userId: string, userContext: any) => Promise<{ + status: "OK"; + email: string; + } | { + status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; + }>; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -69,28 +45,26 @@ export declare type RecipeInterface = { userId: string; email: string; userContext: any; - }): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + token: string; + } | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + }>; verifyEmailUsingToken(input: { token: string; userContext: any; - }): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - >; - isEmailVerified(input: { userId: string; email: string; userContext: any }): Promise; + }): Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + }>; + isEmailVerified(input: { + userId: string; + email: string; + userContext: any; + }): Promise; revokeEmailVerificationTokens(input: { userId: string; email: string; @@ -117,48 +91,32 @@ export declare type APIOptions = { emailDelivery: EmailDeliveryIngredient; }; export declare type APIInterface = { - verifyEmailPOST: - | undefined - | ((input: { - token: string; - options: APIOptions; - userContext: any; - session?: SessionContainerInterface; - }) => Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - | GeneralErrorResponse - >); - isEmailVerifiedGET: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - session: SessionContainerInterface; - }) => Promise< - | { - status: "OK"; - isVerified: boolean; - } - | GeneralErrorResponse - >); - generateEmailVerifyTokenPOST: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - session: SessionContainerInterface; - }) => Promise< - | { - status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; - } - | GeneralErrorResponse - >); + verifyEmailPOST: undefined | ((input: { + token: string; + options: APIOptions; + userContext: any; + session?: SessionContainerInterface; + }) => Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } | GeneralErrorResponse>); + isEmailVerifiedGET: undefined | ((input: { + options: APIOptions; + userContext: any; + session: SessionContainerInterface; + }) => Promise<{ + status: "OK"; + isVerified: boolean; + } | GeneralErrorResponse>); + generateEmailVerifyTokenPOST: undefined | ((input: { + options: APIOptions; + userContext: any; + session: SessionContainerInterface; + }) => Promise<{ + status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; + } | GeneralErrorResponse>); }; export declare type TypeEmailVerificationEmailDeliveryInput = { type: "EMAIL_VERIFICATION"; @@ -168,15 +126,9 @@ export declare type TypeEmailVerificationEmailDeliveryInput = { }; emailVerifyLink: string; }; -export declare type GetEmailForUserIdFunc = ( - userId: string, - userContext: any -) => Promise< - | { - status: "OK"; - email: string; - } - | { - status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; - } ->; +export declare type GetEmailForUserIdFunc = (userId: string, userContext: any) => Promise<{ + status: "OK"; + email: string; +} | { + status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; +}>; diff --git a/lib/build/recipe/emailverification/utils.d.ts b/lib/build/recipe/emailverification/utils.d.ts index 627176f4a..91dc7b197 100644 --- a/lib/build/recipe/emailverification/utils.d.ts +++ b/lib/build/recipe/emailverification/utils.d.ts @@ -1,12 +1,7 @@ -// @ts-nocheck import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function validateAndNormaliseUserInput( - _: Recipe, - appInfo: NormalisedAppinfo, - config: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(_: Recipe, appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; export declare function getEmailVerifyLink(input: { appInfo: NormalisedAppinfo; token: string; diff --git a/lib/build/recipe/emailverification/utils.js b/lib/build/recipe/emailverification/utils.js index 841c861b8..16fbf90d9 100644 --- a/lib/build/recipe/emailverification/utils.js +++ b/lib/build/recipe/emailverification/utils.js @@ -14,15 +14,10 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.getEmailVerifyLink = exports.validateAndNormaliseUserInput = void 0; const backwardCompatibility_1 = require("./emaildelivery/services/backwardCompatibility"); function validateAndNormaliseUserInput(_, appInfo, config) { - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); function getEmailDeliveryConfig(isInServerlessEnv) { var _a; let emailService = (_a = config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; @@ -34,13 +29,9 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * createAndSendCustomEmail implementation which calls our supertokens API */ if (emailService === undefined) { - emailService = new backwardCompatibility_1.default( - appInfo, - isInServerlessEnv, - config.createAndSendCustomEmail - ); + emailService = new backwardCompatibility_1.default(appInfo, isInServerlessEnv, config.createAndSendCustomEmail); } - return Object.assign(Object.assign({}, config.emailDelivery), { + return Object.assign(Object.assign({}, config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -52,8 +43,7 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService, - }); + service: emailService }); } return { mode: config.mode, @@ -64,14 +54,12 @@ function validateAndNormaliseUserInput(_, appInfo, config) { } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function getEmailVerifyLink(input) { - return ( - input.appInfo.websiteDomain.getAsStringDangerous() + + return (input.appInfo.websiteDomain.getAsStringDangerous() + input.appInfo.websiteBasePath.getAsStringDangerous() + "/verify-email" + "?token=" + input.token + "&rid=" + - input.recipeId - ); + input.recipeId); } exports.getEmailVerifyLink = getEmailVerifyLink; diff --git a/lib/build/recipe/jwt/api/getJWKS.d.ts b/lib/build/recipe/jwt/api/getJWKS.d.ts index 7b983911b..ac9271746 100644 --- a/lib/build/recipe/jwt/api/getJWKS.d.ts +++ b/lib/build/recipe/jwt/api/getJWKS.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export default function getJWKS(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/jwt/api/getJWKS.js b/lib/build/recipe/jwt/api/getJWKS.js index b2e33b23b..5caf51870 100644 --- a/lib/build/recipe/jwt/api/getJWKS.js +++ b/lib/build/recipe/jwt/api/getJWKS.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); @@ -59,7 +37,8 @@ function getJWKS(apiImplementation, options) { if (result.status === "OK") { options.res.setHeader("Access-Control-Allow-Origin", "*", false); utils_1.send200Response(options.res, { keys: result.keys }); - } else { + } + else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/jwt/api/implementation.d.ts b/lib/build/recipe/jwt/api/implementation.d.ts index 0218549fa..75c1214f2 100644 --- a/lib/build/recipe/jwt/api/implementation.d.ts +++ b/lib/build/recipe/jwt/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/jwt/api/implementation.js b/lib/build/recipe/jwt/api/implementation.js index 88600ac6e..c4a859036 100644 --- a/lib/build/recipe/jwt/api/implementation.js +++ b/lib/build/recipe/jwt/api/implementation.js @@ -13,41 +13,19 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getAPIImplementation() { return { - getJWKSGET: function ({ options, userContext }) { + getJWKSGET: function ({ options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.getJWKS({ userContext }); }); diff --git a/lib/build/recipe/jwt/constants.d.ts b/lib/build/recipe/jwt/constants.d.ts index 719f84e81..298c59b58 100644 --- a/lib/build/recipe/jwt/constants.d.ts +++ b/lib/build/recipe/jwt/constants.d.ts @@ -1,2 +1 @@ -// @ts-nocheck export declare const GET_JWKS_API = "/jwt/jwks.json"; diff --git a/lib/build/recipe/jwt/constants.js b/lib/build/recipe/jwt/constants.js index 83abecfc1..b21a20fa1 100644 --- a/lib/build/recipe/jwt/constants.js +++ b/lib/build/recipe/jwt/constants.js @@ -14,4 +14,5 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.GET_JWKS_API = void 0; exports.GET_JWKS_API = "/jwt/jwks.json"; diff --git a/lib/build/recipe/jwt/index.d.ts b/lib/build/recipe/jwt/index.d.ts index 274bd280b..7b001eb8c 100644 --- a/lib/build/recipe/jwt/index.d.ts +++ b/lib/build/recipe/jwt/index.d.ts @@ -1,24 +1,14 @@ -// @ts-nocheck import Recipe from "./recipe"; import { APIInterface, RecipeInterface, APIOptions, JsonWebKey } from "./types"; export default class Wrapper { static init: typeof Recipe.init; - static createJWT( - payload: any, - validitySeconds?: number, - userContext?: any - ): Promise< - | { - status: "OK"; - jwt: string; - } - | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - } - >; - static getJWKS( - userContext?: any - ): Promise<{ + static createJWT(payload: any, validitySeconds?: number, userContext?: any): Promise<{ + status: "OK"; + jwt: string; + } | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + }>; + static getJWKS(userContext?: any): Promise<{ status: "OK"; keys: JsonWebKey[]; }>; diff --git a/lib/build/recipe/jwt/index.js b/lib/build/recipe/jwt/index.js index 3d04b204d..08d8a4ca8 100644 --- a/lib/build/recipe/jwt/index.js +++ b/lib/build/recipe/jwt/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getJWKS = exports.createJWT = exports.init = void 0; const recipe_1 = require("./recipe"); class Wrapper { static createJWT(payload, validitySeconds, userContext) { diff --git a/lib/build/recipe/jwt/recipe.d.ts b/lib/build/recipe/jwt/recipe.d.ts index 714362caa..54e486c45 100644 --- a/lib/build/recipe/jwt/recipe.d.ts +++ b/lib/build/recipe/jwt/recipe.d.ts @@ -1,7 +1,6 @@ -// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; -import NormalisedURLPath from "../../normalisedURLPath"; +import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; import { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction } from "../../types"; import { APIInterface, RecipeInterface, TypeInput, TypeNormalisedInput } from "./types"; @@ -17,13 +16,7 @@ export default class Recipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled(): APIHandled[]; - handleAPIRequest: ( - _: string, - req: BaseRequest, - res: BaseResponse, - __: NormalisedURLPath, - ___: HTTPMethod - ) => Promise; + handleAPIRequest: (_: string, req: BaseRequest, res: BaseResponse, __: normalisedURLPath, ___: HTTPMethod) => Promise; handleError(error: error, _: BaseRequest, __: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; diff --git a/lib/build/recipe/jwt/recipe.js b/lib/build/recipe/jwt/recipe.js index 4e472d87b..4a4b60a8d 100644 --- a/lib/build/recipe/jwt/recipe.js +++ b/lib/build/recipe/jwt/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../../error"); const normalisedURLPath_1 = require("../../normalisedURLPath"); @@ -58,28 +36,21 @@ const supertokens_js_override_1 = require("supertokens-js-override"); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config) { super(recipeId, appInfo); - this.handleAPIRequest = (_, req, res, __, ___) => - __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - }; - return yield getJWKS_1.default(this.apiImpl, options); - }); + this.handleAPIRequest = (_, req, res, __, ___) => __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + }; + return yield getJWKS_1.default(this.apiImpl, options); + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default( - querier_1.Querier.getNewInstanceOrThrowError(recipeId), - this.config, - appInfo - ) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config, appInfo)); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -99,7 +70,8 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } else { + } + else { throw new Error("JWT recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/jwt/recipeImplementation.d.ts b/lib/build/recipe/jwt/recipeImplementation.d.ts index 5109fbcb1..8af46b085 100644 --- a/lib/build/recipe/jwt/recipeImplementation.d.ts +++ b/lib/build/recipe/jwt/recipeImplementation.d.ts @@ -1,9 +1,4 @@ -// @ts-nocheck import { Querier } from "../../querier"; import { NormalisedAppinfo } from "../../types"; import { RecipeInterface, TypeNormalisedInput } from "./types"; -export default function getRecipeInterface( - querier: Querier, - config: TypeNormalisedInput, - appInfo: NormalisedAppinfo -): RecipeInterface; +export default function getRecipeInterface(querier: Querier, config: TypeNormalisedInput, appInfo: NormalisedAppinfo): RecipeInterface; diff --git a/lib/build/recipe/jwt/recipeImplementation.js b/lib/build/recipe/jwt/recipeImplementation.js index 8e7cb7bb3..f81d1c0b2 100644 --- a/lib/build/recipe/jwt/recipeImplementation.js +++ b/lib/build/recipe/jwt/recipeImplementation.js @@ -13,42 +13,20 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); function getRecipeInterface(querier, config, appInfo) { return { - createJWT: function ({ payload, validitySeconds }) { + createJWT: function ({ payload, validitySeconds, }) { return __awaiter(this, void 0, void 0, function* () { if (validitySeconds === undefined) { // If the user does not provide a validity to this function and the config validity is also undefined, use 100 years (in seconds) @@ -65,7 +43,8 @@ function getRecipeInterface(querier, config, appInfo) { status: "OK", jwt: response.jwt, }; - } else { + } + else { return { status: "UNSUPPORTED_ALGORITHM_ERROR", }; diff --git a/lib/build/recipe/jwt/types.d.ts b/lib/build/recipe/jwt/types.d.ts index fc400eff6..914cffa8c 100644 --- a/lib/build/recipe/jwt/types.d.ts +++ b/lib/build/recipe/jwt/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { GeneralErrorResponse } from "../../types"; @@ -13,20 +12,14 @@ export declare type JsonWebKey = { export declare type TypeInput = { jwtValiditySeconds?: number; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { jwtValiditySeconds: number; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -43,15 +36,12 @@ export declare type RecipeInterface = { payload?: any; validitySeconds?: number; userContext: any; - }): Promise< - | { - status: "OK"; - jwt: string; - } - | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + jwt: string; + } | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + }>; getJWKS(input: { userContext: any; }): Promise<{ @@ -60,16 +50,11 @@ export declare type RecipeInterface = { }>; }; export declare type APIInterface = { - getJWKSGET: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - keys: JsonWebKey[]; - } - | GeneralErrorResponse - >); + getJWKSGET: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + keys: JsonWebKey[]; + } | GeneralErrorResponse>); }; diff --git a/lib/build/recipe/jwt/utils.d.ts b/lib/build/recipe/jwt/utils.d.ts index 4025b1b44..371d85a96 100644 --- a/lib/build/recipe/jwt/utils.d.ts +++ b/lib/build/recipe/jwt/utils.d.ts @@ -1,9 +1,4 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput( - _: Recipe, - __: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(_: Recipe, __: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/jwt/utils.js b/lib/build/recipe/jwt/utils.js index f09ea36a2..f3383e481 100644 --- a/lib/build/recipe/jwt/utils.js +++ b/lib/build/recipe/jwt/utils.js @@ -14,20 +14,12 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(_, __, config) { var _a; - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); return { - jwtValiditySeconds: - (_a = config === null || config === void 0 ? void 0 : config.jwtValiditySeconds) !== null && _a !== void 0 - ? _a - : 3153600000, + jwtValiditySeconds: (_a = config === null || config === void 0 ? void 0 : config.jwtValiditySeconds) !== null && _a !== void 0 ? _a : 3153600000, override, }; } diff --git a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts index e1cd1cd3b..2f25a26d2 100644 --- a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts +++ b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts @@ -1,6 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../types"; -export default function getOpenIdDiscoveryConfiguration( - apiImplementation: APIInterface, - options: APIOptions -): Promise; +export default function getOpenIdDiscoveryConfiguration(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js index 9fd8c6e31..4c4434613 100644 --- a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js +++ b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -62,7 +40,8 @@ function getOpenIdDiscoveryConfiguration(apiImplementation, options) { issuer: result.issuer, jwks_uri: result.jwks_uri, }); - } else { + } + else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/openid/api/implementation.d.ts b/lib/build/recipe/openid/api/implementation.d.ts index 0218549fa..75c1214f2 100644 --- a/lib/build/recipe/openid/api/implementation.d.ts +++ b/lib/build/recipe/openid/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/openid/api/implementation.js b/lib/build/recipe/openid/api/implementation.js index 81609c3b2..7afccd7b5 100644 --- a/lib/build/recipe/openid/api/implementation.js +++ b/lib/build/recipe/openid/api/implementation.js @@ -1,39 +1,17 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getAPIImplementation() { return { - getOpenIdDiscoveryConfigurationGET: function ({ options, userContext }) { + getOpenIdDiscoveryConfigurationGET: function ({ options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.getOpenIdDiscoveryConfiguration({ userContext }); }); diff --git a/lib/build/recipe/openid/constants.d.ts b/lib/build/recipe/openid/constants.d.ts index 241a857f7..410727137 100644 --- a/lib/build/recipe/openid/constants.d.ts +++ b/lib/build/recipe/openid/constants.d.ts @@ -1,2 +1 @@ -// @ts-nocheck export declare const GET_DISCOVERY_CONFIG_URL = "/.well-known/openid-configuration"; diff --git a/lib/build/recipe/openid/constants.js b/lib/build/recipe/openid/constants.js index 2aaf67b2e..067eee64a 100644 --- a/lib/build/recipe/openid/constants.js +++ b/lib/build/recipe/openid/constants.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.GET_DISCOVERY_CONFIG_URL = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/openid/index.d.ts b/lib/build/recipe/openid/index.d.ts index c84226a59..af0b20dc3 100644 --- a/lib/build/recipe/openid/index.d.ts +++ b/lib/build/recipe/openid/index.d.ts @@ -1,30 +1,18 @@ -// @ts-nocheck import OpenIdRecipe from "./recipe"; export default class OpenIdRecipeWrapper { static init: typeof OpenIdRecipe.init; - static getOpenIdDiscoveryConfiguration( - userContext?: any - ): Promise<{ + static getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ status: "OK"; issuer: string; jwks_uri: string; }>; - static createJWT( - payload?: any, - validitySeconds?: number, - userContext?: any - ): Promise< - | { - status: "OK"; - jwt: string; - } - | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - } - >; - static getJWKS( - userContext?: any - ): Promise<{ + static createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ + status: "OK"; + jwt: string; + } | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + }>; + static getJWKS(userContext?: any): Promise<{ status: "OK"; keys: import("../jwt").JsonWebKey[]; }>; diff --git a/lib/build/recipe/openid/index.js b/lib/build/recipe/openid/index.js index c1e0300f1..091ce01e2 100644 --- a/lib/build/recipe/openid/index.js +++ b/lib/build/recipe/openid/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getJWKS = exports.createJWT = exports.getOpenIdDiscoveryConfiguration = exports.init = void 0; const recipe_1 = require("./recipe"); class OpenIdRecipeWrapper { static getOpenIdDiscoveryConfiguration(userContext) { diff --git a/lib/build/recipe/openid/recipe.d.ts b/lib/build/recipe/openid/recipe.d.ts index 0de7ecdc7..f8c4677af 100644 --- a/lib/build/recipe/openid/recipe.d.ts +++ b/lib/build/recipe/openid/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import STError from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; @@ -18,13 +17,7 @@ export default class OpenIdRecipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - response: BaseResponse, - path: normalisedURLPath, - method: HTTPMethod - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, response: BaseResponse, path: normalisedURLPath, method: HTTPMethod) => Promise; handleError: (error: STError, request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/openid/recipe.js b/lib/build/recipe/openid/recipe.js index e7463fb80..658647a53 100644 --- a/lib/build/recipe/openid/recipe.js +++ b/lib/build/recipe/openid/recipe.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -69,46 +47,42 @@ class OpenIdRecipe extends recipeModule_1.default { ...this.jwtRecipe.getAPIsHandled(), ]; }; - this.handleAPIRequest = (id, req, response, path, method) => - __awaiter(this, void 0, void 0, function* () { - let apiOptions = { - recipeImplementation: this.recipeImplementation, - config: this.config, - recipeId: this.getRecipeId(), - req, - res: response, - }; - if (id === constants_1.GET_DISCOVERY_CONFIG_URL) { - return yield getOpenIdDiscoveryConfiguration_1.default(this.apiImpl, apiOptions); - } else { - return this.jwtRecipe.handleAPIRequest(id, req, response, path, method); - } - }); - this.handleError = (error, request, response) => - __awaiter(this, void 0, void 0, function* () { - if (error.fromRecipe === OpenIdRecipe.RECIPE_ID) { - throw error; - } else { - return yield this.jwtRecipe.handleError(error, request, response); - } - }); + this.handleAPIRequest = (id, req, response, path, method) => __awaiter(this, void 0, void 0, function* () { + let apiOptions = { + recipeImplementation: this.recipeImplementation, + config: this.config, + recipeId: this.getRecipeId(), + req, + res: response, + }; + if (id === constants_1.GET_DISCOVERY_CONFIG_URL) { + return yield getOpenIdDiscoveryConfiguration_1.default(this.apiImpl, apiOptions); + } + else { + return this.jwtRecipe.handleAPIRequest(id, req, response, path, method); + } + }); + this.handleError = (error, request, response) => __awaiter(this, void 0, void 0, function* () { + if (error.fromRecipe === OpenIdRecipe.RECIPE_ID) { + throw error; + } + else { + return yield this.jwtRecipe.handleError(error, request, response); + } + }); this.getAllCORSHeaders = () => { return [...this.jwtRecipe.getAllCORSHeaders()]; }; this.isErrorFromThisRecipe = (err) => { - return ( - (error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === OpenIdRecipe.RECIPE_ID) || - this.jwtRecipe.isErrorFromThisRecipe(err) - ); + return ((error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === OpenIdRecipe.RECIPE_ID) || + this.jwtRecipe.isErrorFromThisRecipe(err)); }; this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); this.jwtRecipe = new recipe_1.default(recipeId, appInfo, isInServerlessEnv, { jwtValiditySeconds: this.config.jwtValiditySeconds, override: this.config.override.jwtFeature, }); - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(this.config, this.jwtRecipe.recipeInterfaceImpl) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(this.config, this.jwtRecipe.recipeInterfaceImpl)); this.recipeImplementation = builder.override(this.config.override.functions).build(); let apiBuilder = new supertokens_js_override_1.default(implementation_1.default()); this.apiImpl = apiBuilder.override(this.config.override.apis).build(); @@ -124,7 +98,8 @@ class OpenIdRecipe extends recipeModule_1.default { if (OpenIdRecipe.instance === undefined) { OpenIdRecipe.instance = new OpenIdRecipe(OpenIdRecipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return OpenIdRecipe.instance; - } else { + } + else { throw new Error("OpenId recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/openid/recipeImplementation.d.ts b/lib/build/recipe/openid/recipeImplementation.d.ts index d4698099c..5c27012a7 100644 --- a/lib/build/recipe/openid/recipeImplementation.d.ts +++ b/lib/build/recipe/openid/recipeImplementation.d.ts @@ -1,7 +1,3 @@ -// @ts-nocheck import { RecipeInterface, TypeNormalisedInput } from "./types"; import { RecipeInterface as JWTRecipeInterface } from "../jwt/types"; -export default function getRecipeInterface( - config: TypeNormalisedInput, - jwtRecipeImplementation: JWTRecipeInterface -): RecipeInterface; +export default function getRecipeInterface(config: TypeNormalisedInput, jwtRecipeImplementation: JWTRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/openid/recipeImplementation.js b/lib/build/recipe/openid/recipeImplementation.js index d673f5973..8b8b68384 100644 --- a/lib/build/recipe/openid/recipeImplementation.js +++ b/lib/build/recipe/openid/recipeImplementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); const constants_1 = require("../jwt/constants"); @@ -38,11 +16,8 @@ function getRecipeInterface(config, jwtRecipeImplementation) { getOpenIdDiscoveryConfiguration: function () { return __awaiter(this, void 0, void 0, function* () { let issuer = config.issuerDomain.getAsStringDangerous() + config.issuerPath.getAsStringDangerous(); - let jwks_uri = - config.issuerDomain.getAsStringDangerous() + - config.issuerPath - .appendPath(new normalisedURLPath_1.default(constants_1.GET_JWKS_API)) - .getAsStringDangerous(); + let jwks_uri = config.issuerDomain.getAsStringDangerous() + + config.issuerPath.appendPath(new normalisedURLPath_1.default(constants_1.GET_JWKS_API)).getAsStringDangerous(); return { status: "OK", issuer, @@ -50,7 +25,7 @@ function getRecipeInterface(config, jwtRecipeImplementation) { }; }); }, - createJWT: function ({ payload, validitySeconds, userContext }) { + createJWT: function ({ payload, validitySeconds, userContext, }) { return __awaiter(this, void 0, void 0, function* () { payload = payload === undefined || payload === null ? {} : payload; let issuer = config.issuerDomain.getAsStringDangerous() + config.issuerPath.getAsStringDangerous(); diff --git a/lib/build/recipe/openid/types.d.ts b/lib/build/recipe/openid/types.d.ts index a480f4b98..95149cd80 100644 --- a/lib/build/recipe/openid/types.d.ts +++ b/lib/build/recipe/openid/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import { BaseRequest, BaseResponse } from "../../framework"; import NormalisedURLDomain from "../../normalisedURLDomain"; @@ -9,20 +8,11 @@ export declare type TypeInput = { issuer?: string; jwtValiditySeconds?: number; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; jwtFeature?: { - functions?: ( - originalImplementation: JWTRecipeInterface, - builder?: OverrideableBuilder - ) => JWTRecipeInterface; - apis?: ( - originalImplementation: JWTAPIInterface, - builder?: OverrideableBuilder - ) => JWTAPIInterface; + functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; + apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; }; }; }; @@ -31,20 +21,11 @@ export declare type TypeNormalisedInput = { issuerPath: NormalisedURLPath; jwtValiditySeconds?: number; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; jwtFeature?: { - functions?: ( - originalImplementation: JWTRecipeInterface, - builder?: OverrideableBuilder - ) => JWTRecipeInterface; - apis?: ( - originalImplementation: JWTAPIInterface, - builder?: OverrideableBuilder - ) => JWTAPIInterface; + functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; + apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; }; }; }; @@ -56,19 +37,14 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - getOpenIdDiscoveryConfigurationGET: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - issuer: string; - jwks_uri: string; - } - | GeneralErrorResponse - >); + getOpenIdDiscoveryConfigurationGET: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + issuer: string; + jwks_uri: string; + } | GeneralErrorResponse>); }; export declare type RecipeInterface = { getOpenIdDiscoveryConfiguration(input: { @@ -82,15 +58,12 @@ export declare type RecipeInterface = { payload?: any; validitySeconds?: number; userContext: any; - }): Promise< - | { - status: "OK"; - jwt: string; - } - | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + jwt: string; + } | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + }>; getJWKS(input: { userContext: any; }): Promise<{ diff --git a/lib/build/recipe/openid/utils.d.ts b/lib/build/recipe/openid/utils.d.ts index 6b5abd280..238a8cda5 100644 --- a/lib/build/recipe/openid/utils.d.ts +++ b/lib/build/recipe/openid/utils.d.ts @@ -1,7 +1,3 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput( - appInfo: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/openid/utils.js b/lib/build/recipe/openid/utils.js index 394ba1783..03050fd85 100644 --- a/lib/build/recipe/openid/utils.js +++ b/lib/build/recipe/openid/utils.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormaliseUserInput = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -28,13 +29,7 @@ function validateAndNormaliseUserInput(appInfo, config) { throw new Error("The path of the issuer URL must be equal to the apiBasePath. The default value is /auth"); } } - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); return { issuerDomain, issuerPath, diff --git a/lib/build/recipe/passwordless/api/consumeCode.d.ts b/lib/build/recipe/passwordless/api/consumeCode.d.ts index 0f21b8d73..9163dc48d 100644 --- a/lib/build/recipe/passwordless/api/consumeCode.d.ts +++ b/lib/build/recipe/passwordless/api/consumeCode.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function consumeCode(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/consumeCode.js b/lib/build/recipe/passwordless/api/consumeCode.js index d856703ea..989997784 100644 --- a/lib/build/recipe/passwordless/api/consumeCode.js +++ b/lib/build/recipe/passwordless/api/consumeCode.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); @@ -77,29 +55,28 @@ function consumeCode(apiImplementation, options) { message: "Please provide both deviceId and userInputCode", }); } - } else if (linkCode === undefined) { + } + else if (linkCode === undefined) { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, message: "Please provide one of (linkCode) or (deviceId+userInputCode) and not both", }); } const userContext = utils_2.makeDefaultUserContextFromAPI(options.req); - let result = yield apiImplementation.consumeCodePOST( - deviceId !== undefined - ? { - deviceId, - userInputCode, - preAuthSessionId, - options, - userContext, - } - : { - linkCode, - options, - preAuthSessionId, - userContext, - } - ); + let result = yield apiImplementation.consumeCodePOST(deviceId !== undefined + ? { + deviceId, + userInputCode, + preAuthSessionId, + options, + userContext, + } + : { + linkCode, + options, + preAuthSessionId, + userContext, + }); if (result.status === "OK") { delete result.session; } diff --git a/lib/build/recipe/passwordless/api/createCode.d.ts b/lib/build/recipe/passwordless/api/createCode.d.ts index d72ea96e0..45f20a34f 100644 --- a/lib/build/recipe/passwordless/api/createCode.d.ts +++ b/lib/build/recipe/passwordless/api/createCode.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function createCode(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/createCode.js b/lib/build/recipe/passwordless/api/createCode.js index 143a6c305..dcbce299a 100644 --- a/lib/build/recipe/passwordless/api/createCode.js +++ b/lib/build/recipe/passwordless/api/createCode.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); @@ -76,10 +54,8 @@ function createCode(apiImplementation, options) { }); } // normalise and validate format of input - if ( - email !== undefined && - (options.config.contactMethod === "EMAIL" || options.config.contactMethod === "EMAIL_OR_PHONE") - ) { + if (email !== undefined && + (options.config.contactMethod === "EMAIL" || options.config.contactMethod === "EMAIL_OR_PHONE")) { email = email.trim(); const validateError = yield options.config.validateEmailAddress(email); if (validateError !== undefined) { @@ -90,10 +66,8 @@ function createCode(apiImplementation, options) { return true; } } - if ( - phoneNumber !== undefined && - (options.config.contactMethod === "PHONE" || options.config.contactMethod === "EMAIL_OR_PHONE") - ) { + if (phoneNumber !== undefined && + (options.config.contactMethod === "PHONE" || options.config.contactMethod === "EMAIL_OR_PHONE")) { const validateError = yield options.config.validatePhoneNumber(phoneNumber); if (validateError !== undefined) { utils_1.send200Response(options.res, { @@ -107,15 +81,14 @@ function createCode(apiImplementation, options) { // this can come here if the user has provided their own impl of validatePhoneNumber and // the phone number is valid according to their impl, but not according to the libphonenumber-js lib. phoneNumber = phoneNumber.trim(); - } else { + } + else { phoneNumber = parsedPhoneNumber.format("E.164"); } } - let result = yield apiImplementation.createCodePOST( - email !== undefined - ? { email, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) } - : { phoneNumber: phoneNumber, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) } - ); + let result = yield apiImplementation.createCodePOST(email !== undefined + ? { email, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) } + : { phoneNumber: phoneNumber, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) }); utils_1.send200Response(options.res, result); return true; }); diff --git a/lib/build/recipe/passwordless/api/emailExists.d.ts b/lib/build/recipe/passwordless/api/emailExists.d.ts index 74f301a87..e0f0ae4d8 100644 --- a/lib/build/recipe/passwordless/api/emailExists.d.ts +++ b/lib/build/recipe/passwordless/api/emailExists.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function emailExists(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/emailExists.js b/lib/build/recipe/passwordless/api/emailExists.js index 5fcea71e0..5725639be 100644 --- a/lib/build/recipe/passwordless/api/emailExists.js +++ b/lib/build/recipe/passwordless/api/emailExists.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); diff --git a/lib/build/recipe/passwordless/api/implementation.d.ts b/lib/build/recipe/passwordless/api/implementation.d.ts index 402db9918..a1619b2fd 100644 --- a/lib/build/recipe/passwordless/api/implementation.d.ts +++ b/lib/build/recipe/passwordless/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/passwordless/api/implementation.js b/lib/build/recipe/passwordless/api/implementation.js index 75c95fa84..ba9101f02 100644 --- a/lib/build/recipe/passwordless/api/implementation.js +++ b/lib/build/recipe/passwordless/api/implementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const recipe_1 = require("../../emailverification/recipe"); @@ -38,20 +16,18 @@ function getAPIImplementation() { return { consumeCodePOST: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield input.options.recipeImplementation.consumeCode( - "deviceId" in input - ? { - preAuthSessionId: input.preAuthSessionId, - deviceId: input.deviceId, - userInputCode: input.userInputCode, - userContext: input.userContext, - } - : { - preAuthSessionId: input.preAuthSessionId, - linkCode: input.linkCode, - userContext: input.userContext, - } - ); + let response = yield input.options.recipeImplementation.consumeCode("deviceId" in input + ? { + preAuthSessionId: input.preAuthSessionId, + deviceId: input.deviceId, + userInputCode: input.userInputCode, + userContext: input.userContext, + } + : { + preAuthSessionId: input.preAuthSessionId, + linkCode: input.linkCode, + userContext: input.userContext, + }); if (response.status !== "OK") { return response; } @@ -59,13 +35,11 @@ function getAPIImplementation() { if (user.email !== undefined) { const emailVerificationInstance = recipe_1.default.getInstance(); if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: user.recipeUserId, - email: user.email, - userContext: input.userContext, - } - ); + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ + userId: user.recipeUserId, + email: user.email, + userContext: input.userContext, + }); if (tokenResponse.status === "OK") { yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ token: tokenResponse.token, @@ -74,14 +48,7 @@ function getAPIImplementation() { } } } - const session = yield session_1.default.createNewSession( - input.options.res, - user.id, - user.recipeUserId, - {}, - {}, - input.userContext - ); + const session = yield session_1.default.createNewSession(input.options.req, input.options.res, user.id, user.recipeUserId, {}, {}, input.userContext); return { status: "OK", createdNewUser: response.createdNewUser, @@ -93,25 +60,21 @@ function getAPIImplementation() { }, createCodePOST: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield input.options.recipeImplementation.createCode( - "email" in input - ? { - userContext: input.userContext, - email: input.email, - userInputCode: - input.options.config.getCustomUserInputCode === undefined - ? undefined - : yield input.options.config.getCustomUserInputCode(input.userContext), - } - : { - userContext: input.userContext, - phoneNumber: input.phoneNumber, - userInputCode: - input.options.config.getCustomUserInputCode === undefined - ? undefined - : yield input.options.config.getCustomUserInputCode(input.userContext), - } - ); + let response = yield input.options.recipeImplementation.createCode("email" in input + ? { + userContext: input.userContext, + email: input.email, + userInputCode: input.options.config.getCustomUserInputCode === undefined + ? undefined + : yield input.options.config.getCustomUserInputCode(input.userContext), + } + : { + userContext: input.userContext, + phoneNumber: input.phoneNumber, + userInputCode: input.options.config.getCustomUserInputCode === undefined + ? undefined + : yield input.options.config.getCustomUserInputCode(input.userContext), + }); // now we send the email / text message. let magicLink = undefined; let userInputCode = undefined; @@ -119,14 +82,14 @@ function getAPIImplementation() { if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = input.options.appInfo.websiteDomain.getAsStringDangerous() + - input.options.appInfo.websiteBasePath.getAsStringDangerous() + - "/verify" + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + input.options.appInfo.websiteBasePath.getAsStringDangerous() + + "/verify" + + "?rid=" + + input.options.recipeId + + "&preAuthSessionId=" + + response.preAuthSessionId + + "#" + + response.linkCode; } if (flowType === "USER_INPUT_CODE" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { userInputCode = response.userInputCode; @@ -134,10 +97,8 @@ function getAPIImplementation() { // we don't do something special for serverless env here // cause we want to wait for service's reply since it can show // a UI error message for if sending an SMS / email failed or not. - if ( - input.options.config.contactMethod === "PHONE" || - (input.options.config.contactMethod === "EMAIL_OR_PHONE" && "phoneNumber" in input) - ) { + if (input.options.config.contactMethod === "PHONE" || + (input.options.config.contactMethod === "EMAIL_OR_PHONE" && "phoneNumber" in input)) { logger_1.logDebugMessage(`Sending passwordless login SMS to ${input.phoneNumber}`); yield input.options.smsDelivery.ingredientInterfaceImpl.sendSms({ type: "PASSWORDLESS_LOGIN", @@ -148,7 +109,8 @@ function getAPIImplementation() { userInputCode, userContext: input.userContext, }); - } else { + } + else { logger_1.logDebugMessage(`Sending passwordless login email to ${input.email}`); yield input.options.emailDelivery.ingredientInterfaceImpl.sendEmail({ type: "PASSWORDLESS_LOGIN", @@ -203,10 +165,8 @@ function getAPIImplementation() { status: "RESTART_FLOW_ERROR", }; } - if ( - (input.options.config.contactMethod === "PHONE" && deviceInfo.phoneNumber === undefined) || - (input.options.config.contactMethod === "EMAIL" && deviceInfo.email === undefined) - ) { + if ((input.options.config.contactMethod === "PHONE" && deviceInfo.phoneNumber === undefined) || + (input.options.config.contactMethod === "EMAIL" && deviceInfo.email === undefined)) { return { status: "RESTART_FLOW_ERROR", }; @@ -217,10 +177,9 @@ function getAPIImplementation() { let response = yield input.options.recipeImplementation.createNewCodeForDevice({ userContext: input.userContext, deviceId: input.deviceId, - userInputCode: - input.options.config.getCustomUserInputCode === undefined - ? undefined - : yield input.options.config.getCustomUserInputCode(input.userContext), + userInputCode: input.options.config.getCustomUserInputCode === undefined + ? undefined + : yield input.options.config.getCustomUserInputCode(input.userContext), }); if (response.status === "USER_INPUT_CODE_ALREADY_USED_ERROR") { if (numberOfTriesToCreateNewCode >= 3) { @@ -239,14 +198,14 @@ function getAPIImplementation() { if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = input.options.appInfo.websiteDomain.getAsStringDangerous() + - input.options.appInfo.websiteBasePath.getAsStringDangerous() + - "/verify" + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + input.options.appInfo.websiteBasePath.getAsStringDangerous() + + "/verify" + + "?rid=" + + input.options.recipeId + + "&preAuthSessionId=" + + response.preAuthSessionId + + "#" + + response.linkCode; } if (flowType === "USER_INPUT_CODE" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { userInputCode = response.userInputCode; @@ -254,11 +213,9 @@ function getAPIImplementation() { // we don't do something special for serverless env here // cause we want to wait for service's reply since it can show // a UI error message for if sending an SMS / email failed or not. - if ( - input.options.config.contactMethod === "PHONE" || + if (input.options.config.contactMethod === "PHONE" || (input.options.config.contactMethod === "EMAIL_OR_PHONE" && - deviceInfo.phoneNumber !== undefined) - ) { + deviceInfo.phoneNumber !== undefined)) { logger_1.logDebugMessage(`Sending passwordless login SMS to ${input.phoneNumber}`); yield input.options.smsDelivery.ingredientInterfaceImpl.sendSms({ type: "PASSWORDLESS_LOGIN", @@ -269,7 +226,8 @@ function getAPIImplementation() { userInputCode, userContext: input.userContext, }); - } else { + } + else { logger_1.logDebugMessage(`Sending passwordless login email to ${input.email}`); yield input.options.emailDelivery.ingredientInterfaceImpl.sendEmail({ type: "PASSWORDLESS_LOGIN", diff --git a/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts b/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts index 9416f0cda..45f1a72ff 100644 --- a/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts +++ b/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function phoneNumberExists(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/phoneNumberExists.js b/lib/build/recipe/passwordless/api/phoneNumberExists.js index 0e9e84e27..2f525b640 100644 --- a/lib/build/recipe/passwordless/api/phoneNumberExists.js +++ b/lib/build/recipe/passwordless/api/phoneNumberExists.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); diff --git a/lib/build/recipe/passwordless/api/resendCode.d.ts b/lib/build/recipe/passwordless/api/resendCode.d.ts index ad4629bb6..80b411dd8 100644 --- a/lib/build/recipe/passwordless/api/resendCode.d.ts +++ b/lib/build/recipe/passwordless/api/resendCode.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function resendCode(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/resendCode.js b/lib/build/recipe/passwordless/api/resendCode.js index 0866c8513..e957b6471 100644 --- a/lib/build/recipe/passwordless/api/resendCode.js +++ b/lib/build/recipe/passwordless/api/resendCode.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); diff --git a/lib/build/recipe/passwordless/constants.d.ts b/lib/build/recipe/passwordless/constants.d.ts index f7438a00e..02bb019f4 100644 --- a/lib/build/recipe/passwordless/constants.d.ts +++ b/lib/build/recipe/passwordless/constants.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export declare const CREATE_CODE_API = "/signinup/code"; export declare const RESEND_CODE_API = "/signinup/code/resend"; export declare const CONSUME_CODE_API = "/signinup/code/consume"; diff --git a/lib/build/recipe/passwordless/constants.js b/lib/build/recipe/passwordless/constants.js index 6679661ed..cd5590dc1 100644 --- a/lib/build/recipe/passwordless/constants.js +++ b/lib/build/recipe/passwordless/constants.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.DOES_PHONE_NUMBER_EXIST_API = exports.DOES_EMAIL_EXIST_API = exports.CONSUME_CODE_API = exports.RESEND_CODE_API = exports.CREATE_CODE_API = void 0; exports.CREATE_CODE_API = "/signinup/code"; exports.RESEND_CODE_API = "/signinup/code/resend"; exports.CONSUME_CODE_API = "/signinup/code/consume"; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts index 2f0015dda..539d63aa8 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,26 +1,16 @@ -// @ts-nocheck import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; -export default class BackwardCompatibilityService - implements EmailDeliveryInterface { +export default class BackwardCompatibilityService implements EmailDeliveryInterface { private createAndSendCustomEmail; - constructor( - appInfo: NormalisedAppinfo, - createAndSendCustomEmail?: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise - ); - sendEmail: ( - input: TypePasswordlessEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + constructor(appInfo: NormalisedAppinfo, createAndSendCustomEmail?: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise); + sendEmail: (input: TypePasswordlessEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js index dc99888f8..97870e798 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js @@ -1,115 +1,85 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = require("axios"); const logger_1 = require("../../../../../logger"); function defaultCreateAndSendCustomEmail(appInfo) { - return (input, _) => - __awaiter(this, void 0, void 0, function* () { - if (process.env.TEST_MODE === "testing") { - return; - } - try { - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.io/0/st/auth/passwordless/login", - data: { - email: input.email, - appName: appInfo.appName, - codeLifetime: input.codeLifetime, - urlWithLinkCode: input.urlWithLinkCode, - userInputCode: input.userInputCode, - }, - headers: { - "api-version": 0, - }, - }); - logger_1.logDebugMessage(`Email sent to ${input.email}`); - } catch (error) { - logger_1.logDebugMessage("Error sending passwordless login email"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } - } else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + return (input, _) => __awaiter(this, void 0, void 0, function* () { + if (process.env.TEST_MODE === "testing") { + return; + } + try { + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.io/0/st/auth/passwordless/login", + data: { + email: input.email, + appName: appInfo.appName, + codeLifetime: input.codeLifetime, + urlWithLinkCode: input.urlWithLinkCode, + userInputCode: input.userInputCode, + }, + headers: { + "api-version": 0, + }, + }); + logger_1.logDebugMessage(`Email sent to ${input.email}`); + } + catch (error) { + logger_1.logDebugMessage("Error sending passwordless login email"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage( - JSON.stringify( - { - email: input.email, - appName: appInfo.appName, - codeLifetime: input.codeLifetime, - urlWithLinkCode: input.urlWithLinkCode, - userInputCode: input.userInputCode, - }, - null, - 2 - ) - ); - /** - * if the error is thrown from API, the response object - * will be of type `{err: string}` - */ - if (axios_1.default.isAxiosError(error) && error.response !== undefined) { - if (error.response.data.err !== undefined) { - throw Error(error.response.data.err); - } + else { + logger_1.logDebugMessage(`Error: ${err.message}`); } - throw error; } - }); + else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + } + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage(JSON.stringify({ + email: input.email, + appName: appInfo.appName, + codeLifetime: input.codeLifetime, + urlWithLinkCode: input.urlWithLinkCode, + userInputCode: input.userInputCode, + }, null, 2)); + /** + * if the error is thrown from API, the response object + * will be of type `{err: string}` + */ + if (axios_1.default.isAxiosError(error) && error.response !== undefined) { + if (error.response.data.err !== undefined) { + throw Error(error.response.data.err); + } + } + throw error; + } + }); } class BackwardCompatibilityService { constructor(appInfo, createAndSendCustomEmail) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.createAndSendCustomEmail( - { - email: input.email, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - preAuthSessionId: input.preAuthSessionId, - codeLifetime: input.codeLifetime, - }, - input.userContext - ); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.createAndSendCustomEmail({ + email: input.email, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + preAuthSessionId: input.preAuthSessionId, + codeLifetime: input.codeLifetime, + }, input.userContext); + }); this.createAndSendCustomEmail = createAndSendCustomEmail === undefined ? defaultCreateAndSendCustomEmail(appInfo) diff --git a/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts index 4de04d983..dd2ef062c 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/index.js b/lib/build/recipe/passwordless/emaildelivery/services/index.js index b38b12ec2..9a1dcbe44 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/index.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts index 3cda03b71..0e9b7843e 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts @@ -1,13 +1,10 @@ -// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { TypePasswordlessEmailDeliveryInput } from "../../../types"; export default class SMTPService implements EmailDeliveryInterface { serviceImpl: ServiceInterface; constructor(config: TypeInput); - sendEmail: ( - input: TypePasswordlessEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + sendEmail: (input: TypePasswordlessEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js index 2975b7375..a91e9c1e1 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js @@ -1,48 +1,23 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = require("supertokens-js-override"); const serviceImplementation_1 = require("./serviceImplementation"); class SMTPService { constructor(config) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - yield this.serviceImpl.sendRawEmail( - Object.assign(Object.assign({}, content), { userContext: input.userContext }) - ); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + yield this.serviceImpl.sendRawEmail(Object.assign(Object.assign({}, content), { userContext: input.userContext })); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -52,9 +27,7 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default( - serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) - ); + let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts index e3ae65d56..dadee437f 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts @@ -1,11 +1,4 @@ -// @ts-nocheck import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; export default function getPasswordlessLoginEmailContent(input: TypePasswordlessEmailDeliveryInput): GetContentResult; -export declare function getPasswordlessLoginEmailHTML( - appName: string, - email: string, - codeLifetime: number, - urlWithLinkCode?: string, - userInputCode?: string -): string; +export declare function getPasswordlessLoginEmailHTML(appName: string, email: string, codeLifetime: number, urlWithLinkCode?: string, userInputCode?: string): string; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js index 835283425..ae37a0a7b 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js @@ -1,17 +1,12 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getPasswordlessLoginEmailHTML = void 0; const supertokens_1 = require("../../../../../supertokens"); const utils_1 = require("../../../../../utils"); function getPasswordlessLoginEmailContent(input) { let supertokens = supertokens_1.default.getInstanceOrThrowError(); let appName = supertokens.appInfo.appName; - let body = getPasswordlessLoginEmailHTML( - appName, - input.email, - input.codeLifetime, - input.urlWithLinkCode, - input.userInputCode - ); + let body = getPasswordlessLoginEmailHTML(appName, input.email, input.codeLifetime, input.urlWithLinkCode, input.userInputCode); return { body, toEmail: input.email, @@ -506,13 +501,6 @@ function getPasswordlessLoginOTPBody(appName, email, codeLifetime, userInputCode text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, @@ -1421,13 +1409,6 @@ function getPasswordlessLoginURLLinkBody(appName, email, codeLifetime, urlWithLi text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, @@ -2351,13 +2332,6 @@ function getPasswordlessLoginOTPAndURLLinkBody(appName, email, codeLifetime, url text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, @@ -2858,24 +2832,13 @@ function getPasswordlessLoginOTPAndURLLinkBody(appName, email, codeLifetime, url } function getPasswordlessLoginEmailHTML(appName, email, codeLifetime, urlWithLinkCode, userInputCode) { if (urlWithLinkCode !== undefined && userInputCode !== undefined) { - return getPasswordlessLoginOTPAndURLLinkBody( - appName, - email, - utils_1.humaniseMilliseconds(codeLifetime), - urlWithLinkCode, - userInputCode - ); + return getPasswordlessLoginOTPAndURLLinkBody(appName, email, utils_1.humaniseMilliseconds(codeLifetime), urlWithLinkCode, userInputCode); } if (userInputCode !== undefined) { return getPasswordlessLoginOTPBody(appName, email, utils_1.humaniseMilliseconds(codeLifetime), userInputCode); } if (urlWithLinkCode !== undefined) { - return getPasswordlessLoginURLLinkBody( - appName, - email, - utils_1.humaniseMilliseconds(codeLifetime), - urlWithLinkCode - ); + return getPasswordlessLoginURLLinkBody(appName, email, utils_1.humaniseMilliseconds(codeLifetime), urlWithLinkCode); } throw Error("this should never be thrown"); } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts index 7a58ac4e4..c6827160f 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts @@ -1,11 +1,7 @@ -// @ts-nocheck import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation( - transporter: Transporter, - from: { - name: string; - email: string; - } -): ServiceInterface; +export declare function getServiceImplementation(transporter: Transporter, from: { + name: string; + email: string; +}): ServiceInterface; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js index 3ff71620c..a8061a55d 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getServiceImplementation = void 0; const passwordlessLogin_1 = require("./passwordlessLogin"); function getServiceImplementation(transporter, from) { return { @@ -57,7 +36,8 @@ function getServiceImplementation(transporter, from) { subject: input.subject, html: input.body, }); - } else { + } + else { yield transporter.sendMail({ from: `${from.name} <${from.email}>`, to: input.toEmail, diff --git a/lib/build/recipe/passwordless/error.d.ts b/lib/build/recipe/passwordless/error.d.ts index 486758b61..71d57623f 100644 --- a/lib/build/recipe/passwordless/error.d.ts +++ b/lib/build/recipe/passwordless/error.d.ts @@ -1,5 +1,7 @@ -// @ts-nocheck import STError from "../../error"; export default class SessionError extends STError { - constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); + constructor(options: { + type: "BAD_INPUT_ERROR"; + message: string; + }); } diff --git a/lib/build/recipe/passwordless/index.d.ts b/lib/build/recipe/passwordless/index.d.ts index f8966f784..e2cc0591c 100644 --- a/lib/build/recipe/passwordless/index.d.ts +++ b/lib/build/recipe/passwordless/index.d.ts @@ -1,30 +1,17 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; -import { - RecipeInterface, - User, - APIOptions, - APIInterface, - TypePasswordlessEmailDeliveryInput, - TypePasswordlessSmsDeliveryInput, -} from "./types"; +import { RecipeInterface, User, APIOptions, APIInterface, TypePasswordlessEmailDeliveryInput, TypePasswordlessSmsDeliveryInput } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static createCode( - input: ( - | { - email: string; - } - | { - phoneNumber: string; - } - ) & { - userInputCode?: string; - userContext?: any; - } - ): Promise<{ + static createCode(input: ({ + email: string; + } | { + phoneNumber: string; + }) & { + userInputCode?: string; + userContext?: any; + }): Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -38,52 +25,50 @@ export default class Wrapper { deviceId: string; userInputCode?: string; userContext?: any; - }): Promise< - | { - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } - | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - } - >; - static consumeCode( - input: - | { - preAuthSessionId: string; - userInputCode: string; - deviceId: string; - userContext?: any; - } - | { - preAuthSessionId: string; - linkCode: string; - userContext?: any; - } - ): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | { - status: "RESTART_FLOW_ERROR"; - } - >; - static getUserById(input: { userId: string; userContext?: any }): Promise; - static getUserByEmail(input: { email: string; userContext?: any }): Promise; - static getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise; + }): Promise<{ + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + }>; + static consumeCode(input: { + preAuthSessionId: string; + userInputCode: string; + deviceId: string; + userContext?: any; + } | { + preAuthSessionId: string; + linkCode: string; + userContext?: any; + }): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | { + status: "RESTART_FLOW_ERROR"; + }>; + static getUserById(input: { + userId: string; + userContext?: any; + }): Promise; + static getUserByEmail(input: { + email: string; + userContext?: any; + }): Promise; + static getUserByPhoneNumber(input: { + phoneNumber: string; + userContext?: any; + }): Promise; static updateUser(input: { userId: string; email?: string | null; @@ -92,17 +77,13 @@ export default class Wrapper { }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - static revokeAllCodes( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ): Promise<{ + static revokeAllCodes(input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }): Promise<{ status: "OK"; }>; static revokeCode(input: { @@ -111,7 +92,10 @@ export default class Wrapper { }): Promise<{ status: "OK"; }>; - static listCodesByEmail(input: { email: string; userContext?: any }): Promise; + static listCodesByEmail(input: { + email: string; + userContext?: any; + }): Promise; static listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any; @@ -124,42 +108,30 @@ export default class Wrapper { preAuthSessionId: string; userContext?: any; }): Promise; - static createMagicLink( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ): Promise; - static signInUp( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ): Promise<{ + static createMagicLink(input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }): Promise; + static signInUp(input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }): Promise<{ status: string; createdNewUser: boolean; user: User; }>; - static sendEmail( - input: TypePasswordlessEmailDeliveryInput & { - userContext?: any; - } - ): Promise; - static sendSms( - input: TypePasswordlessSmsDeliveryInput & { - userContext?: any; - } - ): Promise; + static sendEmail(input: TypePasswordlessEmailDeliveryInput & { + userContext?: any; + }): Promise; + static sendSms(input: TypePasswordlessSmsDeliveryInput & { + userContext?: any; + }): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/passwordless/index.js b/lib/build/recipe/passwordless/index.js index 8c5f5c54c..a43a8f702 100644 --- a/lib/build/recipe/passwordless/index.js +++ b/lib/build/recipe/passwordless/index.js @@ -13,105 +13,58 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.sendSms = exports.sendEmail = exports.signInUp = exports.createMagicLink = exports.revokeCode = exports.revokeAllCodes = exports.updateUser = exports.createNewCodeForDevice = exports.listCodesByPreAuthSessionId = exports.listCodesByPhoneNumber = exports.listCodesByEmail = exports.listCodesByDeviceId = exports.getUserByPhoneNumber = exports.getUserById = exports.getUserByEmail = exports.consumeCode = exports.createCode = exports.Error = exports.init = void 0; const recipe_1 = require("./recipe"); const error_1 = require("./error"); class Wrapper { static createCode(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); } static createNewCodeForDevice(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); } static consumeCode(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); } static getUserById(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getUserById(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserById(Object.assign({ userContext: {} }, input)); } static getUserByEmail(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getUserByEmail(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByEmail(Object.assign({ userContext: {} }, input)); } static getUserByPhoneNumber(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); } static updateUser(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.updateUser(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updateUser(Object.assign({ userContext: {} }, input)); } static revokeAllCodes(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); } static revokeCode(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); } static listCodesByEmail(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); } static listCodesByPhoneNumber(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); } static listCodesByDeviceId(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); } static listCodesByPreAuthSessionId(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); } static createMagicLink(input) { return recipe_1.default.getInstanceOrThrowError().createMagicLink(Object.assign({ userContext: {} }, input)); @@ -121,16 +74,12 @@ class Wrapper { } static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default.getInstanceOrThrowError().emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } static sendSms(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default.getInstanceOrThrowError().smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); }); } } diff --git a/lib/build/recipe/passwordless/recipe.d.ts b/lib/build/recipe/passwordless/recipe.d.ts index 42b76df0a..8d038dba9 100644 --- a/lib/build/recipe/passwordless/recipe.d.ts +++ b/lib/build/recipe/passwordless/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface } from "./types"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; @@ -18,52 +17,32 @@ export default class Recipe extends RecipeModule { isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; smsDelivery: SmsDeliveryIngredient; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - smsDelivery: SmsDeliveryIngredient | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + smsDelivery: SmsDeliveryIngredient | undefined; + }); static getInstanceOrThrowError(): Recipe; static init(config: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - _: NormalisedURLPath, - __: HTTPMethod - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _: NormalisedURLPath, __: HTTPMethod) => Promise; handleError: (err: STError, _: BaseRequest, __: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; - createMagicLink: ( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ) => Promise; - signInUp: ( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ) => Promise<{ + createMagicLink: (input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }) => Promise; + signInUp: (input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }) => Promise<{ status: string; createdNewUser: boolean; user: import("./types").User; diff --git a/lib/build/recipe/passwordless/recipe.js b/lib/build/recipe/passwordless/recipe.js index 8744f6da7..dc678ef91 100644 --- a/lib/build/recipe/passwordless/recipe.js +++ b/lib/build/recipe/passwordless/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -101,35 +79,37 @@ class Recipe extends recipeModule_1.default { }, ]; }; - this.handleAPIRequest = (id, req, res, _, __) => - __awaiter(this, void 0, void 0, function* () { - const options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - emailDelivery: this.emailDelivery, - smsDelivery: this.smsDelivery, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.CONSUME_CODE_API) { - return yield consumeCode_1.default(this.apiImpl, options); - } else if (id === constants_1.CREATE_CODE_API) { - return yield createCode_1.default(this.apiImpl, options); - } else if (id === constants_1.DOES_EMAIL_EXIST_API) { - return yield emailExists_1.default(this.apiImpl, options); - } else if (id === constants_1.DOES_PHONE_NUMBER_EXIST_API) { - return yield phoneNumberExists_1.default(this.apiImpl, options); - } else { - return yield resendCode_1.default(this.apiImpl, options); - } - }); - this.handleError = (err, _, __) => - __awaiter(this, void 0, void 0, function* () { - throw err; - }); + this.handleAPIRequest = (id, req, res, _, __) => __awaiter(this, void 0, void 0, function* () { + const options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + emailDelivery: this.emailDelivery, + smsDelivery: this.smsDelivery, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.CONSUME_CODE_API) { + return yield consumeCode_1.default(this.apiImpl, options); + } + else if (id === constants_1.CREATE_CODE_API) { + return yield createCode_1.default(this.apiImpl, options); + } + else if (id === constants_1.DOES_EMAIL_EXIST_API) { + return yield emailExists_1.default(this.apiImpl, options); + } + else if (id === constants_1.DOES_PHONE_NUMBER_EXIST_API) { + return yield phoneNumberExists_1.default(this.apiImpl, options); + } + else { + return yield resendCode_1.default(this.apiImpl, options); + } + }); + this.handleError = (err, _, __) => __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; @@ -137,100 +117,88 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; // helper functions below... - this.createMagicLink = (input) => - __awaiter(this, void 0, void 0, function* () { - let userInputCode = - this.config.getCustomUserInputCode !== undefined - ? yield this.config.getCustomUserInputCode(input.userContext) - : undefined; - const codeInfo = yield this.recipeInterfaceImpl.createCode( - "email" in input - ? { - email: input.email, - userInputCode, - userContext: input.userContext, - } - : { - phoneNumber: input.phoneNumber, - userInputCode, - userContext: input.userContext, - } - ); - const appInfo = this.getAppInfo(); - let magicLink = - appInfo.websiteDomain.getAsStringDangerous() + - appInfo.websiteBasePath.getAsStringDangerous() + - "/verify" + - "?rid=" + - this.getRecipeId() + - "&preAuthSessionId=" + - codeInfo.preAuthSessionId + - "#" + - codeInfo.linkCode; - return magicLink; - }); - this.signInUp = (input) => - __awaiter(this, void 0, void 0, function* () { - let codeInfo = yield this.recipeInterfaceImpl.createCode( - "email" in input - ? { - email: input.email, - userContext: input.userContext, - } - : { - phoneNumber: input.phoneNumber, - userContext: input.userContext, - } - ); - let consumeCodeResponse = yield this.recipeInterfaceImpl.consumeCode( - this.config.flowType === "MAGIC_LINK" - ? { - preAuthSessionId: codeInfo.preAuthSessionId, - linkCode: codeInfo.linkCode, - userContext: input.userContext, - } - : { - preAuthSessionId: codeInfo.preAuthSessionId, - deviceId: codeInfo.deviceId, - userInputCode: codeInfo.userInputCode, - userContext: input.userContext, - } - ); - if (consumeCodeResponse.status === "OK") { - return { - status: "OK", - createdNewUser: consumeCodeResponse.createdNewUser, - user: consumeCodeResponse.user, - }; - } else { - throw new Error("Failed to create user. Please retry"); + this.createMagicLink = (input) => __awaiter(this, void 0, void 0, function* () { + let userInputCode = this.config.getCustomUserInputCode !== undefined + ? yield this.config.getCustomUserInputCode(input.userContext) + : undefined; + const codeInfo = yield this.recipeInterfaceImpl.createCode("email" in input + ? { + email: input.email, + userInputCode, + userContext: input.userContext, + } + : { + phoneNumber: input.phoneNumber, + userInputCode, + userContext: input.userContext, + }); + const appInfo = this.getAppInfo(); + let magicLink = appInfo.websiteDomain.getAsStringDangerous() + + appInfo.websiteBasePath.getAsStringDangerous() + + "/verify" + + "?rid=" + + this.getRecipeId() + + "&preAuthSessionId=" + + codeInfo.preAuthSessionId + + "#" + + codeInfo.linkCode; + return magicLink; + }); + this.signInUp = (input) => __awaiter(this, void 0, void 0, function* () { + let codeInfo = yield this.recipeInterfaceImpl.createCode("email" in input + ? { + email: input.email, + userContext: input.userContext, } - }); + : { + phoneNumber: input.phoneNumber, + userContext: input.userContext, + }); + let consumeCodeResponse = yield this.recipeInterfaceImpl.consumeCode(this.config.flowType === "MAGIC_LINK" + ? { + preAuthSessionId: codeInfo.preAuthSessionId, + linkCode: codeInfo.linkCode, + userContext: input.userContext, + } + : { + preAuthSessionId: codeInfo.preAuthSessionId, + deviceId: codeInfo.deviceId, + userInputCode: codeInfo.userInputCode, + userContext: input.userContext, + }); + if (consumeCodeResponse.status === "OK") { + return { + status: "OK", + createdNewUser: consumeCodeResponse.createdNewUser, + user: consumeCodeResponse.user, + }; + } + else { + throw new Error("Failed to create user. Please retry"); + } + }); // helper functions... - this.getEmailForUserId = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo !== undefined) { - if (userInfo.email !== undefined) { - return { - status: "OK", - email: userInfo.email, - }; - } + this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo !== undefined) { + if (userInfo.email !== undefined) { return { - status: "EMAIL_DOES_NOT_EXIST_ERROR", + status: "OK", + email: userInfo.email, }; } return { - status: "UNKNOWN_USER_ID_ERROR", + status: "EMAIL_DOES_NOT_EXIST_ERROR", }; - }); + } + return { + status: "UNKNOWN_USER_ID_ERROR", + }; + }); this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -270,7 +238,8 @@ class Recipe extends recipeModule_1.default { smsDelivery: undefined, }); return Recipe.instance; - } else { + } + else { throw new Error("Passwordless recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/passwordless/recipeImplementation.d.ts b/lib/build/recipe/passwordless/recipeImplementation.d.ts index 86bf78a27..8a3a26d7c 100644 --- a/lib/build/recipe/passwordless/recipeImplementation.d.ts +++ b/lib/build/recipe/passwordless/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/passwordless/recipeImplementation.js b/lib/build/recipe/passwordless/recipeImplementation.js index dc0d87d31..48085373e 100644 --- a/lib/build/recipe/passwordless/recipeImplementation.js +++ b/lib/build/recipe/passwordless/recipeImplementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); function getRecipeInterface(querier) { @@ -41,37 +19,25 @@ function getRecipeInterface(querier) { return { consumeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/signinup/code/consume"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code/consume"), copyAndRemoveUserContext(input)); return response; }); }, createCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/signinup/code"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code"), copyAndRemoveUserContext(input)); return response; }); }, createNewCodeForDevice: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/signinup/code"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code"), copyAndRemoveUserContext(input)); return response; }); }, getUserByEmail: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/user"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); if (response.status === "OK") { return response.user; } @@ -80,10 +46,7 @@ function getRecipeInterface(querier) { }, getUserById: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/user"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); if (response.status === "OK") { return response.user; } @@ -92,10 +55,7 @@ function getRecipeInterface(querier) { }, getUserByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/user"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); if (response.status === "OK") { return response.user; } @@ -104,46 +64,31 @@ function getRecipeInterface(querier) { }, listCodesByDeviceId: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/signinup/codes"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); return response.devices.length === 1 ? response.devices[0] : undefined; }); }, listCodesByEmail: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/signinup/codes"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); return response.devices; }); }, listCodesByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/signinup/codes"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); return response.devices; }); }, listCodesByPreAuthSessionId: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/signinup/codes"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); return response.devices.length === 1 ? response.devices[0] : undefined; }); }, revokeAllCodes: function (input) { return __awaiter(this, void 0, void 0, function* () { - yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/signinup/codes/remove"), - copyAndRemoveUserContext(input) - ); + yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/codes/remove"), copyAndRemoveUserContext(input)); return { status: "OK", }; @@ -151,19 +96,13 @@ function getRecipeInterface(querier) { }, revokeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/signinup/code/remove"), - copyAndRemoveUserContext(input) - ); + yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code/remove"), copyAndRemoveUserContext(input)); return { status: "OK" }; }); }, updateUser: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPutRequest( - new normalisedURLPath_1.default("/recipe/user"), - copyAndRemoveUserContext(input) - ); + let response = yield querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); return response; }); }, diff --git a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts index d1477c878..cf45ff3d4 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts @@ -1,25 +1,16 @@ -// @ts-nocheck import { TypePasswordlessSmsDeliveryInput } from "../../../types"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; export default class BackwardCompatibilityService implements SmsDeliveryInterface { private createAndSendCustomSms; - constructor( - appInfo: NormalisedAppinfo, - createAndSendCustomSms?: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise - ); - sendSms: ( - input: TypePasswordlessSmsDeliveryInput & { - userContext: any; - } - ) => Promise; + constructor(appInfo: NormalisedAppinfo, createAndSendCustomSms?: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise); + sendSms: (input: TypePasswordlessSmsDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js index c610d0f48..9fca07090 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js @@ -1,141 +1,117 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = require("axios"); const supertokens_1 = require("../../../../../ingredients/smsdelivery/services/supertokens"); const supertokens_2 = require("../../../../../supertokens"); const logger_1 = require("../../../../../logger"); function defaultCreateAndSendCustomSms(_) { - return (input, _) => - __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_2.default.getInstanceOrThrowError(); - let appName = supertokens.appInfo.appName; - try { - yield axios_1.default({ - method: "post", - url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, - data: { - smsInput: { - appName, - type: "PASSWORDLESS_LOGIN", - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - codeLifetime: input.codeLifetime, - }, - }, - headers: { - "api-version": "0", + return (input, _) => __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_2.default.getInstanceOrThrowError(); + let appName = supertokens.appInfo.appName; + try { + yield axios_1.default({ + method: "post", + url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, + data: { + smsInput: { + appName, + type: "PASSWORDLESS_LOGIN", + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + codeLifetime: input.codeLifetime, }, - }); - logger_1.logDebugMessage(`Passwordless login SMS sent to ${input.phoneNumber}`); - return; - } catch (error) { - logger_1.logDebugMessage("Error sending passwordless login SMS"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } - if (err.response) { - if (err.response.status !== 429) { - /** - * if the error is thrown from API, the response object - * will be of type `{err: string}` - */ - if (err.response.data.err !== undefined) { - throw Error(err.response.data.err); - } else { - throw err; - } + }, + headers: { + "api-version": "0", + }, + }); + logger_1.logDebugMessage(`Passwordless login SMS sent to ${input.phoneNumber}`); + return; + } + catch (error) { + logger_1.logDebugMessage("Error sending passwordless login SMS"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + } + else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + if (err.response) { + if (err.response.status !== 429) { + /** + * if the error is thrown from API, the response object + * will be of type `{err: string}` + */ + if (err.response.data.err !== undefined) { + throw Error(err.response.data.err); + } + else { + throw err; } - } else { - throw err; } - } else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); - throw error; + } + else { + throw err; } } - console.log( - "Free daily SMS quota reached. If you want to use SuperTokens to send SMS, please sign up on supertokens.com to get your SMS API key, else you can also define your own method by overriding the service. For now, we are logging it below:" - ); - /** - * if we do console.log(`SMS content: ${input}`); - * Output would be: - * SMS content: [object Object] - */ - /** - * JSON.stringify takes 3 inputs - * - value: usually an object or array, to be converted - * - replacer: An array of strings and numbers that acts - * as an approved list for selecting the object - * properties that will be stringified - * - space: Adds indentation, white space, and line break characters - * to the return-value JSON text to make it easier to read - * - * console.log(JSON.stringify({"a": 1, "b": 2})) - * Output: - * {"a":1,"b":2} - * - * console.log(JSON.stringify({"a": 1, "b": 2}, null, 2)) - * Output: - * { - * "a": 1, - * "b": 2 - * } - */ - console.log(`\nSMS content: ${JSON.stringify(input, null, 2)}`); - }); + else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + throw error; + } + } + console.log("Free daily SMS quota reached. If you want to use SuperTokens to send SMS, please sign up on supertokens.com to get your SMS API key, else you can also define your own method by overriding the service. For now, we are logging it below:"); + /** + * if we do console.log(`SMS content: ${input}`); + * Output would be: + * SMS content: [object Object] + */ + /** + * JSON.stringify takes 3 inputs + * - value: usually an object or array, to be converted + * - replacer: An array of strings and numbers that acts + * as an approved list for selecting the object + * properties that will be stringified + * - space: Adds indentation, white space, and line break characters + * to the return-value JSON text to make it easier to read + * + * console.log(JSON.stringify({"a": 1, "b": 2})) + * Output: + * {"a":1,"b":2} + * + * console.log(JSON.stringify({"a": 1, "b": 2}, null, 2)) + * Output: + * { + * "a": 1, + * "b": 2 + * } + */ + console.log(`\nSMS content: ${JSON.stringify(input, null, 2)}`); + }); } class BackwardCompatibilityService { constructor(appInfo, createAndSendCustomSms) { - this.sendSms = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.createAndSendCustomSms( - { - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - preAuthSessionId: input.preAuthSessionId, - codeLifetime: input.codeLifetime, - }, - input.userContext - ); - }); + this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.createAndSendCustomSms({ + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + preAuthSessionId: input.preAuthSessionId, + codeLifetime: input.codeLifetime, + }, input.userContext); + }); this.createAndSendCustomSms = createAndSendCustomSms === undefined ? defaultCreateAndSendCustomSms(appInfo) : createAndSendCustomSms; } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts index f14aacf83..4e73dbb4d 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import Twilio from "./twilio"; import Supertokens from "./supertokens"; export declare let TwilioService: typeof Twilio; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/index.js b/lib/build/recipe/passwordless/smsdelivery/services/index.js index 562ec1b75..2be4d323e 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.SupertokensService = exports.TwilioService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts index 501ecbce0..0326d42c0 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypePasswordlessSmsDeliveryInput } from "../../../types"; export default class SupertokensService implements SmsDeliveryInterface { diff --git a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js index e38283c46..c23cf6496 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -51,60 +29,56 @@ const supertokens_2 = require("../../../../../supertokens"); const logger_1 = require("../../../../../logger"); class SupertokensService { constructor(apiKey) { - this.sendSms = (input) => - __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_2.default.getInstanceOrThrowError(); - let appName = supertokens.appInfo.appName; - try { - yield axios_1.default({ - method: "post", - url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, - data: { - apiKey: this.apiKey, - smsInput: { - type: input.type, - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - codeLifetime: input.codeLifetime, - appName, - }, + this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_2.default.getInstanceOrThrowError(); + let appName = supertokens.appInfo.appName; + try { + yield axios_1.default({ + method: "post", + url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, + data: { + apiKey: this.apiKey, + smsInput: { + type: input.type, + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + codeLifetime: input.codeLifetime, + appName, }, - headers: { - "api-version": "0", - }, - }); - } catch (error) { - logger_1.logDebugMessage("Error sending SMS"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } - } else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + }, + headers: { + "api-version": "0", + }, + }); + } + catch (error) { + logger_1.logDebugMessage("Error sending SMS"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + } + else { + logger_1.logDebugMessage(`Error: ${err.message}`); } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage( - JSON.stringify( - { - type: input.type, - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - codeLifetime: input.codeLifetime, - appName, - }, - null, - 2 - ) - ); - throw error; } - }); + else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + } + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage(JSON.stringify({ + type: input.type, + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + codeLifetime: input.codeLifetime, + appName, + }, null, 2)); + throw error; + } + }); this.apiKey = apiKey; } } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts index ef7c09e1d..0e767ac70 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/smsdelivery/services/twilio"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypePasswordlessSmsDeliveryInput } from "../../../types"; @@ -6,9 +5,7 @@ export default class TwilioService implements SmsDeliveryInterface; private config; constructor(config: TypeInput); - sendSms: ( - input: TypePasswordlessSmsDeliveryInput & { - userContext: any; - } - ) => Promise; + sendSms: (input: TypePasswordlessSmsDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js index 2d6ba28a9..2a97b2dc2 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -51,34 +29,18 @@ const supertokens_js_override_1 = require("supertokens-js-override"); const serviceImplementation_1 = require("./serviceImplementation"); class TwilioService { constructor(config) { - this.sendSms = (input) => - __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - if ("from" in this.config.twilioSettings) { - yield this.serviceImpl.sendRawSms( - Object.assign(Object.assign({}, content), { - userContext: input.userContext, - from: this.config.twilioSettings.from, - }) - ); - } else { - yield this.serviceImpl.sendRawSms( - Object.assign(Object.assign({}, content), { - userContext: input.userContext, - messagingServiceSid: this.config.twilioSettings.messagingServiceSid, - }) - ); - } - }); + this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + if ("from" in this.config.twilioSettings) { + yield this.serviceImpl.sendRawSms(Object.assign(Object.assign({}, content), { userContext: input.userContext, from: this.config.twilioSettings.from })); + } + else { + yield this.serviceImpl.sendRawSms(Object.assign(Object.assign({}, content), { userContext: input.userContext, messagingServiceSid: this.config.twilioSettings.messagingServiceSid })); + } + }); this.config = twilio_1.normaliseUserInputConfig(config); - const twilioClient = Twilio( - config.twilioSettings.accountSid, - config.twilioSettings.authToken, - config.twilioSettings.opts - ); - let builder = new supertokens_js_override_1.default( - serviceImplementation_1.getServiceImplementation(twilioClient) - ); + const twilioClient = Twilio(config.twilioSettings.accountSid, config.twilioSettings.authToken, config.twilioSettings.opts); + let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(twilioClient)); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts index 16af07d5e..a39956f9d 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypePasswordlessSmsDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/smsdelivery/services/twilio"; export default function getPasswordlessLoginSmsContent(input: TypePasswordlessSmsDeliveryInput): GetContentResult; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js index e22b1a693..9b50a2f8c 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js @@ -16,9 +16,11 @@ function getPasswordlessLoginSmsBody(appName, codeLifetime, urlWithLinkCode, use let message = ""; if (urlWithLinkCode !== undefined && userInputCode !== undefined) { message += `OTP to login is ${userInputCode} for ${appName}\n\nOR click ${urlWithLinkCode} to login.\n\n`; - } else if (urlWithLinkCode !== undefined) { + } + else if (urlWithLinkCode !== undefined) { message += `Click ${urlWithLinkCode} to login to ${appName}\n\n`; - } else { + } + else { message += `OTP to login is ${userInputCode} for ${appName}\n\n`; } const humanisedCodeLifetime = utils_1.humaniseMilliseconds(codeLifetime); diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts index 8ed40bcf4..248d37f8f 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import { TypePasswordlessSmsDeliveryInput } from "../../../types"; import * as Twilio from "twilio"; import { ServiceInterface } from "../../../../../ingredients/smsdelivery/services/twilio"; -export declare function getServiceImplementation( - twilioClient: Twilio.Twilio -): ServiceInterface; +export declare function getServiceImplementation(twilioClient: Twilio.Twilio): ServiceInterface; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js index 65afb2505..21263ee24 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getServiceImplementation = void 0; const passwordlessLogin_1 = require("./passwordlessLogin"); function getServiceImplementation(twilioClient) { return { @@ -56,7 +35,8 @@ function getServiceImplementation(twilioClient) { body: input.body, from: input.from, }); - } else { + } + else { yield twilioClient.messages.create({ to: input.toPhoneNumber, body: input.body, diff --git a/lib/build/recipe/passwordless/types.d.ts b/lib/build/recipe/passwordless/types.d.ts index 755f79c85..49f593fb3 100644 --- a/lib/build/recipe/passwordless/types.d.ts +++ b/lib/build/recipe/passwordless/types.d.ts @@ -1,16 +1,9 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { - TypeInput as EmailDeliveryTypeInput, - TypeInputWithService as EmailDeliveryTypeInputWithService, -} from "../../ingredients/emaildelivery/types"; +import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; -import { - TypeInput as SmsDeliveryTypeInput, - TypeInputWithService as SmsDeliveryTypeInputWithService, -} from "../../ingredients/smsdelivery/types"; +import { TypeInput as SmsDeliveryTypeInput, TypeInputWithService as SmsDeliveryTypeInputWithService } from "../../ingredients/smsdelivery/types"; import SmsDeliveryIngredient from "../../ingredients/smsdelivery"; import { GeneralErrorResponse, NormalisedAppinfo } from "../../types"; export declare type User = { @@ -20,126 +13,95 @@ export declare type User = { phoneNumber?: string; timeJoined: number; }; -export declare type TypeInput = ( - | { - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } -) & { +export declare type TypeInput = ({ + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +}) & { flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; emailDelivery?: EmailDeliveryTypeInput; smsDelivery?: SmsDeliveryTypeInput; getCustomUserInputCode?: (userContext: any) => Promise | string; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder: OverrideableBuilder) => APIInterface; }; }; -export declare type TypeNormalisedInput = ( - | { - contactMethod: "PHONE"; - validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress: (email: string) => Promise | string | undefined; - } - | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress: (email: string) => Promise | string | undefined; - validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; - } -) & { +export declare type TypeNormalisedInput = ({ + contactMethod: "PHONE"; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; +} | { + contactMethod: "EMAIL"; + validateEmailAddress: (email: string) => Promise | string | undefined; +} | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress: (email: string) => Promise | string | undefined; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; +}) & { flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; getCustomUserInputCode?: (userContext: any) => Promise | string; getSmsDeliveryConfig: () => SmsDeliveryTypeInputWithService; getEmailDeliveryConfig: () => EmailDeliveryTypeInputWithService; override: { - functions: ( - originalImplementation: RecipeInterface, - builder: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - createCode: ( - input: ( - | { - email: string; - } - | { - phoneNumber: string; - } - ) & { - userInputCode?: string; - userContext: any; - } - ) => Promise<{ + createCode: (input: ({ + email: string; + } | { + phoneNumber: string; + }) & { + userInputCode?: string; + userContext: any; + }) => Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -153,52 +115,50 @@ export declare type RecipeInterface = { deviceId: string; userInputCode?: string; userContext: any; - }) => Promise< - | { - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } - | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - } - >; - consumeCode: ( - input: - | { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - userContext: any; - } - | { - linkCode: string; - preAuthSessionId: string; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | { - status: "RESTART_FLOW_ERROR"; - } - >; - getUserById: (input: { userId: string; userContext: any }) => Promise; - getUserByEmail: (input: { email: string; userContext: any }) => Promise; - getUserByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; + }) => Promise<{ + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + }>; + consumeCode: (input: { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + userContext: any; + } | { + linkCode: string; + preAuthSessionId: string; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | { + status: "RESTART_FLOW_ERROR"; + }>; + getUserById: (input: { + userId: string; + userContext: any; + }) => Promise; + getUserByEmail: (input: { + email: string; + userContext: any; + }) => Promise; + getUserByPhoneNumber: (input: { + phoneNumber: string; + userContext: any; + }) => Promise; updateUser: (input: { userId: string; email?: string | null; @@ -207,17 +167,13 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - revokeAllCodes: ( - input: - | { - email: string; - userContext: any; - } - | { - phoneNumber: string; - userContext: any; - } - ) => Promise<{ + revokeAllCodes: (input: { + email: string; + userContext: any; + } | { + phoneNumber: string; + userContext: any; + }) => Promise<{ status: "OK"; }>; revokeCode: (input: { @@ -226,9 +182,18 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; - listCodesByEmail: (input: { email: string; userContext: any }) => Promise; - listCodesByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; - listCodesByDeviceId: (input: { deviceId: string; userContext: any }) => Promise; + listCodesByEmail: (input: { + email: string; + userContext: any; + }) => Promise; + listCodesByPhoneNumber: (input: { + phoneNumber: string; + userContext: any; + }) => Promise; + listCodesByDeviceId: (input: { + deviceId: string; + userContext: any; + }) => Promise; listCodesByPreAuthSessionId: (input: { preAuthSessionId: string; userContext: any; @@ -257,147 +222,103 @@ export declare type APIOptions = { smsDelivery: SmsDeliveryIngredient; }; export declare type APIInterface = { - createCodePOST?: ( - input: ( - | { - email: string; - } - | { - phoneNumber: string; - } - ) & { - options: APIOptions; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - deviceId: string; - preAuthSessionId: string; - flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; - } - | GeneralErrorResponse - >; - resendCodePOST?: ( - input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: APIOptions; - userContext: any; - } - ) => Promise< - | GeneralErrorResponse - | { - status: "RESTART_FLOW_ERROR" | "OK"; - } - >; - consumeCodePOST?: ( - input: ( - | { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } - | { - linkCode: string; - preAuthSessionId: string; - } - ) & { - options: APIOptions; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | GeneralErrorResponse - | { - status: "RESTART_FLOW_ERROR"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - >; - linkAccountToExistingAccountPOST: - | undefined - | (( - input: ( - | { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } - | { - linkCode: string; - preAuthSessionId: string; - } - ) & { - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); + createCodePOST?: (input: ({ + email: string; + } | { + phoneNumber: string; + }) & { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + deviceId: string; + preAuthSessionId: string; + flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; + } | GeneralErrorResponse>; + resendCodePOST?: (input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: APIOptions; + userContext: any; + }) => Promise; + consumeCodePOST?: (input: ({ + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } | { + linkCode: string; + preAuthSessionId: string; + }) & { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | GeneralErrorResponse | { + status: "RESTART_FLOW_ERROR"; + } | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + }>; + linkAccountToExistingAccountPOST: undefined | ((input: ({ + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } | { + linkCode: string; + preAuthSessionId: string; + }) & { + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } | GeneralErrorResponse>); emailExistsGET?: (input: { email: string; options: APIOptions; userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >; + }) => Promise<{ + status: "OK"; + exists: boolean; + } | GeneralErrorResponse>; phoneNumberExistsGET?: (input: { phoneNumber: string; options: APIOptions; userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >; + }) => Promise<{ + status: "OK"; + exists: boolean; + } | GeneralErrorResponse>; }; export declare type TypePasswordlessEmailDeliveryInput = { type: "PASSWORDLESS_LOGIN"; diff --git a/lib/build/recipe/passwordless/utils.d.ts b/lib/build/recipe/passwordless/utils.d.ts index f00fc5184..99ab887b6 100644 --- a/lib/build/recipe/passwordless/utils.d.ts +++ b/lib/build/recipe/passwordless/utils.d.ts @@ -1,11 +1,6 @@ -// @ts-nocheck import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function validateAndNormaliseUserInput( - _: Recipe, - appInfo: NormalisedAppinfo, - config: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(_: Recipe, appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; export declare function defaultValidatePhoneNumber(value: string): Promise | string | undefined; export declare function defaultValidateEmail(value: string): Promise | string | undefined; diff --git a/lib/build/recipe/passwordless/utils.js b/lib/build/recipe/passwordless/utils.js index 21b7956d7..5aef932ef 100644 --- a/lib/build/recipe/passwordless/utils.js +++ b/lib/build/recipe/passwordless/utils.js @@ -14,27 +14,20 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultValidateEmail = exports.defaultValidatePhoneNumber = exports.validateAndNormaliseUserInput = void 0; const max_1 = require("libphonenumber-js/max"); const backwardCompatibility_1 = require("./emaildelivery/services/backwardCompatibility"); const backwardCompatibility_2 = require("./smsdelivery/services/backwardCompatibility"); function validateAndNormaliseUserInput(_, appInfo, config) { - if ( - config.contactMethod !== "PHONE" && + if (config.contactMethod !== "PHONE" && config.contactMethod !== "EMAIL" && - config.contactMethod !== "EMAIL_OR_PHONE" - ) { + config.contactMethod !== "EMAIL_OR_PHONE") { throw new Error('Please pass one of "PHONE", "EMAIL" or "EMAIL_OR_PHONE" as the contactMethod'); } if (config.flowType === undefined) { throw new Error("Please pass flowType argument in the config"); } - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); function getEmailDeliveryConfig() { var _a; let emailService = (_a = config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; @@ -49,7 +42,7 @@ function validateAndNormaliseUserInput(_, appInfo, config) { if (emailService === undefined) { emailService = new backwardCompatibility_1.default(appInfo, createAndSendCustomEmail); } - let emailDelivery = Object.assign(Object.assign({}, config.emailDelivery), { + let emailDelivery = Object.assign(Object.assign({}, config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -61,15 +54,13 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService, - }); + service: emailService }); return emailDelivery; } function getSmsDeliveryConfig() { var _a; let smsService = (_a = config.smsDelivery) === null || _a === void 0 ? void 0 : _a.service; - let createAndSendCustomTextMessage = - config.contactMethod === "EMAIL" ? undefined : config.createAndSendCustomTextMessage; + let createAndSendCustomTextMessage = config.contactMethod === "EMAIL" ? undefined : config.createAndSendCustomTextMessage; /** * following code is for backward compatibility. * if user has not passed emailDelivery config, we @@ -80,7 +71,7 @@ function validateAndNormaliseUserInput(_, appInfo, config) { if (smsService === undefined) { smsService = new backwardCompatibility_2.default(appInfo, createAndSendCustomTextMessage); } - let smsDelivery = Object.assign(Object.assign({}, config.smsDelivery), { + let smsDelivery = Object.assign(Object.assign({}, config.smsDelivery), { /** * if we do * let smsDelivery = { @@ -92,8 +83,7 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: smsService, - }); + service: smsService }); return smsDelivery; } if (config.contactMethod === "EMAIL") { @@ -103,32 +93,30 @@ function validateAndNormaliseUserInput(_, appInfo, config) { getSmsDeliveryConfig, flowType: config.flowType, contactMethod: "EMAIL", - validateEmailAddress: - config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, getCustomUserInputCode: config.getCustomUserInputCode, }; - } else if (config.contactMethod === "PHONE") { + } + else if (config.contactMethod === "PHONE") { return { override, getEmailDeliveryConfig, getSmsDeliveryConfig, flowType: config.flowType, contactMethod: "PHONE", - validatePhoneNumber: - config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; - } else { + } + else { return { override, getEmailDeliveryConfig, getSmsDeliveryConfig, flowType: config.flowType, contactMethod: "EMAIL_OR_PHONE", - validateEmailAddress: - config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, - validatePhoneNumber: - config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; } @@ -153,11 +141,7 @@ function defaultValidateEmail(value) { if (typeof value !== "string") { return "Development bug: Please make sure the email field is a string"; } - if ( - value.match( - /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ - ) === null - ) { + if (value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/) === null) { return "Email is invalid"; } return undefined; diff --git a/lib/build/recipe/session/accessToken.d.ts b/lib/build/recipe/session/accessToken.d.ts index 656d2a37b..cc0f114c1 100644 --- a/lib/build/recipe/session/accessToken.d.ts +++ b/lib/build/recipe/session/accessToken.d.ts @@ -1,9 +1,5 @@ -// @ts-nocheck -export declare function getInfoFromAccessToken( - token: string, - jwtSigningPublicKey: string, - doAntiCsrfCheck: boolean -): Promise<{ +import { ParsedJWTInfo } from "./jwt"; +export declare function getInfoFromAccessToken(jwtInfo: ParsedJWTInfo, jwtSigningPublicKey: string, doAntiCsrfCheck: boolean): Promise<{ sessionHandle: string; userId: string; recipeUserId: string; @@ -14,4 +10,5 @@ export declare function getInfoFromAccessToken( expiryTime: number; timeCreated: number; }>; +export declare function validateAccessTokenStructure(payload: any): void; export declare function sanitizeNumberInput(field: any): number | undefined; diff --git a/lib/build/recipe/session/accessToken.js b/lib/build/recipe/session/accessToken.js index f7d1ad4b1..31909e6b7 100644 --- a/lib/build/recipe/session/accessToken.js +++ b/lib/build/recipe/session/accessToken.js @@ -13,44 +13,27 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.sanitizeNumberInput = exports.validateAccessTokenStructure = exports.getInfoFromAccessToken = void 0; const error_1 = require("./error"); const jwt_1 = require("./jwt"); -function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { +function getInfoFromAccessToken(jwtInfo, jwtSigningPublicKey, doAntiCsrfCheck) { return __awaiter(this, void 0, void 0, function* () { try { - let payload = jwt_1.verifyJWTAndGetPayload(token, jwtSigningPublicKey); + jwt_1.verifyJWT(jwtInfo, jwtSigningPublicKey); + const payload = jwtInfo.payload; + // This should be called before this function, but the check is very quick, so we can also do them here + validateAccessTokenStructure(payload); + // We can mark these as defined (the ! after the calls), since validateAccessTokenPayload checks this let sessionHandle = sanitizeStringInput(payload.sessionHandle); let userId = sanitizeStringInput(payload.userId); let recipeUserId = sanitizeStringInput(payload.recipeUserId); @@ -60,18 +43,8 @@ function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { let antiCsrfToken = sanitizeStringInput(payload.antiCsrfToken); let expiryTime = sanitizeNumberInput(payload.expiryTime); let timeCreated = sanitizeNumberInput(payload.timeCreated); - if ( - sessionHandle === undefined || - userId === undefined || - recipeUserId === undefined || - refreshTokenHash1 === undefined || - userData === undefined || - (antiCsrfToken === undefined && doAntiCsrfCheck) || - expiryTime === undefined || - timeCreated === undefined - ) { - // it would come here if we change the structure of the JWT. - throw Error("Access token does not contain all the information. Maybe the structure has changed?"); + if (antiCsrfToken === undefined && doAntiCsrfCheck) { + throw Error("Access token does not contain the anti-csrf token."); } if (expiryTime < Date.now()) { throw Error("Access token expired"); @@ -87,7 +60,8 @@ function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { timeCreated, recipeUserId, }; - } catch (err) { + } + catch (err) { throw new error_1.default({ message: "Failed to verify access token", type: error_1.default.TRY_REFRESH_TOKEN, @@ -96,6 +70,19 @@ function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { }); } exports.getInfoFromAccessToken = getInfoFromAccessToken; +function validateAccessTokenStructure(payload) { + if (typeof payload.sessionHandle !== "string" || + typeof payload.userId !== "string" || + typeof payload.recipeUserId !== "string" || + typeof payload.refreshTokenHash1 !== "string" || + payload.userData === undefined || + typeof payload.expiryTime !== "number" || + typeof payload.timeCreated !== "number") { + // it would come here if we change the structure of the JWT. + throw Error("Access token does not contain all the information. Maybe the structure has changed?"); + } +} +exports.validateAccessTokenStructure = validateAccessTokenStructure; function sanitizeStringInput(field) { if (field === "") { return ""; @@ -106,7 +93,8 @@ function sanitizeStringInput(field) { try { let result = field.trim(); return result; - } catch (err) {} + } + catch (err) { } return undefined; } function sanitizeNumberInput(field) { diff --git a/lib/build/recipe/session/api/implementation.d.ts b/lib/build/recipe/session/api/implementation.d.ts index dd40e7025..b3c21a436 100644 --- a/lib/build/recipe/session/api/implementation.d.ts +++ b/lib/build/recipe/session/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../"; export default function getAPIInterface(): APIInterface; diff --git a/lib/build/recipe/session/api/implementation.js b/lib/build/recipe/session/api/implementation.js index b8d7f2824..a1a9db7e5 100644 --- a/lib/build/recipe/session/api/implementation.js +++ b/lib/build/recipe/session/api/implementation.js @@ -1,42 +1,20 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const normalisedURLPath_1 = require("../../../normalisedURLPath"); const utils_2 = require("../utils"); function getAPIInterface() { return { - refreshPOST: function ({ options, userContext }) { + refreshPOST: function ({ options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.refreshSession({ req: options.req, @@ -45,7 +23,7 @@ function getAPIInterface() { }); }); }, - verifySession: function ({ verifySessionOptions, options, userContext }) { + verifySession: function ({ verifySessionOptions, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let method = utils_1.normaliseHttpMethod(options.req.getMethod()); if (method === "options" || method === "trace") { @@ -59,7 +37,8 @@ function getAPIInterface() { res: options.res, userContext, }); - } else { + } + else { const session = yield options.recipeImplementation.getSession({ req: options.req, res: options.res, @@ -67,20 +46,14 @@ function getAPIInterface() { userContext, }); if (session !== undefined) { - const claimValidators = yield utils_2.getRequiredClaimValidators( - session, - verifySessionOptions === null || verifySessionOptions === void 0 - ? void 0 - : verifySessionOptions.overrideGlobalClaimValidators, - userContext - ); + const claimValidators = yield utils_2.getRequiredClaimValidators(session, verifySessionOptions === null || verifySessionOptions === void 0 ? void 0 : verifySessionOptions.overrideGlobalClaimValidators, userContext); yield session.assertClaims(claimValidators, userContext); } return session; } }); }, - signOutPOST: function ({ session, userContext }) { + signOutPOST: function ({ session, userContext, }) { return __awaiter(this, void 0, void 0, function* () { if (session !== undefined) { yield session.revokeSession(userContext); diff --git a/lib/build/recipe/session/api/refresh.d.ts b/lib/build/recipe/session/api/refresh.d.ts index 6b4746e67..a24161ed0 100644 --- a/lib/build/recipe/session/api/refresh.d.ts +++ b/lib/build/recipe/session/api/refresh.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function handleRefreshAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/session/api/refresh.js b/lib/build/recipe/session/api/refresh.js index 6ae4b4a31..b65d91e1b 100644 --- a/lib/build/recipe/session/api/refresh.js +++ b/lib/build/recipe/session/api/refresh.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); @@ -52,10 +30,7 @@ function handleRefreshAPI(apiImplementation, options) { if (apiImplementation.refreshPOST === undefined) { return false; } - yield apiImplementation.refreshPOST({ - options, - userContext: utils_2.makeDefaultUserContextFromAPI(options.req), - }); + yield apiImplementation.refreshPOST({ options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) }); utils_1.send200Response(options.res, {}); return true; }); diff --git a/lib/build/recipe/session/api/signout.d.ts b/lib/build/recipe/session/api/signout.d.ts index 0e1d985d3..93bd2141e 100644 --- a/lib/build/recipe/session/api/signout.d.ts +++ b/lib/build/recipe/session/api/signout.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signOutAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/session/api/signout.js b/lib/build/recipe/session/api/signout.js index d0ca3e50c..6fc07fa62 100644 --- a/lib/build/recipe/session/api/signout.js +++ b/lib/build/recipe/session/api/signout.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); diff --git a/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts index ba5736f3f..f5085c633 100644 --- a/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { SessionClaim, SessionClaimValidator } from "../types"; import { PrimitiveClaim } from "./primitiveClaim"; export declare class BooleanClaim extends PrimitiveClaim { diff --git a/lib/build/recipe/session/claimBaseClasses/booleanClaim.js b/lib/build/recipe/session/claimBaseClasses/booleanClaim.js index 2f0d179cf..f3d21b4de 100644 --- a/lib/build/recipe/session/claimBaseClasses/booleanClaim.js +++ b/lib/build/recipe/session/claimBaseClasses/booleanClaim.js @@ -1,13 +1,11 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.BooleanClaim = void 0; const primitiveClaim_1 = require("./primitiveClaim"); class BooleanClaim extends primitiveClaim_1.PrimitiveClaim { constructor(conf) { super(conf); - this.validators = Object.assign(Object.assign({}, this.validators), { - isTrue: (maxAge, id) => this.validators.hasValue(true, maxAge, id), - isFalse: (maxAge, id) => this.validators.hasValue(false, maxAge, id), - }); + this.validators = Object.assign(Object.assign({}, this.validators), { isTrue: (maxAge, id) => this.validators.hasValue(true, maxAge, id), isFalse: (maxAge, id) => this.validators.hasValue(false, maxAge, id) }); } } exports.BooleanClaim = BooleanClaim; diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts index 9593151f1..2a841563b 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts @@ -1,14 +1,13 @@ -// @ts-nocheck import { JSONPrimitive } from "../../../types"; import { SessionClaim, SessionClaimValidator } from "../types"; export declare class PrimitiveArrayClaim extends SessionClaim { - readonly fetchValue: ( - userId: string, - recipeUserId: string, - userContext: any - ) => Promise | T[] | undefined; + readonly fetchValue: (userId: string, recipeUserId: string, userContext: any) => Promise | T[] | undefined; readonly defaultMaxAgeInSeconds: number | undefined; - constructor(config: { key: string; fetchValue: SessionClaim["fetchValue"]; defaultMaxAgeInSeconds?: number }); + constructor(config: { + key: string; + fetchValue: SessionClaim["fetchValue"]; + defaultMaxAgeInSeconds?: number; + }); addToPayload_internal(payload: any, value: T[], _userContext: any): any; removeFromPayloadByMerge_internal(payload: any, _userContext?: any): any; removeFromPayload(payload: any, _userContext?: any): any; diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js index 39a7e5694..ec14d7569 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js +++ b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.PrimitiveArrayClaim = void 0; const types_1 = require("../types"); class PrimitiveArrayClaim extends types_1.SessionClaim { constructor(config) { @@ -40,178 +19,154 @@ class PrimitiveArrayClaim extends types_1.SessionClaim { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => - this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => - __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { - message: "value does not exist", - expectedToInclude: val, - actualValue: claimVal, - }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - if (!claimVal.includes(val)) { - return { - isValid: false, - reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, - }; - } - return { isValid: true }; - }), + validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { message: "value does not exist", expectedToInclude: val, actualValue: claimVal }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + if (!claimVal.includes(val)) { + return { + isValid: false, + reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, + }; + } + return { isValid: true }; + }), }; }, excludes: (val, maxAgeInSeconds = this.defaultMaxAgeInSeconds, id) => { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => - this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => - __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { - message: "value does not exist", - expectedToNotInclude: val, - actualValue: claimVal, - }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - if (claimVal.includes(val)) { - return { - isValid: false, - reason: { - message: "wrong value", - expectedToNotInclude: val, - actualValue: claimVal, - }, - }; - } - return { isValid: true }; - }), + validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { + message: "value does not exist", + expectedToNotInclude: val, + actualValue: claimVal, + }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + if (claimVal.includes(val)) { + return { + isValid: false, + reason: { message: "wrong value", expectedToNotInclude: val, actualValue: claimVal }, + }; + } + return { isValid: true }; + }), }; }, includesAll: (val, maxAgeInSeconds = this.defaultMaxAgeInSeconds, id) => { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => - this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => - __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { - message: "value does not exist", - expectedToInclude: val, - actualValue: claimVal, - }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - const claimSet = new Set(claimVal); - const isValid = val.every((v) => claimSet.has(v)); - return isValid - ? { isValid } - : { - isValid, - reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, - }; - }), + validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { message: "value does not exist", expectedToInclude: val, actualValue: claimVal }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + const claimSet = new Set(claimVal); + const isValid = val.every((v) => claimSet.has(v)); + return isValid + ? { isValid } + : { + isValid, + reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, + }; + }), }; }, excludesAll: (val, maxAgeInSeconds = this.defaultMaxAgeInSeconds, id) => { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => - this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => - __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { - message: "value does not exist", - expectedToNotInclude: val, - actualValue: claimVal, - }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - const claimSet = new Set(claimVal); - const isValid = val.every((v) => !claimSet.has(v)); - return isValid - ? { isValid: isValid } - : { - isValid, - reason: { - message: "wrong value", - expectedToNotInclude: val, - actualValue: claimVal, - }, - }; - }), + validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { + message: "value does not exist", + expectedToNotInclude: val, + actualValue: claimVal, + }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + const claimSet = new Set(claimVal); + const isValid = val.every((v) => !claimSet.has(v)); + return isValid + ? { isValid: isValid } + : { + isValid, + reason: { message: "wrong value", expectedToNotInclude: val, actualValue: claimVal }, + }; + }), }; }, }; @@ -219,12 +174,10 @@ class PrimitiveArrayClaim extends types_1.SessionClaim { this.defaultMaxAgeInSeconds = config.defaultMaxAgeInSeconds; } addToPayload_internal(payload, value, _userContext) { - return Object.assign(Object.assign({}, payload), { - [this.key]: { + return Object.assign(Object.assign({}, payload), { [this.key]: { v: value, t: Date.now(), - }, - }); + } }); } removeFromPayloadByMerge_internal(payload, _userContext) { const res = Object.assign(Object.assign({}, payload), { [this.key]: null }); diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts index dbc3f5355..c51c640ac 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts @@ -1,14 +1,13 @@ -// @ts-nocheck import { JSONPrimitive } from "../../../types"; import { SessionClaim, SessionClaimValidator } from "../types"; export declare class PrimitiveClaim extends SessionClaim { - readonly fetchValue: ( - userId: string, - recipeUserId: string, - userContext: any - ) => Promise | T | undefined; + readonly fetchValue: (userId: string, recipeUserId: string, userContext: any) => Promise | T | undefined; readonly defaultMaxAgeInSeconds: number | undefined; - constructor(config: { key: string; fetchValue: SessionClaim["fetchValue"]; defaultMaxAgeInSeconds?: number }); + constructor(config: { + key: string; + fetchValue: SessionClaim["fetchValue"]; + defaultMaxAgeInSeconds?: number; + }); addToPayload_internal(payload: any, value: T, _userContext: any): any; removeFromPayloadByMerge_internal(payload: any, _userContext?: any): any; removeFromPayload(payload: any, _userContext?: any): any; diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js index 65d5250e6..e3abfb5cc 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js +++ b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.PrimitiveClaim = void 0; const types_1 = require("../types"); class PrimitiveClaim extends types_1.SessionClaim { constructor(config) { @@ -40,42 +19,36 @@ class PrimitiveClaim extends types_1.SessionClaim { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => - this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || (maxAgeInSeconds !== undefined && // We know payload[this.id] is defined since the value is not undefined in this branch payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => - __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { - message: "value does not exist", - expectedValue: val, - actualValue: claimVal, - }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - if (claimVal !== val) { - return { - isValid: false, - reason: { message: "wrong value", expectedValue: val, actualValue: claimVal }, - }; - } - return { isValid: true }; - }), + validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { message: "value does not exist", expectedValue: val, actualValue: claimVal }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + if (claimVal !== val) { + return { + isValid: false, + reason: { message: "wrong value", expectedValue: val, actualValue: claimVal }, + }; + } + return { isValid: true }; + }), }; }, }; @@ -83,12 +56,10 @@ class PrimitiveClaim extends types_1.SessionClaim { this.defaultMaxAgeInSeconds = config.defaultMaxAgeInSeconds; } addToPayload_internal(payload, value, _userContext) { - return Object.assign(Object.assign({}, payload), { - [this.key]: { + return Object.assign(Object.assign({}, payload), { [this.key]: { v: value, t: Date.now(), - }, - }); + } }); } removeFromPayloadByMerge_internal(payload, _userContext) { const res = Object.assign(Object.assign({}, payload), { [this.key]: null }); diff --git a/lib/build/recipe/session/claims.d.ts b/lib/build/recipe/session/claims.d.ts index ae6b132bd..03561b33f 100644 --- a/lib/build/recipe/session/claims.d.ts +++ b/lib/build/recipe/session/claims.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export { SessionClaim } from "./types"; export { PrimitiveClaim } from "./claimBaseClasses/primitiveClaim"; export { PrimitiveArrayClaim } from "./claimBaseClasses/primitiveArrayClaim"; diff --git a/lib/build/recipe/session/claims.js b/lib/build/recipe/session/claims.js index 6915f11bf..4a547fb2e 100644 --- a/lib/build/recipe/session/claims.js +++ b/lib/build/recipe/session/claims.js @@ -1,10 +1,11 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.BooleanClaim = exports.PrimitiveArrayClaim = exports.PrimitiveClaim = exports.SessionClaim = void 0; var types_1 = require("./types"); -exports.SessionClaim = types_1.SessionClaim; +Object.defineProperty(exports, "SessionClaim", { enumerable: true, get: function () { return types_1.SessionClaim; } }); var primitiveClaim_1 = require("./claimBaseClasses/primitiveClaim"); -exports.PrimitiveClaim = primitiveClaim_1.PrimitiveClaim; +Object.defineProperty(exports, "PrimitiveClaim", { enumerable: true, get: function () { return primitiveClaim_1.PrimitiveClaim; } }); var primitiveArrayClaim_1 = require("./claimBaseClasses/primitiveArrayClaim"); -exports.PrimitiveArrayClaim = primitiveArrayClaim_1.PrimitiveArrayClaim; +Object.defineProperty(exports, "PrimitiveArrayClaim", { enumerable: true, get: function () { return primitiveArrayClaim_1.PrimitiveArrayClaim; } }); var booleanClaim_1 = require("./claimBaseClasses/booleanClaim"); -exports.BooleanClaim = booleanClaim_1.BooleanClaim; +Object.defineProperty(exports, "BooleanClaim", { enumerable: true, get: function () { return booleanClaim_1.BooleanClaim; } }); diff --git a/lib/build/recipe/session/constants.d.ts b/lib/build/recipe/session/constants.d.ts index 82a2b430c..51bf0ed63 100644 --- a/lib/build/recipe/session/constants.d.ts +++ b/lib/build/recipe/session/constants.d.ts @@ -1,3 +1,4 @@ -// @ts-nocheck +import { TokenTransferMethod } from "./types"; export declare const REFRESH_API_PATH = "/session/refresh"; export declare const SIGNOUT_API_PATH = "/signout"; +export declare const availableTokenTransferMethods: TokenTransferMethod[]; diff --git a/lib/build/recipe/session/constants.js b/lib/build/recipe/session/constants.js index 128fe07ce..742008e66 100644 --- a/lib/build/recipe/session/constants.js +++ b/lib/build/recipe/session/constants.js @@ -14,5 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.availableTokenTransferMethods = exports.SIGNOUT_API_PATH = exports.REFRESH_API_PATH = void 0; exports.REFRESH_API_PATH = "/session/refresh"; exports.SIGNOUT_API_PATH = "/signout"; +exports.availableTokenTransferMethods = ["cookie", "header"]; diff --git a/lib/build/recipe/session/cookieAndHeaders.d.ts b/lib/build/recipe/session/cookieAndHeaders.d.ts index 7bd9547b6..d83e96310 100644 --- a/lib/build/recipe/session/cookieAndHeaders.d.ts +++ b/lib/build/recipe/session/cookieAndHeaders.d.ts @@ -1,47 +1,14 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; -import { TypeNormalisedInput } from "./types"; -/** - * @description clears all the auth cookies from the response - */ -export declare function clearSessionFromCookie(config: TypeNormalisedInput, res: BaseResponse): void; -/** - * @param expiry: must be time in milliseconds from epoch time. - */ -export declare function attachAccessTokenToCookie( - config: TypeNormalisedInput, - res: BaseResponse, - token: string, - expiry: number -): void; -/** - * @param expiry: must be time in milliseconds from epoch time. - */ -export declare function attachRefreshTokenToCookie( - config: TypeNormalisedInput, - res: BaseResponse, - token: string, - expiry: number -): void; -export declare function getAccessTokenFromCookie(req: BaseRequest): string | undefined; -export declare function getRefreshTokenFromCookie(req: BaseRequest): string | undefined; +import { TokenTransferMethod, TokenType, TypeNormalisedInput } from "./types"; +export declare function clearSessionFromAllTokenTransferMethods(config: TypeNormalisedInput, res: BaseResponse): void; +export declare function clearSession(config: TypeNormalisedInput, res: BaseResponse, transferMethod: TokenTransferMethod): void; export declare function getAntiCsrfTokenFromHeaders(req: BaseRequest): string | undefined; -export declare function getRidFromHeader(req: BaseRequest): string | undefined; -export declare function getIdRefreshTokenFromCookie(req: BaseRequest): string | undefined; export declare function setAntiCsrfTokenInHeaders(res: BaseResponse, antiCsrfToken: string): void; -export declare function setIdRefreshTokenInHeaderAndCookie( - config: TypeNormalisedInput, - res: BaseResponse, - idRefreshToken: string, - expiry: number -): void; -export declare function setFrontTokenInHeaders( - res: BaseResponse, - userId: string, - atExpiry: number, - accessTokenPayload: any -): void; +export declare function setFrontTokenInHeaders(res: BaseResponse, userId: string, atExpiry: number, accessTokenPayload: any): void; export declare function getCORSAllowedHeaders(): string[]; +export declare function getToken(req: BaseRequest, tokenType: TokenType, transferMethod: TokenTransferMethod): string | undefined; +export declare function setToken(config: TypeNormalisedInput, res: BaseResponse, tokenType: TokenType, value: string, expires: number, transferMethod: TokenTransferMethod): void; +export declare function setHeader(res: BaseResponse, name: string, value: string): void; /** * * @param res @@ -53,11 +20,5 @@ export declare function getCORSAllowedHeaders(): string[]; * @param expires * @param path */ -export declare function setCookie( - config: TypeNormalisedInput, - res: BaseResponse, - name: string, - value: string, - expires: number, - pathType: "refreshTokenPath" | "accessTokenPath" -): void; +export declare function setCookie(config: TypeNormalisedInput, res: BaseResponse, name: string, value: string, expires: number, pathType: "refreshTokenPath" | "accessTokenPath"): void; +export declare function getAuthModeFromHeader(req: BaseRequest): string | undefined; diff --git a/lib/build/recipe/session/cookieAndHeaders.js b/lib/build/recipe/session/cookieAndHeaders.js index 2cc7b1eb8..f86e11765 100644 --- a/lib/build/recipe/session/cookieAndHeaders.js +++ b/lib/build/recipe/session/cookieAndHeaders.js @@ -1,69 +1,63 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getAuthModeFromHeader = exports.setCookie = exports.setHeader = exports.setToken = exports.getToken = exports.getCORSAllowedHeaders = exports.setFrontTokenInHeaders = exports.setAntiCsrfTokenInHeaders = exports.getAntiCsrfTokenFromHeaders = exports.clearSession = exports.clearSessionFromAllTokenTransferMethods = void 0; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +const constants_1 = require("../../constants"); +const constants_2 = require("./constants"); +const authorizationHeaderKey = "authorization"; const accessTokenCookieKey = "sAccessToken"; +const accessTokenHeaderKey = "st-access-token"; const refreshTokenCookieKey = "sRefreshToken"; -// there are two of them because one is used by the server to check if the user is logged in and the other is checked by the frontend to see if the user is logged in. -const idRefreshTokenCookieKey = "sIdRefreshToken"; -const idRefreshTokenHeaderKey = "id-refresh-token"; +const refreshTokenHeaderKey = "st-refresh-token"; const antiCsrfHeaderKey = "anti-csrf"; -const ridHeaderKey = "rid"; const frontTokenHeaderKey = "front-token"; -/** - * @description clears all the auth cookies from the response - */ -function clearSessionFromCookie(config, res) { - setCookie(config, res, accessTokenCookieKey, "", 0, "accessTokenPath"); - setCookie(config, res, refreshTokenCookieKey, "", 0, "refreshTokenPath"); - setCookie(config, res, idRefreshTokenCookieKey, "", 0, "accessTokenPath"); - res.setHeader(idRefreshTokenHeaderKey, "remove", false); - res.setHeader("Access-Control-Expose-Headers", idRefreshTokenHeaderKey, true); -} -exports.clearSessionFromCookie = clearSessionFromCookie; -/** - * @param expiry: must be time in milliseconds from epoch time. - */ -function attachAccessTokenToCookie(config, res, token, expiry) { - setCookie(config, res, accessTokenCookieKey, token, expiry, "accessTokenPath"); -} -exports.attachAccessTokenToCookie = attachAccessTokenToCookie; -/** - * @param expiry: must be time in milliseconds from epoch time. - */ -function attachRefreshTokenToCookie(config, res, token, expiry) { - setCookie(config, res, refreshTokenCookieKey, token, expiry, "refreshTokenPath"); -} -exports.attachRefreshTokenToCookie = attachRefreshTokenToCookie; -function getAccessTokenFromCookie(req) { - return req.getCookieValue(accessTokenCookieKey); +const authModeHeaderKey = "st-auth-mode"; +function clearSessionFromAllTokenTransferMethods(config, res) { + // We are clearing the session in all transfermethods to be sure to override cookies in case they have been already added to the response. + // This is done to handle the following use-case: + // If the app overrides signInPOST to check the ban status of the user after the original implementation and throwing an UNAUTHORISED error + // In this case: the SDK has attached cookies to the response, but none was sent with the request + // We can't know which to clear since we can't reliably query or remove the set-cookie header added to the response (causes issues in some frameworks, i.e.: hapi) + // The safe solution in this case is to overwrite all the response cookies/headers with an empty value, which is what we are doing here + for (const transferMethod of constants_2.availableTokenTransferMethods) { + clearSession(config, res, transferMethod); + } } -exports.getAccessTokenFromCookie = getAccessTokenFromCookie; -function getRefreshTokenFromCookie(req) { - return req.getCookieValue(refreshTokenCookieKey); +exports.clearSessionFromAllTokenTransferMethods = clearSessionFromAllTokenTransferMethods; +function clearSession(config, res, transferMethod) { + // If we can be specific about which transferMethod we want to clear, there is no reason to clear the other ones + const tokenTypes = ["access", "refresh"]; + for (const token of tokenTypes) { + setToken(config, res, token, "", 0, transferMethod); + } + res.removeHeader(antiCsrfHeaderKey); + // This can be added multiple times in some cases, but that should be OK + res.setHeader(frontTokenHeaderKey, "remove", false); + res.setHeader("Access-Control-Expose-Headers", frontTokenHeaderKey, true); } -exports.getRefreshTokenFromCookie = getRefreshTokenFromCookie; +exports.clearSession = clearSession; function getAntiCsrfTokenFromHeaders(req) { return req.getHeaderValue(antiCsrfHeaderKey); } exports.getAntiCsrfTokenFromHeaders = getAntiCsrfTokenFromHeaders; -function getRidFromHeader(req) { - return req.getHeaderValue(ridHeaderKey); -} -exports.getRidFromHeader = getRidFromHeader; -function getIdRefreshTokenFromCookie(req) { - return req.getCookieValue(idRefreshTokenCookieKey); -} -exports.getIdRefreshTokenFromCookie = getIdRefreshTokenFromCookie; function setAntiCsrfTokenInHeaders(res, antiCsrfToken) { res.setHeader(antiCsrfHeaderKey, antiCsrfToken, false); res.setHeader("Access-Control-Expose-Headers", antiCsrfHeaderKey, true); } exports.setAntiCsrfTokenInHeaders = setAntiCsrfTokenInHeaders; -function setIdRefreshTokenInHeaderAndCookie(config, res, idRefreshToken, expiry) { - res.setHeader(idRefreshTokenHeaderKey, idRefreshToken + ";" + expiry, false); - res.setHeader("Access-Control-Expose-Headers", idRefreshTokenHeaderKey, true); - setCookie(config, res, idRefreshTokenCookieKey, idRefreshToken, expiry, "accessTokenPath"); -} -exports.setIdRefreshTokenInHeaderAndCookie = setIdRefreshTokenInHeaderAndCookie; function setFrontTokenInHeaders(res, userId, atExpiry, accessTokenPayload) { const tokenInfo = { uid: userId, @@ -75,9 +69,59 @@ function setFrontTokenInHeaders(res, userId, atExpiry, accessTokenPayload) { } exports.setFrontTokenInHeaders = setFrontTokenInHeaders; function getCORSAllowedHeaders() { - return [antiCsrfHeaderKey, ridHeaderKey]; + return [antiCsrfHeaderKey, constants_1.HEADER_RID, authorizationHeaderKey, authModeHeaderKey]; } exports.getCORSAllowedHeaders = getCORSAllowedHeaders; +function getCookieNameFromTokenType(tokenType) { + switch (tokenType) { + case "access": + return accessTokenCookieKey; + case "refresh": + return refreshTokenCookieKey; + default: + throw new Error("Unknown token type, should never happen."); + } +} +function getResponseHeaderNameForTokenType(tokenType) { + switch (tokenType) { + case "access": + return accessTokenHeaderKey; + case "refresh": + return refreshTokenHeaderKey; + default: + throw new Error("Unknown token type, should never happen."); + } +} +function getToken(req, tokenType, transferMethod) { + if (transferMethod === "cookie") { + return req.getCookieValue(getCookieNameFromTokenType(tokenType)); + } + else if (transferMethod === "header") { + const value = req.getHeaderValue(authorizationHeaderKey); + if (value === undefined || !value.startsWith("Bearer ")) { + return undefined; + } + return value.replace(/^Bearer /, "").trim(); + } + else { + throw new Error("Should never happen: Unknown transferMethod: " + transferMethod); + } +} +exports.getToken = getToken; +function setToken(config, res, tokenType, value, expires, transferMethod) { + if (transferMethod === "cookie") { + setCookie(config, res, getCookieNameFromTokenType(tokenType), value, expires, tokenType === "refresh" ? "refreshTokenPath" : "accessTokenPath"); + } + else if (transferMethod === "header") { + setHeader(res, getResponseHeaderNameForTokenType(tokenType), value); + } +} +exports.setToken = setToken; +function setHeader(res, name, value) { + res.setHeader(name, value, false); + res.setHeader("Access-Control-Expose-Headers", name, true); +} +exports.setHeader = setHeader; /** * * @param res @@ -96,10 +140,16 @@ function setCookie(config, res, name, value, expires, pathType) { let path = ""; if (pathType === "refreshTokenPath") { path = config.refreshTokenPath.getAsStringDangerous(); - } else if (pathType === "accessTokenPath") { + } + else if (pathType === "accessTokenPath") { path = "/"; } let httpOnly = true; return res.setCookie(name, value, domain, secure, httpOnly, expires, path, sameSite); } exports.setCookie = setCookie; +function getAuthModeFromHeader(req) { + var _a; + return (_a = req.getHeaderValue(authModeHeaderKey)) === null || _a === void 0 ? void 0 : _a.toLowerCase(); +} +exports.getAuthModeFromHeader = getAuthModeFromHeader; diff --git a/lib/build/recipe/session/error.d.ts b/lib/build/recipe/session/error.d.ts index 5aa6bfa7a..6c26bb4a9 100644 --- a/lib/build/recipe/session/error.d.ts +++ b/lib/build/recipe/session/error.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import STError from "../../error"; import { ClaimValidationError } from "./types"; export default class SessionError extends STError { @@ -6,32 +5,26 @@ export default class SessionError extends STError { static TRY_REFRESH_TOKEN: "TRY_REFRESH_TOKEN"; static TOKEN_THEFT_DETECTED: "TOKEN_THEFT_DETECTED"; static INVALID_CLAIMS: "INVALID_CLAIMS"; - constructor( - options: - | { - message: string; - type: "UNAUTHORISED"; - payload?: { - clearCookies: boolean; - }; - } - | { - message: string; - type: "TRY_REFRESH_TOKEN"; - } - | { - message: string; - type: "TOKEN_THEFT_DETECTED"; - payload: { - userId: string; - recipeUserId: string; - sessionHandle: string; - }; - } - | { - message: string; - type: "INVALID_CLAIMS"; - payload: ClaimValidationError[]; - } - ); + constructor(options: { + message: string; + type: "UNAUTHORISED"; + payload?: { + clearTokens: boolean; + }; + } | { + message: string; + type: "TRY_REFRESH_TOKEN"; + } | { + message: string; + type: "TOKEN_THEFT_DETECTED"; + payload: { + userId: string; + recipeUserId: string; + sessionHandle: string; + }; + } | { + message: string; + type: "INVALID_CLAIMS"; + payload: ClaimValidationError[]; + }); } diff --git a/lib/build/recipe/session/error.js b/lib/build/recipe/session/error.js index f5d18639b..d1f0dbeeb 100644 --- a/lib/build/recipe/session/error.js +++ b/lib/build/recipe/session/error.js @@ -17,15 +17,10 @@ Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../../error"); class SessionError extends error_1.default { constructor(options) { - super( - options.type === "UNAUTHORISED" && options.payload === undefined - ? Object.assign(Object.assign({}, options), { - payload: { - clearCookies: true, - }, - }) - : Object.assign({}, options) - ); + super(options.type === "UNAUTHORISED" && options.payload === undefined + ? Object.assign(Object.assign({}, options), { payload: { + clearTokens: true, + } }) : Object.assign({}, options)); this.fromRecipe = "session"; } } diff --git a/lib/build/recipe/session/framework/awsLambda.d.ts b/lib/build/recipe/session/framework/awsLambda.d.ts index 2b5f88975..90ed03730 100644 --- a/lib/build/recipe/session/framework/awsLambda.d.ts +++ b/lib/build/recipe/session/framework/awsLambda.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import type { Handler } from "aws-lambda"; import { VerifySessionOptions } from ".."; export declare function verifySession(handler: Handler, verifySessionOptions?: VerifySessionOptions): Handler; diff --git a/lib/build/recipe/session/framework/awsLambda.js b/lib/build/recipe/session/framework/awsLambda.js index ad6ab8ed3..730104d8e 100644 --- a/lib/build/recipe/session/framework/awsLambda.js +++ b/lib/build/recipe/session/framework/awsLambda.js @@ -1,57 +1,36 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySession = void 0; const framework_1 = require("../../../framework/awsLambda/framework"); const supertokens_1 = require("../../../supertokens"); const recipe_1 = require("../recipe"); function verifySession(handler, verifySessionOptions) { - return (event, context, callback) => - __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new framework_1.AWSRequest(event); - let response = new framework_1.AWSResponse(event); - try { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - event.session = yield sessionRecipe.verifySession(verifySessionOptions, request, response); - let handlerResult = yield handler(event, context, callback); - return response.sendResponse(handlerResult); - } catch (err) { - yield supertokens.errorHandler(err, request, response); - if (response.responseSet) { - return response.sendResponse({}); - } - throw err; + return (event, context, callback) => __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new framework_1.AWSRequest(event); + let response = new framework_1.AWSResponse(event); + try { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + event.session = yield sessionRecipe.verifySession(verifySessionOptions, request, response); + let handlerResult = yield handler(event, context, callback); + return response.sendResponse(handlerResult); + } + catch (err) { + yield supertokens.errorHandler(err, request, response); + if (response.responseSet) { + return response.sendResponse({}); } - }); + throw err; + } + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/express.d.ts b/lib/build/recipe/session/framework/express.d.ts index bcb0bf234..f9242acc5 100644 --- a/lib/build/recipe/session/framework/express.d.ts +++ b/lib/build/recipe/session/framework/express.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import type { VerifySessionOptions } from ".."; import type { SessionRequest } from "../../../framework/express/framework"; import type { NextFunction, Response } from "express"; -export declare function verifySession( - options?: VerifySessionOptions -): (req: SessionRequest, res: Response, next: NextFunction) => Promise; +export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, res: Response, next: NextFunction) => Promise; diff --git a/lib/build/recipe/session/framework/express.js b/lib/build/recipe/session/framework/express.js index 07cd4bdb8..e2bc29f29 100644 --- a/lib/build/recipe/session/framework/express.js +++ b/lib/build/recipe/session/framework/express.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -49,22 +28,23 @@ const recipe_1 = require("../recipe"); const framework_1 = require("../../../framework/express/framework"); const supertokens_1 = require("../../../supertokens"); function verifySession(options) { - return (req, res, next) => - __awaiter(this, void 0, void 0, function* () { - const request = new framework_1.ExpressRequest(req); - const response = new framework_1.ExpressResponse(res); + return (req, res, next) => __awaiter(this, void 0, void 0, function* () { + const request = new framework_1.ExpressRequest(req); + const response = new framework_1.ExpressResponse(res); + try { + const sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + req.session = yield sessionRecipe.verifySession(options, request, response); + next(); + } + catch (err) { try { - const sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - req.session = yield sessionRecipe.verifySession(options, request, response); - next(); - } catch (err) { - try { - const supertokens = supertokens_1.default.getInstanceOrThrowError(); - yield supertokens.errorHandler(err, request, response); - } catch (_a) { - next(err); - } + const supertokens = supertokens_1.default.getInstanceOrThrowError(); + yield supertokens.errorHandler(err, request, response); + } + catch (_a) { + next(err); } - }); + } + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/fastify.d.ts b/lib/build/recipe/session/framework/fastify.d.ts index 6d8e9fe45..4b9b31671 100644 --- a/lib/build/recipe/session/framework/fastify.d.ts +++ b/lib/build/recipe/session/framework/fastify.d.ts @@ -1,17 +1,4 @@ -// @ts-nocheck -/// import { VerifySessionOptions } from ".."; import { SessionRequest } from "../../../framework/fastify/framework"; import { FastifyReply } from "fastify"; -export declare function verifySession( - options?: VerifySessionOptions -): ( - req: SessionRequest, - res: FastifyReply< - import("http").Server, - import("http").IncomingMessage, - import("http").ServerResponse, - import("fastify/types/route").RouteGenericInterface, - unknown - > -) => Promise; +export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, res: FastifyReply) => Promise; diff --git a/lib/build/recipe/session/framework/fastify.js b/lib/build/recipe/session/framework/fastify.js index 1675b9cd1..5e3e190bc 100644 --- a/lib/build/recipe/session/framework/fastify.js +++ b/lib/build/recipe/session/framework/fastify.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -49,18 +28,18 @@ const recipe_1 = require("../recipe"); const framework_1 = require("../../../framework/fastify/framework"); const supertokens_1 = require("../../../supertokens"); function verifySession(options) { - return (req, res) => - __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let request = new framework_1.FastifyRequest(req); - let response = new framework_1.FastifyResponse(res); - try { - req.session = yield sessionRecipe.verifySession(options, request, response); - } catch (err) { - const supertokens = supertokens_1.default.getInstanceOrThrowError(); - yield supertokens.errorHandler(err, request, response); - throw err; - } - }); + return (req, res) => __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let request = new framework_1.FastifyRequest(req); + let response = new framework_1.FastifyResponse(res); + try { + req.session = yield sessionRecipe.verifySession(options, request, response); + } + catch (err) { + const supertokens = supertokens_1.default.getInstanceOrThrowError(); + yield supertokens.errorHandler(err, request, response); + throw err; + } + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/hapi.d.ts b/lib/build/recipe/session/framework/hapi.d.ts index 0181a9012..86a67c0ff 100644 --- a/lib/build/recipe/session/framework/hapi.d.ts +++ b/lib/build/recipe/session/framework/hapi.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import { VerifySessionOptions } from ".."; import { ResponseToolkit } from "@hapi/hapi"; import { SessionRequest } from "../../../framework/hapi/framework"; -export declare function verifySession( - options?: VerifySessionOptions -): (req: SessionRequest, h: ResponseToolkit) => Promise; +export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, h: ResponseToolkit) => Promise; diff --git a/lib/build/recipe/session/framework/hapi.js b/lib/build/recipe/session/framework/hapi.js index 9f2d4ce11..7e468b1e1 100644 --- a/lib/build/recipe/session/framework/hapi.js +++ b/lib/build/recipe/session/framework/hapi.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -48,13 +27,12 @@ Object.defineProperty(exports, "__esModule", { value: true }); const recipe_1 = require("../recipe"); const framework_1 = require("../../../framework/hapi/framework"); function verifySession(options) { - return (req, h) => - __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let request = new framework_1.HapiRequest(req); - let response = new framework_1.HapiResponse(h); - req.session = yield sessionRecipe.verifySession(options, request, response); - return h.continue; - }); + return (req, h) => __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let request = new framework_1.HapiRequest(req); + let response = new framework_1.HapiResponse(h); + req.session = yield sessionRecipe.verifySession(options, request, response); + return h.continue; + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/index.d.ts b/lib/build/recipe/session/framework/index.d.ts index dfba9d1f7..b71f31cb4 100644 --- a/lib/build/recipe/session/framework/index.d.ts +++ b/lib/build/recipe/session/framework/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import * as expressFramework from "./express"; import * as fastifyFramework from "./fastify"; import * as hapiFramework from "./hapi"; diff --git a/lib/build/recipe/session/framework/index.js b/lib/build/recipe/session/framework/index.js index 0f0ccf5cd..41aa6ecd5 100644 --- a/lib/build/recipe/session/framework/index.js +++ b/lib/build/recipe/session/framework/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.awsLambda = exports.koa = exports.loopback = exports.hapi = exports.fastify = exports.express = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/session/framework/koa.d.ts b/lib/build/recipe/session/framework/koa.d.ts index 9e23ae80b..11b54f3b1 100644 --- a/lib/build/recipe/session/framework/koa.d.ts +++ b/lib/build/recipe/session/framework/koa.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import type { VerifySessionOptions } from ".."; import type { Next } from "koa"; import type { SessionContext } from "../../../framework/koa/framework"; -export declare function verifySession( - options?: VerifySessionOptions -): (ctx: SessionContext, next: Next) => Promise; +export declare function verifySession(options?: VerifySessionOptions): (ctx: SessionContext, next: Next) => Promise; diff --git a/lib/build/recipe/session/framework/koa.js b/lib/build/recipe/session/framework/koa.js index e7a5704e8..ba8641727 100644 --- a/lib/build/recipe/session/framework/koa.js +++ b/lib/build/recipe/session/framework/koa.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -48,13 +27,12 @@ Object.defineProperty(exports, "__esModule", { value: true }); const recipe_1 = require("../recipe"); const framework_1 = require("../../../framework/koa/framework"); function verifySession(options) { - return (ctx, next) => - __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let request = new framework_1.KoaRequest(ctx); - let response = new framework_1.KoaResponse(ctx); - ctx.session = yield sessionRecipe.verifySession(options, request, response); - yield next(); - }); + return (ctx, next) => __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let request = new framework_1.KoaRequest(ctx); + let response = new framework_1.KoaResponse(ctx); + ctx.session = yield sessionRecipe.verifySession(options, request, response); + yield next(); + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/loopback.d.ts b/lib/build/recipe/session/framework/loopback.d.ts index ee251753d..32a45a77f 100644 --- a/lib/build/recipe/session/framework/loopback.d.ts +++ b/lib/build/recipe/session/framework/loopback.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { VerifySessionOptions } from ".."; import { InterceptorOrKey } from "@loopback/core"; export declare function verifySession(options?: VerifySessionOptions): InterceptorOrKey; diff --git a/lib/build/recipe/session/framework/loopback.js b/lib/build/recipe/session/framework/loopback.js index 14fa6c6c6..139f65c7a 100644 --- a/lib/build/recipe/session/framework/loopback.js +++ b/lib/build/recipe/session/framework/loopback.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -48,14 +27,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); const recipe_1 = require("../recipe"); const framework_1 = require("../../../framework/loopback/framework"); function verifySession(options) { - return (ctx, next) => - __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let middlewareCtx = yield ctx.get("middleware.http.context"); - let request = new framework_1.LoopbackRequest(middlewareCtx); - let response = new framework_1.LoopbackResponse(middlewareCtx); - middlewareCtx.session = yield sessionRecipe.verifySession(options, request, response); - return yield next(); - }); + return (ctx, next) => __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let middlewareCtx = yield ctx.get("middleware.http.context"); + let request = new framework_1.LoopbackRequest(middlewareCtx); + let response = new framework_1.LoopbackResponse(middlewareCtx); + middlewareCtx.session = yield sessionRecipe.verifySession(options, request, response); + return yield next(); + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/index.d.ts b/lib/build/recipe/session/index.d.ts index 0151800cb..09db79bfa 100644 --- a/lib/build/recipe/session/index.d.ts +++ b/lib/build/recipe/session/index.d.ts @@ -1,63 +1,24 @@ -// @ts-nocheck import SuperTokensError from "./error"; -import { - VerifySessionOptions, - RecipeInterface, - SessionContainerInterface as SessionContainer, - SessionInformation, - APIInterface, - APIOptions, - SessionClaimValidator, - SessionClaim, - ClaimValidationError, -} from "./types"; +import { VerifySessionOptions, RecipeInterface, SessionContainerInterface as SessionContainer, SessionInformation, APIInterface, APIOptions, SessionClaimValidator, SessionClaim, ClaimValidationError } from "./types"; import Recipe from "./recipe"; import { JSONObject } from "../../types"; export default class SessionWrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static createNewSession( - res: any, - userId: string, - recipeUserId?: string, - accessTokenPayload?: any, - sessionData?: any, - userContext?: any - ): Promise; - static validateClaimsForSessionHandle( - sessionHandle: string, - overrideGlobalClaimValidators?: ( - globalClaimValidators: SessionClaimValidator[], - sessionInfo: SessionInformation, - userContext: any - ) => Promise | SessionClaimValidator[], - userContext?: any - ): Promise< - | { - status: "SESSION_DOES_NOT_EXIST_ERROR"; - } - | { - status: "OK"; - invalidClaims: ClaimValidationError[]; - } - >; + static createNewSession(req: any, res: any, userId: string, recipeUserId?: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise; + static validateClaimsForSessionHandle(sessionHandle: string, overrideGlobalClaimValidators?: (globalClaimValidators: SessionClaimValidator[], sessionInfo: SessionInformation, userContext: any) => Promise | SessionClaimValidator[], userContext?: any): Promise<{ + status: "SESSION_DOES_NOT_EXIST_ERROR"; + } | { + status: "OK"; + invalidClaims: ClaimValidationError[]; + }>; static getSession(req: any, res: any): Promise; - static getSession( - req: any, - res: any, - options?: VerifySessionOptions & { - sessionRequired?: true; - }, - userContext?: any - ): Promise; - static getSession( - req: any, - res: any, - options?: VerifySessionOptions & { - sessionRequired: false; - }, - userContext?: any - ): Promise; + static getSession(req: any, res: any, options?: VerifySessionOptions & { + sessionRequired?: true; + }, userContext?: any): Promise; + static getSession(req: any, res: any, options?: VerifySessionOptions & { + sessionRequired: false; + }, userContext?: any): Promise; static getSessionInformation(sessionHandle: string, userContext?: any): Promise; static refreshSession(req: any, res: any, userContext?: any): Promise; static revokeAllSessionsForUser(userId: string, userContext?: any): Promise; @@ -65,85 +26,45 @@ export default class SessionWrapper { static revokeSession(sessionHandle: string, userContext?: any): Promise; static revokeMultipleSessions(sessionHandles: string[], userContext?: any): Promise; static updateSessionData(sessionHandle: string, newSessionData: any, userContext?: any): Promise; - static regenerateAccessToken( - accessToken: string, - newAccessTokenPayload?: any, - userContext?: any - ): Promise< - | { - status: "OK"; - session: { - handle: string; - userId: string; - recipeUserId: string; - userDataInJWT: any; - }; - accessToken?: - | { - token: string; - expiry: number; - createdTime: number; - } - | undefined; - } - | undefined - >; - static updateAccessTokenPayload( - sessionHandle: string, - newAccessTokenPayload: any, - userContext?: any - ): Promise; - static mergeIntoAccessTokenPayload( - sessionHandle: string, - accessTokenPayloadUpdate: JSONObject, - userContext?: any - ): Promise; - static createJWT( - payload?: any, - validitySeconds?: number, - userContext?: any - ): Promise< - | { - status: "OK"; - jwt: string; - } - | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - } - >; - static getJWKS( - userContext?: any - ): Promise<{ + static regenerateAccessToken(accessToken: string, newAccessTokenPayload?: any, userContext?: any): Promise<{ + status: "OK"; + session: { + handle: string; + userId: string; + recipeUserId: string; + userDataInJWT: any; + }; + accessToken?: { + token: string; + expiry: number; + createdTime: number; + } | undefined; + } | undefined>; + static updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, userContext?: any): Promise; + static mergeIntoAccessTokenPayload(sessionHandle: string, accessTokenPayloadUpdate: JSONObject, userContext?: any): Promise; + static createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ + status: "OK"; + jwt: string; + } | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + }>; + static getJWKS(userContext?: any): Promise<{ status: "OK"; keys: import("../jwt").JsonWebKey[]; }>; - static getOpenIdDiscoveryConfiguration( - userContext?: any - ): Promise<{ + static getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ status: "OK"; issuer: string; jwks_uri: string; }>; static fetchAndSetClaim(sessionHandle: string, claim: SessionClaim, userContext?: any): Promise; - static setClaimValue( - sessionHandle: string, - claim: SessionClaim, - value: T, - userContext?: any - ): Promise; - static getClaimValue( - sessionHandle: string, - claim: SessionClaim, - userContext?: any - ): Promise< - | { - status: "SESSION_DOES_NOT_EXIST_ERROR"; - } - | { - status: "OK"; - value: T | undefined; - } - >; + static setClaimValue(sessionHandle: string, claim: SessionClaim, value: T, userContext?: any): Promise; + static getClaimValue(sessionHandle: string, claim: SessionClaim, userContext?: any): Promise<{ + status: "SESSION_DOES_NOT_EXIST_ERROR"; + } | { + status: "OK"; + value: T | undefined; + }>; static removeClaim(sessionHandle: string, claim: SessionClaim, userContext?: any): Promise; } export declare let init: typeof Recipe.init; @@ -167,12 +88,4 @@ export declare let Error: typeof SuperTokensError; export declare let createJWT: typeof SessionWrapper.createJWT; export declare let getJWKS: typeof SessionWrapper.getJWKS; export declare let getOpenIdDiscoveryConfiguration: typeof SessionWrapper.getOpenIdDiscoveryConfiguration; -export type { - VerifySessionOptions, - RecipeInterface, - SessionContainer, - APIInterface, - APIOptions, - SessionInformation, - SessionClaimValidator, -}; +export type { VerifySessionOptions, RecipeInterface, SessionContainer, APIInterface, APIOptions, SessionInformation, SessionClaimValidator, }; diff --git a/lib/build/recipe/session/index.js b/lib/build/recipe/session/index.js index ab0ee4c3d..4d80c94ee 100644 --- a/lib/build/recipe/session/index.js +++ b/lib/build/recipe/session/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getOpenIdDiscoveryConfiguration = exports.getJWKS = exports.createJWT = exports.Error = exports.validateClaimsForSessionHandle = exports.removeClaim = exports.getClaimValue = exports.setClaimValue = exports.fetchAndSetClaim = exports.mergeIntoAccessTokenPayload = exports.updateAccessTokenPayload = exports.updateSessionData = exports.revokeMultipleSessions = exports.revokeSession = exports.getAllSessionHandlesForUser = exports.revokeAllSessionsForUser = exports.refreshSession = exports.getSessionInformation = exports.getSession = exports.createNewSession = exports.init = void 0; const error_1 = require("./error"); const recipe_1 = require("./recipe"); const framework_1 = require("../../framework"); @@ -52,7 +31,7 @@ const supertokens_1 = require("../../supertokens"); const utils_1 = require("./utils"); // For Express class SessionWrapper { - static createNewSession(res, userId, recipeUserId, accessTokenPayload = {}, sessionData = {}, userContext = {}) { + static createNewSession(req, res, userId, recipeUserId, accessTokenPayload = {}, sessionData = {}, userContext = {}) { return __awaiter(this, void 0, void 0, function* () { const claimsAddedByOtherRecipes = recipe_1.default.getInstanceOrThrowError().getClaimsAddedByOtherRecipes(); let finalAccessTokenPayload = accessTokenPayload; @@ -60,10 +39,14 @@ class SessionWrapper { const update = yield claim.build(userId, recipeUserId, userContext); finalAccessTokenPayload = Object.assign(Object.assign({}, finalAccessTokenPayload), update); } + if (!req.wrapperUsed) { + req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest(req); + } if (!res.wrapperUsed) { res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse(res); } return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createNewSession({ + req, res, userId, recipeUserId, @@ -85,19 +68,16 @@ class SessionWrapper { status: "SESSION_DOES_NOT_EXIST_ERROR", }; } - const claimValidatorsAddedByOtherRecipes = recipe_1.default - .getInstanceOrThrowError() - .getClaimValidatorsAddedByOtherRecipes(); + const claimValidatorsAddedByOtherRecipes = recipe_1.default.getInstanceOrThrowError().getClaimValidatorsAddedByOtherRecipes(); const globalClaimValidators = yield recipeImpl.getGlobalClaimValidators({ userId: sessionInfo.userId, recipeUserId: sessionInfo.recipeUserId, claimValidatorsAddedByOtherRecipes, userContext, }); - const claimValidators = - overrideGlobalClaimValidators !== undefined - ? yield overrideGlobalClaimValidators(globalClaimValidators, sessionInfo, userContext) - : globalClaimValidators; + const claimValidators = overrideGlobalClaimValidators !== undefined + ? yield overrideGlobalClaimValidators(globalClaimValidators, sessionInfo, userContext) + : globalClaimValidators; let claimValidationResponse = yield recipeImpl.validateClaims({ userId: sessionInfo.userId, recipeUserId: sessionInfo.recipeUserId, @@ -106,13 +86,11 @@ class SessionWrapper { userContext, }); if (claimValidationResponse.accessTokenPayloadUpdate !== undefined) { - if ( - !(yield recipeImpl.mergeIntoAccessTokenPayload({ - sessionHandle, - accessTokenPayloadUpdate: claimValidationResponse.accessTokenPayloadUpdate, - userContext, - })) - ) { + if (!(yield recipeImpl.mergeIntoAccessTokenPayload({ + sessionHandle, + accessTokenPayloadUpdate: claimValidationResponse.accessTokenPayloadUpdate, + userContext, + }))) { return { status: "SESSION_DOES_NOT_EXIST_ERROR", }; @@ -135,11 +113,7 @@ class SessionWrapper { const recipeInterfaceImpl = recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl; const session = yield recipeInterfaceImpl.getSession({ req, res, options, userContext }); if (session !== undefined) { - const claimValidators = yield utils_1.getRequiredClaimValidators( - session, - options === null || options === void 0 ? void 0 : options.overrideGlobalClaimValidators, - userContext - ); + const claimValidators = yield utils_1.getRequiredClaimValidators(session, options === null || options === void 0 ? void 0 : options.overrideGlobalClaimValidators, userContext); yield session.assertClaims(claimValidators, userContext); } return session; @@ -161,9 +135,7 @@ class SessionWrapper { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.refreshSession({ req, res, userContext }); } static revokeAllSessionsForUser(userId, userContext = {}) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.revokeAllSessionsForUser({ userId, userContext }); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeAllSessionsForUser({ userId, userContext }); } static getAllSessionHandlesForUser(userId, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getAllSessionHandlesForUser({ @@ -172,9 +144,7 @@ class SessionWrapper { }); } static revokeSession(sessionHandle, userContext = {}) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.revokeSession({ sessionHandle, userContext }); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeSession({ sessionHandle, userContext }); } static revokeMultipleSessions(sessionHandles, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeMultipleSessions({ @@ -215,27 +185,21 @@ class SessionWrapper { if (openIdRecipe !== undefined) { return openIdRecipe.recipeImplementation.createJWT({ payload, validitySeconds, userContext }); } - throw new global.Error( - "createJWT cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe" - ); + throw new global.Error("createJWT cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe"); } static getJWKS(userContext = {}) { let openIdRecipe = recipe_1.default.getInstanceOrThrowError().openIdRecipe; if (openIdRecipe !== undefined) { return openIdRecipe.recipeImplementation.getJWKS({ userContext }); } - throw new global.Error( - "getJWKS cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe" - ); + throw new global.Error("getJWKS cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe"); } static getOpenIdDiscoveryConfiguration(userContext = {}) { let openIdRecipe = recipe_1.default.getInstanceOrThrowError().openIdRecipe; if (openIdRecipe !== undefined) { return openIdRecipe.recipeImplementation.getOpenIdDiscoveryConfiguration({ userContext }); } - throw new global.Error( - "getOpenIdDiscoveryConfiguration cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe" - ); + throw new global.Error("getOpenIdDiscoveryConfiguration cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe"); } static fetchAndSetClaim(sessionHandle, claim, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.fetchAndSetClaim({ diff --git a/lib/build/recipe/session/jwt.d.ts b/lib/build/recipe/session/jwt.d.ts index 04e1066e4..e4ab56b66 100644 --- a/lib/build/recipe/session/jwt.d.ts +++ b/lib/build/recipe/session/jwt.d.ts @@ -1,12 +1,9 @@ -// @ts-nocheck -export declare function verifyJWTAndGetPayload( - jwt: string, - jwtSigningPublicKey: string -): { - [key: string]: any; -}; -export declare function getPayloadWithoutVerifiying( - jwt: string -): { - [key: string]: any; +export declare type ParsedJWTInfo = { + rawTokenString: string; + rawPayload: string; + header: string; + payload: any; + signature: string; }; +export declare function parseJWTWithoutSignatureVerification(jwt: string): ParsedJWTInfo; +export declare function verifyJWT({ header, rawPayload, signature }: ParsedJWTInfo, jwtSigningPublicKey: string): void; diff --git a/lib/build/recipe/session/jwt.js b/lib/build/recipe/session/jwt.js index e544545ce..bf21150cd 100644 --- a/lib/build/recipe/session/jwt.js +++ b/lib/build/recipe/session/jwt.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyJWT = exports.parseJWTWithoutSignatureVerification = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -16,22 +17,18 @@ Object.defineProperty(exports, "__esModule", { value: true }); */ const crypto = require("crypto"); const HEADERS = new Set([ - Buffer.from( - JSON.stringify({ - alg: "RS256", - typ: "JWT", - version: "1", - }) - ).toString("base64"), - Buffer.from( - JSON.stringify({ - alg: "RS256", - typ: "JWT", - version: "2", - }) - ).toString("base64"), + Buffer.from(JSON.stringify({ + alg: "RS256", + typ: "JWT", + version: "1", + })).toString("base64"), + Buffer.from(JSON.stringify({ + alg: "RS256", + typ: "JWT", + version: "2", + })).toString("base64"), ]); -function verifyJWTAndGetPayload(jwt, jwtSigningPublicKey) { +function parseJWTWithoutSignatureVerification(jwt) { const splittedInput = jwt.split("."); if (splittedInput.length !== 3) { throw new Error("Invalid JWT"); @@ -40,31 +37,23 @@ function verifyJWTAndGetPayload(jwt, jwtSigningPublicKey) { if (!HEADERS.has(splittedInput[0])) { throw new Error("JWT header mismatch"); } - let payload = splittedInput[1]; + return { + rawTokenString: jwt, + rawPayload: splittedInput[1], + header: splittedInput[0], + // Ideally we would only parse this after the signature verification is done. + // We do this at the start, since we want to check if a token can be a supertokens access token or not + payload: JSON.parse(Buffer.from(splittedInput[1], "base64").toString()), + signature: splittedInput[2], + }; +} +exports.parseJWTWithoutSignatureVerification = parseJWTWithoutSignatureVerification; +function verifyJWT({ header, rawPayload, signature }, jwtSigningPublicKey) { let verifier = crypto.createVerify("sha256"); // convert the jwtSigningPublicKey into .pem format - verifier.update(splittedInput[0] + "." + payload); - if ( - !verifier.verify( - "-----BEGIN PUBLIC KEY-----\n" + jwtSigningPublicKey + "\n-----END PUBLIC KEY-----", - splittedInput[2], - "base64" - ) - ) { + verifier.update(header + "." + rawPayload); + if (!verifier.verify("-----BEGIN PUBLIC KEY-----\n" + jwtSigningPublicKey + "\n-----END PUBLIC KEY-----", signature, "base64")) { throw new Error("JWT verification failed"); } - // sending payload - payload = Buffer.from(payload, "base64").toString(); - return JSON.parse(payload); -} -exports.verifyJWTAndGetPayload = verifyJWTAndGetPayload; -function getPayloadWithoutVerifiying(jwt) { - const splittedInput = jwt.split("."); - if (splittedInput.length !== 3) { - throw new Error("Invalid JWT"); - } - let payload = splittedInput[1]; - payload = Buffer.from(payload, "base64").toString(); - return JSON.parse(payload); } -exports.getPayloadWithoutVerifiying = getPayloadWithoutVerifiying; +exports.verifyJWT = verifyJWT; diff --git a/lib/build/recipe/session/recipe.d.ts b/lib/build/recipe/session/recipe.d.ts index a7d920c95..7970908f7 100644 --- a/lib/build/recipe/session/recipe.d.ts +++ b/lib/build/recipe/session/recipe.d.ts @@ -1,14 +1,5 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; -import { - TypeInput, - TypeNormalisedInput, - RecipeInterface, - APIInterface, - VerifySessionOptions, - SessionClaimValidator, - SessionClaim, -} from "./types"; +import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, VerifySessionOptions, SessionClaimValidator, SessionClaim } from "./types"; import STError from "./error"; import { NormalisedAppinfo, RecipeListFunction, APIHandled, HTTPMethod } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -33,19 +24,9 @@ export default class SessionRecipe extends RecipeModule { addClaimValidatorFromOtherRecipe: (builder: SessionClaimValidator) => void; getClaimValidatorsAddedByOtherRecipes: () => SessionClaimValidator[]; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - path: NormalisedURLPath, - method: HTTPMethod - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; handleError: (err: STError, request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; - verifySession: ( - options: VerifySessionOptions | undefined, - request: BaseRequest, - response: BaseResponse - ) => Promise; + verifySession: (options: VerifySessionOptions | undefined, request: BaseRequest, response: BaseResponse) => Promise; } diff --git a/lib/build/recipe/session/recipe.js b/lib/build/recipe/session/recipe.js index acb94f7b5..b441204c4 100644 --- a/lib/build/recipe/session/recipe.js +++ b/lib/build/recipe/session/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -106,67 +84,64 @@ class SessionRecipe extends recipeModule_1.default { } return apisHandled; }; - this.handleAPIRequest = (id, req, res, path, method) => - __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - }; - if (id === constants_1.REFRESH_API_PATH) { - return yield refresh_1.default(this.apiImpl, options); - } else if (id === constants_1.SIGNOUT_API_PATH) { - return yield signout_1.default(this.apiImpl, options); - } else if (this.openIdRecipe !== undefined) { - return yield this.openIdRecipe.handleAPIRequest(id, req, res, path, method); - } else { - return false; - } - }); - this.handleError = (err, request, response) => - __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === SessionRecipe.RECIPE_ID) { - if (err.type === error_1.default.UNAUTHORISED) { - logger_1.logDebugMessage("errorHandler: returning UNAUTHORISED"); - if ( - err.payload === undefined || - err.payload.clearCookies === undefined || - err.payload.clearCookies === true - ) { - logger_1.logDebugMessage("errorHandler: Clearing cookies because of UNAUTHORISED response"); - cookieAndHeaders_1.clearSessionFromCookie(this.config, response); - } - return yield this.config.errorHandlers.onUnauthorised(err.message, request, response); - } else if (err.type === error_1.default.TRY_REFRESH_TOKEN) { - logger_1.logDebugMessage("errorHandler: returning TRY_REFRESH_TOKEN"); - return yield this.config.errorHandlers.onTryRefreshToken(err.message, request, response); - } else if (err.type === error_1.default.TOKEN_THEFT_DETECTED) { - logger_1.logDebugMessage("errorHandler: returning TOKEN_THEFT_DETECTED"); - logger_1.logDebugMessage( - "errorHandler: Clearing cookies because of TOKEN_THEFT_DETECTED response" - ); - cookieAndHeaders_1.clearSessionFromCookie(this.config, response); - return yield this.config.errorHandlers.onTokenTheftDetected( - err.payload.sessionHandle, - err.payload.userId, - err.payload.recipeUserId, - request, - response - ); - } else if (err.type === error_1.default.INVALID_CLAIMS) { - return yield this.config.errorHandlers.onInvalidClaim(err.payload, request, response); - } else { - throw err; + this.handleAPIRequest = (id, req, res, path, method) => __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + }; + if (id === constants_1.REFRESH_API_PATH) { + return yield refresh_1.default(this.apiImpl, options); + } + else if (id === constants_1.SIGNOUT_API_PATH) { + return yield signout_1.default(this.apiImpl, options); + } + else if (this.openIdRecipe !== undefined) { + return yield this.openIdRecipe.handleAPIRequest(id, req, res, path, method); + } + else { + return false; + } + }); + this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === SessionRecipe.RECIPE_ID) { + if (err.type === error_1.default.UNAUTHORISED) { + logger_1.logDebugMessage("errorHandler: returning UNAUTHORISED"); + if (err.payload === undefined || + err.payload.clearTokens === undefined || + err.payload.clearTokens === true) { + logger_1.logDebugMessage("errorHandler: Clearing tokens because of UNAUTHORISED response"); + cookieAndHeaders_1.clearSessionFromAllTokenTransferMethods(this.config, response); } - } else if (this.openIdRecipe !== undefined) { - return yield this.openIdRecipe.handleError(err, request, response); - } else { + return yield this.config.errorHandlers.onUnauthorised(err.message, request, response); + } + else if (err.type === error_1.default.TRY_REFRESH_TOKEN) { + logger_1.logDebugMessage("errorHandler: returning TRY_REFRESH_TOKEN"); + return yield this.config.errorHandlers.onTryRefreshToken(err.message, request, response); + } + else if (err.type === error_1.default.TOKEN_THEFT_DETECTED) { + logger_1.logDebugMessage("errorHandler: returning TOKEN_THEFT_DETECTED"); + logger_1.logDebugMessage("errorHandler: Clearing tokens because of TOKEN_THEFT_DETECTED response"); + cookieAndHeaders_1.clearSessionFromAllTokenTransferMethods(this.config, response); + return yield this.config.errorHandlers.onTokenTheftDetected(err.payload.sessionHandle, err.payload.userId, err.payload.recipeUserId, request, response); + } + else if (err.type === error_1.default.INVALID_CLAIMS) { + return yield this.config.errorHandlers.onInvalidClaim(err.payload, request, response); + } + else { throw err; } - }); + } + else if (this.openIdRecipe !== undefined) { + return yield this.openIdRecipe.handleError(err, request, response); + } + else { + throw err; + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [...cookieAndHeaders_1.getCORSAllowedHeaders()]; if (this.openIdRecipe !== undefined) { @@ -175,35 +150,30 @@ class SessionRecipe extends recipeModule_1.default { return corsHeaders; }; this.isErrorFromThisRecipe = (err) => { - return ( - error_1.default.isErrorFromSuperTokens(err) && + return (error_1.default.isErrorFromSuperTokens(err) && (err.fromRecipe === SessionRecipe.RECIPE_ID || - (this.openIdRecipe !== undefined && this.openIdRecipe.isErrorFromThisRecipe(err))) - ); + (this.openIdRecipe !== undefined && this.openIdRecipe.isErrorFromThisRecipe(err)))); }; - this.verifySession = (options, request, response) => - __awaiter(this, void 0, void 0, function* () { - return yield this.apiImpl.verifySession({ - verifySessionOptions: options, - options: { - config: this.config, - req: request, - res: response, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - }, - userContext: utils_2.makeDefaultUserContextFromAPI(request), - }); + this.verifySession = (options, request, response) => __awaiter(this, void 0, void 0, function* () { + return yield this.apiImpl.verifySession({ + verifySessionOptions: options, + options: { + config: this.config, + req: request, + res: response, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + }, + userContext: utils_2.makeDefaultUserContextFromAPI(request), }); + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); logger_1.logDebugMessage("session init: antiCsrf: " + this.config.antiCsrf); logger_1.logDebugMessage("session init: cookieDomain: " + this.config.cookieDomain); logger_1.logDebugMessage("session init: cookieSameSite: " + this.config.cookieSameSite); logger_1.logDebugMessage("session init: cookieSecure: " + this.config.cookieSecure); - logger_1.logDebugMessage( - "session init: refreshTokenPath: " + this.config.refreshTokenPath.getAsStringDangerous() - ); + logger_1.logDebugMessage("session init: refreshTokenPath: " + this.config.refreshTokenPath.getAsStringDangerous()); logger_1.logDebugMessage("session init: sessionExpiredStatusCode: " + this.config.sessionExpiredStatusCode); this.isInServerlessEnv = isInServerlessEnv; if (this.config.jwt.enable === true) { @@ -211,33 +181,19 @@ class SessionRecipe extends recipeModule_1.default { issuer: this.config.jwt.issuer, override: this.config.override.openIdFeature, }); - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default( - querier_1.Querier.getNewInstanceOrThrowError(recipeId), - this.config, - () => this.recipeInterfaceImpl - ) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config, this.getAppInfo(), () => this.recipeInterfaceImpl)); this.recipeInterfaceImpl = builder .override((oI) => { - return with_jwt_1.default( - oI, - // this.jwtRecipe is never undefined here - this.openIdRecipe.recipeImplementation, - this.config - ); - }) + return with_jwt_1.default(oI, + // this.jwtRecipe is never undefined here + this.openIdRecipe.recipeImplementation, this.config); + }) .override(this.config.override.functions) .build(); - } else { + } + else { { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default( - querier_1.Querier.getNewInstanceOrThrowError(recipeId), - this.config, - () => this.recipeInterfaceImpl - ) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config, this.getAppInfo(), () => this.recipeInterfaceImpl)); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } } @@ -257,7 +213,8 @@ class SessionRecipe extends recipeModule_1.default { if (SessionRecipe.instance === undefined) { SessionRecipe.instance = new SessionRecipe(SessionRecipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return SessionRecipe.instance; - } else { + } + else { throw new Error("Session recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/session/recipeImplementation.d.ts b/lib/build/recipe/session/recipeImplementation.d.ts index b1bb1480f..bdda2ad96 100644 --- a/lib/build/recipe/session/recipeImplementation.d.ts +++ b/lib/build/recipe/session/recipeImplementation.d.ts @@ -1,19 +1,13 @@ -// @ts-nocheck import { RecipeInterface, TypeNormalisedInput, KeyInfo, AntiCsrfType } from "./types"; import { Querier } from "../../querier"; +import { NormalisedAppinfo } from "../../types"; export declare class HandshakeInfo { antiCsrf: AntiCsrfType; accessTokenBlacklistingEnabled: boolean; accessTokenValidity: number; refreshTokenValidity: number; private rawJwtSigningPublicKeyList; - constructor( - antiCsrf: AntiCsrfType, - accessTokenBlacklistingEnabled: boolean, - accessTokenValidity: number, - refreshTokenValidity: number, - rawJwtSigningPublicKeyList: KeyInfo[] - ); + constructor(antiCsrf: AntiCsrfType, accessTokenBlacklistingEnabled: boolean, accessTokenValidity: number, refreshTokenValidity: number, rawJwtSigningPublicKeyList: KeyInfo[]); setJwtSigningPublicKeyList(updatedList: KeyInfo[]): void; getJwtSigningPublicKeyList(): KeyInfo[]; clone(): HandshakeInfo; @@ -23,10 +17,7 @@ export declare type Helpers = { getHandshakeInfo: (forceRefetch?: boolean) => Promise; updateJwtSigningPublicKeyInfo: (keyList: KeyInfo[] | undefined, publicKey: string, expiryTime: number) => void; config: TypeNormalisedInput; + appInfo: NormalisedAppinfo; getRecipeImpl: () => RecipeInterface; }; -export default function getRecipeInterface( - querier: Querier, - config: TypeNormalisedInput, - getRecipeImplAfterOverrides: () => RecipeInterface -): RecipeInterface; +export default function getRecipeInterface(querier: Querier, config: TypeNormalisedInput, appInfo: NormalisedAppinfo, getRecipeImplAfterOverrides: () => RecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/session/recipeImplementation.js b/lib/build/recipe/session/recipeImplementation.js index c6bf605b6..47b83123e 100644 --- a/lib/build/recipe/session/recipeImplementation.js +++ b/lib/build/recipe/session/recipeImplementation.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.HandshakeInfo = void 0; const SessionFunctions = require("./sessionFunctions"); const cookieAndHeaders_1 = require("./cookieAndHeaders"); const utils_1 = require("./utils"); @@ -40,14 +19,11 @@ const utils_2 = require("../../utils"); const processState_1 = require("../../processState"); const normalisedURLPath_1 = require("../../normalisedURLPath"); const logger_1 = require("../../logger"); +const constants_1 = require("./constants"); +const jwt_1 = require("./jwt"); +const accessToken_1 = require("./accessToken"); class HandshakeInfo { - constructor( - antiCsrf, - accessTokenBlacklistingEnabled, - accessTokenValidity, - refreshTokenValidity, - rawJwtSigningPublicKeyList - ) { + constructor(antiCsrf, accessTokenBlacklistingEnabled, accessTokenValidity, refreshTokenValidity, rawJwtSigningPublicKeyList) { this.antiCsrf = antiCsrf; this.accessTokenBlacklistingEnabled = accessTokenBlacklistingEnabled; this.accessTokenValidity = accessTokenValidity; @@ -61,42 +37,22 @@ class HandshakeInfo { return this.rawJwtSigningPublicKeyList.filter((key) => key.expiryTime > Date.now()); } clone() { - return new HandshakeInfo( - this.antiCsrf, - this.accessTokenBlacklistingEnabled, - this.accessTokenValidity, - this.refreshTokenValidity, - this.rawJwtSigningPublicKeyList - ); + return new HandshakeInfo(this.antiCsrf, this.accessTokenBlacklistingEnabled, this.accessTokenValidity, this.refreshTokenValidity, this.rawJwtSigningPublicKeyList); } } exports.HandshakeInfo = HandshakeInfo; -function getRecipeInterface(querier, config, getRecipeImplAfterOverrides) { +// We are defining this here to reduce the scope of legacy code +const LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME = "sIdRefreshToken"; +function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverrides) { let handshakeInfo; function getHandshakeInfo(forceRefetch = false) { return __awaiter(this, void 0, void 0, function* () { - if ( - handshakeInfo === undefined || - handshakeInfo.getJwtSigningPublicKeyList().length === 0 || - forceRefetch - ) { + if (handshakeInfo === undefined || handshakeInfo.getJwtSigningPublicKeyList().length === 0 || forceRefetch) { let antiCsrf = config.antiCsrf; - processState_1.ProcessState.getInstance().addState( - processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_HANDSHAKE_INFO - ); + processState_1.ProcessState.getInstance().addState(processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_HANDSHAKE_INFO); let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/handshake"), {}); - handshakeInfo = new HandshakeInfo( - antiCsrf, - response.accessTokenBlacklistingEnabled, - response.accessTokenValidity, - response.refreshTokenValidity, - response.jwtSigningPublicKeyList - ); - updateJwtSigningPublicKeyInfo( - response.jwtSigningPublicKeyList, - response.jwtSigningPublicKey, - response.jwtSigningPublicKeyExpiryTime - ); + handshakeInfo = new HandshakeInfo(antiCsrf, response.accessTokenBlacklistingEnabled, response.accessTokenValidity, response.refreshTokenValidity, response.jwtSigningPublicKeyList); + updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); } return handshakeInfo; }); @@ -111,25 +67,34 @@ function getRecipeInterface(querier, config, getRecipeImplAfterOverrides) { } } let obj = { - createNewSession: function ({ res, userId, recipeUserId, accessTokenPayload = {}, sessionData = {} }) { + createNewSession: function ({ req, res, userId, recipeUserId, accessTokenPayload = {}, sessionData = {}, userContext, }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield SessionFunctions.createNewSession( - helpers, - userId, - recipeUserId, - accessTokenPayload, - sessionData - ); - utils_1.attachCreateOrRefreshSessionResponseToExpressRes(config, res, response); - return new sessionClass_1.default( - helpers, - response.accessToken.token, - response.session.handle, - response.session.userId, - response.session.recipeUserId, - response.session.userDataInJWT, - res - ); + logger_1.logDebugMessage("createNewSession: Started"); + let outputTransferMethod = config.getTokenTransferMethod({ req, forCreateNewSession: true, userContext }); + if (outputTransferMethod === "any") { + outputTransferMethod = "header"; + } + logger_1.logDebugMessage("createNewSession: using transfer method " + outputTransferMethod); + if (outputTransferMethod === "cookie" && + helpers.config.cookieSameSite === "none" && + !helpers.config.cookieSecure && + !((helpers.appInfo.topLevelAPIDomain === "localhost" || + utils_2.isAnIpAddress(helpers.appInfo.topLevelAPIDomain)) && + (helpers.appInfo.topLevelWebsiteDomain === "localhost" || + utils_2.isAnIpAddress(helpers.appInfo.topLevelWebsiteDomain)))) { + // We can allow insecure cookie when both website & API domain are localhost or an IP + // When either of them is a different domain, API domain needs to have https and a secure cookie to work + throw new Error("Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false."); + } + const disableAntiCSRF = outputTransferMethod === "header"; + let response = yield SessionFunctions.createNewSession(helpers, userId, disableAntiCSRF, recipeUserId, accessTokenPayload, sessionData); + for (const transferMethod of constants_1.availableTokenTransferMethods) { + if (transferMethod !== outputTransferMethod && cookieAndHeaders_1.getToken(req, "access", transferMethod) !== undefined) { + cookieAndHeaders_1.clearSession(config, res, transferMethod); + } + } + utils_1.attachTokensToResponse(config, res, response, outputTransferMethod); + return new sessionClass_1.default(helpers, response.accessToken.token, response.session.handle, response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, res, req, outputTransferMethod); }); }, getGlobalClaimValidators: function (input) { @@ -137,98 +102,98 @@ function getRecipeInterface(querier, config, getRecipeImplAfterOverrides) { return input.claimValidatorsAddedByOtherRecipes; }); }, - getSession: function ({ req, res, options }) { + /* In all cases if sIdRefreshToken token exists (so it's a legacy session) we return TRY_REFRESH_TOKEN. The refresh endpoint will clear this cookie and try to upgrade the session. + Check https://supertokens.com/docs/contribute/decisions/session/0007 for further details and a table of expected behaviours + */ + getSession: function ({ req, res, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("getSession: Started"); - logger_1.logDebugMessage("getSession: rid in header: " + utils_2.frontendHasInterceptor(req)); - logger_1.logDebugMessage("getSession: request method: " + req.getMethod()); - let doAntiCsrfCheck = options !== undefined ? options.antiCsrfCheck : undefined; - let idRefreshToken = cookieAndHeaders_1.getIdRefreshTokenFromCookie(req); - if (idRefreshToken === undefined) { - // we do not clear cookies here because of a - // race condition mentioned here: https://github.com/supertokens/supertokens-node/issues/17 - if (options !== undefined && typeof options !== "boolean" && options.sessionRequired === false) { - logger_1.logDebugMessage( - "getSession: returning undefined because idRefreshToken is undefined and sessionRequired is false" - ); + // This token isn't handled by getToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + // This could create a spike on refresh calls during the update of the backend SDK + throw new error_1.default({ + message: "using legacy session, please call the refresh API", + type: error_1.default.TRY_REFRESH_TOKEN, + }); + } + const sessionOptional = (options === null || options === void 0 ? void 0 : options.sessionRequired) === false; + logger_1.logDebugMessage("getSession: optional validation: " + sessionOptional); + const accessTokens = {}; + // We check all token transfer methods for available access tokens + for (const transferMethod of constants_1.availableTokenTransferMethods) { + const tokenString = cookieAndHeaders_1.getToken(req, "access", transferMethod); + if (tokenString !== undefined) { + try { + const info = jwt_1.parseJWTWithoutSignatureVerification(tokenString); + accessToken_1.validateAccessTokenStructure(info.payload); + logger_1.logDebugMessage("getSession: got access token from " + transferMethod); + accessTokens[transferMethod] = info; + } + catch (_a) { + logger_1.logDebugMessage(`getSession: ignoring token in ${transferMethod}, because it doesn't match our access token structure`); + } + } + } + const allowedTransferMethod = config.getTokenTransferMethod({ + req, + forCreateNewSession: false, + userContext, + }); + let requestTransferMethod; + let accessToken; + if ((allowedTransferMethod === "any" || allowedTransferMethod === "header") && + accessTokens["header"] !== undefined) { + logger_1.logDebugMessage("getSession: using header transfer method"); + requestTransferMethod = "header"; + accessToken = accessTokens["header"]; + } + else if ((allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && + accessTokens["cookie"] !== undefined) { + logger_1.logDebugMessage("getSession: using cookie transfer method"); + requestTransferMethod = "cookie"; + accessToken = accessTokens["cookie"]; + } + else { + if (sessionOptional) { + logger_1.logDebugMessage("getSession: returning undefined because accessToken is undefined and sessionRequired is false"); // there is no session that exists here, and the user wants session verification // to be optional. So we return undefined. return undefined; } - logger_1.logDebugMessage( - "getSession: UNAUTHORISED because idRefreshToken from cookies is undefined" - ); + logger_1.logDebugMessage("getSession: UNAUTHORISED because accessToken in request is undefined"); throw new error_1.default({ - message: - "Session does not exist. Are you sending the session tokens in the request as cookies?", + message: "Session does not exist. Are you sending the session tokens in the request with the appropriate token transfer method?", type: error_1.default.UNAUTHORISED, payload: { - clearCookies: false, + // we do not clear the session here because of a + // race condition mentioned here: https://github.com/supertokens/supertokens-node/issues/17 + clearTokens: false, }, }); } - let accessToken = cookieAndHeaders_1.getAccessTokenFromCookie(req); - if (accessToken === undefined) { - // maybe the access token has expired. - /** - * Based on issue: #156 (spertokens-node) - * we throw TRY_REFRESH_TOKEN only if - * options.sessionRequired === true || (frontendHasInterceptor or request method is get), - * else we should return undefined - */ - if ( - options === undefined || - (options !== undefined && options.sessionRequired === true) || - utils_2.frontendHasInterceptor(req) || - utils_2.normaliseHttpMethod(req.getMethod()) === "get" - ) { - logger_1.logDebugMessage( - "getSession: Returning try refresh token because access token from cookies is undefined" - ); - throw new error_1.default({ - message: "Access token has expired. Please call the refresh API", - type: error_1.default.TRY_REFRESH_TOKEN, - }); - } - return undefined; - } let antiCsrfToken = cookieAndHeaders_1.getAntiCsrfTokenFromHeaders(req); + let doAntiCsrfCheck = options !== undefined ? options.antiCsrfCheck : undefined; if (doAntiCsrfCheck === undefined) { doAntiCsrfCheck = utils_2.normaliseHttpMethod(req.getMethod()) !== "get"; } + if (requestTransferMethod === "header") { + doAntiCsrfCheck = false; + } logger_1.logDebugMessage("getSession: Value of doAntiCsrfCheck is: " + doAntiCsrfCheck); - let response = yield SessionFunctions.getSession( - helpers, - accessToken, - antiCsrfToken, - doAntiCsrfCheck, - cookieAndHeaders_1.getRidFromHeader(req) !== undefined - ); + let response = yield SessionFunctions.getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, utils_2.getRidFromHeader(req) !== undefined); + let accessTokenString = accessToken.rawTokenString; if (response.accessToken !== undefined) { - cookieAndHeaders_1.setFrontTokenInHeaders( - res, - response.session.userId, - response.accessToken.expiry, - response.session.userDataInJWT - ); - cookieAndHeaders_1.attachAccessTokenToCookie( - config, - res, - response.accessToken.token, - response.accessToken.expiry - ); - accessToken = response.accessToken.token; + cookieAndHeaders_1.setFrontTokenInHeaders(res, response.session.userId, response.accessToken.expiry, response.session.userDataInJWT); + cookieAndHeaders_1.setToken(config, res, "access", response.accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, requestTransferMethod); + accessTokenString = response.accessToken.token; } logger_1.logDebugMessage("getSession: Success!"); - const session = new sessionClass_1.default( - helpers, - accessToken, - response.session.handle, - response.session.userId, - response.session.recipeUserId, - response.session.userDataInJWT, - res - ); + const session = new sessionClass_1.default(helpers, accessTokenString, response.session.handle, response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, res, req, requestTransferMethod); return session; }); }, @@ -238,110 +203,122 @@ function getRecipeInterface(querier, config, getRecipeImplAfterOverrides) { let accessTokenPayloadUpdate = undefined; const origSessionClaimPayloadJSON = JSON.stringify(accessTokenPayload); for (const validator of input.claimValidators) { - logger_1.logDebugMessage( - "updateClaimsInPayloadIfNeeded checking shouldRefetch for " + validator.id - ); - if ( - "claim" in validator && - (yield validator.shouldRefetch(accessTokenPayload, input.userContext)) - ) { + logger_1.logDebugMessage("updateClaimsInPayloadIfNeeded checking shouldRefetch for " + validator.id); + if ("claim" in validator && (yield validator.shouldRefetch(accessTokenPayload, input.userContext))) { logger_1.logDebugMessage("updateClaimsInPayloadIfNeeded refetching " + validator.id); - const value = yield validator.claim.fetchValue( - input.userId, - input.recipeUserId, - input.userContext - ); - logger_1.logDebugMessage( - "updateClaimsInPayloadIfNeeded " + validator.id + " refetch result " + JSON.stringify(value) - ); + const value = yield validator.claim.fetchValue(input.userId, input.recipeUserId, input.userContext); + logger_1.logDebugMessage("updateClaimsInPayloadIfNeeded " + validator.id + " refetch result " + JSON.stringify(value)); if (value !== undefined) { - accessTokenPayload = validator.claim.addToPayload_internal( - accessTokenPayload, - value, - input.userContext - ); + accessTokenPayload = validator.claim.addToPayload_internal(accessTokenPayload, value, input.userContext); } } } if (JSON.stringify(accessTokenPayload) !== origSessionClaimPayloadJSON) { accessTokenPayloadUpdate = accessTokenPayload; } - const invalidClaims = yield utils_1.validateClaimsInPayload( - input.claimValidators, - accessTokenPayload, - input.userContext - ); + const invalidClaims = yield utils_1.validateClaimsInPayload(input.claimValidators, accessTokenPayload, input.userContext); return { invalidClaims, accessTokenPayloadUpdate, }; }); }, - getSessionInformation: function ({ sessionHandle }) { + getSessionInformation: function ({ sessionHandle, }) { return __awaiter(this, void 0, void 0, function* () { return SessionFunctions.getSessionInformation(helpers, sessionHandle); }); }, - refreshSession: function ({ req, res }) { + /* + In all cases: if sIdRefreshToken token exists (so it's a legacy session) we clear it. + Check http://localhost:3002/docs/contribute/decisions/session/0008 for further details and a table of expected behaviours + */ + refreshSession: function ({ req, res, userContext }) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("refreshSession: Started"); - let inputIdRefreshToken = cookieAndHeaders_1.getIdRefreshTokenFromCookie(req); - if (inputIdRefreshToken === undefined) { - logger_1.logDebugMessage( - "refreshSession: UNAUTHORISED because idRefreshToken from cookies is undefined" - ); - // we do not clear cookies here because of a - // race condition mentioned here: https://github.com/supertokens/supertokens-node/issues/17 - throw new error_1.default({ - message: - "Session does not exist. Are you sending the session tokens in the request as cookies?", - type: error_1.default.UNAUTHORISED, - }); + const refreshTokens = {}; + // We check all token transfer methods for available refresh tokens + // We do this so that we can later clear all we are not overwriting + for (const transferMethod of constants_1.availableTokenTransferMethods) { + refreshTokens[transferMethod] = cookieAndHeaders_1.getToken(req, "refresh", transferMethod); + if (refreshTokens[transferMethod] !== undefined) { + logger_1.logDebugMessage("refreshSession: got refresh token from " + transferMethod); + } + } + const allowedTransferMethod = config.getTokenTransferMethod({ + req, + forCreateNewSession: false, + userContext, + }); + logger_1.logDebugMessage("refreshSession: getTokenTransferMethod returned " + allowedTransferMethod); + let requestTransferMethod; + let refreshToken; + if ((allowedTransferMethod === "any" || allowedTransferMethod === "header") && + refreshTokens["header"] !== undefined) { + logger_1.logDebugMessage("refreshSession: using header transfer method"); + requestTransferMethod = "header"; + refreshToken = refreshTokens["header"]; } - let inputRefreshToken = cookieAndHeaders_1.getRefreshTokenFromCookie(req); - if (inputRefreshToken === undefined) { - logger_1.logDebugMessage( - "refreshSession: UNAUTHORISED because refresh token from cookies is undefined" - ); + else if ((allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && + refreshTokens["cookie"]) { + logger_1.logDebugMessage("refreshSession: using cookie transfer method"); + requestTransferMethod = "cookie"; + refreshToken = refreshTokens["cookie"]; + } + else { + // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + logger_1.logDebugMessage("refreshSession: cleared legacy id refresh token because refresh token was not found"); + cookieAndHeaders_1.setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + } + logger_1.logDebugMessage("refreshSession: UNAUTHORISED because refresh token in request is undefined"); throw new error_1.default({ - message: - "Refresh token not found. Are you sending the refresh token in the request as a cookie?", + message: "Refresh token not found. Are you sending the refresh token in the request?", + payload: { + clearTokens: false, + }, type: error_1.default.UNAUTHORISED, }); } - let antiCsrfToken = cookieAndHeaders_1.getAntiCsrfTokenFromHeaders(req); - let response = yield SessionFunctions.refreshSession( - helpers, - inputRefreshToken, - antiCsrfToken, - cookieAndHeaders_1.getRidFromHeader(req) !== undefined - ); - utils_1.attachCreateOrRefreshSessionResponseToExpressRes(config, res, response); - logger_1.logDebugMessage("refreshSession: Success!"); - return new sessionClass_1.default( - helpers, - response.accessToken.token, - response.session.handle, - response.session.userId, - response.session.recipeUserId, - response.session.userDataInJWT, - res - ); + try { + let antiCsrfToken = cookieAndHeaders_1.getAntiCsrfTokenFromHeaders(req); + let response = yield SessionFunctions.refreshSession(helpers, refreshToken, antiCsrfToken, utils_2.getRidFromHeader(req) !== undefined, requestTransferMethod); + logger_1.logDebugMessage("refreshSession: Attaching refreshed session info as " + requestTransferMethod); + // We clear the tokens in all token transfer methods we are not going to overwrite + for (const transferMethod of constants_1.availableTokenTransferMethods) { + if (transferMethod !== requestTransferMethod && refreshTokens[transferMethod] !== undefined) { + cookieAndHeaders_1.clearSession(config, res, transferMethod); + } + } + utils_1.attachTokensToResponse(config, res, response, requestTransferMethod); + logger_1.logDebugMessage("refreshSession: Success!"); + // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + logger_1.logDebugMessage("refreshSession: cleared legacy id refresh token after successful refresh"); + cookieAndHeaders_1.setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + } + return new sessionClass_1.default(helpers, response.accessToken.token, response.session.handle, response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, res, req, requestTransferMethod); + } + catch (err) { + if (err.type === error_1.default.TOKEN_THEFT_DETECTED || err.payload.clearTokens) { + // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + logger_1.logDebugMessage("refreshSession: cleared legacy id refresh token because refresh is clearing other tokens"); + cookieAndHeaders_1.setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + } + } + throw err; + } }); }, regenerateAccessToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - let newAccessTokenPayload = - input.newAccessTokenPayload === null || input.newAccessTokenPayload === undefined - ? {} - : input.newAccessTokenPayload; - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/session/regenerate"), - { - accessToken: input.accessToken, - userDataInJWT: newAccessTokenPayload, - } - ); + let newAccessTokenPayload = input.newAccessTokenPayload === null || input.newAccessTokenPayload === undefined + ? {} + : input.newAccessTokenPayload; + let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/regenerate"), { + accessToken: input.accessToken, + userDataInJWT: newAccessTokenPayload, + }); if (response.status === "UNAUTHORISED") { return undefined; } @@ -360,22 +337,19 @@ function getRecipeInterface(querier, config, getRecipeImplAfterOverrides) { revokeMultipleSessions: function ({ sessionHandles }) { return SessionFunctions.revokeMultipleSessions(helpers, sessionHandles); }, - updateSessionData: function ({ sessionHandle, newSessionData }) { + updateSessionData: function ({ sessionHandle, newSessionData, }) { return SessionFunctions.updateSessionData(helpers, sessionHandle, newSessionData); }, - updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload }) { + updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, }) { return SessionFunctions.updateAccessTokenPayload(helpers, sessionHandle, newAccessTokenPayload); }, - mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext }) { + mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext, }) { return __awaiter(this, void 0, void 0, function* () { const sessionInfo = yield this.getSessionInformation({ sessionHandle, userContext }); if (sessionInfo === undefined) { return false; } - const newAccessTokenPayload = Object.assign( - Object.assign({}, sessionInfo.accessTokenPayload), - accessTokenPayloadUpdate - ); + const newAccessTokenPayload = Object.assign(Object.assign({}, sessionInfo.accessTokenPayload), accessTokenPayloadUpdate); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete newAccessTokenPayload[key]; @@ -403,11 +377,7 @@ function getRecipeInterface(querier, config, getRecipeImplAfterOverrides) { if (sessionInfo === undefined) { return false; } - const accessTokenPayloadUpdate = yield input.claim.build( - sessionInfo.userId, - sessionInfo.recipeUserId, - input.userContext - ); + const accessTokenPayloadUpdate = yield input.claim.build(sessionInfo.userId, sessionInfo.recipeUserId, input.userContext); return this.mergeIntoAccessTokenPayload({ sessionHandle: input.sessionHandle, accessTokenPayloadUpdate, @@ -454,6 +424,7 @@ function getRecipeInterface(querier, config, getRecipeImplAfterOverrides) { updateJwtSigningPublicKeyInfo, getHandshakeInfo, config, + appInfo, getRecipeImpl: getRecipeImplAfterOverrides, }; if (process.env.TEST_MODE === "testing") { diff --git a/lib/build/recipe/session/sessionClass.d.ts b/lib/build/recipe/session/sessionClass.d.ts index 0a25121ef..5961a31fb 100644 --- a/lib/build/recipe/session/sessionClass.d.ts +++ b/lib/build/recipe/session/sessionClass.d.ts @@ -1,24 +1,17 @@ -// @ts-nocheck -import { BaseResponse } from "../../framework"; -import { SessionClaim, SessionClaimValidator, SessionContainerInterface } from "./types"; +import { BaseRequest, BaseResponse } from "../../framework"; +import { SessionClaim, SessionClaimValidator, SessionContainerInterface, TokenTransferMethod } from "./types"; import { Helpers } from "./recipeImplementation"; export default class Session implements SessionContainerInterface { + protected helpers: Helpers; + protected accessToken: string; protected sessionHandle: string; protected userId: string; + protected recipeUserId: string; protected userDataInAccessToken: any; protected res: BaseResponse; - protected accessToken: string; - protected helpers: Helpers; - protected recipeUserId: string; - constructor( - helpers: Helpers, - accessToken: string, - sessionHandle: string, - userId: string, - recipeUserId: string, - userDataInAccessToken: any, - res: BaseResponse - ); + protected readonly req: BaseRequest; + protected readonly transferMethod: TokenTransferMethod; + constructor(helpers: Helpers, accessToken: string, sessionHandle: string, userId: string, recipeUserId: string, userDataInAccessToken: any, res: BaseResponse, req: BaseRequest, transferMethod: TokenTransferMethod); getRecipeUserId(_userContext?: any): string; revokeSession(userContext?: any): Promise; getSessionData(userContext?: any): Promise; diff --git a/lib/build/recipe/session/sessionClass.js b/lib/build/recipe/session/sessionClass.js index 257a43594..2fe2d8a02 100644 --- a/lib/build/recipe/session/sessionClass.js +++ b/lib/build/recipe/session/sessionClass.js @@ -1,47 +1,27 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const cookieAndHeaders_1 = require("./cookieAndHeaders"); const error_1 = require("./error"); class Session { - constructor(helpers, accessToken, sessionHandle, userId, recipeUserId, userDataInAccessToken, res) { + constructor(helpers, accessToken, sessionHandle, userId, recipeUserId, userDataInAccessToken, res, req, transferMethod) { + this.helpers = helpers; + this.accessToken = accessToken; this.sessionHandle = sessionHandle; this.userId = userId; + this.recipeUserId = recipeUserId; this.userDataInAccessToken = userDataInAccessToken; this.res = res; - this.accessToken = accessToken; - this.helpers = helpers; - this.recipeUserId = recipeUserId; + this.req = req; + this.transferMethod = transferMethod; } getRecipeUserId(_userContext) { return this.recipeUserId; @@ -58,7 +38,7 @@ class Session { // If we instead clear the cookies only when revokeSession // returns true, it can cause this kind of a bug: // https://github.com/supertokens/supertokens-node/issues/343 - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + cookieAndHeaders_1.clearSession(this.helpers.config, this.res, this.transferMethod); }); } getSessionData(userContext) { @@ -78,13 +58,11 @@ class Session { } updateSessionData(newSessionData, userContext) { return __awaiter(this, void 0, void 0, function* () { - if ( - !(yield this.helpers.getRecipeImpl().updateSessionData({ - sessionHandle: this.sessionHandle, - newSessionData, - userContext: userContext === undefined ? {} : userContext, - })) - ) { + if (!(yield this.helpers.getRecipeImpl().updateSessionData({ + sessionHandle: this.sessionHandle, + newSessionData, + userContext: userContext === undefined ? {} : userContext, + }))) { throw new error_1.default({ message: "Session does not exist anymore", type: error_1.default.UNAUTHORISED, @@ -107,10 +85,7 @@ class Session { // Any update to this function should also be reflected in the respective JWT version mergeIntoAccessTokenPayload(accessTokenPayloadUpdate, userContext) { return __awaiter(this, void 0, void 0, function* () { - const updatedPayload = Object.assign( - Object.assign({}, this.getAccessTokenPayload(userContext)), - accessTokenPayloadUpdate - ); + const updatedPayload = Object.assign(Object.assign({}, this.getAccessTokenPayload(userContext)), accessTokenPayloadUpdate); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete updatedPayload[key]; @@ -174,11 +149,7 @@ class Session { // Any update to this function should also be reflected in the respective JWT version fetchAndSetClaim(claim, userContext) { return __awaiter(this, void 0, void 0, function* () { - const update = yield claim.build( - this.getUserId(userContext), - this.getRecipeUserId(userContext), - userContext - ); + const update = yield claim.build(this.getUserId(userContext), this.getRecipeUserId(userContext), userContext); return this.mergeIntoAccessTokenPayload(update, userContext); }); } @@ -217,18 +188,13 @@ class Session { this.userDataInAccessToken = response.session.userDataInJWT; if (response.accessToken !== undefined) { this.accessToken = response.accessToken.token; - cookieAndHeaders_1.setFrontTokenInHeaders( - this.res, - response.session.userId, - response.accessToken.expiry, - response.session.userDataInJWT - ); - cookieAndHeaders_1.attachAccessTokenToCookie( - this.helpers.config, - this.res, - response.accessToken.token, - response.accessToken.expiry - ); + cookieAndHeaders_1.setFrontTokenInHeaders(this.res, response.session.userId, response.accessToken.expiry, response.session.userDataInJWT); + cookieAndHeaders_1.setToken(this.helpers.config, this.res, "access", response.accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, this.transferMethod); } }); } diff --git a/lib/build/recipe/session/sessionFunctions.d.ts b/lib/build/recipe/session/sessionFunctions.d.ts index 67716ec7d..25363ed0d 100644 --- a/lib/build/recipe/session/sessionFunctions.d.ts +++ b/lib/build/recipe/session/sessionFunctions.d.ts @@ -1,26 +1,14 @@ -// @ts-nocheck -import { CreateOrRefreshAPIResponse, SessionInformation } from "./types"; +import { ParsedJWTInfo } from "./jwt"; +import { CreateOrRefreshAPIResponse, SessionInformation, TokenTransferMethod } from "./types"; import { Helpers } from "./recipeImplementation"; /** * @description call this to "login" a user. */ -export declare function createNewSession( - helpers: Helpers, - userId: string, - recipeUserId?: string, - accessTokenPayload?: any, - sessionData?: any -): Promise; +export declare function createNewSession(helpers: Helpers, userId: string, disableAntiCsrf: boolean, recipeUserId?: string, accessTokenPayload?: any, sessionData?: any): Promise; /** * @description authenticates a session. To be used in APIs that require authentication */ -export declare function getSession( - helpers: Helpers, - accessToken: string, - antiCsrfToken: string | undefined, - doAntiCsrfCheck: boolean, - containsCustomHeader: boolean -): Promise<{ +export declare function getSession(helpers: Helpers, parsedAccessToken: ParsedJWTInfo, antiCsrfToken: string | undefined, doAntiCsrfCheck: boolean, containsCustomHeader: boolean): Promise<{ session: { handle: string; userId: string; @@ -37,20 +25,12 @@ export declare function getSession( * @description Retrieves session information from storage for a given session handle * @returns session data stored in the database, including userData and access token payload, or undefined if sessionHandle is invalid */ -export declare function getSessionInformation( - helpers: Helpers, - sessionHandle: string -): Promise; +export declare function getSessionInformation(helpers: Helpers, sessionHandle: string): Promise; /** * @description generates new access and refresh tokens for a given refresh token. Called when client's access token has expired. * @sideEffects calls onTokenTheftDetection if token theft is detected. */ -export declare function refreshSession( - helpers: Helpers, - refreshToken: string, - antiCsrfToken: string | undefined, - containsCustomHeader: boolean -): Promise; +export declare function refreshSession(helpers: Helpers, refreshToken: string, antiCsrfToken: string | undefined, containsCustomHeader: boolean, transferMethod: TokenTransferMethod): Promise; /** * @description deletes session info of a user from db. This only invalidates the refresh token. Not the access token. * Access tokens cannot be immediately invalidated. Unless we add a blacklisting method. Or changed the private key to sign them. @@ -73,13 +53,5 @@ export declare function revokeMultipleSessions(helpers: Helpers, sessionHandles: /** * @description: It provides no locking mechanism in case other processes are updating session data for this session as well. */ -export declare function updateSessionData( - helpers: Helpers, - sessionHandle: string, - newSessionData: any -): Promise; -export declare function updateAccessTokenPayload( - helpers: Helpers, - sessionHandle: string, - newAccessTokenPayload: any -): Promise; +export declare function updateSessionData(helpers: Helpers, sessionHandle: string, newSessionData: any): Promise; +export declare function updateAccessTokenPayload(helpers: Helpers, sessionHandle: string, newAccessTokenPayload: any): Promise; diff --git a/lib/build/recipe/session/sessionFunctions.js b/lib/build/recipe/session/sessionFunctions.js index 58a390da6..de8e545e2 100644 --- a/lib/build/recipe/session/sessionFunctions.js +++ b/lib/build/recipe/session/sessionFunctions.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.updateAccessTokenPayload = exports.updateSessionData = exports.revokeMultipleSessions = exports.revokeSession = exports.getAllSessionHandlesForUser = exports.revokeAllSessionsForUser = exports.refreshSession = exports.getSessionInformation = exports.getSession = exports.createNewSession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -46,7 +25,6 @@ Object.defineProperty(exports, "__esModule", { value: true }); * under the License. */ const accessToken_1 = require("./accessToken"); -const jwt_1 = require("./jwt"); const error_1 = require("./error"); const processState_1 = require("../../processState"); const normalisedURLPath_1 = require("../../normalisedURLPath"); @@ -55,7 +33,7 @@ const logger_1 = require("../../logger"); /** * @description call this to "login" a user. */ -function createNewSession(helpers, userId, recipeUserId, accessTokenPayload = {}, sessionData = {}) { +function createNewSession(helpers, userId, disableAntiCsrf, recipeUserId, accessTokenPayload = {}, sessionData = {}) { return __awaiter(this, void 0, void 0, function* () { accessTokenPayload = accessTokenPayload === null || accessTokenPayload === undefined ? {} : accessTokenPayload; sessionData = sessionData === null || sessionData === undefined ? {} : sessionData; @@ -66,16 +44,9 @@ function createNewSession(helpers, userId, recipeUserId, accessTokenPayload = {} userDataInDatabase: sessionData, }; let handShakeInfo = yield helpers.getHandshakeInfo(); - requestBody.enableAntiCsrf = handShakeInfo.antiCsrf === "VIA_TOKEN"; - let response = yield helpers.querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/session"), - requestBody - ); - helpers.updateJwtSigningPublicKeyInfo( - response.jwtSigningPublicKeyList, - response.jwtSigningPublicKey, - response.jwtSigningPublicKeyExpiryTime - ); + requestBody.enableAntiCsrf = !disableAntiCsrf && handShakeInfo.antiCsrf === "VIA_TOKEN"; + let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session"), requestBody); + helpers.updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); delete response.status; delete response.jwtSigningPublicKey; delete response.jwtSigningPublicKeyExpiryTime; @@ -87,7 +58,7 @@ exports.createNewSession = createNewSession; /** * @description authenticates a session. To be used in APIs that require authentication */ -function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, containsCustomHeader) { +function getSession(helpers, parsedAccessToken, antiCsrfToken, doAntiCsrfCheck, containsCustomHeader) { return __awaiter(this, void 0, void 0, function* () { let handShakeInfo = yield helpers.getHandshakeInfo(); let accessTokenInfo; @@ -98,13 +69,10 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai /** * get access token info using existing signingKey */ - accessTokenInfo = yield accessToken_1.getInfoFromAccessToken( - accessToken, - key.publicKey, - handShakeInfo.antiCsrf === "VIA_TOKEN" && doAntiCsrfCheck - ); + accessTokenInfo = yield accessToken_1.getInfoFromAccessToken(parsedAccessToken, key.publicKey, handShakeInfo.antiCsrf === "VIA_TOKEN" && doAntiCsrfCheck); foundASigningKeyThatIsOlderThanTheAccessToken = true; - } catch (err) { + } + catch (err) { /** * if error type is not TRY_REFRESH_TOKEN, we return the * error to the user @@ -130,15 +98,7 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai * so if foundASigningKeyThatIsOlderThanTheAccessToken is still false after * the loop we just return TRY_REFRESH_TOKEN */ - let payload; - try { - payload = jwt_1.getPayloadWithoutVerifiying(accessToken); - } catch (_) { - throw err; - } - if (payload === undefined) { - throw err; - } + let payload = parsedAccessToken.payload; const timeCreated = accessToken_1.sanitizeNumberInput(payload.timeCreated); const expiryTime = accessToken_1.sanitizeNumberInput(payload.expiryTime); if (expiryTime === undefined || expiryTime < Date.now()) { @@ -174,18 +134,14 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai if (accessTokenInfo !== undefined) { if (antiCsrfToken === undefined || antiCsrfToken !== accessTokenInfo.antiCsrfToken) { if (antiCsrfToken === undefined) { - logger_1.logDebugMessage( - "getSession: Returning TRY_REFRESH_TOKEN because antiCsrfToken is missing from request" - ); + logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because antiCsrfToken is missing from request"); throw new error_1.default({ - message: - "Provided antiCsrfToken is undefined. If you do not want anti-csrf check for this API, please set doAntiCsrfCheck to false for this API", + message: "Provided antiCsrfToken is undefined. If you do not want anti-csrf check for this API, please set doAntiCsrfCheck to false for this API", type: error_1.default.TRY_REFRESH_TOKEN, }); - } else { - logger_1.logDebugMessage( - "getSession: Returning TRY_REFRESH_TOKEN because the passed antiCsrfToken is not the same as in the access token" - ); + } + else { + logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because the passed antiCsrfToken is not the same as in the access token"); throw new error_1.default({ message: "anti-csrf check failed", type: error_1.default.TRY_REFRESH_TOKEN, @@ -193,24 +149,20 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai } } } - } else if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { + } + else if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { if (!containsCustomHeader) { - logger_1.logDebugMessage( - "getSession: Returning TRY_REFRESH_TOKEN because custom header (rid) was not passed" - ); + logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because custom header (rid) was not passed"); throw new error_1.default({ - message: - "anti-csrf check failed. Please pass 'rid: \"session\"' header in the request, or set doAntiCsrfCheck to false for this API", + message: "anti-csrf check failed. Please pass 'rid: \"session\"' header in the request, or set doAntiCsrfCheck to false for this API", type: error_1.default.TRY_REFRESH_TOKEN, }); } } } - if ( - accessTokenInfo !== undefined && + if (accessTokenInfo !== undefined && !handShakeInfo.accessTokenBlacklistingEnabled && - accessTokenInfo.parentRefreshTokenHash1 === undefined - ) { + accessTokenInfo.parentRefreshTokenHash1 === undefined) { return { session: { handle: accessTokenInfo.sessionHandle, @@ -222,48 +174,38 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai } processState_1.ProcessState.getInstance().addState(processState_1.PROCESS_STATE.CALLING_SERVICE_IN_VERIFY); let requestBody = { - accessToken, + accessToken: parsedAccessToken.rawTokenString, antiCsrfToken, doAntiCsrfCheck, enableAntiCsrf: handShakeInfo.antiCsrf === "VIA_TOKEN", }; - let response = yield helpers.querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/session/verify"), - requestBody - ); + let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/verify"), requestBody); if (response.status === "OK") { - helpers.updateJwtSigningPublicKeyInfo( - response.jwtSigningPublicKeyList, - response.jwtSigningPublicKey, - response.jwtSigningPublicKeyExpiryTime - ); + helpers.updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); delete response.status; delete response.jwtSigningPublicKey; delete response.jwtSigningPublicKeyExpiryTime; delete response.jwtSigningPublicKeyList; return response; - } else if (response.status === "UNAUTHORISED") { + } + else if (response.status === "UNAUTHORISED") { logger_1.logDebugMessage("getSession: Returning UNAUTHORISED because of core response"); throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, }); - } else { - if ( - response.jwtSigningPublicKeyList !== undefined || - (response.jwtSigningPublicKey !== undefined && response.jwtSigningPublicKeyExpiryTime !== undefined) - ) { + } + else { + if (response.jwtSigningPublicKeyList !== undefined || + (response.jwtSigningPublicKey !== undefined && response.jwtSigningPublicKeyExpiryTime !== undefined)) { // after CDI 2.7.1, the API returns the new keys - helpers.updateJwtSigningPublicKeyInfo( - response.jwtSigningPublicKeyList, - response.jwtSigningPublicKey, - response.jwtSigningPublicKeyExpiryTime - ); - } else { + helpers.updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); + } + else { // we force update the signing keys... yield helpers.getHandshakeInfo(true); } - logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because of core response"); + logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because of core response."); throw new error_1.default({ message: response.message, type: error_1.default.TRY_REFRESH_TOKEN, @@ -292,7 +234,8 @@ function getSessionInformation(helpers, sessionHandle) { delete response.userDataInJWT; delete response.userDataInJWT; return response; - } else { + } + else { return undefined; } }); @@ -302,42 +245,39 @@ exports.getSessionInformation = getSessionInformation; * @description generates new access and refresh tokens for a given refresh token. Called when client's access token has expired. * @sideEffects calls onTokenTheftDetection if token theft is detected. */ -function refreshSession(helpers, refreshToken, antiCsrfToken, containsCustomHeader) { +function refreshSession(helpers, refreshToken, antiCsrfToken, containsCustomHeader, transferMethod) { return __awaiter(this, void 0, void 0, function* () { let handShakeInfo = yield helpers.getHandshakeInfo(); let requestBody = { refreshToken, antiCsrfToken, - enableAntiCsrf: handShakeInfo.antiCsrf === "VIA_TOKEN", + enableAntiCsrf: transferMethod === "cookie" && handShakeInfo.antiCsrf === "VIA_TOKEN", }; - if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { + if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER" && transferMethod === "cookie") { if (!containsCustomHeader) { - logger_1.logDebugMessage( - "refreshSession: Returning UNAUTHORISED because custom header (rid) was not passed" - ); + logger_1.logDebugMessage("refreshSession: Returning UNAUTHORISED because custom header (rid) was not passed"); throw new error_1.default({ message: "anti-csrf check failed. Please pass 'rid: \"session\"' header in the request.", type: error_1.default.UNAUTHORISED, payload: { - clearCookies: false, + clearTokens: false, // see https://github.com/supertokens/supertokens-node/issues/141 }, }); } } - let response = yield helpers.querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/session/refresh"), - requestBody - ); + let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/refresh"), requestBody); if (response.status === "OK") { delete response.status; return response; - } else if (response.status === "UNAUTHORISED") { + } + else if (response.status === "UNAUTHORISED") { logger_1.logDebugMessage("refreshSession: Returning UNAUTHORISED because of core response"); throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, }); - } else { + } + else { logger_1.logDebugMessage("refreshSession: Returning TOKEN_THEFT_DETECTED because of core response"); throw new error_1.default({ message: "Token theft detected", @@ -358,12 +298,9 @@ exports.refreshSession = refreshSession; */ function revokeAllSessionsForUser(helpers, userId) { return __awaiter(this, void 0, void 0, function* () { - let response = yield helpers.querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/session/remove"), - { - userId, - } - ); + let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/remove"), { + userId, + }); return response.sessionHandlesRevoked; }); } @@ -386,12 +323,9 @@ exports.getAllSessionHandlesForUser = getAllSessionHandlesForUser; */ function revokeSession(helpers, sessionHandle) { return __awaiter(this, void 0, void 0, function* () { - let response = yield helpers.querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/session/remove"), - { - sessionHandles: [sessionHandle], - } - ); + let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/remove"), { + sessionHandles: [sessionHandle], + }); return response.sessionHandlesRevoked.length === 1; }); } @@ -402,12 +336,9 @@ exports.revokeSession = revokeSession; */ function revokeMultipleSessions(helpers, sessionHandles) { return __awaiter(this, void 0, void 0, function* () { - let response = yield helpers.querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/session/remove"), - { - sessionHandles, - } - ); + let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/remove"), { + sessionHandles, + }); return response.sessionHandlesRevoked; }); } diff --git a/lib/build/recipe/session/types.d.ts b/lib/build/recipe/session/types.d.ts index c2facbce4..f26f541bd 100644 --- a/lib/build/recipe/session/types.d.ts +++ b/lib/build/recipe/session/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import NormalisedURLPath from "../../normalisedURLPath"; import { RecipeInterface as JWTRecipeInterface, APIInterface as JWTAPIInterface } from "../jwt/types"; @@ -17,16 +16,13 @@ export declare type StoredHandshakeInfo = { accessTokenBlacklistingEnabled: boolean; accessTokenValidity: number; refreshTokenValidity: number; -} & ( - | { - jwtSigningPublicKeyList: KeyInfo[]; - } - | { - jwtSigningPublicKeyList: undefined; - jwtSigningPublicKey: string; - jwtSigningPublicKeyExpiryTime: number; - } -); +} & ({ + jwtSigningPublicKeyList: KeyInfo[]; +} | { + jwtSigningPublicKeyList: undefined; + jwtSigningPublicKey: string; + jwtSigningPublicKeyExpiryTime: number; +}); export declare type CreateOrRefreshAPIResponse = { session: { handle: string; @@ -44,11 +40,6 @@ export declare type CreateOrRefreshAPIResponse = { expiry: number; createdTime: number; }; - idRefreshToken: { - token: string; - expiry: number; - createdTime: number; - }; antiCsrfToken: string | undefined; }; export interface ErrorHandlers { @@ -56,47 +47,37 @@ export interface ErrorHandlers { onTokenTheftDetected?: TokenTheftErrorHandlerMiddleware; onInvalidClaim?: InvalidClaimErrorHandlerMiddleware; } +export declare type TokenType = "access" | "refresh"; +export declare type TokenTransferMethod = "header" | "cookie"; export declare type TypeInput = { + sessionExpiredStatusCode?: number; + invalidClaimStatusCode?: number; cookieSecure?: boolean; cookieSameSite?: "strict" | "lax" | "none"; - sessionExpiredStatusCode?: number; cookieDomain?: string; + getTokenTransferMethod?: (input: { + req: BaseRequest; + forCreateNewSession: boolean; + userContext: any; + }) => TokenTransferMethod | "any"; errorHandlers?: ErrorHandlers; antiCsrf?: "VIA_TOKEN" | "VIA_CUSTOM_HEADER" | "NONE"; - invalidClaimStatusCode?: number; - jwt?: - | { - enable: true; - propertyNameInAccessTokenPayload?: string; - issuer?: string; - } - | { - enable: false; - }; + jwt?: { + enable: true; + propertyNameInAccessTokenPayload?: string; + issuer?: string; + } | { + enable: false; + }; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; openIdFeature?: { - functions?: ( - originalImplementation: OpenIdRecipeInterface, - builder?: OverrideableBuilder - ) => OpenIdRecipeInterface; - apis?: ( - originalImplementation: OpenIdAPIInterface, - builder?: OverrideableBuilder - ) => OpenIdAPIInterface; + functions?: (originalImplementation: OpenIdRecipeInterface, builder?: OverrideableBuilder) => OpenIdRecipeInterface; + apis?: (originalImplementation: OpenIdAPIInterface, builder?: OverrideableBuilder) => OpenIdAPIInterface; jwtFeature?: { - functions?: ( - originalImplementation: JWTRecipeInterface, - builder?: OverrideableBuilder - ) => JWTRecipeInterface; - apis?: ( - originalImplementation: JWTAPIInterface, - builder?: OverrideableBuilder - ) => JWTAPIInterface; + functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; + apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; }; }; }; @@ -109,6 +90,11 @@ export declare type TypeNormalisedInput = { sessionExpiredStatusCode: number; errorHandlers: NormalisedErrorHandlers; antiCsrf: "VIA_TOKEN" | "VIA_CUSTOM_HEADER" | "NONE"; + getTokenTransferMethod: (input: { + req: BaseRequest; + forCreateNewSession: boolean; + userContext: any; + }) => TokenTransferMethod | "any"; invalidClaimStatusCode: number; jwt: { enable: boolean; @@ -116,29 +102,14 @@ export declare type TypeNormalisedInput = { issuer?: string; }; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; openIdFeature?: { - functions?: ( - originalImplementation: OpenIdRecipeInterface, - builder?: OverrideableBuilder - ) => OpenIdRecipeInterface; - apis?: ( - originalImplementation: OpenIdAPIInterface, - builder?: OverrideableBuilder - ) => OpenIdAPIInterface; + functions?: (originalImplementation: OpenIdRecipeInterface, builder?: OverrideableBuilder) => OpenIdRecipeInterface; + apis?: (originalImplementation: OpenIdAPIInterface, builder?: OverrideableBuilder) => OpenIdAPIInterface; jwtFeature?: { - functions?: ( - originalImplementation: JWTRecipeInterface, - builder?: OverrideableBuilder - ) => JWTRecipeInterface; - apis?: ( - originalImplementation: JWTAPIInterface, - builder?: OverrideableBuilder - ) => JWTAPIInterface; + functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; + apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; }; }; }; @@ -150,13 +121,7 @@ export interface ErrorHandlerMiddleware { (message: string, request: BaseRequest, response: BaseResponse): Promise; } export interface TokenTheftErrorHandlerMiddleware { - ( - sessionHandle: string, - userId: string, - recipeUserId: string, - request: BaseRequest, - response: BaseResponse - ): Promise; + (sessionHandle: string, userId: string, recipeUserId: string, request: BaseRequest, response: BaseResponse): Promise; } export interface InvalidClaimErrorHandlerMiddleware { (validatorErrors: ClaimValidationError[], request: BaseRequest, response: BaseResponse): Promise; @@ -170,14 +135,11 @@ export interface NormalisedErrorHandlers { export interface VerifySessionOptions { antiCsrfCheck?: boolean; sessionRequired?: boolean; - overrideGlobalClaimValidators?: ( - globalClaimValidators: SessionClaimValidator[], - session: SessionContainerInterface, - userContext: any - ) => Promise | SessionClaimValidator[]; + overrideGlobalClaimValidators?: (globalClaimValidators: SessionClaimValidator[], session: SessionContainerInterface, userContext: any) => Promise | SessionClaimValidator[]; } export declare type RecipeInterface = { createNewSession(input: { + req: BaseRequest; res: BaseResponse; userId: string; recipeUserId?: string; @@ -209,12 +171,31 @@ export declare type RecipeInterface = { * * Returns undefined if the sessionHandle does not exist */ - getSessionInformation(input: { sessionHandle: string; userContext: any }): Promise; - revokeAllSessionsForUser(input: { userId: string; userContext: any }): Promise; - getAllSessionHandlesForUser(input: { userId: string; userContext: any }): Promise; - revokeSession(input: { sessionHandle: string; userContext: any }): Promise; - revokeMultipleSessions(input: { sessionHandles: string[]; userContext: any }): Promise; - updateSessionData(input: { sessionHandle: string; newSessionData: any; userContext: any }): Promise; + getSessionInformation(input: { + sessionHandle: string; + userContext: any; + }): Promise; + revokeAllSessionsForUser(input: { + userId: string; + userContext: any; + }): Promise; + getAllSessionHandlesForUser(input: { + userId: string; + userContext: any; + }): Promise; + revokeSession(input: { + sessionHandle: string; + userContext: any; + }): Promise; + revokeMultipleSessions(input: { + sessionHandles: string[]; + userContext: any; + }): Promise; + updateSessionData(input: { + sessionHandle: string; + newSessionData: any; + userContext: any; + }): Promise; /** * @deprecated Use mergeIntoAccessTokenPayload instead * @returns {Promise} Returns false if the sessionHandle does not exist @@ -236,25 +217,26 @@ export declare type RecipeInterface = { accessToken: string; newAccessTokenPayload?: any; userContext: any; - }): Promise< - | { - status: "OK"; - session: { - handle: string; - userId: string; - recipeUserId: string; - userDataInJWT: any; - }; - accessToken?: { - token: string; - expiry: number; - createdTime: number; - }; - } - | undefined - >; - getAccessTokenLifeTimeMS(input: { userContext: any }): Promise; - getRefreshTokenLifeTimeMS(input: { userContext: any }): Promise; + }): Promise<{ + status: "OK"; + session: { + handle: string; + userId: string; + recipeUserId: string; + userDataInJWT: any; + }; + accessToken?: { + token: string; + expiry: number; + createdTime: number; + }; + } | undefined>; + getAccessTokenLifeTimeMS(input: { + userContext: any; + }): Promise; + getRefreshTokenLifeTimeMS(input: { + userContext: any; + }): Promise; validateClaims(input: { userId: string; recipeUserId: string; @@ -265,7 +247,11 @@ export declare type RecipeInterface = { invalidClaims: ClaimValidationError[]; accessTokenPayloadUpdate?: any; }>; - fetchAndSetClaim(input: { sessionHandle: string; claim: SessionClaim; userContext: any }): Promise; + fetchAndSetClaim(input: { + sessionHandle: string; + claim: SessionClaim; + userContext: any; + }): Promise; setClaimValue(input: { sessionHandle: string; claim: SessionClaim; @@ -276,16 +262,17 @@ export declare type RecipeInterface = { sessionHandle: string; claim: SessionClaim; userContext: any; - }): Promise< - | { - status: "SESSION_DOES_NOT_EXIST_ERROR"; - } - | { - status: "OK"; - value: T | undefined; - } - >; - removeClaim(input: { sessionHandle: string; claim: SessionClaim; userContext: any }): Promise; + }): Promise<{ + status: "SESSION_DOES_NOT_EXIST_ERROR"; + } | { + status: "OK"; + value: T | undefined; + }>; + removeClaim(input: { + sessionHandle: string; + claim: SessionClaim; + userContext: any; + }): Promise; }; export interface SessionContainerInterface { revokeSession(userContext?: any): Promise; @@ -323,19 +310,17 @@ export declare type APIInterface = { * since it's not something that is directly called by the user on the * frontend anyway */ - refreshPOST: undefined | ((input: { options: APIOptions; userContext: any }) => Promise); - signOutPOST: - | undefined - | ((input: { - options: APIOptions; - session: SessionContainerInterface | undefined; - userContext: any; - }) => Promise< - | { - status: "OK"; - } - | GeneralErrorResponse - >); + refreshPOST: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise); + signOutPOST: undefined | ((input: { + options: APIOptions; + session: SessionContainerInterface | undefined; + userContext: any; + }) => Promise<{ + status: "OK"; + } | GeneralErrorResponse>); verifySession(input: { verifySessionOptions: VerifySessionOptions | undefined; options: APIOptions; @@ -351,30 +336,25 @@ export declare type SessionInformation = { accessTokenPayload: any; timeCreated: number; }; -export declare type ClaimValidationResult = - | { - isValid: true; - } - | { - isValid: false; - reason?: JSONValue; - }; +export declare type ClaimValidationResult = { + isValid: true; +} | { + isValid: false; + reason?: JSONValue; +}; export declare type ClaimValidationError = { id: string; reason?: JSONValue; }; -export declare type SessionClaimValidator = ( - | // We split the type like this to express that either both claim and shouldRefetch is defined or neither. - { - claim: SessionClaim; - /** - * Decides if we need to refetch the claim value before checking the payload with `isValid`. - * E.g.: if the information in the payload is expired, or is not sufficient for this check. - */ - shouldRefetch: (payload: any, userContext: any) => Promise | boolean; - } - | {} -) & { +export declare type SessionClaimValidator = (// We split the type like this to express that either both claim and shouldRefetch is defined or neither. +{ + claim: SessionClaim; + /** + * Decides if we need to refetch the claim value before checking the payload with `isValid`. + * E.g.: if the information in the payload is expired, or is not sufficient for this check. + */ + shouldRefetch: (payload: any, userContext: any) => Promise | boolean; +} | {}) & { id: string; /** * Decides if the claim is valid based on the payload (and not checking DB or anything else) diff --git a/lib/build/recipe/session/types.js b/lib/build/recipe/session/types.js index 1616509fd..1e23a6a70 100644 --- a/lib/build/recipe/session/types.js +++ b/lib/build/recipe/session/types.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.SessionClaim = void 0; class SessionClaim { constructor(key) { this.key = key; diff --git a/lib/build/recipe/session/utils.d.ts b/lib/build/recipe/session/utils.d.ts index 4084d12f5..0bdb57d95 100644 --- a/lib/build/recipe/session/utils.d.ts +++ b/lib/build/recipe/session/utils.d.ts @@ -1,68 +1,18 @@ -// @ts-nocheck -import { - CreateOrRefreshAPIResponse, - TypeInput, - TypeNormalisedInput, - ClaimValidationError, - SessionClaimValidator, - SessionContainerInterface, - VerifySessionOptions, -} from "./types"; +import { CreateOrRefreshAPIResponse, TypeInput, TypeNormalisedInput, ClaimValidationError, SessionClaimValidator, SessionContainerInterface, VerifySessionOptions, TokenTransferMethod } from "./types"; import SessionRecipe from "./recipe"; import { NormalisedAppinfo } from "../../types"; import { BaseRequest, BaseResponse } from "../../framework"; -export declare function sendTryRefreshTokenResponse( - recipeInstance: SessionRecipe, - _: string, - __: BaseRequest, - response: BaseResponse -): Promise; -export declare function sendUnauthorisedResponse( - recipeInstance: SessionRecipe, - _: string, - __: BaseRequest, - response: BaseResponse -): Promise; -export declare function sendInvalidClaimResponse( - recipeInstance: SessionRecipe, - claimValidationErrors: ClaimValidationError[], - __: BaseRequest, - response: BaseResponse -): Promise; -export declare function sendTokenTheftDetectedResponse( - recipeInstance: SessionRecipe, - sessionHandle: string, - _: string, - __: string, - ___: BaseRequest, - response: BaseResponse -): Promise; +export declare function sendTryRefreshTokenResponse(recipeInstance: SessionRecipe, _: string, __: BaseRequest, response: BaseResponse): Promise; +export declare function sendUnauthorisedResponse(recipeInstance: SessionRecipe, _: string, __: BaseRequest, response: BaseResponse): Promise; +export declare function sendInvalidClaimResponse(recipeInstance: SessionRecipe, claimValidationErrors: ClaimValidationError[], __: BaseRequest, response: BaseResponse): Promise; +export declare function sendTokenTheftDetectedResponse(recipeInstance: SessionRecipe, sessionHandle: string, _: string, __: string, ___: BaseRequest, response: BaseResponse): Promise; export declare function normaliseSessionScopeOrThrowError(sessionScope: string): string; -export declare function getTopLevelDomainForSameSiteResolution(url: string): string; export declare function getURLProtocol(url: string): string; -export declare function validateAndNormaliseUserInput( - recipeInstance: SessionRecipe, - appInfo: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(recipeInstance: SessionRecipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; export declare function normaliseSameSiteOrThrowError(sameSite: string): "strict" | "lax" | "none"; -export declare function attachCreateOrRefreshSessionResponseToExpressRes( - config: TypeNormalisedInput, - res: BaseResponse, - response: CreateOrRefreshAPIResponse -): void; -export declare function getRequiredClaimValidators( - session: SessionContainerInterface, - overrideGlobalClaimValidators: VerifySessionOptions["overrideGlobalClaimValidators"], - userContext: any -): Promise; -export declare function validateClaimsInPayload( - claimValidators: SessionClaimValidator[], - newAccessTokenPayload: any, - userContext: any -): Promise< - { - id: string; - reason: import("../../types").JSONValue; - }[] ->; +export declare function attachTokensToResponse(config: TypeNormalisedInput, res: BaseResponse, response: CreateOrRefreshAPIResponse, transferMethod: TokenTransferMethod): void; +export declare function getRequiredClaimValidators(session: SessionContainerInterface, overrideGlobalClaimValidators: VerifySessionOptions["overrideGlobalClaimValidators"], userContext: any): Promise; +export declare function validateClaimsInPayload(claimValidators: SessionClaimValidator[], newAccessTokenPayload: any, userContext: any): Promise<{ + id: string; + reason: import("../../types").JSONValue; +}[]>; diff --git a/lib/build/recipe/session/utils.js b/lib/build/recipe/session/utils.js index f12f8ebcd..19dab7caf 100644 --- a/lib/build/recipe/session/utils.js +++ b/lib/build/recipe/session/utils.js @@ -13,55 +13,29 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateClaimsInPayload = exports.getRequiredClaimValidators = exports.attachTokensToResponse = exports.normaliseSameSiteOrThrowError = exports.validateAndNormaliseUserInput = exports.getURLProtocol = exports.normaliseSessionScopeOrThrowError = exports.sendTokenTheftDetectedResponse = exports.sendInvalidClaimResponse = exports.sendUnauthorisedResponse = exports.sendTryRefreshTokenResponse = void 0; const cookieAndHeaders_1 = require("./cookieAndHeaders"); const url_1 = require("url"); const recipe_1 = require("./recipe"); const constants_1 = require("./constants"); const normalisedURLPath_1 = require("../../normalisedURLPath"); -const psl = require("psl"); const utils_1 = require("../../utils"); const utils_2 = require("../../utils"); const constants_2 = require("./with-jwt/constants"); const logger_1 = require("../../logger"); function sendTryRefreshTokenResponse(recipeInstance, _, __, response) { return __awaiter(this, void 0, void 0, function* () { - utils_2.sendNon200ResponseWithMessage( - response, - "try refresh token", - recipeInstance.config.sessionExpiredStatusCode - ); + utils_2.sendNon200ResponseWithMessage(response, "try refresh token", recipeInstance.config.sessionExpiredStatusCode); }); } exports.sendTryRefreshTokenResponse = sendTryRefreshTokenResponse; @@ -83,11 +57,7 @@ exports.sendInvalidClaimResponse = sendInvalidClaimResponse; function sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, _, __, ___, response) { return __awaiter(this, void 0, void 0, function* () { yield recipeInstance.recipeInterfaceImpl.revokeSession({ sessionHandle, userContext: {} }); - utils_2.sendNon200ResponseWithMessage( - response, - "token theft detected", - recipeInstance.config.sessionExpiredStatusCode - ); + utils_2.sendNon200ResponseWithMessage(response, "token theft detected", recipeInstance.config.sessionExpiredStatusCode); }); } exports.sendTokenTheftDetectedResponse = sendTokenTheftDetectedResponse; @@ -109,7 +79,8 @@ function normaliseSessionScopeOrThrowError(sessionScope) { sessionScope = sessionScope.substr(1); } return sessionScope; - } catch (err) { + } + catch (err) { throw new Error("Please provide a valid sessionScope"); } } @@ -123,20 +94,6 @@ function normaliseSessionScopeOrThrowError(sessionScope) { return noDotNormalised; } exports.normaliseSessionScopeOrThrowError = normaliseSessionScopeOrThrowError; -function getTopLevelDomainForSameSiteResolution(url) { - let urlObj = new url_1.URL(url); - let hostname = urlObj.hostname; - if (hostname.startsWith("localhost") || hostname.startsWith("localhost.org") || utils_1.isAnIpAddress(hostname)) { - // we treat these as the same TLDs since we can use sameSite lax for all of them. - return "localhost"; - } - let parsedURL = psl.parse(hostname); - if (parsedURL.domain === null) { - throw new Error("Please make sure that the apiDomain and websiteDomain have correct values"); - } - return parsedURL.domain; -} -exports.getTopLevelDomainForSameSiteResolution = getTopLevelDomainForSameSiteResolution; function getURLProtocol(url) { let urlObj = new url_1.URL(url); return urlObj.protocol; @@ -144,30 +101,23 @@ function getURLProtocol(url) { exports.getURLProtocol = getURLProtocol; function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { var _a; - let cookieDomain = - config === undefined || config.cookieDomain === undefined - ? undefined - : normaliseSessionScopeOrThrowError(config.cookieDomain); - let topLevelAPIDomain = getTopLevelDomainForSameSiteResolution(appInfo.apiDomain.getAsStringDangerous()); - let topLevelWebsiteDomain = getTopLevelDomainForSameSiteResolution(appInfo.websiteDomain.getAsStringDangerous()); + let cookieDomain = config === undefined || config.cookieDomain === undefined + ? undefined + : normaliseSessionScopeOrThrowError(config.cookieDomain); let protocolOfAPIDomain = getURLProtocol(appInfo.apiDomain.getAsStringDangerous()); let protocolOfWebsiteDomain = getURLProtocol(appInfo.websiteDomain.getAsStringDangerous()); - let cookieSameSite = - topLevelAPIDomain !== topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain ? "none" : "lax"; + let cookieSameSite = appInfo.topLevelAPIDomain !== appInfo.topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain + ? "none" + : "lax"; cookieSameSite = config === undefined || config.cookieSameSite === undefined ? cookieSameSite : normaliseSameSiteOrThrowError(config.cookieSameSite); - let cookieSecure = - config === undefined || config.cookieSecure === undefined - ? appInfo.apiDomain.getAsStringDangerous().startsWith("https") - : config.cookieSecure; - let sessionExpiredStatusCode = - config === undefined || config.sessionExpiredStatusCode === undefined ? 401 : config.sessionExpiredStatusCode; - const invalidClaimStatusCode = - (_a = config === null || config === void 0 ? void 0 : config.invalidClaimStatusCode) !== null && _a !== void 0 - ? _a - : 403; + let cookieSecure = config === undefined || config.cookieSecure === undefined + ? appInfo.apiDomain.getAsStringDangerous().startsWith("https") + : config.cookieSecure; + let sessionExpiredStatusCode = config === undefined || config.sessionExpiredStatusCode === undefined ? 401 : config.sessionExpiredStatusCode; + const invalidClaimStatusCode = (_a = config === null || config === void 0 ? void 0 : config.invalidClaimStatusCode) !== null && _a !== void 0 ? _a : 403; if (sessionExpiredStatusCode === invalidClaimStatusCode) { throw new Error("sessionExpiredStatusCode and sessionExpiredStatusCode must be different"); } @@ -176,32 +126,21 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { throw new Error("antiCsrf config must be one of 'NONE' or 'VIA_CUSTOM_HEADER' or 'VIA_TOKEN'"); } } - let antiCsrf = - config === undefined || config.antiCsrf === undefined - ? cookieSameSite === "none" - ? "VIA_CUSTOM_HEADER" - : "NONE" - : config.antiCsrf; + let antiCsrf = config === undefined || config.antiCsrf === undefined + ? cookieSameSite === "none" + ? "VIA_CUSTOM_HEADER" + : "NONE" + : config.antiCsrf; let errorHandlers = { - onTokenTheftDetected: (sessionHandle, userId, recipeUserId, request, response) => - __awaiter(this, void 0, void 0, function* () { - return yield sendTokenTheftDetectedResponse( - recipeInstance, - sessionHandle, - userId, - recipeUserId, - request, - response - ); - }), - onTryRefreshToken: (message, request, response) => - __awaiter(this, void 0, void 0, function* () { - return yield sendTryRefreshTokenResponse(recipeInstance, message, request, response); - }), - onUnauthorised: (message, request, response) => - __awaiter(this, void 0, void 0, function* () { - return yield sendUnauthorisedResponse(recipeInstance, message, request, response); - }), + onTokenTheftDetected: (sessionHandle, userId, recipeUserId, request, response) => __awaiter(this, void 0, void 0, function* () { + return yield sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, userId, recipeUserId, request, response); + }), + onTryRefreshToken: (message, request, response) => __awaiter(this, void 0, void 0, function* () { + return yield sendTryRefreshTokenResponse(recipeInstance, message, request, response); + }), + onUnauthorised: (message, request, response) => __awaiter(this, void 0, void 0, function* () { + return yield sendUnauthorisedResponse(recipeInstance, message, request, response); + }), onInvalidClaim: (validationErrors, request, response) => { return sendInvalidClaimResponse(recipeInstance, validationErrors, request, response); }, @@ -217,20 +156,6 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { errorHandlers.onInvalidClaim = config.errorHandlers.onInvalidClaim; } } - if ( - cookieSameSite === "none" && - !cookieSecure && - !( - (topLevelAPIDomain === "localhost" || utils_1.isAnIpAddress(topLevelAPIDomain)) && - (topLevelWebsiteDomain === "localhost" || utils_1.isAnIpAddress(topLevelWebsiteDomain)) - ) - ) { - // We can allow insecure cookie when both website & API domain are localhost or an IP - // When either of them is a different domain, API domain needs to have https and a secure cookie to work - throw new Error( - "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." - ); - } let enableJWT = false; let accessTokenPayloadJWTPropertyName = "jwt"; let issuer; @@ -245,15 +170,12 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { accessTokenPayloadJWTPropertyName = jwtPropertyName; } } - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); return { refreshTokenPath: appInfo.apiBasePath.appendPath(new normalisedURLPath_1.default(constants_1.REFRESH_API_PATH)), + getTokenTransferMethod: (config === null || config === void 0 ? void 0 : config.getTokenTransferMethod) === undefined + ? defaultGetTokenTransferMethod + : config.getTokenTransferMethod, cookieDomain, cookieSameSite, cookieSecure, @@ -279,37 +201,31 @@ function normaliseSameSiteOrThrowError(sameSite) { return sameSite; } exports.normaliseSameSiteOrThrowError = normaliseSameSiteOrThrowError; -function attachCreateOrRefreshSessionResponseToExpressRes(config, res, response) { +function attachTokensToResponse(config, res, response, transferMethod) { let accessToken = response.accessToken; let refreshToken = response.refreshToken; - let idRefreshToken = response.idRefreshToken; - cookieAndHeaders_1.setFrontTokenInHeaders( - res, - response.session.userId, - response.accessToken.expiry, - response.session.userDataInJWT - ); - cookieAndHeaders_1.attachAccessTokenToCookie(config, res, accessToken.token, accessToken.expiry); - cookieAndHeaders_1.attachRefreshTokenToCookie(config, res, refreshToken.token, refreshToken.expiry); - cookieAndHeaders_1.setIdRefreshTokenInHeaderAndCookie(config, res, idRefreshToken.token, idRefreshToken.expiry); + cookieAndHeaders_1.setFrontTokenInHeaders(res, response.session.userId, response.accessToken.expiry, response.session.userDataInJWT); + cookieAndHeaders_1.setToken(config, res, "access", accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, transferMethod); + cookieAndHeaders_1.setToken(config, res, "refresh", refreshToken.token, refreshToken.expiry, transferMethod); if (response.antiCsrfToken !== undefined) { cookieAndHeaders_1.setAntiCsrfTokenInHeaders(res, response.antiCsrfToken); } } -exports.attachCreateOrRefreshSessionResponseToExpressRes = attachCreateOrRefreshSessionResponseToExpressRes; +exports.attachTokensToResponse = attachTokensToResponse; function getRequiredClaimValidators(session, overrideGlobalClaimValidators, userContext) { return __awaiter(this, void 0, void 0, function* () { - const claimValidatorsAddedByOtherRecipes = recipe_1.default - .getInstanceOrThrowError() - .getClaimValidatorsAddedByOtherRecipes(); - const globalClaimValidators = yield recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getGlobalClaimValidators({ - userId: session.getUserId(), - recipeUserId: session.getRecipeUserId(), - claimValidatorsAddedByOtherRecipes, - userContext, - }); + const claimValidatorsAddedByOtherRecipes = recipe_1.default.getInstanceOrThrowError().getClaimValidatorsAddedByOtherRecipes(); + const globalClaimValidators = yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getGlobalClaimValidators({ + userId: session.getUserId(), + recipeUserId: session.getRecipeUserId(), + claimValidatorsAddedByOtherRecipes, + userContext, + }); return overrideGlobalClaimValidators !== undefined ? yield overrideGlobalClaimValidators(globalClaimValidators, session, userContext) : globalClaimValidators; @@ -321,9 +237,7 @@ function validateClaimsInPayload(claimValidators, newAccessTokenPayload, userCon const validationErrors = []; for (const validator of claimValidators) { const claimValidationResult = yield validator.validate(newAccessTokenPayload, userContext); - logger_1.logDebugMessage( - "validateClaimsInPayload " + validator.id + " validation res " + JSON.stringify(claimValidationResult) - ); + logger_1.logDebugMessage("validateClaimsInPayload " + validator.id + " validation res " + JSON.stringify(claimValidationResult)); if (!claimValidationResult.isValid) { validationErrors.push({ id: validator.id, @@ -335,3 +249,18 @@ function validateClaimsInPayload(claimValidators, newAccessTokenPayload, userCon }); } exports.validateClaimsInPayload = validateClaimsInPayload; +function defaultGetTokenTransferMethod({ req, forCreateNewSession, }) { + // We allow fallback (checking headers then cookies) by default when validating + if (!forCreateNewSession) { + return "any"; + } + // In create new session we respect the frontend preference by default + switch (cookieAndHeaders_1.getAuthModeFromHeader(req)) { + case "header": + return "header"; + case "cookie": + return "cookie"; + default: + return "any"; + } +} diff --git a/lib/build/recipe/session/with-jwt/constants.d.ts b/lib/build/recipe/session/with-jwt/constants.d.ts index 324030f7b..5260dd27a 100644 --- a/lib/build/recipe/session/with-jwt/constants.d.ts +++ b/lib/build/recipe/session/with-jwt/constants.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck export declare const ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY = "_jwtPName"; export declare const JWT_RESERVED_KEY_USE_ERROR_MESSAGE: string; diff --git a/lib/build/recipe/session/with-jwt/constants.js b/lib/build/recipe/session/with-jwt/constants.js index 4822ad3e4..b3a616064 100644 --- a/lib/build/recipe/session/with-jwt/constants.js +++ b/lib/build/recipe/session/with-jwt/constants.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.JWT_RESERVED_KEY_USE_ERROR_MESSAGE = exports.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/session/with-jwt/index.d.ts b/lib/build/recipe/session/with-jwt/index.d.ts index f8ccc90af..3e972865f 100644 --- a/lib/build/recipe/session/with-jwt/index.d.ts +++ b/lib/build/recipe/session/with-jwt/index.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import OriginalImplementation from "./recipeImplementation"; export default OriginalImplementation; diff --git a/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts b/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts index debe5ce4b..17547f84f 100644 --- a/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts +++ b/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts @@ -1,10 +1,5 @@ -// @ts-nocheck import { RecipeInterface } from "../"; import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; import { TypeNormalisedInput } from "../types"; export declare function setJWTExpiryOffsetSecondsForTesting(offset: number): void; -export default function ( - originalImplementation: RecipeInterface, - openIdRecipeImplementation: OpenIdRecipeInterface, - config: TypeNormalisedInput -): RecipeInterface; +export default function (originalImplementation: RecipeInterface, openIdRecipeImplementation: OpenIdRecipeInterface, config: TypeNormalisedInput): RecipeInterface; diff --git a/lib/build/recipe/session/with-jwt/recipeImplementation.js b/lib/build/recipe/session/with-jwt/recipeImplementation.js index b276fcd0e..8ddf0b678 100644 --- a/lib/build/recipe/session/with-jwt/recipeImplementation.js +++ b/lib/build/recipe/session/with-jwt/recipeImplementation.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.setJWTExpiryOffsetSecondsForTesting = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -80,7 +59,7 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { let currentTimeInSeconds = Date.now() / 1000; let decodedPayload = JsonWebToken.decode(existingJwt, { json: true }); // JsonWebToken.decode possibly returns null - if (decodedPayload === null) { + if (decodedPayload === null || decodedPayload.exp === undefined) { throw new Error("Error reading JWT from session"); } let jwtExpiry = decodedPayload.exp - currentTimeInSeconds; @@ -107,14 +86,11 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { }); }); } - return Object.assign(Object.assign({}, originalImplementation), { - createNewSession: function ({ res, userId, recipeUserId, accessTokenPayload, sessionData, userContext }) { + return Object.assign(Object.assign({}, originalImplementation), { createNewSession: function ({ req, res, userId, recipeUserId, accessTokenPayload, sessionData, userContext, }) { return __awaiter(this, void 0, void 0, function* () { accessTokenPayload = accessTokenPayload === null || accessTokenPayload === undefined ? {} : accessTokenPayload; - let accessTokenValidityInSeconds = Math.ceil( - (yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000 - ); + let accessTokenValidityInSeconds = Math.ceil((yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000); accessTokenPayload = yield utils_1.addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry: getJWTExpiry(accessTokenValidityInSeconds), @@ -124,6 +100,7 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { userContext, }); let sessionContainer = yield originalImplementation.createNewSession({ + req, res, userId, recipeUserId, @@ -133,8 +110,7 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { }); return new sessionClass_1.default(sessionContainer, openIdRecipeImplementation); }); - }, - getSession: function ({ req, res, options, userContext }) { + }, getSession: function ({ req, res, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let sessionContainer = yield originalImplementation.getSession({ req, res, options, userContext }); if (sessionContainer === undefined) { @@ -142,12 +118,9 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { } return new sessionClass_1.default(sessionContainer, openIdRecipeImplementation); }); - }, - refreshSession: function ({ req, res, userContext }) { + }, refreshSession: function ({ req, res, userContext, }) { return __awaiter(this, void 0, void 0, function* () { - let accessTokenValidityInSeconds = Math.ceil( - (yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000 - ); + let accessTokenValidityInSeconds = Math.ceil((yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000); // Refresh session first because this will create a new access token let newSession = yield originalImplementation.refreshSession({ req, res, userContext }); let accessTokenPayload = newSession.getAccessTokenPayload(); @@ -162,17 +135,13 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { yield newSession.updateAccessTokenPayload(accessTokenPayload); return new sessionClass_1.default(newSession, openIdRecipeImplementation); }); - }, - mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext }) { + }, mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let sessionInformation = yield this.getSessionInformation({ sessionHandle, userContext }); if (!sessionInformation) { return false; } - let newAccessTokenPayload = Object.assign( - Object.assign({}, sessionInformation.accessTokenPayload), - accessTokenPayloadUpdate - ); + let newAccessTokenPayload = Object.assign(Object.assign({}, sessionInformation.accessTokenPayload), accessTokenPayloadUpdate); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete newAccessTokenPayload[key]; @@ -180,11 +149,11 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { } return jwtAwareUpdateAccessTokenPayload(sessionInformation, newAccessTokenPayload, userContext); }); - }, + }, /** * @deprecated use mergeIntoAccessTokenPayload instead */ - updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext }) { + updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext, }) { return __awaiter(this, void 0, void 0, function* () { newAccessTokenPayload = newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; @@ -194,7 +163,6 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { } return jwtAwareUpdateAccessTokenPayload(sessionInformation, newAccessTokenPayload, userContext); }); - }, - }); + } }); } exports.default = default_1; diff --git a/lib/build/recipe/session/with-jwt/sessionClass.d.ts b/lib/build/recipe/session/with-jwt/sessionClass.d.ts index a354342c4..3d33f3c4c 100644 --- a/lib/build/recipe/session/with-jwt/sessionClass.d.ts +++ b/lib/build/recipe/session/with-jwt/sessionClass.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; import { SessionClaim, SessionClaimValidator, SessionContainerInterface } from "../types"; export default class SessionClassWithJWT implements SessionContainerInterface { @@ -20,17 +19,9 @@ export default class SessionClassWithJWT implements SessionContainerInterface { setClaimValue(this: SessionClassWithJWT, claim: SessionClaim, value: T, userContext?: any): Promise; getClaimValue(this: SessionClassWithJWT, claim: SessionClaim, userContext?: any): Promise; removeClaim(this: SessionClassWithJWT, claim: SessionClaim, userContext?: any): Promise; - mergeIntoAccessTokenPayload( - this: SessionClassWithJWT, - accessTokenPayloadUpdate: any, - userContext?: any - ): Promise; + mergeIntoAccessTokenPayload(this: SessionClassWithJWT, accessTokenPayloadUpdate: any, userContext?: any): Promise; /** * @deprecated use mergeIntoAccessTokenPayload instead */ - updateAccessTokenPayload( - this: SessionClassWithJWT, - newAccessTokenPayload: any | undefined, - userContext?: any - ): Promise; + updateAccessTokenPayload(this: SessionClassWithJWT, newAccessTokenPayload: any | undefined, userContext?: any): Promise; } diff --git a/lib/build/recipe/session/with-jwt/sessionClass.js b/lib/build/recipe/session/with-jwt/sessionClass.js index 8cb88388a..82d6e9786 100644 --- a/lib/build/recipe/session/with-jwt/sessionClass.js +++ b/lib/build/recipe/session/with-jwt/sessionClass.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -89,15 +67,13 @@ class SessionClassWithJWT { // We copy the implementation here, since we want to override updateAccessTokenPayload assertClaims(claimValidators, userContext) { return __awaiter(this, void 0, void 0, function* () { - let validateClaimResponse = yield recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.validateClaims({ - accessTokenPayload: this.getAccessTokenPayload(userContext), - userId: this.getUserId(userContext), - recipeUserId: this.getRecipeUserId(userContext), - claimValidators, - userContext, - }); + let validateClaimResponse = yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.validateClaims({ + accessTokenPayload: this.getAccessTokenPayload(userContext), + userId: this.getUserId(userContext), + recipeUserId: this.getRecipeUserId(userContext), + claimValidators, + userContext, + }); if (validateClaimResponse.accessTokenPayloadUpdate !== undefined) { yield this.mergeIntoAccessTokenPayload(validateClaimResponse.accessTokenPayloadUpdate, userContext); } @@ -113,11 +89,7 @@ class SessionClassWithJWT { // We copy the implementation here, since we want to override updateAccessTokenPayload fetchAndSetClaim(claim, userContext) { return __awaiter(this, void 0, void 0, function* () { - const update = yield claim.build( - this.getUserId(userContext), - this.getRecipeUserId(userContext), - userContext - ); + const update = yield claim.build(this.getUserId(userContext), this.getRecipeUserId(userContext), userContext); return this.mergeIntoAccessTokenPayload(update, userContext); }); } @@ -140,10 +112,7 @@ class SessionClassWithJWT { // We copy the implementation here, since we want to override updateAccessTokenPayload mergeIntoAccessTokenPayload(accessTokenPayloadUpdate, userContext) { return __awaiter(this, void 0, void 0, function* () { - const updatedPayload = Object.assign( - Object.assign({}, this.getAccessTokenPayload(userContext)), - accessTokenPayloadUpdate - ); + const updatedPayload = Object.assign(Object.assign({}, this.getAccessTokenPayload(userContext)), accessTokenPayloadUpdate); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete updatedPayload[key]; @@ -170,7 +139,7 @@ class SessionClassWithJWT { let currentTimeInSeconds = Date.now() / 1000; let decodedPayload = JsonWebToken.decode(existingJWT, { json: true }); // JsonWebToken.decode possibly returns null - if (decodedPayload === null) { + if (decodedPayload === null || decodedPayload.exp === undefined) { throw new Error("Error reading JWT from session"); } let jwtExpiry = decodedPayload.exp - currentTimeInSeconds; diff --git a/lib/build/recipe/session/with-jwt/utils.d.ts b/lib/build/recipe/session/with-jwt/utils.d.ts index 3a4b54185..772df0b99 100644 --- a/lib/build/recipe/session/with-jwt/utils.d.ts +++ b/lib/build/recipe/session/with-jwt/utils.d.ts @@ -1,13 +1,5 @@ -// @ts-nocheck import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; -export declare function addJWTToAccessTokenPayload({ - accessTokenPayload, - jwtExpiry, - userId, - jwtPropertyName, - openIdRecipeImplementation, - userContext, -}: { +export declare function addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry, userId, jwtPropertyName, openIdRecipeImplementation, userContext, }: { accessTokenPayload: any; jwtExpiry: number; userId: string; diff --git a/lib/build/recipe/session/with-jwt/utils.js b/lib/build/recipe/session/with-jwt/utils.js index 49c1d7531..4b5492e66 100644 --- a/lib/build/recipe/session/with-jwt/utils.js +++ b/lib/build/recipe/session/with-jwt/utils.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.addJWTToAccessTokenPayload = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -46,14 +25,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); * under the License. */ const constants_1 = require("./constants"); -function addJWTToAccessTokenPayload({ - accessTokenPayload, - jwtExpiry, - userId, - jwtPropertyName, - openIdRecipeImplementation, - userContext, -}) { +function addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry, userId, jwtPropertyName, openIdRecipeImplementation, userContext, }) { return __awaiter(this, void 0, void 0, function* () { // If jwtPropertyName is not undefined it means that the JWT was added to the access token payload already let existingJwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; @@ -64,16 +36,12 @@ function addJWTToAccessTokenPayload({ } // Create the JWT let jwtResponse = yield openIdRecipeImplementation.createJWT({ - payload: Object.assign( - { - /* + payload: Object.assign({ + /* We add our claims before the user provided ones so that if they use the same claims then the final payload will use the values they provide */ - sub: userId, - }, - accessTokenPayload - ), + sub: userId }, accessTokenPayload), validitySeconds: jwtExpiry, userContext, }); @@ -82,7 +50,7 @@ function addJWTToAccessTokenPayload({ throw new Error("JWT Signing algorithm not supported"); } // Add the jwt and the property name to the access token payload - accessTokenPayload = Object.assign(Object.assign({}, accessTokenPayload), { + accessTokenPayload = Object.assign(Object.assign({}, accessTokenPayload), { /* We add the JWT after the user defined keys because we want to make sure that it never gets overwritten by a user defined key. Using the same key as the one configured (or defaulting) @@ -99,9 +67,7 @@ function addJWTToAccessTokenPayload({ guaranteed that the right JWT is returned. This case is considered to be a rare requirement and we assume that users will not need multiple JWT representations of their access token payload. */ - [jwtPropertyName]: jwtResponse.jwt, - [constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]: jwtPropertyName, - }); + [jwtPropertyName]: jwtResponse.jwt, [constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]: jwtPropertyName }); return accessTokenPayload; }); } diff --git a/lib/build/recipe/thirdparty/api/appleRedirect.d.ts b/lib/build/recipe/thirdparty/api/appleRedirect.d.ts index df930a9a1..177615549 100644 --- a/lib/build/recipe/thirdparty/api/appleRedirect.d.ts +++ b/lib/build/recipe/thirdparty/api/appleRedirect.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function appleRedirectHandler(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/thirdparty/api/appleRedirect.js b/lib/build/recipe/thirdparty/api/appleRedirect.js index caf7cad15..5e659d3bc 100644 --- a/lib/build/recipe/thirdparty/api/appleRedirect.js +++ b/lib/build/recipe/thirdparty/api/appleRedirect.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); function appleRedirectHandler(apiImplementation, options) { diff --git a/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts b/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts index 5603eb9c1..068abfe81 100644 --- a/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts +++ b/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function authorisationUrlAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/thirdparty/api/authorisationUrl.js b/lib/build/recipe/thirdparty/api/authorisationUrl.js index 047ebc0f0..588ca4510 100644 --- a/lib/build/recipe/thirdparty/api/authorisationUrl.js +++ b/lib/build/recipe/thirdparty/api/authorisationUrl.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = require("../error"); diff --git a/lib/build/recipe/thirdparty/api/implementation.d.ts b/lib/build/recipe/thirdparty/api/implementation.d.ts index a594ecb37..d88ce94d8 100644 --- a/lib/build/recipe/thirdparty/api/implementation.d.ts +++ b/lib/build/recipe/thirdparty/api/implementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface } from "../"; export default function getAPIInterface(): APIInterface; export declare function getActualClientIdFromDevelopmentClientId(client_id: string): string; diff --git a/lib/build/recipe/thirdparty/api/implementation.js b/lib/build/recipe/thirdparty/api/implementation.js index 8ce0eed87..3d5013575 100644 --- a/lib/build/recipe/thirdparty/api/implementation.js +++ b/lib/build/recipe/thirdparty/api/implementation.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getActualClientIdFromDevelopmentClientId = void 0; const session_1 = require("../../session"); const url_1 = require("url"); const axios = require("axios"); @@ -47,7 +26,7 @@ function getAPIInterface() { }; }); }, - authorisationUrlGET: function ({ provider, options, userContext }) { + authorisationUrlGET: function ({ provider, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let providerInfo = provider.get(undefined, undefined, userContext); let params = {}; @@ -57,10 +36,8 @@ function getAPIInterface() { let value = providerInfo.authorisationRedirect.params[key]; params[key] = typeof value === "function" ? yield value(options.req.original) : value; } - if ( - providerInfo.getRedirectURI !== undefined && - !isUsingDevelopmentClientId(providerInfo.getClientId(userContext)) - ) { + if (providerInfo.getRedirectURI !== undefined && + !isUsingDevelopmentClientId(providerInfo.getClientId(userContext))) { // the backend wants to set the redirectURI - so we set that here. // we add the not development keys because the oauth provider will // redirect to supertokens.io's URL which will redirect the app @@ -73,9 +50,7 @@ function getAPIInterface() { params["actual_redirect_uri"] = providerInfo.authorisationRedirect.url; Object.keys(params).forEach((key) => { if (params[key] === providerInfo.getClientId(userContext)) { - params[key] = getActualClientIdFromDevelopmentClientId( - providerInfo.getClientId(userContext) - ); + params[key] = getActualClientIdFromDevelopmentClientId(providerInfo.getClientId(userContext)); } }); } @@ -90,7 +65,7 @@ function getAPIInterface() { }; }); }, - signInUpPOST: function ({ provider, code, redirectURI, authCodeResponse, options, userContext }) { + signInUpPOST: function ({ provider, code, redirectURI, authCodeResponse, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let userInfo; let accessTokenAPIResponse; @@ -98,7 +73,8 @@ function getAPIInterface() { let providerInfo = provider.get(undefined, undefined, userContext); if (isUsingDevelopmentClientId(providerInfo.getClientId(userContext))) { redirectURI = DEV_OAUTH_REDIRECT_URL; - } else if (providerInfo.getRedirectURI !== undefined) { + } + else if (providerInfo.getRedirectURI !== undefined) { // we overwrite the redirectURI provided by the frontend // since the backend wants to take charge of setting this. redirectURI = providerInfo.getRedirectURI(userContext); @@ -109,14 +85,13 @@ function getAPIInterface() { accessTokenAPIResponse = { data: authCodeResponse, }; - } else { + } + else { // we should use code to get the authCodeResponse body if (isUsingDevelopmentClientId(providerInfo.getClientId(userContext))) { Object.keys(providerInfo.accessTokenAPI.params).forEach((key) => { if (providerInfo.accessTokenAPI.params[key] === providerInfo.getClientId(userContext)) { - providerInfo.accessTokenAPI.params[key] = getActualClientIdFromDevelopmentClientId( - providerInfo.getClientId(userContext) - ); + providerInfo.accessTokenAPI.params[key] = getActualClientIdFromDevelopmentClientId(providerInfo.getClientId(userContext)); } }); } @@ -126,7 +101,7 @@ function getAPIInterface() { data: qs.stringify(providerInfo.accessTokenAPI.params), headers: { "content-type": "application/x-www-form-urlencoded", - accept: "application/json", + accept: "application/json", // few providers like github don't send back json response by default }, }); } @@ -148,13 +123,11 @@ function getAPIInterface() { if (emailInfo.isVerified) { const emailVerificationInstance = recipe_1.default.getInstance(); if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: response.user.id, - email: response.user.email, - userContext, - } - ); + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ + userId: response.user.id, + email: response.user.email, + userContext, + }); if (tokenResponse.status === "OK") { yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ token: tokenResponse.token, @@ -163,14 +136,7 @@ function getAPIInterface() { } } } - let session = yield session_1.default.createNewSession( - options.res, - response.user.id, - response.user.recipeUserId, - {}, - {}, - userContext - ); + let session = yield session_1.default.createNewSession(options.req, options.res, response.user.id, response.user.recipeUserId, {}, {}, userContext); return { status: "OK", createdNewUser: response.createdNewUser, @@ -183,16 +149,13 @@ function getAPIInterface() { }, appleRedirectHandlerPOST: function ({ code, state, options }) { return __awaiter(this, void 0, void 0, function* () { - const redirectURL = - options.appInfo.websiteDomain.getAsStringDangerous() + + const redirectURL = options.appInfo.websiteDomain.getAsStringDangerous() + options.appInfo.websiteBasePath.getAsStringDangerous() + "/callback/apple?state=" + state + "&code=" + code; - options.res.sendHTMLResponse( - `` - ); + options.res.sendHTMLResponse(``); }); }, }; @@ -203,7 +166,7 @@ const DEV_OAUTH_REDIRECT_URL = "https://supertokens.io/dev/oauth/redirect-to-app // If Third Party login is used with one of the following development keys, then the dev authorization url and the redirect url will be used. const DEV_OAUTH_CLIENT_IDS = [ "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", - "467101b197249757c71f", + "467101b197249757c71f", // github ]; const DEV_KEY_IDENTIFIER = "4398792-"; function isUsingDevelopmentClientId(client_id) { diff --git a/lib/build/recipe/thirdparty/api/signinup.d.ts b/lib/build/recipe/thirdparty/api/signinup.d.ts index b8fc4501c..93a9bd803 100644 --- a/lib/build/recipe/thirdparty/api/signinup.d.ts +++ b/lib/build/recipe/thirdparty/api/signinup.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signInUpAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/thirdparty/api/signinup.js b/lib/build/recipe/thirdparty/api/signinup.js index 54f91d1b8..0c44ae8b5 100644 --- a/lib/build/recipe/thirdparty/api/signinup.js +++ b/lib/build/recipe/thirdparty/api/signinup.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../error"); const utils_1 = require("../../../utils"); @@ -95,14 +73,13 @@ function signInUpAPI(apiImplementation, options) { if (clientId === undefined) { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, - message: - "The third party provider " + thirdPartyId + ` seems to be missing from the backend configs.`, + message: "The third party provider " + thirdPartyId + ` seems to be missing from the backend configs.`, }); - } else { + } + else { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, - message: - "The third party provider " + + message: "The third party provider " + thirdPartyId + ` seems to be missing from the backend configs. If it is configured, then please make sure that you are passing the correct clientId from the frontend.`, }); @@ -123,11 +100,13 @@ function signInUpAPI(apiImplementation, options) { user: result.user, createdNewUser: result.createdNewUser, }); - } else if (result.status === "NO_EMAIL_GIVEN_BY_PROVIDER") { + } + else if (result.status === "NO_EMAIL_GIVEN_BY_PROVIDER") { utils_1.send200Response(options.res, { status: "NO_EMAIL_GIVEN_BY_PROVIDER", }); - } else { + } + else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/thirdparty/constants.d.ts b/lib/build/recipe/thirdparty/constants.d.ts index e2235e1bf..809ae0592 100644 --- a/lib/build/recipe/thirdparty/constants.d.ts +++ b/lib/build/recipe/thirdparty/constants.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export declare const AUTHORISATION_API = "/authorisationurl"; export declare const SIGN_IN_UP_API = "/signinup"; export declare const APPLE_REDIRECT_HANDLER = "/callback/apple"; diff --git a/lib/build/recipe/thirdparty/constants.js b/lib/build/recipe/thirdparty/constants.js index 5149bd18d..531579d94 100644 --- a/lib/build/recipe/thirdparty/constants.js +++ b/lib/build/recipe/thirdparty/constants.js @@ -14,6 +14,7 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.APPLE_REDIRECT_HANDLER = exports.SIGN_IN_UP_API = exports.AUTHORISATION_API = void 0; exports.AUTHORISATION_API = "/authorisationurl"; exports.SIGN_IN_UP_API = "/signinup"; exports.APPLE_REDIRECT_HANDLER = "/callback/apple"; diff --git a/lib/build/recipe/thirdparty/error.d.ts b/lib/build/recipe/thirdparty/error.d.ts index cc9e34552..d1e71e0b1 100644 --- a/lib/build/recipe/thirdparty/error.d.ts +++ b/lib/build/recipe/thirdparty/error.d.ts @@ -1,5 +1,7 @@ -// @ts-nocheck import STError from "../../error"; export default class ThirdPartyError extends STError { - constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); + constructor(options: { + type: "BAD_INPUT_ERROR"; + message: string; + }); } diff --git a/lib/build/recipe/thirdparty/index.d.ts b/lib/build/recipe/thirdparty/index.d.ts index 3d49463a7..e8d9582d5 100644 --- a/lib/build/recipe/thirdparty/index.d.ts +++ b/lib/build/recipe/thirdparty/index.d.ts @@ -1,27 +1,17 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIInterface, APIOptions, TypeProvider } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static signInUp( - thirdPartyId: string, - thirdPartyUserId: string, - email: string, - userContext?: any - ): Promise<{ + static signInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ status: "OK"; createdNewUser: boolean; user: User; }>; static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise; - static getUserByThirdPartyInfo( - thirdPartyId: string, - thirdPartyUserId: string, - userContext?: any - ): Promise; + static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; static Google: typeof import("./providers/google").default; static Github: typeof import("./providers/github").default; static Facebook: typeof import("./providers/facebook").default; diff --git a/lib/build/recipe/thirdparty/index.js b/lib/build/recipe/thirdparty/index.js index b6b4276c5..78696ac0c 100644 --- a/lib/build/recipe/thirdparty/index.js +++ b/lib/build/recipe/thirdparty/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.getUserByThirdPartyInfo = exports.getUsersByEmail = exports.getUserById = exports.signInUp = exports.Error = exports.init = void 0; const recipe_1 = require("./recipe"); const error_1 = require("./error"); const thirdPartyProviders = require("./providers"); diff --git a/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts b/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts index f6617924f..e69de29bb 100644 --- a/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts +++ b/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts @@ -1 +0,0 @@ -// @ts-nocheck diff --git a/lib/build/recipe/thirdparty/providers/apple.d.ts b/lib/build/recipe/thirdparty/providers/apple.d.ts index 5370e2111..897f6e5f7 100644 --- a/lib/build/recipe/thirdparty/providers/apple.d.ts +++ b/lib/build/recipe/thirdparty/providers/apple.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderAppleConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/apple.js b/lib/build/recipe/thirdparty/providers/apple.js index 7005957c1..ca66a32f4 100644 --- a/lib/build/recipe/thirdparty/providers/apple.js +++ b/lib/build/recipe/thirdparty/providers/apple.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const jsonwebtoken_1 = require("jsonwebtoken"); const error_1 = require("../error"); @@ -40,27 +18,19 @@ const verify_apple_id_token_1 = require("verify-apple-id-token"); function Apple(config) { const id = "apple"; function getClientSecret(clientId, keyId, teamId, privateKey) { - return jsonwebtoken_1.sign( - { - iss: teamId, - iat: Math.floor(Date.now() / 1000), - exp: Math.floor(Date.now() / 1000) + 86400 * 180, - aud: "https://appleid.apple.com", - sub: implementation_1.getActualClientIdFromDevelopmentClientId(clientId), - }, - privateKey.replace(/\\n/g, "\n"), - { algorithm: "ES256", keyid: keyId } - ); + return jsonwebtoken_1.sign({ + iss: teamId, + iat: Math.floor(Date.now() / 1000), + exp: Math.floor(Date.now() / 1000) + 86400 * 180, + aud: "https://appleid.apple.com", + sub: implementation_1.getActualClientIdFromDevelopmentClientId(clientId), + }, privateKey.replace(/\\n/g, "\n"), { algorithm: "ES256", keyid: keyId }); } try { // trying to generate a client secret, in case client has not passed the values correctly - getClientSecret( - config.clientId, - config.clientSecret.keyId, - config.clientSecret.teamId, - config.clientSecret.privateKey - ); - } catch (error) { + getClientSecret(config.clientId, config.clientSecret.keyId, config.clientSecret.teamId, config.clientSecret.privateKey); + } + catch (error) { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, message: error.message, @@ -68,12 +38,7 @@ function Apple(config) { } function get(redirectURI, authCodeFromRequest) { let accessTokenAPIURL = "https://appleid.apple.com/auth/token"; - let clientSecret = getClientSecret( - config.clientId, - config.clientSecret.keyId, - config.clientSecret.teamId, - config.clientSecret.privateKey - ); + let clientSecret = getClientSecret(config.clientId, config.clientSecret.keyId, config.clientSecret.teamId, config.clientSecret.privateKey); let accessTokenAPIParams = { client_id: config.clientId, client_secret: clientSecret, @@ -91,14 +56,10 @@ function Apple(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = - config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign( - { scope: scopes.join(" "), response_mode: "form_post", response_type: "code", client_id: config.clientId }, - additionalParams - ); + let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), response_mode: "form_post", response_type: "code", client_id: config.clientId }, additionalParams); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { /* @@ -131,11 +92,9 @@ function Apple(config) { } function getRedirectURI() { let supertokens = supertokens_1.default.getInstanceOrThrowError(); - return ( - supertokens.appInfo.apiDomain.getAsStringDangerous() + + return (supertokens.appInfo.apiDomain.getAsStringDangerous() + supertokens.appInfo.apiBasePath.getAsStringDangerous() + - constants_1.APPLE_REDIRECT_HANDLER - ); + constants_1.APPLE_REDIRECT_HANDLER); } return { accessTokenAPI: { diff --git a/lib/build/recipe/thirdparty/providers/discord.d.ts b/lib/build/recipe/thirdparty/providers/discord.d.ts index 926e9d737..2f39d56aa 100644 --- a/lib/build/recipe/thirdparty/providers/discord.d.ts +++ b/lib/build/recipe/thirdparty/providers/discord.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderDiscordConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/discord.js b/lib/build/recipe/thirdparty/providers/discord.js index 16fa3f8d0..9d86a3a78 100644 --- a/lib/build/recipe/thirdparty/providers/discord.js +++ b/lib/build/recipe/thirdparty/providers/discord.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = require("axios"); function Discord(config) { @@ -53,14 +31,10 @@ function Discord(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = - config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign( - { scope: scopes.join(" "), client_id: config.clientId, response_type: "code" }, - additionalParams - ); + let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), client_id: config.clientId, response_type: "code" }, additionalParams); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { let accessToken = accessTokenAPIResponse.access_token; @@ -75,13 +49,12 @@ function Discord(config) { let userInfo = response.data; return { id: userInfo.id, - email: - userInfo.email === undefined - ? undefined - : { - id: userInfo.email, - isVerified: userInfo.verified, - }, + email: userInfo.email === undefined + ? undefined + : { + id: userInfo.email, + isVerified: userInfo.verified, + }, }; }); } diff --git a/lib/build/recipe/thirdparty/providers/facebook.d.ts b/lib/build/recipe/thirdparty/providers/facebook.d.ts index 71b678eee..02d3c5d91 100644 --- a/lib/build/recipe/thirdparty/providers/facebook.d.ts +++ b/lib/build/recipe/thirdparty/providers/facebook.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderFacebookConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/facebook.js b/lib/build/recipe/thirdparty/providers/facebook.js index f54a7d4ba..368119ea9 100644 --- a/lib/build/recipe/thirdparty/providers/facebook.js +++ b/lib/build/recipe/thirdparty/providers/facebook.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = require("axios"); function Facebook(config) { diff --git a/lib/build/recipe/thirdparty/providers/github.d.ts b/lib/build/recipe/thirdparty/providers/github.d.ts index 105f3adae..17d76dc22 100644 --- a/lib/build/recipe/thirdparty/providers/github.d.ts +++ b/lib/build/recipe/thirdparty/providers/github.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderGithubConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/github.js b/lib/build/recipe/thirdparty/providers/github.js index 184960d58..3851c3edd 100644 --- a/lib/build/recipe/thirdparty/providers/github.js +++ b/lib/build/recipe/thirdparty/providers/github.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = require("axios"); function Github(config) { @@ -52,14 +30,10 @@ function Github(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = - config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign( - { scope: scopes.join(" "), client_id: config.clientId }, - additionalParams - ); + let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), client_id: config.clientId }, additionalParams); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { let accessToken = accessTokenAPIResponse.access_token; @@ -106,13 +80,12 @@ function Github(config) { let isVerified = emailInfo !== undefined ? emailInfo.verified : false; return { id, - email: - emailInfo.email === undefined - ? undefined - : { - id: emailInfo.email, - isVerified, - }, + email: emailInfo.email === undefined + ? undefined + : { + id: emailInfo.email, + isVerified, + }, }; }); } diff --git a/lib/build/recipe/thirdparty/providers/google.d.ts b/lib/build/recipe/thirdparty/providers/google.d.ts index 4baaaccce..f3e23cada 100644 --- a/lib/build/recipe/thirdparty/providers/google.d.ts +++ b/lib/build/recipe/thirdparty/providers/google.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderGoogleConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/google.js b/lib/build/recipe/thirdparty/providers/google.js index 71e2352a7..3ae88cb4f 100644 --- a/lib/build/recipe/thirdparty/providers/google.js +++ b/lib/build/recipe/thirdparty/providers/google.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = require("axios"); function Google(config) { @@ -53,20 +31,10 @@ function Google(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = - config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign( - { - scope: scopes.join(" "), - access_type: "offline", - include_granted_scopes: "true", - response_type: "code", - client_id: config.clientId, - }, - additionalParams - ); + let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), access_type: "offline", include_granted_scopes: "true", response_type: "code", client_id: config.clientId }, additionalParams); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { let accessToken = accessTokenAPIResponse.access_token; diff --git a/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts b/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts index cf313c6ac..fbd94579e 100644 --- a/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts +++ b/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderGoogleWorkspacesConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/googleWorkspaces.js b/lib/build/recipe/thirdparty/providers/googleWorkspaces.js index 8a1e526f6..e616bbe26 100644 --- a/lib/build/recipe/thirdparty/providers/googleWorkspaces.js +++ b/lib/build/recipe/thirdparty/providers/googleWorkspaces.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("./utils"); const implementation_1 = require("../api/implementation"); @@ -55,31 +33,16 @@ function GW(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = - config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign( - { - scope: scopes.join(" "), - access_type: "offline", - include_granted_scopes: "true", - response_type: "code", - client_id: config.clientId, - hd: domain, - }, - additionalParams - ); + let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), access_type: "offline", include_granted_scopes: "true", response_type: "code", client_id: config.clientId, hd: domain }, additionalParams); function getProfileInfo(authCodeResponse) { return __awaiter(this, void 0, void 0, function* () { - let payload = yield utils_1.verifyIdTokenFromJWKSEndpoint( - authCodeResponse.id_token, - "https://www.googleapis.com/oauth2/v3/certs", - { - audience: implementation_1.getActualClientIdFromDevelopmentClientId(config.clientId), - issuer: ["https://accounts.google.com", "accounts.google.com"], - } - ); + let payload = yield utils_1.verifyIdTokenFromJWKSEndpoint(authCodeResponse.id_token, "https://www.googleapis.com/oauth2/v3/certs", { + audience: implementation_1.getActualClientIdFromDevelopmentClientId(config.clientId), + issuer: ["https://accounts.google.com", "accounts.google.com"], + }); if (payload.email === undefined) { throw new Error("Could not get email. Please use a different login method"); } diff --git a/lib/build/recipe/thirdparty/providers/index.d.ts b/lib/build/recipe/thirdparty/providers/index.d.ts index f1c5f5501..0c0096be4 100644 --- a/lib/build/recipe/thirdparty/providers/index.d.ts +++ b/lib/build/recipe/thirdparty/providers/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import ProviderGoogle from "./google"; import ProviderFacebook from "./facebook"; import ProviderGithub from "./github"; diff --git a/lib/build/recipe/thirdparty/providers/index.js b/lib/build/recipe/thirdparty/providers/index.js index e9e63ada8..f8eacb3b4 100644 --- a/lib/build/recipe/thirdparty/providers/index.js +++ b/lib/build/recipe/thirdparty/providers/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Github = exports.Facebook = exports.Google = void 0; const google_1 = require("./google"); const facebook_1 = require("./facebook"); const github_1 = require("./github"); diff --git a/lib/build/recipe/thirdparty/providers/okta.d.ts b/lib/build/recipe/thirdparty/providers/okta.d.ts index f6617924f..e69de29bb 100644 --- a/lib/build/recipe/thirdparty/providers/okta.d.ts +++ b/lib/build/recipe/thirdparty/providers/okta.d.ts @@ -1 +0,0 @@ -// @ts-nocheck diff --git a/lib/build/recipe/thirdparty/providers/utils.d.ts b/lib/build/recipe/thirdparty/providers/utils.d.ts index 51573e0d8..5c5e8d7c3 100644 --- a/lib/build/recipe/thirdparty/providers/utils.d.ts +++ b/lib/build/recipe/thirdparty/providers/utils.d.ts @@ -1,7 +1,2 @@ -// @ts-nocheck import * as jwt from "jsonwebtoken"; -export declare function verifyIdTokenFromJWKSEndpoint( - idToken: string, - jwksUri: string, - otherOptions: jwt.VerifyOptions -): Promise; +export declare function verifyIdTokenFromJWKSEndpoint(idToken: string, jwksUri: string, otherOptions: jwt.VerifyOptions): Promise; diff --git a/lib/build/recipe/thirdparty/providers/utils.js b/lib/build/recipe/thirdparty/providers/utils.js index 542100115..47c27b34d 100644 --- a/lib/build/recipe/thirdparty/providers/utils.js +++ b/lib/build/recipe/thirdparty/providers/utils.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyIdTokenFromJWKSEndpoint = void 0; const jwt = require("jsonwebtoken"); const jwksClient = require("jwks-rsa"); function verifyIdTokenFromJWKSEndpoint(idToken, jwksUri, otherOptions) { @@ -48,7 +27,8 @@ function verifyIdTokenFromJWKSEndpoint(idToken, jwksUri, otherOptions) { jwt.verify(idToken, getKey, otherOptions, function (err, decoded) { if (err) { reject(err); - } else { + } + else { resolve(decoded); } }); diff --git a/lib/build/recipe/thirdparty/recipe.d.ts b/lib/build/recipe/thirdparty/recipe.d.ts index 4c4f5dae3..f1e31112b 100644 --- a/lib/build/recipe/thirdparty/recipe.d.ts +++ b/lib/build/recipe/thirdparty/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import { TypeInput, TypeNormalisedInput, TypeProvider, RecipeInterface, APIInterface } from "./types"; @@ -14,25 +13,12 @@ export default class Recipe extends RecipeModule { recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; isInServerlessEnv: boolean; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - _recipes: {}, - _ingredients: {} - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, _recipes: {}, _ingredients: {}); static init(config: TypeInput): RecipeListFunction; static getInstanceOrThrowError(): Recipe; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - _path: NormalisedURLPath, - _method: HTTPMethod - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _path: NormalisedURLPath, _method: HTTPMethod) => Promise; handleError: (err: STError, _request: BaseRequest, _response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/thirdparty/recipe.js b/lib/build/recipe/thirdparty/recipe.js index 06399364e..38cb2b0ce 100644 --- a/lib/build/recipe/thirdparty/recipe.js +++ b/lib/build/recipe/thirdparty/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = require("../../recipeModule"); const utils_1 = require("./utils"); @@ -84,31 +62,31 @@ class Recipe extends recipeModule_1.default { }, ]; }; - this.handleAPIRequest = (id, req, res, _path, _method) => - __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - providers: this.providers, - req, - res, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.SIGN_IN_UP_API) { - return yield signinup_1.default(this.apiImpl, options); - } else if (id === constants_1.AUTHORISATION_API) { - return yield authorisationUrl_1.default(this.apiImpl, options); - } else if (id === constants_1.APPLE_REDIRECT_HANDLER) { - return yield appleRedirect_1.default(this.apiImpl, options); - } - return false; - }); - this.handleError = (err, _request, _response) => - __awaiter(this, void 0, void 0, function* () { - throw err; - }); + this.handleAPIRequest = (id, req, res, _path, _method) => __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + providers: this.providers, + req, + res, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.SIGN_IN_UP_API) { + return yield signinup_1.default(this.apiImpl, options); + } + else if (id === constants_1.AUTHORISATION_API) { + return yield authorisationUrl_1.default(this.apiImpl, options); + } + else if (id === constants_1.APPLE_REDIRECT_HANDLER) { + return yield appleRedirect_1.default(this.apiImpl, options); + } + return false; + }); + this.handleError = (err, _request, _response) => __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; @@ -116,26 +94,23 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; // helper functions... - this.getEmailForUserId = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo !== undefined) { - return { - status: "OK", - email: userInfo.email, - }; - } + this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo !== undefined) { return { - status: "UNKNOWN_USER_ID_ERROR", + status: "OK", + email: userInfo.email, }; - }); + } + return { + status: "UNKNOWN_USER_ID_ERROR", + }; + }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); this.isInServerlessEnv = isInServerlessEnv; this.providers = this.config.signInAndUpFeature.providers; { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -152,18 +127,12 @@ class Recipe extends recipeModule_1.default { static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe( - Recipe.RECIPE_ID, - appInfo, - isInServerlessEnv, - config, - {}, - { - emailDelivery: undefined, - } - ); + Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config, {}, { + emailDelivery: undefined, + }); return Recipe.instance; - } else { + } + else { throw new Error("ThirdParty recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/thirdparty/recipeImplementation.d.ts b/lib/build/recipe/thirdparty/recipeImplementation.d.ts index 7d1180bfb..8db107c07 100644 --- a/lib/build/recipe/thirdparty/recipeImplementation.d.ts +++ b/lib/build/recipe/thirdparty/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeImplementation(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/thirdparty/recipeImplementation.js b/lib/build/recipe/thirdparty/recipeImplementation.js index fdd3642d8..094eacaac 100644 --- a/lib/build/recipe/thirdparty/recipeImplementation.js +++ b/lib/build/recipe/thirdparty/recipeImplementation.js @@ -1,40 +1,18 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = require("../../normalisedURLPath"); function getRecipeImplementation(querier) { return { - signInUp: function ({ thirdPartyId, thirdPartyUserId, email }) { + signInUp: function ({ thirdPartyId, thirdPartyUserId, email, }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup"), { thirdPartyId, @@ -55,23 +33,21 @@ function getRecipeImplementation(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } else { + } + else { return undefined; } }); }, getUsersByEmail: function ({ email }) { return __awaiter(this, void 0, void 0, function* () { - const { users } = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/users/by-email"), - { - email, - } - ); + const { users } = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/users/by-email"), { + email, + }); return users; }); }, - getUserByThirdPartyInfo: function ({ thirdPartyId, thirdPartyUserId }) { + getUserByThirdPartyInfo: function ({ thirdPartyId, thirdPartyUserId, }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { thirdPartyId, @@ -79,7 +55,8 @@ function getRecipeImplementation(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } else { + } + else { return undefined; } }); diff --git a/lib/build/recipe/thirdparty/types.d.ts b/lib/build/recipe/thirdparty/types.d.ts index f4fe4b459..2ad0c31fd 100644 --- a/lib/build/recipe/thirdparty/types.d.ts +++ b/lib/build/recipe/thirdparty/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import { NormalisedAppinfo } from "../../types"; import OverrideableBuilder from "supertokens-js-override"; @@ -30,11 +29,7 @@ export declare type TypeProviderGetResponse = { }; export declare type TypeProvider = { id: string; - get: ( - redirectURI: string | undefined, - authCodeFromRequest: string | undefined, - userContext: any - ) => TypeProviderGetResponse; + get: (redirectURI: string | undefined, authCodeFromRequest: string | undefined, userContext: any) => TypeProviderGetResponse; isDefault?: boolean; }; export declare type User = { @@ -56,26 +51,26 @@ export declare type TypeNormalisedInputSignInAndUp = { export declare type TypeInput = { signInAndUpFeature: TypeInputSignInAndUp; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { signInAndUpFeature: TypeNormalisedInputSignInAndUp; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getUserById(input: { userId: string; userContext: any }): Promise; - getUsersByEmail(input: { email: string; userContext: any }): Promise; + getUserById(input: { + userId: string; + userContext: any; + }): Promise; + getUsersByEmail(input: { + email: string; + userContext: any; + }): Promise; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -103,94 +98,75 @@ export declare type APIOptions = { appInfo: NormalisedAppinfo; }; export declare type APIInterface = { - authorisationUrlGET: - | undefined - | ((input: { - provider: TypeProvider; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - url: string; - } - | GeneralErrorResponse - >); - signInUpPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } - | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - | { - status: "SIGNIN_NOT_ALLOWED"; - primaryUserId: string; - description: string; - } - | GeneralErrorResponse - >); - linkAccountToExistingAccountPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - authCodeResponse: any; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); - appleRedirectHandlerPOST: - | undefined - | ((input: { code: string; state: string; options: APIOptions; userContext: any }) => Promise); + authorisationUrlGET: undefined | ((input: { + provider: TypeProvider; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + url: string; + } | GeneralErrorResponse>); + signInUpPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } | { + status: "SIGNIN_NOT_ALLOWED"; + primaryUserId: string; + description: string; + } | GeneralErrorResponse>); + linkAccountToExistingAccountPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + authCodeResponse: any; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } | GeneralErrorResponse>); + appleRedirectHandlerPOST: undefined | ((input: { + code: string; + state: string; + options: APIOptions; + userContext: any; + }) => Promise); }; diff --git a/lib/build/recipe/thirdparty/utils.d.ts b/lib/build/recipe/thirdparty/utils.d.ts index 2c878466d..7e28d0a8c 100644 --- a/lib/build/recipe/thirdparty/utils.d.ts +++ b/lib/build/recipe/thirdparty/utils.d.ts @@ -1,13 +1,5 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeProvider } from "./types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput( - appInfo: NormalisedAppinfo, - config: TypeInput -): TypeNormalisedInput; -export declare function findRightProvider( - providers: TypeProvider[], - thirdPartyId: string, - clientId?: string -): TypeProvider | undefined; +export declare function validateAndNormaliseUserInput(appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; +export declare function findRightProvider(providers: TypeProvider[], thirdPartyId: string, clientId?: string): TypeProvider | undefined; diff --git a/lib/build/recipe/thirdparty/utils.js b/lib/build/recipe/thirdparty/utils.js index 4087402d7..873ce97c8 100644 --- a/lib/build/recipe/thirdparty/utils.js +++ b/lib/build/recipe/thirdparty/utils.js @@ -14,15 +14,10 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.findRightProvider = exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(appInfo, config) { let signInAndUpFeature = validateAndNormaliseSignInAndUpConfig(appInfo, config.signInAndUpFeature); - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); return { signInAndUpFeature, override, @@ -53,9 +48,7 @@ exports.findRightProvider = findRightProvider; function validateAndNormaliseSignInAndUpConfig(_, config) { let providers = config.providers; if (providers === undefined || providers.length === 0) { - throw new Error( - "thirdparty recipe requires atleast 1 provider to be passed in signInAndUpFeature.providers config" - ); + throw new Error("thirdparty recipe requires atleast 1 provider to be passed in signInAndUpFeature.providers config"); } // we check if there are multiple providers with the same id that have isDefault as true. // In this case, we want to throw an error.. @@ -75,18 +68,14 @@ function validateAndNormaliseSignInAndUpConfig(_, config) { } if (isDefault) { if (isDefaultProvidersSet.has(id)) { - throw new Error( - `You have provided multiple third party providers that have the id: "${id}" and are marked as "isDefault: true". Please only mark one of them as isDefault.` - ); + throw new Error(`You have provided multiple third party providers that have the id: "${id}" and are marked as "isDefault: true". Please only mark one of them as isDefault.`); } isDefaultProvidersSet.add(id); } }); if (isDefaultProvidersSet.size !== allProvidersSet.size) { // this means that there is no provider marked as isDefault - throw new Error( - `The providers array has multiple entries for the same third party provider. Please mark one of them as the default one by using "isDefault: true".` - ); + throw new Error(`The providers array has multiple entries for the same third party provider. Please mark one of them as the default one by using "isDefault: true".`); } return { providers, diff --git a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts index 74122e450..3a64abf0d 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface } from "../../emailpassword"; import { APIInterface as ThirdPartyEmailPasswordAPIInterface } from "../"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyEmailPasswordAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js index ecdb8e01a..8e25733ae 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js @@ -3,28 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e, _f; return { - emailExistsGET: - (_a = apiImplmentation.emailPasswordEmailExistsGET) === null || _a === void 0 - ? void 0 - : _a.bind(apiImplmentation), - generatePasswordResetTokenPOST: - (_b = apiImplmentation.generatePasswordResetTokenPOST) === null || _b === void 0 - ? void 0 - : _b.bind(apiImplmentation), - passwordResetPOST: - (_c = apiImplmentation.passwordResetPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - signInPOST: - (_d = apiImplmentation.emailPasswordSignInPOST) === null || _d === void 0 - ? void 0 - : _d.bind(apiImplmentation), - signUpPOST: - (_e = apiImplmentation.emailPasswordSignUpPOST) === null || _e === void 0 - ? void 0 - : _e.bind(apiImplmentation), - linkAccountToExistingAccountPOST: - (_f = apiImplmentation.linkEmailPasswordAccountToExistingAccountPOST) === null || _f === void 0 - ? void 0 - : _f.bind(apiImplmentation), + emailExistsGET: (_a = apiImplmentation.emailPasswordEmailExistsGET) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation), + generatePasswordResetTokenPOST: (_b = apiImplmentation.generatePasswordResetTokenPOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), + passwordResetPOST: (_c = apiImplmentation.passwordResetPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + signInPOST: (_d = apiImplmentation.emailPasswordSignInPOST) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), + signUpPOST: (_e = apiImplmentation.emailPasswordSignUpPOST) === null || _e === void 0 ? void 0 : _e.bind(apiImplmentation), + linkAccountToExistingAccountPOST: (_f = apiImplmentation.linkEmailPasswordAccountToExistingAccountPOST) === null || _f === void 0 ? void 0 : _f.bind(apiImplmentation), }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts index 402db9918..a1619b2fd 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/implementation.js b/lib/build/recipe/thirdpartyemailpassword/api/implementation.js index dad8e9631..b1584884d 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/implementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/implementation.js @@ -9,46 +9,16 @@ function getAPIImplementation() { let emailPasswordImplementation = implementation_1.default(); let thirdPartyImplementation = implementation_2.default(); return { - emailPasswordEmailExistsGET: - (_a = emailPasswordImplementation.emailExistsGET) === null || _a === void 0 - ? void 0 - : _a.bind(emailPasswordAPIImplementation_1.default(this)), - authorisationUrlGET: - (_b = thirdPartyImplementation.authorisationUrlGET) === null || _b === void 0 - ? void 0 - : _b.bind(thirdPartyAPIImplementation_1.default(this)), - emailPasswordSignInPOST: - (_c = emailPasswordImplementation.signInPOST) === null || _c === void 0 - ? void 0 - : _c.bind(emailPasswordAPIImplementation_1.default(this)), - emailPasswordSignUpPOST: - (_d = emailPasswordImplementation.signUpPOST) === null || _d === void 0 - ? void 0 - : _d.bind(emailPasswordAPIImplementation_1.default(this)), - generatePasswordResetTokenPOST: - (_e = emailPasswordImplementation.generatePasswordResetTokenPOST) === null || _e === void 0 - ? void 0 - : _e.bind(emailPasswordAPIImplementation_1.default(this)), - linkEmailPasswordAccountToExistingAccountPOST: - (_f = emailPasswordImplementation.linkAccountToExistingAccountPOST) === null || _f === void 0 - ? void 0 - : _f.bind(emailPasswordAPIImplementation_1.default(this)), - linkThirdPartyAccountToExistingAccountPOST: - (_g = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _g === void 0 - ? void 0 - : _g.bind(thirdPartyAPIImplementation_1.default(this)), - passwordResetPOST: - (_h = emailPasswordImplementation.passwordResetPOST) === null || _h === void 0 - ? void 0 - : _h.bind(emailPasswordAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: - (_j = thirdPartyImplementation.signInUpPOST) === null || _j === void 0 - ? void 0 - : _j.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: - (_k = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _k === void 0 - ? void 0 - : _k.bind(thirdPartyAPIImplementation_1.default(this)), + emailPasswordEmailExistsGET: (_a = emailPasswordImplementation.emailExistsGET) === null || _a === void 0 ? void 0 : _a.bind(emailPasswordAPIImplementation_1.default(this)), + authorisationUrlGET: (_b = thirdPartyImplementation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(thirdPartyAPIImplementation_1.default(this)), + emailPasswordSignInPOST: (_c = emailPasswordImplementation.signInPOST) === null || _c === void 0 ? void 0 : _c.bind(emailPasswordAPIImplementation_1.default(this)), + emailPasswordSignUpPOST: (_d = emailPasswordImplementation.signUpPOST) === null || _d === void 0 ? void 0 : _d.bind(emailPasswordAPIImplementation_1.default(this)), + generatePasswordResetTokenPOST: (_e = emailPasswordImplementation.generatePasswordResetTokenPOST) === null || _e === void 0 ? void 0 : _e.bind(emailPasswordAPIImplementation_1.default(this)), + linkEmailPasswordAccountToExistingAccountPOST: (_f = emailPasswordImplementation.linkAccountToExistingAccountPOST) === null || _f === void 0 ? void 0 : _f.bind(emailPasswordAPIImplementation_1.default(this)), + linkThirdPartyAccountToExistingAccountPOST: (_g = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), + passwordResetPOST: (_h = emailPasswordImplementation.passwordResetPOST) === null || _h === void 0 ? void 0 : _h.bind(emailPasswordAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: (_j = thirdPartyImplementation.signInUpPOST) === null || _j === void 0 ? void 0 : _j.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: (_k = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _k === void 0 ? void 0 : _k.bind(thirdPartyAPIImplementation_1.default(this)), }; } exports.default = getAPIImplementation; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts index b0827c889..7143eeaef 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface } from "../../thirdparty"; import { APIInterface as ThirdPartyEmailPasswordAPIInterface } from "../"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyEmailPasswordAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js index f440fdfb5..4e020209b 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js @@ -1,89 +1,49 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d; - const signInUpPOSTFromThirdPartyEmailPassword = - (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); - const linkThirdPartyAccountToExistingAccountPOST = - (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 - ? void 0 - : _b.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyEmailPassword = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const linkThirdPartyAccountToExistingAccountPOST = (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation); return { - authorisationUrlGET: - (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - appleRedirectHandlerPOST: - (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 - ? void 0 - : _d.bind(apiImplmentation), - linkAccountToExistingAccountPOST: - linkThirdPartyAccountToExistingAccountPOST === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield linkThirdPartyAccountToExistingAccountPOST(input); - if (result.status === "OK") { - if (result.user.thirdParty === undefined) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { - user: Object.assign(Object.assign({}, result.user), { - thirdParty: Object.assign({}, result.user.thirdParty), - }), - }); - } - return result; - }); - }, - signInUpPOST: - signInUpPOSTFromThirdPartyEmailPassword === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield signInUpPOSTFromThirdPartyEmailPassword(input); - if (result.status === "OK") { - if (result.user.thirdParty === undefined) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { - user: Object.assign(Object.assign({}, result.user), { - thirdParty: Object.assign({}, result.user.thirdParty), - }), - }); - } - return result; - }); - }, + authorisationUrlGET: (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + appleRedirectHandlerPOST: (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), + linkAccountToExistingAccountPOST: linkThirdPartyAccountToExistingAccountPOST === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield linkThirdPartyAccountToExistingAccountPOST(input); + if (result.status === "OK") { + if (result.user.thirdParty === undefined) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); + } + return result; + }); + }, + signInUpPOST: signInUpPOSTFromThirdPartyEmailPassword === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield signInUpPOSTFromThirdPartyEmailPassword(input); + if (result.status === "OK") { + if (result.user.thirdParty === undefined) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); + } + return result; + }); + }, }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 83eec483b..b45efddbd 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,26 +1,13 @@ -// @ts-nocheck import { TypeThirdPartyEmailPasswordEmailDeliveryInput, User } from "../../../types"; import { RecipeInterface as EmailPasswordRecipeInterface } from "../../../../emailpassword"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService - implements EmailDeliveryInterface { +export default class BackwardCompatibilityService implements EmailDeliveryInterface { private emailPasswordBackwardCompatibilityService; - constructor( - emailPasswordRecipeInterfaceImpl: EmailPasswordRecipeInterface, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - resetPasswordUsingTokenFeature?: { - createAndSendCustomEmail?: ( - user: User, - passwordResetURLWithToken: string, - userContext: any - ) => Promise; - } - ); - sendEmail: ( - input: import("../../../../emailpassword/types").TypeEmailPasswordPasswordResetEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + constructor(emailPasswordRecipeInterfaceImpl: EmailPasswordRecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, resetPasswordUsingTokenFeature?: { + createAndSendCustomEmail?: (user: User, passwordResetURLWithToken: string, userContext: any) => Promise; + }); + sendEmail: (input: TypeThirdPartyEmailPasswordEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js index 823bd0411..feada7580 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -1,50 +1,22 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const backwardCompatibility_1 = require("../../../../emailpassword/emaildelivery/services/backwardCompatibility"); class BackwardCompatibilityService { constructor(emailPasswordRecipeInterfaceImpl, appInfo, isInServerlessEnv, resetPasswordUsingTokenFeature) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.emailPasswordBackwardCompatibilityService.sendEmail(input); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.emailPasswordBackwardCompatibilityService.sendEmail(input); + }); { - this.emailPasswordBackwardCompatibilityService = new backwardCompatibility_1.default( - emailPasswordRecipeInterfaceImpl, - appInfo, - isInServerlessEnv, - resetPasswordUsingTokenFeature - ); + this.emailPasswordBackwardCompatibilityService = new backwardCompatibility_1.default(emailPasswordRecipeInterfaceImpl, appInfo, isInServerlessEnv, resetPasswordUsingTokenFeature); } } } diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts index 4de04d983..dd2ef062c 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js index b38b12ec2..9a1dcbe44 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts index a533b4b2e..9c7db38da 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts @@ -1,13 +1,10 @@ -// @ts-nocheck import { TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { TypeThirdPartyEmailPasswordEmailDeliveryInput } from "../../../types"; export default class SMTPService implements EmailDeliveryInterface { private emailPasswordSMTPService; constructor(config: TypeInput); - sendEmail: ( - input: import("../../../../emailpassword/types").TypeEmailPasswordPasswordResetEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + sendEmail: (input: TypeThirdPartyEmailPasswordEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js index cf4b25a6e..e0b8191ed 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js @@ -1,43 +1,20 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const smtp_1 = require("../../../../emailpassword/emaildelivery/services/smtp"); class SMTPService { constructor(config) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.emailPasswordSMTPService.sendEmail(input); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.emailPasswordSMTPService.sendEmail(input); + }); this.emailPasswordSMTPService = new smtp_1.default(config); } } diff --git a/lib/build/recipe/thirdpartyemailpassword/error.d.ts b/lib/build/recipe/thirdpartyemailpassword/error.d.ts index 1d9c33665..3dc8820ff 100644 --- a/lib/build/recipe/thirdpartyemailpassword/error.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/error.d.ts @@ -1,5 +1,7 @@ -// @ts-nocheck import STError from "../../error"; export default class ThirdPartyEmailPasswordError extends STError { - constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); + constructor(options: { + type: "BAD_INPUT_ERROR"; + message: string; + }); } diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index 020257c41..5e37caeeb 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIInterface, EmailPasswordAPIOptions, ThirdPartyAPIOptions } from "./types"; @@ -7,76 +6,39 @@ import { TypeEmailPasswordEmailDeliveryInput } from "../emailpassword/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp( - thirdPartyId: string, - thirdPartyUserId: string, - email: string, - userContext?: any - ): Promise<{ + static thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ status: "OK"; createdNewUser: boolean; user: User; }>; - static getUserByThirdPartyInfo( - thirdPartyId: string, - thirdPartyUserId: string, - userContext?: any - ): Promise; - static emailPasswordSignUp( - email: string, - password: string, - userContext?: any - ): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - >; - static emailPasswordSignIn( - email: string, - password: string, - userContext?: any - ): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - >; + static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; + static emailPasswordSignUp(email: string, password: string, userContext?: any): Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + }>; + static emailPasswordSignIn(email: string, password: string, userContext?: any): Promise<{ + status: "OK"; + user: User; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + }>; static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise; - static createResetPasswordToken( - userId: string, - email: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "UNKNOWN_USER_ID_ERROR"; - } - >; - static resetPasswordUsingToken( - token: string, - newPassword: string, - userContext?: any - ): Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + static createResetPasswordToken(userId: string, email: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "UNKNOWN_USER_ID_ERROR"; + }>; + static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ + status: "OK"; + email: string; + userId: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; static updateEmailOrPassword(input: { userId: string; email?: string; @@ -91,11 +53,9 @@ export default class Wrapper { static Apple: typeof import("../thirdparty/providers/apple").default; static Discord: typeof import("../thirdparty/providers/discord").default; static GoogleWorkspaces: typeof import("../thirdparty/providers/googleWorkspaces").default; - static sendEmail( - input: TypeEmailPasswordEmailDeliveryInput & { - userContext?: any; - } - ): Promise; + static sendEmail(input: TypeEmailPasswordEmailDeliveryInput & { + userContext?: any; + }): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/thirdpartyemailpassword/index.js b/lib/build/recipe/thirdpartyemailpassword/index.js index 90b6c5a35..004947b97 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.sendEmail = exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.updateEmailOrPassword = exports.resetPasswordUsingToken = exports.createResetPasswordToken = exports.getUsersByEmail = exports.getUserByThirdPartyInfo = exports.getUserById = exports.thirdPartySignInUp = exports.emailPasswordSignIn = exports.emailPasswordSignUp = exports.Error = exports.init = void 0; const recipe_1 = require("./recipe"); const error_1 = require("./error"); const thirdPartyProviders = require("../thirdparty/providers"); @@ -99,17 +78,13 @@ class Wrapper { }); } static updateEmailOrPassword(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); } // static Okta = thirdPartyProviders.Okta; // static ActiveDirectory = thirdPartyProviders.ActiveDirectory; static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default.getInstanceOrThrowError().emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } } diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts index 36494b074..4b05b5419 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts @@ -1,17 +1,10 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import EmailPasswordRecipe from "../emailpassword/recipe"; import ThirdPartyRecipe from "../thirdparty/recipe"; import { BaseRequest, BaseResponse } from "../../framework"; import STError from "./error"; -import { - TypeInput, - TypeNormalisedInput, - RecipeInterface, - APIInterface, - TypeThirdPartyEmailPasswordEmailDeliveryInput, -} from "./types"; +import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, TypeThirdPartyEmailPasswordEmailDeliveryInput } from "./types"; import STErrorEmailPassword from "../emailpassword/error"; import STErrorThirdParty from "../thirdparty/error"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -26,35 +19,18 @@ export default class Recipe extends RecipeModule { apiImpl: APIInterface; isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - recipes: { - thirdPartyInstance: ThirdPartyRecipe | undefined; - emailPasswordInstance: EmailPasswordRecipe | undefined; - }, - ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { + thirdPartyInstance: ThirdPartyRecipe | undefined; + emailPasswordInstance: EmailPasswordRecipe | undefined; + }, ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + }); static init(config: TypeInput): RecipeListFunction; static reset(): void; static getInstanceOrThrowError(): Recipe; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - path: NormalisedURLPath, - method: HTTPMethod - ) => Promise; - handleError: ( - err: STErrorEmailPassword | STErrorThirdParty, - request: BaseRequest, - response: BaseResponse - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; + handleError: (err: STErrorEmailPassword | STErrorThirdParty, request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; } diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.js b/lib/build/recipe/thirdpartyemailpassword/recipe.js index d1bf60332..b6edff251 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -69,35 +47,30 @@ class Recipe extends recipeModule_1.default { } return apisHandled; }; - this.handleAPIRequest = (id, req, res, path, method) => - __awaiter(this, void 0, void 0, function* () { - if (this.emailPasswordRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { - return yield this.emailPasswordRecipe.handleAPIRequest(id, req, res, path, method); - } - if ( - this.thirdPartyRecipe !== undefined && - this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined - ) { - return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); + this.handleAPIRequest = (id, req, res, path, method) => __awaiter(this, void 0, void 0, function* () { + if (this.emailPasswordRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { + return yield this.emailPasswordRecipe.handleAPIRequest(id, req, res, path, method); + } + if (this.thirdPartyRecipe !== undefined && + this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { + return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); + } + return false; + }); + this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + throw err; + } + else { + if (this.emailPasswordRecipe.isErrorFromThisRecipe(err)) { + return yield this.emailPasswordRecipe.handleError(err, request, response); } - return false; - }); - this.handleError = (err, request, response) => - __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - throw err; - } else { - if (this.emailPasswordRecipe.isErrorFromThisRecipe(err)) { - return yield this.emailPasswordRecipe.handleError(err, request, response); - } else if ( - this.thirdPartyRecipe !== undefined && - this.thirdPartyRecipe.isErrorFromThisRecipe(err) - ) { - return yield this.thirdPartyRecipe.handleError(err, request, response); - } - throw err; + else if (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)) { + return yield this.thirdPartyRecipe.handleError(err, request, response); } - }); + throw err; + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [...this.emailPasswordRecipe.getAllCORSHeaders()]; if (this.thirdPartyRecipe !== undefined) { @@ -106,22 +79,15 @@ class Recipe extends recipeModule_1.default { return corsHeaders; }; this.isErrorFromThisRecipe = (err) => { - return ( - error_1.default.isErrorFromSuperTokens(err) && + return (error_1.default.isErrorFromSuperTokens(err) && (err.fromRecipe === Recipe.RECIPE_ID || this.emailPasswordRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) - ); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); }; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default( - querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), - querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID) - ) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -135,84 +101,61 @@ class Recipe extends recipeModule_1.default { */ this.emailDelivery = ingredients.emailDelivery === undefined - ? new emaildelivery_1.default( - this.config.getEmailDeliveryConfig(emailPasswordRecipeImplementation, this.isInServerlessEnv) - ) + ? new emaildelivery_1.default(this.config.getEmailDeliveryConfig(emailPasswordRecipeImplementation, this.isInServerlessEnv)) : ingredients.emailDelivery; this.emailPasswordRecipe = recipes.emailPasswordInstance !== undefined ? recipes.emailPasswordInstance - : new recipe_1.default( - recipeId, - appInfo, - isInServerlessEnv, - { - override: { - functions: (_) => { - return emailPasswordRecipeImplementation; - }, - apis: (_) => { - return emailPasswordAPIImplementation_1.default(this.apiImpl); - }, - }, - signUpFeature: { - formFields: this.config.signUpFeature.formFields, - }, - resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, - }, - { - emailDelivery: this.emailDelivery, - } - ); + : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, { + override: { + functions: (_) => { + return emailPasswordRecipeImplementation; + }, + apis: (_) => { + return emailPasswordAPIImplementation_1.default(this.apiImpl); + }, + }, + signUpFeature: { + formFields: this.config.signUpFeature.formFields, + }, + resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, + }, { + emailDelivery: this.emailDelivery, + }); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_2.default( - recipeId, - appInfo, - isInServerlessEnv, - { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, - {}, - { - emailDelivery: this.emailDelivery, - } - ); + : new recipe_2.default(recipeId, appInfo, isInServerlessEnv, { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, {}, { + emailDelivery: this.emailDelivery, + }); } } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe( - Recipe.RECIPE_ID, - appInfo, - isInServerlessEnv, - config, - { - emailPasswordInstance: undefined, - thirdPartyInstance: undefined, - }, - { - emailDelivery: undefined, - } - ); + Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config, { + emailPasswordInstance: undefined, + thirdPartyInstance: undefined, + }, { + emailDelivery: undefined, + }); return Recipe.instance; - } else { - throw new Error( - "ThirdPartyEmailPassword recipe has already been initialised. Please check your code for bugs." - ); + } + else { + throw new Error("ThirdPartyEmailPassword recipe has already been initialised. Please check your code for bugs."); } }; } diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts index 26119b84e..919de07f8 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "../../emailpassword/types"; import { RecipeInterface as ThirdPartyEmailPasswordRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPasswordRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js index 8d8772bdd..2ce58f790 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts index d24f05e67..601b0f21c 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "../types"; import { Querier } from "../../../querier"; export default function getRecipeInterface(emailPasswordQuerier: Querier, thirdPartyQuerier?: Querier): RecipeInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js index a0b965a09..aa4e850e1 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeImplementation_1 = require("../../emailpassword/recipeImplementation"); const recipeImplementation_2 = require("../../thirdparty/recipeImplementation"); @@ -44,16 +22,12 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { return { emailPasswordSignUp: function (input) { return __awaiter(this, void 0, void 0, function* () { - return yield originalEmailPasswordImplementation.signUp.bind( - emailPasswordRecipeImplementation_1.default(this) - )(input); + return yield originalEmailPasswordImplementation.signUp.bind(emailPasswordRecipeImplementation_1.default(this))(input); }); }, emailPasswordSignIn: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.signIn.bind( - emailPasswordRecipeImplementation_1.default(this) - )(input); + return originalEmailPasswordImplementation.signIn.bind(emailPasswordRecipeImplementation_1.default(this))(input); }); }, thirdPartySignInUp: function (input) { @@ -61,38 +35,28 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { throw new Error("No thirdparty provider configured"); } - return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))( - input - ); + return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))(input); }); }, getUserById: function (input) { return __awaiter(this, void 0, void 0, function* () { - let user = yield originalEmailPasswordImplementation.getUserById.bind( - emailPasswordRecipeImplementation_1.default(this) - )(input); + let user = yield originalEmailPasswordImplementation.getUserById.bind(emailPasswordRecipeImplementation_1.default(this))(input); if (user !== undefined) { return user; } if (originalThirdPartyImplementation === undefined) { return undefined; } - return yield originalThirdPartyImplementation.getUserById.bind( - thirdPartyRecipeImplementation_1.default(this) - )(input); + return yield originalThirdPartyImplementation.getUserById.bind(thirdPartyRecipeImplementation_1.default(this))(input); }); }, getUsersByEmail: function ({ email, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let userFromEmailPass = yield originalEmailPasswordImplementation.getUserByEmail.bind( - emailPasswordRecipeImplementation_1.default(this) - )({ email, userContext }); + let userFromEmailPass = yield originalEmailPasswordImplementation.getUserByEmail.bind(emailPasswordRecipeImplementation_1.default(this))({ email, userContext }); if (originalThirdPartyImplementation === undefined) { return userFromEmailPass === undefined ? [] : [userFromEmailPass]; } - let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind( - thirdPartyRecipeImplementation_1.default(this) - )({ email, userContext }); + let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind(thirdPartyRecipeImplementation_1.default(this))({ email, userContext }); if (userFromEmailPass !== undefined) { return [...usersFromThirdParty, userFromEmailPass]; } @@ -104,23 +68,17 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { return undefined; } - return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind( - thirdPartyRecipeImplementation_1.default(this) - )(input); + return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind(thirdPartyRecipeImplementation_1.default(this))(input); }); }, createResetPasswordToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.createResetPasswordToken.bind( - emailPasswordRecipeImplementation_1.default(this) - )(input); + return originalEmailPasswordImplementation.createResetPasswordToken.bind(emailPasswordRecipeImplementation_1.default(this))(input); }); }, resetPasswordUsingToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.resetPasswordUsingToken.bind( - emailPasswordRecipeImplementation_1.default(this) - )(input); + return originalEmailPasswordImplementation.resetPasswordUsingToken.bind(emailPasswordRecipeImplementation_1.default(this))(input); }); }, updateEmailOrPassword: function (input) { @@ -130,12 +88,11 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { return { status: "UNKNOWN_USER_ID_ERROR", }; - } else if (user.thirdParty !== undefined) { + } + else if (user.thirdParty !== undefined) { throw new Error("Cannot update email or password of a user who signed up using third party login."); } - return originalEmailPasswordImplementation.updateEmailOrPassword.bind( - emailPasswordRecipeImplementation_1.default(this) - )(input); + return originalEmailPasswordImplementation.updateEmailOrPassword.bind(emailPasswordRecipeImplementation_1.default(this))(input); }); }, }; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts index fc596f02a..2ede71963 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "../../thirdparty/types"; import { RecipeInterface as ThirdPartyEmailPasswordRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPasswordRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js index 1b2784d4e..63b33a0c1 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartyemailpassword/types.d.ts b/lib/build/recipe/thirdpartyemailpassword/types.d.ts index 2abd1a64d..83d111b58 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -1,20 +1,8 @@ -// @ts-nocheck import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; -import { - NormalisedFormField, - TypeFormField, - TypeInputFormField, - TypeInputResetPasswordUsingTokenFeature, - APIOptions as EmailPasswordAPIOptionsOriginal, - TypeEmailPasswordEmailDeliveryInput, - RecipeInterface as EPRecipeInterface, -} from "../emailpassword/types"; +import { NormalisedFormField, TypeFormField, TypeInputFormField, TypeInputResetPasswordUsingTokenFeature, APIOptions as EmailPasswordAPIOptionsOriginal, TypeEmailPasswordEmailDeliveryInput, RecipeInterface as EPRecipeInterface } from "../emailpassword/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { - TypeInput as EmailDeliveryTypeInput, - TypeInputWithService as EmailDeliveryTypeInputWithService, -} from "../../ingredients/emaildelivery/types"; +import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; import { GeneralErrorResponse } from "../../types"; export declare type User = { id: string; @@ -49,32 +37,29 @@ export declare type TypeInput = { emailDelivery?: EmailDeliveryTypeInput; resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { signUpFeature: TypeNormalisedInputSignUp; providers: TypeProvider[]; - getEmailDeliveryConfig: ( - emailPasswordRecipeImpl: EPRecipeInterface, - isInServerlessEnv: boolean - ) => EmailDeliveryTypeInputWithService; + getEmailDeliveryConfig: (emailPasswordRecipeImpl: EPRecipeInterface, isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getUserById(input: { userId: string; userContext: any }): Promise; - getUsersByEmail(input: { email: string; userContext: any }): Promise; + getUserById(input: { + userId: string; + userContext: any; + }): Promise; + getUsersByEmail(input: { + email: string; + userContext: any; + }): Promise; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -94,55 +79,43 @@ export declare type RecipeInterface = { email: string; password: string; userContext: any; - }): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + }>; emailPasswordSignIn(input: { email: string; password: string; userContext: any; - }): Promise< - | { - status: "OK"; - user: User; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + user: User; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + }>; createResetPasswordToken(input: { userId: string; email: string; userContext: any; - }): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "UNKNOWN_USER_ID_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + token: string; + } | { + status: "UNKNOWN_USER_ID_ERROR"; + }>; resetPasswordUsingToken(input: { token: string; newPassword: string; userContext: any; - }): Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + email: string; + userId: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; updateEmailOrPassword(input: { userId: string; email?: string; @@ -155,232 +128,174 @@ export declare type RecipeInterface = { export declare type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; export declare type ThirdPartyAPIOptions = ThirdPartyAPIOptionsOriginal; export declare type APIInterface = { - linkThirdPartyAccountToExistingAccountPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - session: SessionContainerInterface; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - authCodeResponse: any; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); - authorisationUrlGET: - | undefined - | ((input: { - provider: TypeProvider; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - url: string; - } - | GeneralErrorResponse - >); - emailPasswordEmailExistsGET: - | undefined - | ((input: { - email: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >); - generatePasswordResetTokenPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - } - | { - status: "PASSWORD_RESET_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); - passwordResetPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - | GeneralErrorResponse - >); - thirdPartySignInUpPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } - | GeneralErrorResponse - | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - | { - status: "SIGNIN_NOT_ALLOWED"; - primaryUserId: string; - description: string; - } - >); - linkEmailPasswordAccountToExistingAccountPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - session: SessionContainerInterface; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); - emailPasswordSignInPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - | GeneralErrorResponse - >); - emailPasswordSignUpPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewUser: boolean; - session: SessionContainerInterface; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); - appleRedirectHandlerPOST: - | undefined - | ((input: { code: string; state: string; options: ThirdPartyAPIOptions; userContext: any }) => Promise); + linkThirdPartyAccountToExistingAccountPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + session: SessionContainerInterface; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + authCodeResponse: any; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } | GeneralErrorResponse>); + authorisationUrlGET: undefined | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + url: string; + } | GeneralErrorResponse>); + emailPasswordEmailExistsGET: undefined | ((input: { + email: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + } | GeneralErrorResponse>); + generatePasswordResetTokenPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + } | { + status: "PASSWORD_RESET_NOT_ALLOWED"; + reason: string; + } | GeneralErrorResponse>); + passwordResetPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + email: string; + userId: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } | GeneralErrorResponse>); + thirdPartySignInUpPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } | GeneralErrorResponse | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } | { + status: "SIGNIN_NOT_ALLOWED"; + primaryUserId: string; + description: string; + }>); + linkEmailPasswordAccountToExistingAccountPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + session: SessionContainerInterface; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } | GeneralErrorResponse>); + emailPasswordSignInPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + session: SessionContainerInterface; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + } | GeneralErrorResponse>); + emailPasswordSignUpPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewUser: boolean; + session: SessionContainerInterface; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } | GeneralErrorResponse>); + appleRedirectHandlerPOST: undefined | ((input: { + code: string; + state: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise); }; export declare type TypeThirdPartyEmailPasswordEmailDeliveryInput = TypeEmailPasswordEmailDeliveryInput; diff --git a/lib/build/recipe/thirdpartyemailpassword/utils.d.ts b/lib/build/recipe/thirdpartyemailpassword/utils.d.ts index 60b02c8b9..ff87c17db 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/utils.d.ts @@ -1,9 +1,4 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; import Recipe from "./recipe"; -export declare function validateAndNormaliseUserInput( - recipeInstance: Recipe, - appInfo: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/thirdpartyemailpassword/utils.js b/lib/build/recipe/thirdpartyemailpassword/utils.js index 7ef3b2d23..8ad1968a0 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.js +++ b/lib/build/recipe/thirdpartyemailpassword/utils.js @@ -14,29 +14,17 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormaliseUserInput = void 0; const utils_1 = require("../emailpassword/utils"); const backwardCompatibility_1 = require("./emaildelivery/services/backwardCompatibility"); function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { - let signUpFeature = validateAndNormaliseSignUpConfig( - recipeInstance, - appInfo, - config === undefined ? undefined : config.signUpFeature - ); + let signUpFeature = validateAndNormaliseSignUpConfig(recipeInstance, appInfo, config === undefined ? undefined : config.signUpFeature); let resetPasswordUsingTokenFeature = config === undefined ? undefined : config.resetPasswordUsingTokenFeature; let providers = config === undefined || config.providers === undefined ? [] : config.providers; - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); function getEmailDeliveryConfig(emailPasswordRecipeImpl, isInServerlessEnv) { var _a; - let emailService = - (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 - ? void 0 - : _a.service; + let emailService = (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; /** * following code is for backward compatibility. * if user has not passed emailDelivery config, we @@ -45,14 +33,9 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { * createAndSendCustomEmail implementation */ if (emailService === undefined) { - emailService = new backwardCompatibility_1.default( - emailPasswordRecipeImpl, - appInfo, - isInServerlessEnv, - config === null || config === void 0 ? void 0 : config.resetPasswordUsingTokenFeature - ); + emailService = new backwardCompatibility_1.default(emailPasswordRecipeImpl, appInfo, isInServerlessEnv, config === null || config === void 0 ? void 0 : config.resetPasswordUsingTokenFeature); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -64,8 +47,7 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService, - }); + service: emailService }); } return { override, diff --git a/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts b/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts index 0218549fa..75c1214f2 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/api/implementation.js b/lib/build/recipe/thirdpartypasswordless/api/implementation.js index 5e16c51f5..94e59a0ae 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/implementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/implementation.js @@ -9,46 +9,16 @@ function getAPIImplementation() { let passwordlessImplementation = implementation_1.default(); let thirdPartyImplementation = implementation_2.default(); return { - consumeCodePOST: - (_a = passwordlessImplementation.consumeCodePOST) === null || _a === void 0 - ? void 0 - : _a.bind(passwordlessAPIImplementation_1.default(this)), - createCodePOST: - (_b = passwordlessImplementation.createCodePOST) === null || _b === void 0 - ? void 0 - : _b.bind(passwordlessAPIImplementation_1.default(this)), - passwordlessUserEmailExistsGET: - (_c = passwordlessImplementation.emailExistsGET) === null || _c === void 0 - ? void 0 - : _c.bind(passwordlessAPIImplementation_1.default(this)), - passwordlessUserPhoneNumberExistsGET: - (_d = passwordlessImplementation.phoneNumberExistsGET) === null || _d === void 0 - ? void 0 - : _d.bind(passwordlessAPIImplementation_1.default(this)), - linkThirdPartyAccountToExistingAccountPOST: - (_e = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _e === void 0 - ? void 0 - : _e.bind(thirdPartyAPIImplementation_1.default(this)), - resendCodePOST: - (_f = passwordlessImplementation.resendCodePOST) === null || _f === void 0 - ? void 0 - : _f.bind(passwordlessAPIImplementation_1.default(this)), - authorisationUrlGET: - (_g = thirdPartyImplementation.authorisationUrlGET) === null || _g === void 0 - ? void 0 - : _g.bind(thirdPartyAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: - (_h = thirdPartyImplementation.signInUpPOST) === null || _h === void 0 - ? void 0 - : _h.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: - (_j = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _j === void 0 - ? void 0 - : _j.bind(thirdPartyAPIImplementation_1.default(this)), - linkPasswordlessAccountToExistingAccountPOST: - (_k = passwordlessImplementation.linkAccountToExistingAccountPOST) === null || _k === void 0 - ? void 0 - : _k.bind(passwordlessAPIImplementation_1.default(this)), + consumeCodePOST: (_a = passwordlessImplementation.consumeCodePOST) === null || _a === void 0 ? void 0 : _a.bind(passwordlessAPIImplementation_1.default(this)), + createCodePOST: (_b = passwordlessImplementation.createCodePOST) === null || _b === void 0 ? void 0 : _b.bind(passwordlessAPIImplementation_1.default(this)), + passwordlessUserEmailExistsGET: (_c = passwordlessImplementation.emailExistsGET) === null || _c === void 0 ? void 0 : _c.bind(passwordlessAPIImplementation_1.default(this)), + passwordlessUserPhoneNumberExistsGET: (_d = passwordlessImplementation.phoneNumberExistsGET) === null || _d === void 0 ? void 0 : _d.bind(passwordlessAPIImplementation_1.default(this)), + linkThirdPartyAccountToExistingAccountPOST: (_e = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _e === void 0 ? void 0 : _e.bind(thirdPartyAPIImplementation_1.default(this)), + resendCodePOST: (_f = passwordlessImplementation.resendCodePOST) === null || _f === void 0 ? void 0 : _f.bind(passwordlessAPIImplementation_1.default(this)), + authorisationUrlGET: (_g = thirdPartyImplementation.authorisationUrlGET) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: (_h = thirdPartyImplementation.signInUpPOST) === null || _h === void 0 ? void 0 : _h.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: (_j = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _j === void 0 ? void 0 : _j.bind(thirdPartyAPIImplementation_1.default(this)), + linkPasswordlessAccountToExistingAccountPOST: (_k = passwordlessImplementation.linkAccountToExistingAccountPOST) === null || _k === void 0 ? void 0 : _k.bind(passwordlessAPIImplementation_1.default(this)), }; } exports.default = getAPIImplementation; diff --git a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts index e37fd1b22..2f1494c18 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface } from "../../passwordless"; import { APIInterface as ThirdPartyPasswordlessAPIInterface } from "../types"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyPasswordlessAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js index 321f35dd6..e111bc8d9 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js @@ -3,24 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e, _f; return { - emailExistsGET: - (_a = apiImplmentation.passwordlessUserEmailExistsGET) === null || _a === void 0 - ? void 0 - : _a.bind(apiImplmentation), - consumeCodePOST: - (_b = apiImplmentation.consumeCodePOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), - createCodePOST: - (_c = apiImplmentation.createCodePOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - phoneNumberExistsGET: - (_d = apiImplmentation.passwordlessUserPhoneNumberExistsGET) === null || _d === void 0 - ? void 0 - : _d.bind(apiImplmentation), - resendCodePOST: - (_e = apiImplmentation.resendCodePOST) === null || _e === void 0 ? void 0 : _e.bind(apiImplmentation), - linkAccountToExistingAccountPOST: - (_f = apiImplmentation.linkPasswordlessAccountToExistingAccountPOST) === null || _f === void 0 - ? void 0 - : _f.bind(apiImplmentation), + emailExistsGET: (_a = apiImplmentation.passwordlessUserEmailExistsGET) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation), + consumeCodePOST: (_b = apiImplmentation.consumeCodePOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), + createCodePOST: (_c = apiImplmentation.createCodePOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + phoneNumberExistsGET: (_d = apiImplmentation.passwordlessUserPhoneNumberExistsGET) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), + resendCodePOST: (_e = apiImplmentation.resendCodePOST) === null || _e === void 0 ? void 0 : _e.bind(apiImplmentation), + linkAccountToExistingAccountPOST: (_f = apiImplmentation.linkPasswordlessAccountToExistingAccountPOST) === null || _f === void 0 ? void 0 : _f.bind(apiImplmentation), }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts index 11fc459c9..a61dbd963 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { APIInterface } from "../../thirdparty"; import { APIInterface as ThirdPartyPasswordlessAPIInterface } from "../types"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyPasswordlessAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js index 83eca8723..71b87509c 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js @@ -1,89 +1,49 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d; - const signInUpPOSTFromThirdPartyPasswordless = - (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); - const linkThirdPartyAccountToExistingAccountPOST = - (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 - ? void 0 - : _b.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyPasswordless = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const linkThirdPartyAccountToExistingAccountPOST = (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation); return { - authorisationUrlGET: - (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - appleRedirectHandlerPOST: - (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 - ? void 0 - : _d.bind(apiImplmentation), - linkAccountToExistingAccountPOST: - linkThirdPartyAccountToExistingAccountPOST === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield linkThirdPartyAccountToExistingAccountPOST(input); - if (result.status === "OK") { - if (!("thirdParty" in result.user)) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { - user: Object.assign(Object.assign({}, result.user), { - thirdParty: Object.assign({}, result.user.thirdParty), - }), - }); - } - return result; - }); - }, - signInUpPOST: - signInUpPOSTFromThirdPartyPasswordless === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield signInUpPOSTFromThirdPartyPasswordless(input); - if (result.status === "OK") { - if (!("thirdParty" in result.user)) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { - user: Object.assign(Object.assign({}, result.user), { - thirdParty: Object.assign({}, result.user.thirdParty), - }), - }); - } - return result; - }); - }, + authorisationUrlGET: (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + appleRedirectHandlerPOST: (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), + linkAccountToExistingAccountPOST: linkThirdPartyAccountToExistingAccountPOST === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield linkThirdPartyAccountToExistingAccountPOST(input); + if (result.status === "OK") { + if (!("thirdParty" in result.user)) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); + } + return result; + }); + }, + signInUpPOST: signInUpPOSTFromThirdPartyPasswordless === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield signInUpPOSTFromThirdPartyPasswordless(input); + if (result.status === "OK") { + if (!("thirdParty" in result.user)) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); + } + return result; + }); + }, }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts index b7b92a0c1..e441c1824 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,28 +1,18 @@ -// @ts-nocheck import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService - implements EmailDeliveryInterface { +export default class BackwardCompatibilityService implements EmailDeliveryInterface { private passwordlessBackwardCompatibilityService; - constructor( - appInfo: NormalisedAppinfo, - passwordlessFeature?: { - createAndSendCustomEmail?: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - ); - sendEmail: ( - input: import("../../../../passwordless/types").TypePasswordlessEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + constructor(appInfo: NormalisedAppinfo, passwordlessFeature?: { + createAndSendCustomEmail?: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + }); + sendEmail: (input: TypeThirdPartyPasswordlessEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js index 3a4698b79..5a1313aa3 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js @@ -1,50 +1,22 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const backwardCompatibility_1 = require("../../../../passwordless/emaildelivery/services/backwardCompatibility"); class BackwardCompatibilityService { constructor(appInfo, passwordlessFeature) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessBackwardCompatibilityService.sendEmail(input); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessBackwardCompatibilityService.sendEmail(input); + }); { - this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default( - appInfo, - passwordlessFeature === null || passwordlessFeature === void 0 - ? void 0 - : passwordlessFeature.createAndSendCustomEmail - ); + this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default(appInfo, passwordlessFeature === null || passwordlessFeature === void 0 ? void 0 : passwordlessFeature.createAndSendCustomEmail); } } } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts index 4de04d983..dd2ef062c 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js index b38b12ec2..9a1dcbe44 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.SMTPService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts index 48d0bf26c..c60364839 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; @@ -6,9 +5,7 @@ export default class SMTPService implements EmailDeliveryInterface; private passwordlessSMTPService; constructor(config: TypeInput); - sendEmail: ( - input: import("../../../../passwordless/types").TypePasswordlessEmailDeliveryInput & { - userContext: any; - } - ) => Promise; + sendEmail: (input: TypeThirdPartyPasswordlessEmailDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js index fff948d60..f4ac99189 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = require("supertokens-js-override"); @@ -38,10 +16,9 @@ const smtp_1 = require("../../../../passwordless/emaildelivery/services/smtp"); const passwordlessServiceImplementation_1 = require("./serviceImplementation/passwordlessServiceImplementation"); class SMTPService { constructor(config) { - this.sendEmail = (input) => - __awaiter(this, void 0, void 0, function* () { - return yield this.passwordlessSMTPService.sendEmail(input); - }); + this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { + return yield this.passwordlessSMTPService.sendEmail(input); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -51,9 +28,7 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default( - serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) - ); + let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts index 87aab5100..52077572f 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts @@ -1,11 +1,7 @@ -// @ts-nocheck import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation( - transporter: Transporter, - from: { - name: string; - email: string; - } -): ServiceInterface; +export declare function getServiceImplementation(transporter: Transporter, from: { + name: string; + email: string; +}): ServiceInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js index 1a201561a..ba9132994 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getServiceImplementation = void 0; const serviceImplementation_1 = require("../../../../../passwordless/emaildelivery/services/smtp/serviceImplementation"); const passwordlessServiceImplementation_1 = require("./passwordlessServiceImplementation"); function getServiceImplementation(transporter, from) { @@ -62,9 +41,7 @@ function getServiceImplementation(transporter, from) { }, getContent: function (input) { return __awaiter(this, void 0, void 0, function* () { - return yield passwordlessServiceImpl.getContent.bind(passwordlessServiceImplementation_1.default(this))( - input - ); + return yield passwordlessServiceImpl.getContent.bind(passwordlessServiceImplementation_1.default(this))(input); }); }, }; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts index 0a0cece68..416506b0d 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../../types"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; import { TypePasswordlessEmailDeliveryInput } from "../../../../../passwordless/types"; -export default function getServiceInterface( - thirdpartyPasswordlessServiceImplementation: ServiceInterface -): ServiceInterface; +export default function getServiceInterface(thirdpartyPasswordlessServiceImplementation: ServiceInterface): ServiceInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js index 9da544281..248634b1f 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getServiceInterface(thirdpartyPasswordlessServiceImplementation) { return { diff --git a/lib/build/recipe/thirdpartypasswordless/error.d.ts b/lib/build/recipe/thirdpartypasswordless/error.d.ts index 1d9c33665..3dc8820ff 100644 --- a/lib/build/recipe/thirdpartypasswordless/error.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/error.d.ts @@ -1,5 +1,7 @@ -// @ts-nocheck import STError from "../../error"; export default class ThirdPartyEmailPasswordError extends STError { - constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); + constructor(options: { + type: "BAD_INPUT_ERROR"; + message: string; + }); } diff --git a/lib/build/recipe/thirdpartypasswordless/index.d.ts b/lib/build/recipe/thirdpartypasswordless/index.d.ts index 06419ad69..7052f81b6 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/index.d.ts @@ -1,94 +1,27 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; -import { - RecipeInterface, - User, - APIInterface, - PasswordlessAPIOptions, - ThirdPartyAPIOptions, - TypeThirdPartyPasswordlessEmailDeliveryInput, -} from "./types"; +import { RecipeInterface, User, APIInterface, PasswordlessAPIOptions, ThirdPartyAPIOptions, TypeThirdPartyPasswordlessEmailDeliveryInput } from "./types"; import { TypeProvider } from "../thirdparty/types"; import { TypePasswordlessSmsDeliveryInput } from "../passwordless/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp( - thirdPartyId: string, - thirdPartyUserId: string, - email: string, - userContext?: any - ): Promise<{ + static thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ status: "OK"; createdNewUser: boolean; user: User; }>; - static getUserByThirdPartyInfo( - thirdPartyId: string, - thirdPartyUserId: string, - userContext?: any - ): Promise< - | ({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - recipeUserId: string; - timeJoined: number; - }) - | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - recipeUserId: string; - timeJoined: number; - }) - | undefined - >; - static getUserById( - userId: string, - userContext?: any - ): Promise< - | ({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - recipeUserId: string; - timeJoined: number; - }) - | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - recipeUserId: string; - timeJoined: number; - }) - | undefined - >; + static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; + static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise; - static createCode( - input: ( - | { - email: string; - } - | { - phoneNumber: string; - } - ) & { - userInputCode?: string; - userContext?: any; - } - ): Promise<{ + static createCode(input: ({ + email: string; + } | { + phoneNumber: string; + }) & { + userInputCode?: string; + userContext?: any; + }): Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -102,74 +35,42 @@ export default class Wrapper { deviceId: string; userInputCode?: string; userContext?: any; - }): Promise< - | { - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } - | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - } - >; - static consumeCode( - input: - | { - preAuthSessionId: string; - userInputCode: string; - deviceId: string; - userContext?: any; - } - | { - preAuthSessionId: string; - linkCode: string; - userContext?: any; - } - ): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | { - status: "RESTART_FLOW_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + }>; + static consumeCode(input: { + preAuthSessionId: string; + userInputCode: string; + deviceId: string; + userContext?: any; + } | { + preAuthSessionId: string; + linkCode: string; + userContext?: any; + }): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | { + status: "RESTART_FLOW_ERROR"; + }>; static getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any; - }): Promise< - | ({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - recipeUserId: string; - timeJoined: number; - }) - | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - recipeUserId: string; - timeJoined: number; - }) - | undefined - >; + }): Promise; static updatePasswordlessUser(input: { userId: string; email?: string | null; @@ -178,17 +79,13 @@ export default class Wrapper { }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - static revokeAllCodes( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ): Promise<{ + static revokeAllCodes(input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }): Promise<{ status: "OK"; }>; static revokeCode(input: { @@ -213,28 +110,20 @@ export default class Wrapper { preAuthSessionId: string; userContext?: any; }): Promise; - static createMagicLink( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ): Promise; - static passwordlessSignInUp( - input: - | { - email: string; - userContext?: any; - } - | { - phoneNumber: string; - userContext?: any; - } - ): Promise<{ + static createMagicLink(input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }): Promise; + static passwordlessSignInUp(input: { + email: string; + userContext?: any; + } | { + phoneNumber: string; + userContext?: any; + }): Promise<{ status: string; createdNewUser: boolean; user: import("../passwordless/types").User; @@ -245,16 +134,12 @@ export default class Wrapper { static Apple: typeof import("../thirdparty/providers/apple").default; static Discord: typeof import("../thirdparty/providers/discord").default; static GoogleWorkspaces: typeof import("../thirdparty/providers/googleWorkspaces").default; - static sendEmail( - input: TypeThirdPartyPasswordlessEmailDeliveryInput & { - userContext?: any; - } - ): Promise; - static sendSms( - input: TypePasswordlessSmsDeliveryInput & { - userContext?: any; - } - ): Promise; + static sendEmail(input: TypeThirdPartyPasswordlessEmailDeliveryInput & { + userContext?: any; + }): Promise; + static sendSms(input: TypePasswordlessSmsDeliveryInput & { + userContext?: any; + }): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/thirdpartypasswordless/index.js b/lib/build/recipe/thirdpartypasswordless/index.js index 3e8df16fc..94764a81e 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.js +++ b/lib/build/recipe/thirdpartypasswordless/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.sendSms = exports.sendEmail = exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.createMagicLink = exports.revokeCode = exports.revokeAllCodes = exports.updatePasswordlessUser = exports.createNewCodeForDevice = exports.listCodesByPreAuthSessionId = exports.listCodesByPhoneNumber = exports.listCodesByEmail = exports.listCodesByDeviceId = exports.getUserByPhoneNumber = exports.consumeCode = exports.createCode = exports.getUsersByEmail = exports.getUserByThirdPartyInfo = exports.getUserById = exports.passwordlessSignInUp = exports.thirdPartySignInUp = exports.Error = exports.init = void 0; const recipe_1 = require("./recipe"); const error_1 = require("./error"); const thirdPartyProviders = require("../thirdparty/providers"); @@ -71,84 +50,54 @@ class Wrapper { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsersByEmail({ email, userContext }); } static createCode(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); } static createNewCodeForDevice(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); } static consumeCode(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); } static getUserByPhoneNumber(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); } static updatePasswordlessUser(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.updatePasswordlessUser(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updatePasswordlessUser(Object.assign({ userContext: {} }, input)); } static revokeAllCodes(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); } static revokeCode(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); } static listCodesByEmail(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); } static listCodesByPhoneNumber(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); } static listCodesByDeviceId(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); } static listCodesByPreAuthSessionId(input) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); } static createMagicLink(input) { - return recipe_1.default - .getInstanceOrThrowError() - .passwordlessRecipe.createMagicLink(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().passwordlessRecipe.createMagicLink(Object.assign({ userContext: {} }, input)); } static passwordlessSignInUp(input) { - return recipe_1.default - .getInstanceOrThrowError() - .passwordlessRecipe.signInUp(Object.assign({ userContext: {} }, input)); + return recipe_1.default.getInstanceOrThrowError().passwordlessRecipe.signInUp(Object.assign({ userContext: {} }, input)); } // static Okta = thirdPartyProviders.Okta; // static ActiveDirectory = thirdPartyProviders.ActiveDirectory; static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default.getInstanceOrThrowError().emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } static sendSms(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default - .getInstanceOrThrowError() - .smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default.getInstanceOrThrowError().smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); }); } } diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts index 25149cc86..9e5128bd3 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts @@ -1,18 +1,10 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import PasswordlessRecipe from "../passwordless/recipe"; import ThirdPartyRecipe from "../thirdparty/recipe"; import { BaseRequest, BaseResponse } from "../../framework"; import STError from "./error"; -import { - TypeInput, - TypeNormalisedInput, - RecipeInterface, - APIInterface, - TypeThirdPartyPasswordlessEmailDeliveryInput, - TypeThirdPartyPasswordlessSmsDeliveryInput, -} from "./types"; +import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, TypeThirdPartyPasswordlessEmailDeliveryInput, TypeThirdPartyPasswordlessSmsDeliveryInput } from "./types"; import STErrorPasswordless from "../passwordless/error"; import STErrorThirdParty from "../thirdparty/error"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -29,36 +21,19 @@ export default class Recipe extends RecipeModule { emailDelivery: EmailDeliveryIngredient; smsDelivery: SmsDeliveryIngredient; isInServerlessEnv: boolean; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - recipes: { - thirdPartyInstance: ThirdPartyRecipe | undefined; - passwordlessInstance: PasswordlessRecipe | undefined; - }, - ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - smsDelivery: SmsDeliveryIngredient | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { + thirdPartyInstance: ThirdPartyRecipe | undefined; + passwordlessInstance: PasswordlessRecipe | undefined; + }, ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + smsDelivery: SmsDeliveryIngredient | undefined; + }); static init(config: TypeInput): RecipeListFunction; static reset(): void; static getInstanceOrThrowError(): Recipe; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: ( - id: string, - req: BaseRequest, - res: BaseResponse, - path: NormalisedURLPath, - method: HTTPMethod - ) => Promise; - handleError: ( - err: STErrorThirdParty | STErrorPasswordless, - request: BaseRequest, - response: BaseResponse - ) => Promise; + handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; + handleError: (err: STErrorPasswordless | STErrorThirdParty, request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; } diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.js b/lib/build/recipe/thirdpartypasswordless/recipe.js index c1288df14..d748ddf89 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.js +++ b/lib/build/recipe/thirdpartypasswordless/recipe.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -70,35 +48,30 @@ class Recipe extends recipeModule_1.default { } return apisHandled; }; - this.handleAPIRequest = (id, req, res, path, method) => - __awaiter(this, void 0, void 0, function* () { - if (this.passwordlessRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { - return yield this.passwordlessRecipe.handleAPIRequest(id, req, res, path, method); - } - if ( - this.thirdPartyRecipe !== undefined && - this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined - ) { - return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); + this.handleAPIRequest = (id, req, res, path, method) => __awaiter(this, void 0, void 0, function* () { + if (this.passwordlessRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { + return yield this.passwordlessRecipe.handleAPIRequest(id, req, res, path, method); + } + if (this.thirdPartyRecipe !== undefined && + this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { + return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); + } + return false; + }); + this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + throw err; + } + else { + if (this.passwordlessRecipe.isErrorFromThisRecipe(err)) { + return yield this.passwordlessRecipe.handleError(err, request, response); } - return false; - }); - this.handleError = (err, request, response) => - __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - throw err; - } else { - if (this.passwordlessRecipe.isErrorFromThisRecipe(err)) { - return yield this.passwordlessRecipe.handleError(err, request, response); - } else if ( - this.thirdPartyRecipe !== undefined && - this.thirdPartyRecipe.isErrorFromThisRecipe(err) - ) { - return yield this.thirdPartyRecipe.handleError(err, request, response); - } - throw err; + else if (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)) { + return yield this.thirdPartyRecipe.handleError(err, request, response); } - }); + throw err; + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [...this.passwordlessRecipe.getAllCORSHeaders()]; if (this.thirdPartyRecipe !== undefined) { @@ -107,22 +80,15 @@ class Recipe extends recipeModule_1.default { return corsHeaders; }; this.isErrorFromThisRecipe = (err) => { - return ( - error_1.default.isErrorFromSuperTokens(err) && + return (error_1.default.isErrorFromSuperTokens(err) && (err.fromRecipe === Recipe.RECIPE_ID || this.passwordlessRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) - ); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); }; this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default( - querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), - querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID) - ) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -131,9 +97,7 @@ class Recipe extends recipeModule_1.default { } this.emailDelivery = ingredients.emailDelivery === undefined - ? new emaildelivery_1.default( - this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) - ) + ? new emaildelivery_1.default(this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv)) : ingredients.emailDelivery; this.smsDelivery = ingredients.smsDelivery === undefined @@ -142,75 +106,52 @@ class Recipe extends recipeModule_1.default { this.passwordlessRecipe = recipes.passwordlessInstance !== undefined ? recipes.passwordlessInstance - : new recipe_1.default( - recipeId, - appInfo, - isInServerlessEnv, - Object.assign(Object.assign({}, this.config), { - override: { - functions: (_) => { - return passwordlessRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return passwordlessAPIImplementation_1.default(this.apiImpl); - }, - }, - }), - { - emailDelivery: this.emailDelivery, - smsDelivery: this.smsDelivery, - } - ); + : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign(Object.assign({}, this.config), { override: { + functions: (_) => { + return passwordlessRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return passwordlessAPIImplementation_1.default(this.apiImpl); + }, + } }), { + emailDelivery: this.emailDelivery, + smsDelivery: this.smsDelivery, + }); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_2.default( - recipeId, - appInfo, - isInServerlessEnv, - { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, - {}, - { - emailDelivery: this.emailDelivery, - } - ); + : new recipe_2.default(recipeId, appInfo, isInServerlessEnv, { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, {}, { + emailDelivery: this.emailDelivery, + }); } } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe( - Recipe.RECIPE_ID, - appInfo, - isInServerlessEnv, - config, - { - passwordlessInstance: undefined, - thirdPartyInstance: undefined, - }, - { - emailDelivery: undefined, - smsDelivery: undefined, - } - ); + Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config, { + passwordlessInstance: undefined, + thirdPartyInstance: undefined, + }, { + emailDelivery: undefined, + smsDelivery: undefined, + }); return Recipe.instance; - } else { - throw new Error( - "ThirdPartyPasswordless recipe has already been initialised. Please check your code for bugs." - ); + } + else { + throw new Error("ThirdPartyPasswordless recipe has already been initialised. Please check your code for bugs."); } }; } diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts index d2d6c2bc2..eb5a8e6a8 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "../types"; import { Querier } from "../../../querier"; export default function getRecipeInterface(passwordlessQuerier: Querier, thirdPartyQuerier?: Querier): RecipeInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js index b1a29cf06..9781499b7 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const recipeImplementation_1 = require("../../passwordless/recipeImplementation"); const recipeImplementation_2 = require("../../thirdparty/recipeImplementation"); @@ -44,72 +22,52 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { return { consumeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.consumeCode.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.consumeCode.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, createCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.createCode.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.createCode.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, createNewCodeForDevice: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.createNewCodeForDevice.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.createNewCodeForDevice.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, getUserByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.getUserByPhoneNumber.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.getUserByPhoneNumber.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, listCodesByDeviceId: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByDeviceId.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.listCodesByDeviceId.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, listCodesByEmail: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByEmail.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.listCodesByEmail.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, listCodesByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByPhoneNumber.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.listCodesByPhoneNumber.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, listCodesByPreAuthSessionId: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByPreAuthSessionId.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.listCodesByPreAuthSessionId.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, revokeAllCodes: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.revokeAllCodes.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.revokeAllCodes.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, revokeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.revokeCode.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + return originalPasswordlessImplementation.revokeCode.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, updatePasswordlessUser: function (input) { @@ -119,14 +77,11 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { return { status: "UNKNOWN_USER_ID_ERROR", }; - } else if ("thirdParty" in user) { - throw new Error( - "Cannot update passwordless user info for those who signed up using third party login." - ); } - return originalPasswordlessImplementation.updateUser.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + else if ("thirdParty" in user) { + throw new Error("Cannot update passwordless user info for those who signed up using third party login."); + } + return originalPasswordlessImplementation.updateUser.bind(passwordlessRecipeImplementation_1.default(this))(input); }); }, thirdPartySignInUp: function (input) { @@ -134,38 +89,28 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { throw new Error("No thirdparty provider configured"); } - return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))( - input - ); + return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))(input); }); }, getUserById: function (input) { return __awaiter(this, void 0, void 0, function* () { - let user = yield originalPasswordlessImplementation.getUserById.bind( - passwordlessRecipeImplementation_1.default(this) - )(input); + let user = yield originalPasswordlessImplementation.getUserById.bind(passwordlessRecipeImplementation_1.default(this))(input); if (user !== undefined) { return user; } if (originalThirdPartyImplementation === undefined) { return undefined; } - return yield originalThirdPartyImplementation.getUserById.bind( - thirdPartyRecipeImplementation_1.default(this) - )(input); + return yield originalThirdPartyImplementation.getUserById.bind(thirdPartyRecipeImplementation_1.default(this))(input); }); }, getUsersByEmail: function ({ email, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let userFromEmailPass = yield originalPasswordlessImplementation.getUserByEmail.bind( - passwordlessRecipeImplementation_1.default(this) - )({ email, userContext }); + let userFromEmailPass = yield originalPasswordlessImplementation.getUserByEmail.bind(passwordlessRecipeImplementation_1.default(this))({ email, userContext }); if (originalThirdPartyImplementation === undefined) { return userFromEmailPass === undefined ? [] : [userFromEmailPass]; } - let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind( - thirdPartyRecipeImplementation_1.default(this) - )({ email, userContext }); + let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind(thirdPartyRecipeImplementation_1.default(this))({ email, userContext }); if (userFromEmailPass !== undefined) { return [...usersFromThirdParty, userFromEmailPass]; } @@ -177,9 +122,7 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { return undefined; } - return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind( - thirdPartyRecipeImplementation_1.default(this) - )(input); + return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind(thirdPartyRecipeImplementation_1.default(this))(input); }); }, }; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts index aafe44945..c61eaeb4e 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "../../passwordless/types"; import { RecipeInterface as ThirdPartyPasswordlessRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyPasswordlessRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js index 34cc8cf85..e4357e3f4 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts index b93917947..283d09f72 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "../../thirdparty/types"; import { RecipeInterface as ThirdPartyPasswordlessRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyPasswordlessRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js index 715a0171f..156808814 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js @@ -1,35 +1,13 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts index 0bc1c09c4..746e6d8e1 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts @@ -1,28 +1,18 @@ -// @ts-nocheck import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; -export default class BackwardCompatibilityService - implements SmsDeliveryInterface { +export default class BackwardCompatibilityService implements SmsDeliveryInterface { private passwordlessBackwardCompatibilityService; - constructor( - appInfo: NormalisedAppinfo, - passwordlessFeature?: { - createAndSendCustomTextMessage?: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - ); - sendSms: ( - input: import("../../../../passwordless/types").TypePasswordlessSmsDeliveryInput & { - userContext: any; - } - ) => Promise; + constructor(appInfo: NormalisedAppinfo, passwordlessFeature?: { + createAndSendCustomTextMessage?: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + }); + sendSms: (input: TypeThirdPartyPasswordlessSmsDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js index 07e97899e..63a159055 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js @@ -1,49 +1,21 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const backwardCompatibility_1 = require("../../../../passwordless/smsdelivery/services/backwardCompatibility"); class BackwardCompatibilityService { constructor(appInfo, passwordlessFeature) { - this.sendSms = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessBackwardCompatibilityService.sendSms(input); - }); - this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default( - appInfo, - passwordlessFeature === null || passwordlessFeature === void 0 - ? void 0 - : passwordlessFeature.createAndSendCustomTextMessage - ); + this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessBackwardCompatibilityService.sendSms(input); + }); + this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default(appInfo, passwordlessFeature === null || passwordlessFeature === void 0 ? void 0 : passwordlessFeature.createAndSendCustomTextMessage); } } exports.default = BackwardCompatibilityService; diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts index f14aacf83..4e73dbb4d 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import Twilio from "./twilio"; import Supertokens from "./supertokens"; export declare let TwilioService: typeof Twilio; diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js index 562ec1b75..2be4d323e 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.SupertokensService = exports.TwilioService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts index 8fa106b5e..01fd7e9c9 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts @@ -1,12 +1,9 @@ -// @ts-nocheck import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; export default class SupertokensService implements SmsDeliveryInterface { private passwordlessSupertokensService; constructor(apiKey: string); - sendSms: ( - input: import("../../../../passwordless/types").TypePasswordlessSmsDeliveryInput & { - userContext: any; - } - ) => Promise; + sendSms: (input: TypeThirdPartyPasswordlessSmsDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js index 35b5a8739..5790c2918 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js @@ -1,43 +1,20 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_1 = require("../../../../passwordless/smsdelivery/services/supertokens"); class SupertokensService { constructor(apiKey) { - this.sendSms = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessSupertokensService.sendSms(input); - }); + this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessSupertokensService.sendSms(input); + }); this.passwordlessSupertokensService = new supertokens_1.default(apiKey); } } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts index 51ef7ac4c..5f6e15e73 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts @@ -1,13 +1,10 @@ -// @ts-nocheck import { TypeInput } from "../../../../../ingredients/smsdelivery/services/twilio"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; export default class TwilioService implements SmsDeliveryInterface { private passwordlessTwilioService; constructor(config: TypeInput); - sendSms: ( - input: import("../../../../passwordless/types").TypePasswordlessSmsDeliveryInput & { - userContext: any; - } - ) => Promise; + sendSms: (input: TypeThirdPartyPasswordlessSmsDeliveryInput & { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js index cf6eb0a7b..322596248 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js @@ -1,43 +1,20 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const index_1 = require("../../../../passwordless/smsdelivery/services/twilio/index"); class TwilioService { constructor(config) { - this.sendSms = (input) => - __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessTwilioService.sendSms(input); - }); + this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessTwilioService.sendSms(input); + }); this.passwordlessTwilioService = new index_1.default(config); } } diff --git a/lib/build/recipe/thirdpartypasswordless/types.d.ts b/lib/build/recipe/thirdpartypasswordless/types.d.ts index 41a5140d4..d8b43a8a0 100644 --- a/lib/build/recipe/thirdpartypasswordless/types.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/types.d.ts @@ -1,107 +1,76 @@ -// @ts-nocheck import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; -import { - DeviceType as DeviceTypeOriginal, - APIOptions as PasswordlessAPIOptionsOriginal, - TypePasswordlessEmailDeliveryInput, - TypePasswordlessSmsDeliveryInput, -} from "../passwordless/types"; +import { DeviceType as DeviceTypeOriginal, APIOptions as PasswordlessAPIOptionsOriginal, TypePasswordlessEmailDeliveryInput, TypePasswordlessSmsDeliveryInput } from "../passwordless/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { - TypeInput as EmailDeliveryTypeInput, - TypeInputWithService as EmailDeliveryTypeInputWithService, -} from "../../ingredients/emaildelivery/types"; -import { - TypeInput as SmsDeliveryTypeInput, - TypeInputWithService as SmsDeliveryTypeInputWithService, -} from "../../ingredients/smsdelivery/types"; +import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; +import { TypeInput as SmsDeliveryTypeInput, TypeInputWithService as SmsDeliveryTypeInputWithService } from "../../ingredients/smsdelivery/types"; import { GeneralErrorResponse } from "../../types"; export declare type DeviceType = DeviceTypeOriginal; -export declare type User = ( - | { - email?: string; - phoneNumber?: string; - } - | { - email: string; - thirdParty: { - id: string; - userId: string; - }; - } -) & { +export declare type User = ({ + email?: string; + phoneNumber?: string; +} | { + email: string; + thirdParty: { + id: string; + userId: string; + }; +}) & { id: string; recipeUserId: string; timeJoined: number; }; -export declare type TypeInput = ( - | { - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } -) & { +export declare type TypeInput = ({ + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +}) & { /** * Unlike passwordless recipe, emailDelivery config is outside here because regardless * of `contactMethod` value, the config is required for email verification recipe @@ -112,48 +81,44 @@ export declare type TypeInput = ( flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; getCustomUserInputCode?: (userContext: any) => Promise | string; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; -export declare type TypeNormalisedInput = ( - | { - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - } - | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - } -) & { +export declare type TypeNormalisedInput = ({ + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; +} | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; +} | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; +}) & { flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; getCustomUserInputCode?: (userContext: any) => Promise | string; providers: TypeProvider[]; - getEmailDeliveryConfig: ( - recipeImpl: RecipeInterface, - isInServerlessEnv: boolean - ) => EmailDeliveryTypeInputWithService; + getEmailDeliveryConfig: (recipeImpl: RecipeInterface, isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; getSmsDeliveryConfig: () => SmsDeliveryTypeInputWithService; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getUserById(input: { userId: string; userContext: any }): Promise; - getUsersByEmail(input: { email: string; userContext: any }): Promise; - getUserByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; + getUserById(input: { + userId: string; + userContext: any; + }): Promise; + getUsersByEmail(input: { + email: string; + userContext: any; + }): Promise; + getUserByPhoneNumber: (input: { + phoneNumber: string; + userContext: any; + }) => Promise; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -169,19 +134,14 @@ export declare type RecipeInterface = { createdNewUser: boolean; user: User; }>; - createCode: ( - input: ( - | { - email: string; - } - | { - phoneNumber: string; - } - ) & { - userInputCode?: string; - userContext: any; - } - ) => Promise<{ + createCode: (input: ({ + email: string; + } | { + phoneNumber: string; + }) & { + userInputCode?: string; + userContext: any; + }) => Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -195,49 +155,38 @@ export declare type RecipeInterface = { deviceId: string; userInputCode?: string; userContext: any; - }) => Promise< - | { - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } - | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - } - >; - consumeCode: ( - input: - | { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - userContext: any; - } - | { - linkCode: string; - preAuthSessionId: string; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | { - status: "RESTART_FLOW_ERROR"; - } - >; + }) => Promise<{ + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + }>; + consumeCode: (input: { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + userContext: any; + } | { + linkCode: string; + preAuthSessionId: string; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | { + status: "RESTART_FLOW_ERROR"; + }>; updatePasswordlessUser: (input: { userId: string; email?: string | null; @@ -246,17 +195,13 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - revokeAllCodes: ( - input: - | { - email: string; - userContext: any; - } - | { - phoneNumber: string; - userContext: any; - } - ) => Promise<{ + revokeAllCodes: (input: { + email: string; + userContext: any; + } | { + phoneNumber: string; + userContext: any; + }) => Promise<{ status: "OK"; }>; revokeCode: (input: { @@ -265,9 +210,18 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; - listCodesByEmail: (input: { email: string; userContext: any }) => Promise; - listCodesByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; - listCodesByDeviceId: (input: { deviceId: string; userContext: any }) => Promise; + listCodesByEmail: (input: { + email: string; + userContext: any; + }) => Promise; + listCodesByPhoneNumber: (input: { + phoneNumber: string; + userContext: any; + }) => Promise; + listCodesByDeviceId: (input: { + deviceId: string; + userContext: any; + }) => Promise; listCodesByPreAuthSessionId: (input: { preAuthSessionId: string; userContext: any; @@ -276,247 +230,174 @@ export declare type RecipeInterface = { export declare type PasswordlessAPIOptions = PasswordlessAPIOptionsOriginal; export declare type ThirdPartyAPIOptions = ThirdPartyAPIOptionsOriginal; export declare type APIInterface = { - authorisationUrlGET: - | undefined - | ((input: { - provider: TypeProvider; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - url: string; - } - | GeneralErrorResponse - >); - linkThirdPartyAccountToExistingAccountPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - session: SessionContainerInterface; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - authCodeResponse: any; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); - thirdPartySignInUpPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } - | GeneralErrorResponse - | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - | { - status: "SIGNIN_NOT_ALLOWED"; - primaryUserId: string; - description: string; - } - >); - appleRedirectHandlerPOST: - | undefined - | ((input: { code: string; state: string; options: ThirdPartyAPIOptions; userContext: any }) => Promise); - createCodePOST: - | undefined - | (( - input: ( - | { - email: string; - } - | { - phoneNumber: string; - } - ) & { - options: PasswordlessAPIOptions; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - deviceId: string; - preAuthSessionId: string; - flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; - } - | GeneralErrorResponse - >); - resendCodePOST: - | undefined - | (( - input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: PasswordlessAPIOptions; - userContext: any; - } - ) => Promise< - | GeneralErrorResponse - | { - status: "RESTART_FLOW_ERROR" | "OK"; - } - >); - consumeCodePOST: - | undefined - | (( - input: ( - | { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } - | { - linkCode: string; - preAuthSessionId: string; - } - ) & { - options: PasswordlessAPIOptions; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | GeneralErrorResponse - | { - status: "RESTART_FLOW_ERROR"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - >); - passwordlessUserEmailExistsGET: - | undefined - | ((input: { - email: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >); - passwordlessUserPhoneNumberExistsGET: - | undefined - | ((input: { - phoneNumber: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >); - linkPasswordlessAccountToExistingAccountPOST: - | undefined - | (( - input: ( - | { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } - | { - linkCode: string; - preAuthSessionId: string; - } - ) & { - session: SessionContainerInterface; - options: PasswordlessAPIOptions; - userContext: any; - } - ) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); + authorisationUrlGET: undefined | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + url: string; + } | GeneralErrorResponse>); + linkThirdPartyAccountToExistingAccountPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + session: SessionContainerInterface; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + authCodeResponse: any; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } | GeneralErrorResponse>); + thirdPartySignInUpPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } | GeneralErrorResponse | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } | { + status: "SIGNIN_NOT_ALLOWED"; + primaryUserId: string; + description: string; + }>); + appleRedirectHandlerPOST: undefined | ((input: { + code: string; + state: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise); + createCodePOST: undefined | ((input: ({ + email: string; + } | { + phoneNumber: string; + }) & { + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + deviceId: string; + preAuthSessionId: string; + flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; + } | GeneralErrorResponse>); + resendCodePOST: undefined | ((input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise); + consumeCodePOST: undefined | ((input: ({ + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } | { + linkCode: string; + preAuthSessionId: string; + }) & { + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | GeneralErrorResponse | { + status: "RESTART_FLOW_ERROR"; + } | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + }>); + passwordlessUserEmailExistsGET: undefined | ((input: { + email: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + } | GeneralErrorResponse>); + passwordlessUserPhoneNumberExistsGET: undefined | ((input: { + phoneNumber: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + } | GeneralErrorResponse>); + linkPasswordlessAccountToExistingAccountPOST: undefined | ((input: ({ + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } | { + linkCode: string; + preAuthSessionId: string; + }) & { + session: SessionContainerInterface; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } | GeneralErrorResponse>); }; export declare type TypeThirdPartyPasswordlessEmailDeliveryInput = TypePasswordlessEmailDeliveryInput; export declare type TypeThirdPartyPasswordlessSmsDeliveryInput = TypePasswordlessSmsDeliveryInput; diff --git a/lib/build/recipe/thirdpartypasswordless/utils.d.ts b/lib/build/recipe/thirdpartypasswordless/utils.d.ts index 0fde7f7fd..77d16fe02 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/utils.d.ts @@ -1,7 +1,3 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput( - appInfo: NormalisedAppinfo, - config: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/thirdpartypasswordless/utils.js b/lib/build/recipe/thirdpartypasswordless/utils.js index c1862e5c9..7c87c881f 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.js +++ b/lib/build/recipe/thirdpartypasswordless/utils.js @@ -14,23 +14,15 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormaliseUserInput = void 0; const backwardCompatibility_1 = require("./emaildelivery/services/backwardCompatibility"); const backwardCompatibility_2 = require("./smsdelivery/services/backwardCompatibility"); function validateAndNormaliseUserInput(appInfo, config) { let providers = config.providers === undefined ? [] : config.providers; - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); function getEmailDeliveryConfig() { var _a; - let emailService = - (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 - ? void 0 - : _a.service; + let emailService = (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; /** * following code is for backward compatibility. * if user has not passed emailDelivery config, we @@ -40,15 +32,10 @@ function validateAndNormaliseUserInput(appInfo, config) { */ if (emailService === undefined) { emailService = new backwardCompatibility_1.default(appInfo, { - createAndSendCustomEmail: - (config === null || config === void 0 ? void 0 : config.contactMethod) !== "PHONE" - ? config === null || config === void 0 - ? void 0 - : config.createAndSendCustomEmail - : undefined, + createAndSendCustomEmail: (config === null || config === void 0 ? void 0 : config.contactMethod) !== "PHONE" ? config === null || config === void 0 ? void 0 : config.createAndSendCustomEmail : undefined, }); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -60,15 +47,11 @@ function validateAndNormaliseUserInput(appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService, - }); + service: emailService }); } function getSmsDeliveryConfig() { var _a; - let smsService = - (_a = config === null || config === void 0 ? void 0 : config.smsDelivery) === null || _a === void 0 - ? void 0 - : _a.service; + let smsService = (_a = config === null || config === void 0 ? void 0 : config.smsDelivery) === null || _a === void 0 ? void 0 : _a.service; /** * following code is for backward compatibility. * if user has not passed smsDelivery config, we @@ -78,15 +61,10 @@ function validateAndNormaliseUserInput(appInfo, config) { */ if (smsService === undefined) { smsService = new backwardCompatibility_2.default(appInfo, { - createAndSendCustomTextMessage: - (config === null || config === void 0 ? void 0 : config.contactMethod) !== "EMAIL" - ? config === null || config === void 0 - ? void 0 - : config.createAndSendCustomTextMessage - : undefined, + createAndSendCustomTextMessage: (config === null || config === void 0 ? void 0 : config.contactMethod) !== "EMAIL" ? config === null || config === void 0 ? void 0 : config.createAndSendCustomTextMessage : undefined, }); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.smsDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.smsDelivery), { /** * if we do * let smsDelivery = { @@ -98,14 +76,11 @@ function validateAndNormaliseUserInput(appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: smsService, - }); + service: smsService }); } - return Object.assign(Object.assign({}, config), { - providers, + return Object.assign(Object.assign({}, config), { providers, override, getEmailDeliveryConfig, - getSmsDeliveryConfig, - }); + getSmsDeliveryConfig }); } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; diff --git a/lib/build/recipe/usermetadata/index.d.ts b/lib/build/recipe/usermetadata/index.d.ts index 91f6865fa..99f4147d1 100644 --- a/lib/build/recipe/usermetadata/index.d.ts +++ b/lib/build/recipe/usermetadata/index.d.ts @@ -1,28 +1,17 @@ -// @ts-nocheck import { JSONObject } from "../../types"; import Recipe from "./recipe"; import { RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; - static getUserMetadata( - userId: string, - userContext?: any - ): Promise<{ + static getUserMetadata(userId: string, userContext?: any): Promise<{ status: "OK"; metadata: any; }>; - static updateUserMetadata( - userId: string, - metadataUpdate: JSONObject, - userContext?: any - ): Promise<{ + static updateUserMetadata(userId: string, metadataUpdate: JSONObject, userContext?: any): Promise<{ status: "OK"; metadata: JSONObject; }>; - static clearUserMetadata( - userId: string, - userContext?: any - ): Promise<{ + static clearUserMetadata(userId: string, userContext?: any): Promise<{ status: "OK"; }>; } diff --git a/lib/build/recipe/usermetadata/index.js b/lib/build/recipe/usermetadata/index.js index 9083e4e1f..e8cae1f3e 100644 --- a/lib/build/recipe/usermetadata/index.js +++ b/lib/build/recipe/usermetadata/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.clearUserMetadata = exports.updateUserMetadata = exports.getUserMetadata = exports.init = void 0; const recipe_1 = require("./recipe"); class Wrapper { static getUserMetadata(userId, userContext) { diff --git a/lib/build/recipe/usermetadata/recipe.d.ts b/lib/build/recipe/usermetadata/recipe.d.ts index bbce8012b..8864bf2bb 100644 --- a/lib/build/recipe/usermetadata/recipe.d.ts +++ b/lib/build/recipe/usermetadata/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; @@ -16,13 +15,7 @@ export default class Recipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled(): APIHandled[]; - handleAPIRequest: ( - _: string, - __: BaseRequest, - ___: BaseResponse, - ____: normalisedURLPath, - _____: HTTPMethod - ) => Promise; + handleAPIRequest: (_: string, __: BaseRequest, ___: BaseResponse, ____: normalisedURLPath, _____: HTTPMethod) => Promise; handleError(error: error, _: BaseRequest, __: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; diff --git a/lib/build/recipe/usermetadata/recipe.js b/lib/build/recipe/usermetadata/recipe.js index bcb27b272..81a3f4196 100644 --- a/lib/build/recipe/usermetadata/recipe.js +++ b/lib/build/recipe/usermetadata/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../../error"); const querier_1 = require("../../querier"); @@ -55,16 +33,13 @@ class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config) { super(recipeId, appInfo); // This stub is required to implement RecipeModule - this.handleAPIRequest = (_, __, ___, ____, _____) => - __awaiter(this, void 0, void 0, function* () { - throw new Error("Should never come here"); - }); + this.handleAPIRequest = (_, __, ___, ____, _____) => __awaiter(this, void 0, void 0, function* () { + throw new Error("Should never come here"); + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } } @@ -73,16 +48,15 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance !== undefined) { return Recipe.instance; } - throw new Error( - "Initialisation not done. Did you forget to call the UserMetadata.init or SuperTokens.init function?" - ); + throw new Error("Initialisation not done. Did you forget to call the UserMetadata.init or SuperTokens.init function?"); } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } else { + } + else { throw new Error("UserMetadata recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/usermetadata/recipeImplementation.d.ts b/lib/build/recipe/usermetadata/recipeImplementation.d.ts index 0c838d977..1bf5d18f5 100644 --- a/lib/build/recipe/usermetadata/recipeImplementation.d.ts +++ b/lib/build/recipe/usermetadata/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "."; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/usermetadata/types.d.ts b/lib/build/recipe/usermetadata/types.d.ts index a88b13312..f1211c840 100644 --- a/lib/build/recipe/usermetadata/types.d.ts +++ b/lib/build/recipe/usermetadata/types.d.ts @@ -1,21 +1,14 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import { JSONObject } from "../../types"; export declare type TypeInput = { override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; diff --git a/lib/build/recipe/usermetadata/utils.d.ts b/lib/build/recipe/usermetadata/utils.d.ts index 4025b1b44..371d85a96 100644 --- a/lib/build/recipe/usermetadata/utils.d.ts +++ b/lib/build/recipe/usermetadata/utils.d.ts @@ -1,9 +1,4 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput( - _: Recipe, - __: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(_: Recipe, __: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/usermetadata/utils.js b/lib/build/recipe/usermetadata/utils.js index 5deab8250..9bdd116e1 100644 --- a/lib/build/recipe/usermetadata/utils.js +++ b/lib/build/recipe/usermetadata/utils.js @@ -14,14 +14,9 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(_, __, config) { - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); return { override, }; diff --git a/lib/build/recipe/userroles/index.d.ts b/lib/build/recipe/userroles/index.d.ts index 0e2210593..cf7a97184 100644 --- a/lib/build/recipe/userroles/index.d.ts +++ b/lib/build/recipe/userroles/index.d.ts @@ -1,99 +1,53 @@ -// @ts-nocheck import Recipe from "./recipe"; import { RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static PermissionClaim: import("./permissionClaim").PermissionClaimClass; static UserRoleClaim: import("./userRoleClaim").UserRoleClaimClass; - static addRoleToUser( - userId: string, - role: string, - userContext?: any - ): Promise< - | { - status: "OK"; - didUserAlreadyHaveRole: boolean; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; - static removeUserRole( - userId: string, - role: string, - userContext?: any - ): Promise< - | { - status: "OK"; - didUserHaveRole: boolean; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; - static getRolesForUser( - userId: string, - userContext?: any - ): Promise<{ + static addRoleToUser(userId: string, role: string, userContext?: any): Promise<{ + status: "OK"; + didUserAlreadyHaveRole: boolean; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; + static removeUserRole(userId: string, role: string, userContext?: any): Promise<{ + status: "OK"; + didUserHaveRole: boolean; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; + static getRolesForUser(userId: string, userContext?: any): Promise<{ status: "OK"; roles: string[]; }>; - static getUsersThatHaveRole( - role: string, - userContext?: any - ): Promise< - | { - status: "OK"; - users: string[]; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; - static createNewRoleOrAddPermissions( - role: string, - permissions: string[], - userContext?: any - ): Promise<{ + static getUsersThatHaveRole(role: string, userContext?: any): Promise<{ + status: "OK"; + users: string[]; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; + static createNewRoleOrAddPermissions(role: string, permissions: string[], userContext?: any): Promise<{ status: "OK"; createdNewRole: boolean; }>; - static getPermissionsForRole( - role: string, - userContext?: any - ): Promise< - | { - status: "OK"; - permissions: string[]; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; - static removePermissionsFromRole( - role: string, - permissions: string[], - userContext?: any - ): Promise<{ + static getPermissionsForRole(role: string, userContext?: any): Promise<{ + status: "OK"; + permissions: string[]; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; + static removePermissionsFromRole(role: string, permissions: string[], userContext?: any): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR"; }>; - static getRolesThatHavePermission( - permission: string, - userContext?: any - ): Promise<{ + static getRolesThatHavePermission(permission: string, userContext?: any): Promise<{ status: "OK"; roles: string[]; }>; - static deleteRole( - role: string, - userContext?: any - ): Promise<{ + static deleteRole(role: string, userContext?: any): Promise<{ status: "OK"; didRoleExist: boolean; }>; - static getAllRoles( - userContext?: any - ): Promise<{ + static getAllRoles(userContext?: any): Promise<{ status: "OK"; roles: string[]; }>; diff --git a/lib/build/recipe/userroles/index.js b/lib/build/recipe/userroles/index.js index 74e490c37..3342ee924 100644 --- a/lib/build/recipe/userroles/index.js +++ b/lib/build/recipe/userroles/index.js @@ -13,38 +13,17 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.PermissionClaim = exports.UserRoleClaim = exports.getAllRoles = exports.deleteRole = exports.getRolesThatHavePermission = exports.removePermissionsFromRole = exports.getPermissionsForRole = exports.createNewRoleOrAddPermissions = exports.getUsersThatHaveRole = exports.getRolesForUser = exports.removeUserRole = exports.addRoleToUser = exports.init = void 0; const permissionClaim_1 = require("./permissionClaim"); const recipe_1 = require("./recipe"); const userRoleClaim_1 = require("./userRoleClaim"); @@ -149,6 +128,6 @@ exports.getRolesThatHavePermission = Wrapper.getRolesThatHavePermission; exports.deleteRole = Wrapper.deleteRole; exports.getAllRoles = Wrapper.getAllRoles; var userRoleClaim_2 = require("./userRoleClaim"); -exports.UserRoleClaim = userRoleClaim_2.UserRoleClaim; +Object.defineProperty(exports, "UserRoleClaim", { enumerable: true, get: function () { return userRoleClaim_2.UserRoleClaim; } }); var permissionClaim_2 = require("./permissionClaim"); -exports.PermissionClaim = permissionClaim_2.PermissionClaim; +Object.defineProperty(exports, "PermissionClaim", { enumerable: true, get: function () { return permissionClaim_2.PermissionClaim; } }); diff --git a/lib/build/recipe/userroles/permissionClaim.d.ts b/lib/build/recipe/userroles/permissionClaim.d.ts index d0c34d159..f910f3f0b 100644 --- a/lib/build/recipe/userroles/permissionClaim.d.ts +++ b/lib/build/recipe/userroles/permissionClaim.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { PrimitiveArrayClaim } from "../session/claimBaseClasses/primitiveArrayClaim"; /** * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. diff --git a/lib/build/recipe/userroles/permissionClaim.js b/lib/build/recipe/userroles/permissionClaim.js index eb4ba0c0a..45a94228b 100644 --- a/lib/build/recipe/userroles/permissionClaim.js +++ b/lib/build/recipe/userroles/permissionClaim.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.PermissionClaim = exports.PermissionClaimClass = void 0; const recipe_1 = require("./recipe"); const primitiveArrayClaim_1 = require("../session/claimBaseClasses/primitiveArrayClaim"); /** diff --git a/lib/build/recipe/userroles/recipe.d.ts b/lib/build/recipe/userroles/recipe.d.ts index bbce8012b..8864bf2bb 100644 --- a/lib/build/recipe/userroles/recipe.d.ts +++ b/lib/build/recipe/userroles/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; @@ -16,13 +15,7 @@ export default class Recipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled(): APIHandled[]; - handleAPIRequest: ( - _: string, - __: BaseRequest, - ___: BaseResponse, - ____: normalisedURLPath, - _____: HTTPMethod - ) => Promise; + handleAPIRequest: (_: string, __: BaseRequest, ___: BaseResponse, ____: normalisedURLPath, _____: HTTPMethod) => Promise; handleError(error: error, _: BaseRequest, __: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; diff --git a/lib/build/recipe/userroles/recipe.js b/lib/build/recipe/userroles/recipe.js index 2904700c3..15cf00e7e 100644 --- a/lib/build/recipe/userroles/recipe.js +++ b/lib/build/recipe/userroles/recipe.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("../../error"); const querier_1 = require("../../querier"); @@ -59,16 +37,13 @@ class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config) { super(recipeId, appInfo); // This stub is required to implement RecipeModule - this.handleAPIRequest = (_, __, ___, ____, _____) => - __awaiter(this, void 0, void 0, function* () { - throw new Error("Should never come here"); - }); + this.handleAPIRequest = (_, __, ___, ____, _____) => __awaiter(this, void 0, void 0, function* () { + throw new Error("Should never come here"); + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } postSuperTokensInitCallbacks_1.PostSuperTokensInitCallbacks.addPostInitCallback(() => { @@ -85,16 +60,15 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance !== undefined) { return Recipe.instance; } - throw new Error( - "Initialisation not done. Did you forget to call the UserRoles.init or SuperTokens.init functions?" - ); + throw new Error("Initialisation not done. Did you forget to call the UserRoles.init or SuperTokens.init functions?"); } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } else { + } + else { throw new Error("UserRoles recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/userroles/recipeImplementation.d.ts b/lib/build/recipe/userroles/recipeImplementation.d.ts index 86bf78a27..8a3a26d7c 100644 --- a/lib/build/recipe/userroles/recipeImplementation.d.ts +++ b/lib/build/recipe/userroles/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/userroles/recipeImplementation.js b/lib/build/recipe/userroles/recipeImplementation.js index fb13b27ad..7b104e10d 100644 --- a/lib/build/recipe/userroles/recipeImplementation.js +++ b/lib/build/recipe/userroles/recipeImplementation.js @@ -21,10 +21,7 @@ function getRecipeInterface(querier) { return querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/user/role"), { userId, role }); }, removeUserRole: function ({ userId, role }) { - return querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/role/remove"), { - userId, - role, - }); + return querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/role/remove"), { userId, role }); }, getRolesForUser: function ({ userId }) { return querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user/roles"), { userId }); diff --git a/lib/build/recipe/userroles/types.d.ts b/lib/build/recipe/userroles/types.d.ts index 9552d9f54..c4c889911 100644 --- a/lib/build/recipe/userroles/types.d.ts +++ b/lib/build/recipe/userroles/types.d.ts @@ -1,13 +1,9 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export declare type TypeInput = { skipAddingRolesToAccessToken?: boolean; skipAddingPermissionsToAccessToken?: boolean; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -15,10 +11,7 @@ export declare type TypeNormalisedInput = { skipAddingRolesToAccessToken: boolean; skipAddingPermissionsToAccessToken: boolean; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -28,28 +21,22 @@ export declare type RecipeInterface = { userId: string; role: string; userContext: any; - }) => Promise< - | { - status: "OK"; - didUserAlreadyHaveRole: boolean; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; + }) => Promise<{ + status: "OK"; + didUserAlreadyHaveRole: boolean; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; removeUserRole: (input: { userId: string; role: string; userContext: any; - }) => Promise< - | { - status: "OK"; - didUserHaveRole: boolean; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; + }) => Promise<{ + status: "OK"; + didUserHaveRole: boolean; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; getRolesForUser: (input: { userId: string; userContext: any; @@ -60,15 +47,12 @@ export declare type RecipeInterface = { getUsersThatHaveRole: (input: { role: string; userContext: any; - }) => Promise< - | { - status: "OK"; - users: string[]; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; + }) => Promise<{ + status: "OK"; + users: string[]; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; createNewRoleOrAddPermissions: (input: { role: string; permissions: string[]; @@ -80,15 +64,12 @@ export declare type RecipeInterface = { getPermissionsForRole: (input: { role: string; userContext: any; - }) => Promise< - | { - status: "OK"; - permissions: string[]; - } - | { - status: "UNKNOWN_ROLE_ERROR"; - } - >; + }) => Promise<{ + status: "OK"; + permissions: string[]; + } | { + status: "UNKNOWN_ROLE_ERROR"; + }>; removePermissionsFromRole: (input: { role: string; permissions: string[]; diff --git a/lib/build/recipe/userroles/userRoleClaim.d.ts b/lib/build/recipe/userroles/userRoleClaim.d.ts index 75c0635d5..3e0a5cd83 100644 --- a/lib/build/recipe/userroles/userRoleClaim.d.ts +++ b/lib/build/recipe/userroles/userRoleClaim.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { PrimitiveArrayClaim } from "../session/claimBaseClasses/primitiveArrayClaim"; /** * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. diff --git a/lib/build/recipe/userroles/userRoleClaim.js b/lib/build/recipe/userroles/userRoleClaim.js index c963df624..2955a5dbe 100644 --- a/lib/build/recipe/userroles/userRoleClaim.js +++ b/lib/build/recipe/userroles/userRoleClaim.js @@ -1,36 +1,15 @@ "use strict"; -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); +exports.UserRoleClaim = exports.UserRoleClaimClass = void 0; const recipe_1 = require("./recipe"); const primitiveArrayClaim_1 = require("../session/claimBaseClasses/primitiveArrayClaim"); /** diff --git a/lib/build/recipe/userroles/utils.d.ts b/lib/build/recipe/userroles/utils.d.ts index 4025b1b44..371d85a96 100644 --- a/lib/build/recipe/userroles/utils.d.ts +++ b/lib/build/recipe/userroles/utils.d.ts @@ -1,9 +1,4 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput( - _: Recipe, - __: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput(_: Recipe, __: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/userroles/utils.js b/lib/build/recipe/userroles/utils.js index fdb70ad86..f392db6ee 100644 --- a/lib/build/recipe/userroles/utils.js +++ b/lib/build/recipe/userroles/utils.js @@ -14,19 +14,12 @@ * under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(_, __, config) { - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); return { - skipAddingRolesToAccessToken: - (config === null || config === void 0 ? void 0 : config.skipAddingRolesToAccessToken) === true, - skipAddingPermissionsToAccessToken: - (config === null || config === void 0 ? void 0 : config.skipAddingPermissionsToAccessToken) === true, + skipAddingRolesToAccessToken: (config === null || config === void 0 ? void 0 : config.skipAddingRolesToAccessToken) === true, + skipAddingPermissionsToAccessToken: (config === null || config === void 0 ? void 0 : config.skipAddingPermissionsToAccessToken) === true, override, }; } diff --git a/lib/build/recipeModule.d.ts b/lib/build/recipeModule.d.ts index aef4fd4c8..001dd5819 100644 --- a/lib/build/recipeModule.d.ts +++ b/lib/build/recipeModule.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import STError from "./error"; import { NormalisedAppinfo, APIHandled, HTTPMethod } from "./types"; import NormalisedURLPath from "./normalisedURLPath"; @@ -11,13 +10,7 @@ export default abstract class RecipeModule { getAppInfo: () => NormalisedAppinfo; returnAPIIdIfCanHandleRequest: (path: NormalisedURLPath, method: HTTPMethod) => string | undefined; abstract getAPIsHandled(): APIHandled[]; - abstract handleAPIRequest( - id: string, - req: BaseRequest, - response: BaseResponse, - path: NormalisedURLPath, - method: HTTPMethod - ): Promise; + abstract handleAPIRequest(id: string, req: BaseRequest, response: BaseResponse, path: NormalisedURLPath, method: HTTPMethod): Promise; abstract handleError(error: STError, request: BaseRequest, response: BaseResponse): Promise; abstract getAllCORSHeaders(): string[]; abstract isErrorFromThisRecipe(err: any): err is STError; diff --git a/lib/build/recipeModule.js b/lib/build/recipeModule.js index efdd876f1..20473d2b2 100644 --- a/lib/build/recipeModule.js +++ b/lib/build/recipeModule.js @@ -26,11 +26,9 @@ class RecipeModule { let apisHandled = this.getAPIsHandled(); for (let i = 0; i < apisHandled.length; i++) { let currAPI = apisHandled[i]; - if ( - !currAPI.disabled && + if (!currAPI.disabled && currAPI.method === method && - this.appInfo.apiBasePath.appendPath(currAPI.pathWithoutApiBasePath).equals(path) - ) { + this.appInfo.apiBasePath.appendPath(currAPI.pathWithoutApiBasePath).equals(path)) { return currAPI.id; } } diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 158fca09b..0b8b92c1e 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeInput, NormalisedAppinfo, HTTPMethod, SuperTokensInfo } from "./types"; import RecipeModule from "./recipeModule"; import NormalisedURLPath from "./normalisedURLPath"; @@ -17,73 +16,51 @@ export default class SuperTokens { static init(config: TypeInput): void; static reset(): void; static getInstanceOrThrowError(): SuperTokens; - handleAPI: ( - matchedRecipe: RecipeModule, - id: string, - request: BaseRequest, - response: BaseResponse, - path: NormalisedURLPath, - method: HTTPMethod - ) => Promise; + handleAPI: (matchedRecipe: RecipeModule, id: string, request: BaseRequest, response: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; getAllCORSHeaders: () => string[]; getUserCount: (includeRecipeIds?: string[] | undefined) => Promise; createUserIdMapping: (input: { superTokensUserId: string; externalUserId: string; - externalUserIdInfo?: string | undefined; - force?: boolean | undefined; - }) => Promise< - | { - status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; - } - | { - status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; - doesSuperTokensUserIdExist: boolean; - doesExternalUserIdExist: boolean; - } - >; + externalUserIdInfo?: string; + force?: boolean; + }) => Promise<{ + status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; + } | { + status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; + doesSuperTokensUserIdExist: boolean; + doesExternalUserIdExist: boolean; + }>; getUserIdMapping: (input: { userId: string; - userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" | undefined; - }) => Promise< - | { - status: "OK"; - superTokensUserId: string; - externalUserId: string; - externalUserIdInfo: string | undefined; - } - | { - status: "UNKNOWN_MAPPING_ERROR"; - } - >; + userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; + }) => Promise<{ + status: "OK"; + superTokensUserId: string; + externalUserId: string; + externalUserIdInfo: string | undefined; + } | { + status: "UNKNOWN_MAPPING_ERROR"; + }>; deleteUserIdMapping: (input: { userId: string; - userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" | undefined; - force?: boolean | undefined; + userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; + force?: boolean; }) => Promise<{ status: "OK"; didMappingExist: boolean; }>; updateOrDeleteUserIdMappingInfo: (input: { userId: string; - userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" | undefined; - externalUserIdInfo?: string | undefined; + userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; + externalUserIdInfo?: string; }) => Promise<{ status: "OK" | "UNKNOWN_MAPPING_ERROR"; }>; middleware: (request: BaseRequest, response: BaseResponse) => Promise; errorHandler: (err: any, request: BaseRequest, response: BaseResponse) => Promise; - getUserForRecipeId: ( - userId: string, - recipeId: string - ) => Promise<{ + getUserForRecipeId: (userId: string, recipeId: string) => Promise<{ user: RecipeLevelUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; + recipe: "emailpassword" | "thirdparty" | "passwordless" | "thirdpartyemailpassword" | "thirdpartypasswordless" | undefined; }>; } diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index b80eeae29..2311fac88 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -13,37 +13,15 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = require("axios"); const utils_1 = require("./utils"); @@ -66,33 +44,32 @@ const thirdpartypasswordless_1 = require("./recipe/thirdpartypasswordless"); class SuperTokens { constructor(config) { var _a, _b; - this.sendTelemetry = () => - __awaiter(this, void 0, void 0, function* () { - try { - let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/telemetry"), {}); - let telemetryId; - if (response.exists) { - telemetryId = response.telemetryId; - } - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.com/0/st/telemetry", - data: { - appName: this.appInfo.appName, - websiteDomain: this.appInfo.websiteDomain.getAsStringDangerous(), - telemetryId, - }, - headers: { - "api-version": 2, - }, - }); - } catch (ignored) {} - }); - this.handleAPI = (matchedRecipe, id, request, response, path, method) => - __awaiter(this, void 0, void 0, function* () { - return yield matchedRecipe.handleAPIRequest(id, request, response, path, method); - }); + this.sendTelemetry = () => __awaiter(this, void 0, void 0, function* () { + try { + let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/telemetry"), {}); + let telemetryId; + if (response.exists) { + telemetryId = response.telemetryId; + } + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.com/0/st/telemetry", + data: { + appName: this.appInfo.appName, + websiteDomain: this.appInfo.websiteDomain.getAsStringDangerous(), + telemetryId, + }, + headers: { + "api-version": 2, + }, + }); + } + catch (ignored) { } + }); + this.handleAPI = (matchedRecipe, id, request, response, path, method) => __awaiter(this, void 0, void 0, function* () { + return yield matchedRecipe.handleAPIRequest(id, request, response, path, method); + }); this.getAllCORSHeaders = () => { let headerSet = new Set(); headerSet.add(constants_1.HEADER_RID); @@ -105,24 +82,21 @@ class SuperTokens { }); return Array.from(headerSet); }; - this.getUserCount = (includeRecipeIds) => - __awaiter(this, void 0, void 0, function* () { - let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); - let apiVersion = yield querier.getAPIVersion(); - if (utils_1.maxVersion(apiVersion, "2.7") === "2.7") { - throw new Error( - "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUserCount() instead (for example, EmailPassword.getUserCount())" - ); - } - let includeRecipeIdsStr = undefined; - if (includeRecipeIds !== undefined) { - includeRecipeIdsStr = includeRecipeIds.join(","); - } - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users/count"), { - includeRecipeIds: includeRecipeIdsStr, - }); - return Number(response.count); + this.getUserCount = (includeRecipeIds) => __awaiter(this, void 0, void 0, function* () { + let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); + let apiVersion = yield querier.getAPIVersion(); + if (utils_1.maxVersion(apiVersion, "2.7") === "2.7") { + throw new Error("Please use core version >= 3.5 to call this function. Otherwise, you can call .getUserCount() instead (for example, EmailPassword.getUserCount())"); + } + let includeRecipeIdsStr = undefined; + if (includeRecipeIds !== undefined) { + includeRecipeIdsStr = includeRecipeIds.join(","); + } + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users/count"), { + includeRecipeIds: includeRecipeIdsStr, }); + return Number(response.count); + }); this.createUserIdMapping = function (input) { return __awaiter(this, void 0, void 0, function* () { let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); @@ -135,7 +109,8 @@ class SuperTokens { externalUserIdInfo: input.externalUserIdInfo, force: input.force, }); - } else { + } + else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); @@ -151,7 +126,8 @@ class SuperTokens { userIdType: input.userIdType, }); return response; - } else { + } + else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); @@ -166,7 +142,8 @@ class SuperTokens { userIdType: input.userIdType, force: input.force, }); - } else { + } + else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); @@ -176,239 +153,212 @@ class SuperTokens { let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); let cdiVersion = yield querier.getAPIVersion(); if (utils_1.maxVersion("2.15", cdiVersion) === cdiVersion) { - return yield querier.sendPutRequest( - new normalisedURLPath_1.default("/recipe/userid/external-user-id-info"), - { - userId: input.userId, - userIdType: input.userIdType, - externalUserIdInfo: input.externalUserIdInfo, - } - ); - } else { + return yield querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/userid/external-user-id-info"), { + userId: input.userId, + userIdType: input.userIdType, + externalUserIdInfo: input.externalUserIdInfo, + }); + } + else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); }; - this.middleware = (request, response) => - __awaiter(this, void 0, void 0, function* () { - logger_1.logDebugMessage("middleware: Started"); - let path = this.appInfo.apiGatewayPath.appendPath( - new normalisedURLPath_1.default(request.getOriginalURL()) - ); - let method = utils_1.normaliseHttpMethod(request.getMethod()); - // if the prefix of the URL doesn't match the base path, we skip - if (!path.startsWith(this.appInfo.apiBasePath)) { - logger_1.logDebugMessage( - "middleware: Not handling because request path did not start with config path. Request path: " + - path.getAsStringDangerous() - ); + this.middleware = (request, response) => __awaiter(this, void 0, void 0, function* () { + logger_1.logDebugMessage("middleware: Started"); + let path = this.appInfo.apiGatewayPath.appendPath(new normalisedURLPath_1.default(request.getOriginalURL())); + let method = utils_1.normaliseHttpMethod(request.getMethod()); + // if the prefix of the URL doesn't match the base path, we skip + if (!path.startsWith(this.appInfo.apiBasePath)) { + logger_1.logDebugMessage("middleware: Not handling because request path did not start with config path. Request path: " + + path.getAsStringDangerous()); + return false; + } + let requestRID = utils_1.getRidFromHeader(request); + logger_1.logDebugMessage("middleware: requestRID is: " + requestRID); + if (requestRID === "anti-csrf") { + // see https://github.com/supertokens/supertokens-node/issues/202 + requestRID = undefined; + } + if (requestRID !== undefined) { + let matchedRecipe = undefined; + // we loop through all recipe modules to find the one with the matching rId + for (let i = 0; i < this.recipeModules.length; i++) { + logger_1.logDebugMessage("middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId()); + if (this.recipeModules[i].getRecipeId() === requestRID) { + matchedRecipe = this.recipeModules[i]; + break; + } + } + if (matchedRecipe === undefined) { + logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); + // we could not find one, so we skip return false; } - let requestRID = request.getHeaderValue(constants_1.HEADER_RID); - logger_1.logDebugMessage("middleware: requestRID is: " + requestRID); - if (requestRID === "anti-csrf") { - // see https://github.com/supertokens/supertokens-node/issues/202 - requestRID = undefined; + logger_1.logDebugMessage("middleware: Matched with recipe ID: " + matchedRecipe.getRecipeId()); + let id = matchedRecipe.returnAPIIdIfCanHandleRequest(path, method); + if (id === undefined) { + logger_1.logDebugMessage("middleware: Not handling because recipe doesn't handle request path or method. Request path: " + + path.getAsStringDangerous() + + ", request method: " + + method); + // the matched recipe doesn't handle this path and http method + return false; } - if (requestRID !== undefined) { - let matchedRecipe = undefined; - // we loop through all recipe modules to find the one with the matching rId - for (let i = 0; i < this.recipeModules.length; i++) { - logger_1.logDebugMessage( - "middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId() - ); - if (this.recipeModules[i].getRecipeId() === requestRID) { - matchedRecipe = this.recipeModules[i]; - break; - } - } - if (matchedRecipe === undefined) { - logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); - // we could not find one, so we skip - return false; - } - logger_1.logDebugMessage("middleware: Matched with recipe ID: " + matchedRecipe.getRecipeId()); - let id = matchedRecipe.returnAPIIdIfCanHandleRequest(path, method); - if (id === undefined) { - logger_1.logDebugMessage( - "middleware: Not handling because recipe doesn't handle request path or method. Request path: " + - path.getAsStringDangerous() + - ", request method: " + - method - ); - // the matched recipe doesn't handle this path and http method - return false; - } - logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); - // give task to the matched recipe - let requestHandled = yield matchedRecipe.handleAPIRequest(id, request, response, path, method); - if (!requestHandled) { - logger_1.logDebugMessage( - "middleware: Not handled because API returned requestHandled as false" - ); - return false; - } - logger_1.logDebugMessage("middleware: Ended"); - return true; - } else { - // we loop through all recipe modules to find the one with the matching path and method - for (let i = 0; i < this.recipeModules.length; i++) { - logger_1.logDebugMessage( - "middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId() - ); - let id = this.recipeModules[i].returnAPIIdIfCanHandleRequest(path, method); - if (id !== undefined) { - logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); - let requestHandled = yield this.recipeModules[i].handleAPIRequest( - id, - request, - response, - path, - method - ); - if (!requestHandled) { - logger_1.logDebugMessage( - "middleware: Not handled because API returned requestHandled as false" - ); - return false; - } - logger_1.logDebugMessage("middleware: Ended"); - return true; + logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); + // give task to the matched recipe + let requestHandled = yield matchedRecipe.handleAPIRequest(id, request, response, path, method); + if (!requestHandled) { + logger_1.logDebugMessage("middleware: Not handled because API returned requestHandled as false"); + return false; + } + logger_1.logDebugMessage("middleware: Ended"); + return true; + } + else { + // we loop through all recipe modules to find the one with the matching path and method + for (let i = 0; i < this.recipeModules.length; i++) { + logger_1.logDebugMessage("middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId()); + let id = this.recipeModules[i].returnAPIIdIfCanHandleRequest(path, method); + if (id !== undefined) { + logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); + let requestHandled = yield this.recipeModules[i].handleAPIRequest(id, request, response, path, method); + if (!requestHandled) { + logger_1.logDebugMessage("middleware: Not handled because API returned requestHandled as false"); + return false; } + logger_1.logDebugMessage("middleware: Ended"); + return true; } - logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); - return false; } - }); - this.errorHandler = (err, request, response) => - __awaiter(this, void 0, void 0, function* () { - logger_1.logDebugMessage("errorHandler: Started"); - if (error_1.default.isErrorFromSuperTokens(err)) { - logger_1.logDebugMessage("errorHandler: Error is from SuperTokens recipe. Message: " + err.message); - if (err.type === error_1.default.BAD_INPUT_ERROR) { - logger_1.logDebugMessage("errorHandler: Sending 400 status code response"); - return utils_1.sendNon200ResponseWithMessage(response, err.message, 400); + logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); + return false; + } + }); + this.errorHandler = (err, request, response) => __awaiter(this, void 0, void 0, function* () { + logger_1.logDebugMessage("errorHandler: Started"); + if (error_1.default.isErrorFromSuperTokens(err)) { + logger_1.logDebugMessage("errorHandler: Error is from SuperTokens recipe. Message: " + err.message); + if (err.type === error_1.default.BAD_INPUT_ERROR) { + logger_1.logDebugMessage("errorHandler: Sending 400 status code response"); + return utils_1.sendNon200ResponseWithMessage(response, err.message, 400); + } + for (let i = 0; i < this.recipeModules.length; i++) { + logger_1.logDebugMessage("errorHandler: Checking recipe for match: " + this.recipeModules[i].getRecipeId()); + if (this.recipeModules[i].isErrorFromThisRecipe(err)) { + logger_1.logDebugMessage("errorHandler: Matched with recipeID: " + this.recipeModules[i].getRecipeId()); + return yield this.recipeModules[i].handleError(err, request, response); } - for (let i = 0; i < this.recipeModules.length; i++) { - logger_1.logDebugMessage( - "errorHandler: Checking recipe for match: " + this.recipeModules[i].getRecipeId() - ); - if (this.recipeModules[i].isErrorFromThisRecipe(err)) { - logger_1.logDebugMessage( - "errorHandler: Matched with recipeID: " + this.recipeModules[i].getRecipeId() - ); - return yield this.recipeModules[i].handleError(err, request, response); - } + } + } + throw err; + }); + this.getUserForRecipeId = (userId, recipeId) => __awaiter(this, void 0, void 0, function* () { + let user; + let recipe; + if (recipeId === recipe_2.default.RECIPE_ID) { + try { + const userResponse = yield emailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); + recipe = "emailpassword"; } } - throw err; - }); - this.getUserForRecipeId = (userId, recipeId) => - __awaiter(this, void 0, void 0, function* () { - let user; - let recipe; - if (recipeId === recipe_2.default.RECIPE_ID) { + catch (e) { + // No - op + } + if (user === undefined) { try { - const userResponse = yield emailpassword_1.default.getUserById(userId); + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); if (userResponse !== undefined) { user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); - recipe = "emailpassword"; + recipe = "thirdpartyemailpassword"; } - } catch (e) { + } + catch (e) { // No - op } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op - } + } + } + else if (recipeId === recipe_3.default.RECIPE_ID) { + try { + const userResponse = yield thirdparty_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdparty"; } - } else if (recipeId === recipe_3.default.RECIPE_ID) { + } + catch (e) { + // No - op + } + if (user === undefined) { try { - const userResponse = yield thirdparty_1.default.getUserById(userId); + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); if (userResponse !== undefined) { user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdparty"; + recipe = "thirdpartyemailpassword"; } - } catch (e) { + } + catch (e) { // No - op } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdpartyemailpassword"; - } - } catch (e) { - // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdpartypasswordless"; } } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } + catch (e) { + // No - op + } + } + } + else if (recipeId === recipe_4.default.RECIPE_ID) { + try { + const userResponse = yield passwordless_1.default.getUserById({ + userId, + }); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); + recipe = "passwordless"; } - } else if (recipeId === recipe_4.default.RECIPE_ID) { + } + catch (e) { + // No - op + } + if (user === undefined) { try { - const userResponse = yield passwordless_1.default.getUserById({ - userId, - }); + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); if (userResponse !== undefined) { user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); - recipe = "passwordless"; + recipe = "thirdpartypasswordless"; } - } catch (e) { - // No - op } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } + catch (e) { + // No - op } } - return { - user, - recipe, - }; - }); + } + return { + user, + recipe, + }; + }); logger_1.logDebugMessage("Started SuperTokens with debug logging (supertokens.init called)"); logger_1.logDebugMessage("appInfo: " + JSON.stringify(config.appInfo)); this.framework = config.framework !== undefined ? config.framework : "express"; logger_1.logDebugMessage("framework: " + this.framework); this.appInfo = utils_1.normaliseInputAppInfoOrThrowError(config.appInfo); this.supertokens = config.supertokens; - querier_1.Querier.init( - (_a = config.supertokens) === null || _a === void 0 - ? void 0 - : _a.connectionURI - .split(";") - .filter((h) => h !== "") - .map((h) => { - return { - domain: new normalisedURLDomain_1.default(h.trim()), - basePath: new normalisedURLPath_1.default(h.trim()), - }; - }), - (_b = config.supertokens) === null || _b === void 0 ? void 0 : _b.apiKey - ); + querier_1.Querier.init((_a = config.supertokens) === null || _a === void 0 ? void 0 : _a.connectionURI.split(";").filter((h) => h !== "").map((h) => { + return { + domain: new normalisedURLDomain_1.default(h.trim()), + basePath: new normalisedURLPath_1.default(h.trim()), + }; + }), (_b = config.supertokens) === null || _b === void 0 ? void 0 : _b.apiKey); if (config.recipeList === undefined || config.recipeList.length === 0) { throw new Error("Please provide at least one recipe to the supertokens.init function call"); } @@ -421,9 +371,7 @@ class SuperTokens { this.recipeModules = config.recipeList.map((func) => { return func(this.appInfo, this.isInServerlessEnv); }); - let isAccountLinkingInitialised = this.recipeModules.find( - (r) => r.getRecipeId() === recipe_1.default.RECIPE_ID - ); + let isAccountLinkingInitialised = this.recipeModules.find((r) => r.getRecipeId() === recipe_1.default.RECIPE_ID); if (!isAccountLinkingInitialised) { this.recipeModules.push(recipe_1.default.init({})(this.appInfo, this.isInServerlessEnv)); } @@ -435,7 +383,8 @@ class SuperTokens { if (randomNum > 7) { this.sendTelemetry(); } - } else { + } + else { this.sendTelemetry(); } } diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index 593ed2a96..adc8c0e03 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "./recipeModule"; import NormalisedURLDomain from "./normalisedURLDomain"; import NormalisedURLPath from "./normalisedURLPath"; @@ -16,6 +15,8 @@ export declare type NormalisedAppinfo = { appName: string; websiteDomain: NormalisedURLDomain; apiDomain: NormalisedURLDomain; + topLevelAPIDomain: string; + topLevelWebsiteDomain: string; apiBasePath: NormalisedURLPath; apiGatewayPath: NormalisedURLPath; websiteBasePath: NormalisedURLPath; diff --git a/lib/build/utils.d.ts b/lib/build/utils.d.ts index 820edfa82..79777afd8 100644 --- a/lib/build/utils.d.ts +++ b/lib/build/utils.d.ts @@ -1,15 +1,15 @@ -// @ts-nocheck import type { AppInfo, NormalisedAppinfo, HTTPMethod, JSONObject } from "./types"; import type { BaseRequest, BaseResponse } from "./framework"; export declare function getLargestVersionFromIntersection(v1: string[], v2: string[]): string | undefined; export declare function maxVersion(version1: string, version2: string): string; export declare function normaliseInputAppInfoOrThrowError(appInfo: AppInfo): NormalisedAppinfo; -export declare function getRIDFromRequest(req: BaseRequest): string | undefined; export declare function normaliseHttpMethod(method: string): HTTPMethod; export declare function sendNon200ResponseWithMessage(res: BaseResponse, message: string, statusCode: number): void; export declare function sendNon200Response(res: BaseResponse, statusCode: number, body: JSONObject): void; export declare function send200Response(res: BaseResponse, responseJson: any): void; export declare function isAnIpAddress(ipaddress: string): boolean; +export declare function getRidFromHeader(req: BaseRequest): string | undefined; export declare function frontendHasInterceptor(req: BaseRequest): boolean; export declare function humaniseMilliseconds(ms: number): string; export declare function makeDefaultUserContextFromAPI(request: BaseRequest): any; +export declare function getTopLevelDomainForSameSiteResolution(url: string): string; diff --git a/lib/build/utils.js b/lib/build/utils.js index 05e6745a9..3d8ee59ce 100644 --- a/lib/build/utils.js +++ b/lib/build/utils.js @@ -1,9 +1,11 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const constants_1 = require("./constants"); +exports.getTopLevelDomainForSameSiteResolution = exports.makeDefaultUserContextFromAPI = exports.humaniseMilliseconds = exports.frontendHasInterceptor = exports.getRidFromHeader = exports.isAnIpAddress = exports.send200Response = exports.sendNon200Response = exports.sendNon200ResponseWithMessage = exports.normaliseHttpMethod = exports.normaliseInputAppInfoOrThrowError = exports.maxVersion = exports.getLargestVersionFromIntersection = void 0; +const psl = require("psl"); const normalisedURLDomain_1 = require("./normalisedURLDomain"); const normalisedURLPath_1 = require("./normalisedURLPath"); const logger_1 = require("./logger"); +const constants_1 = require("./constants"); function getLargestVersionFromIntersection(v1, v2) { let intersection = v1.filter((value) => v2.indexOf(value) !== -1); if (intersection.length === 0) { @@ -25,7 +27,8 @@ function maxVersion(version1, version2) { let v2 = Number(splittedv2[i]); if (v1 > v2) { return version1; - } else if (v2 > v1) { + } + else if (v2 > v1) { return version2; } } @@ -48,31 +51,29 @@ function normaliseInputAppInfoOrThrowError(appInfo) { if (appInfo.websiteDomain === undefined) { throw new Error("Please provide your websiteDomain inside the appInfo object when calling supertokens.init"); } - let apiGatewayPath = - appInfo.apiGatewayPath !== undefined - ? new normalisedURLPath_1.default(appInfo.apiGatewayPath) - : new normalisedURLPath_1.default(""); + let apiGatewayPath = appInfo.apiGatewayPath !== undefined + ? new normalisedURLPath_1.default(appInfo.apiGatewayPath) + : new normalisedURLPath_1.default(""); + const websiteDomain = new normalisedURLDomain_1.default(appInfo.websiteDomain); + const apiDomain = new normalisedURLDomain_1.default(appInfo.apiDomain); + const topLevelAPIDomain = getTopLevelDomainForSameSiteResolution(apiDomain.getAsStringDangerous()); + const topLevelWebsiteDomain = getTopLevelDomainForSameSiteResolution(websiteDomain.getAsStringDangerous()); return { appName: appInfo.appName, - websiteDomain: new normalisedURLDomain_1.default(appInfo.websiteDomain), - apiDomain: new normalisedURLDomain_1.default(appInfo.apiDomain), - apiBasePath: apiGatewayPath.appendPath( - appInfo.apiBasePath === undefined - ? new normalisedURLPath_1.default("/auth") - : new normalisedURLPath_1.default(appInfo.apiBasePath) - ), - websiteBasePath: - appInfo.websiteBasePath === undefined - ? new normalisedURLPath_1.default("/auth") - : new normalisedURLPath_1.default(appInfo.websiteBasePath), + websiteDomain, + apiDomain, + apiBasePath: apiGatewayPath.appendPath(appInfo.apiBasePath === undefined + ? new normalisedURLPath_1.default("/auth") + : new normalisedURLPath_1.default(appInfo.apiBasePath)), + websiteBasePath: appInfo.websiteBasePath === undefined + ? new normalisedURLPath_1.default("/auth") + : new normalisedURLPath_1.default(appInfo.websiteBasePath), apiGatewayPath, + topLevelAPIDomain, + topLevelWebsiteDomain, }; } exports.normaliseInputAppInfoOrThrowError = normaliseInputAppInfoOrThrowError; -function getRIDFromRequest(req) { - return req.getHeaderValue(constants_1.HEADER_RID); -} -exports.getRIDFromRequest = getRIDFromRequest; function normaliseHttpMethod(method) { return method.toLowerCase(); } @@ -97,28 +98,35 @@ function send200Response(res, responseJson) { } exports.send200Response = send200Response; function isAnIpAddress(ipaddress) { - return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test( - ipaddress - ); + return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress); } exports.isAnIpAddress = isAnIpAddress; +function getRidFromHeader(req) { + return req.getHeaderValue(constants_1.HEADER_RID); +} +exports.getRidFromHeader = getRidFromHeader; function frontendHasInterceptor(req) { - return getRIDFromRequest(req) !== undefined; + return getRidFromHeader(req) !== undefined; } exports.frontendHasInterceptor = frontendHasInterceptor; function humaniseMilliseconds(ms) { let t = Math.floor(ms / 1000); let suffix = ""; if (t < 60) { - if (t > 1) suffix = "s"; + if (t > 1) + suffix = "s"; return `${t} second${suffix}`; - } else if (t < 3600) { + } + else if (t < 3600) { const m = Math.floor(t / 60); - if (m > 1) suffix = "s"; + if (m > 1) + suffix = "s"; return `${m} minute${suffix}`; - } else { + } + else { const h = Math.floor(t / 360) / 10; - if (h > 1) suffix = "s"; + if (h > 1) + suffix = "s"; return `${h} hour${suffix}`; } } @@ -131,3 +139,17 @@ function makeDefaultUserContextFromAPI(request) { }; } exports.makeDefaultUserContextFromAPI = makeDefaultUserContextFromAPI; +function getTopLevelDomainForSameSiteResolution(url) { + let urlObj = new URL(url); + let hostname = urlObj.hostname; + if (hostname.startsWith("localhost") || hostname.startsWith("localhost.org") || isAnIpAddress(hostname)) { + // we treat these as the same TLDs since we can use sameSite lax for all of them. + return "localhost"; + } + let parsedURL = psl.parse(hostname); + if (parsedURL.domain === null) { + throw new Error("Please make sure that the apiDomain and websiteDomain have correct values"); + } + return parsedURL.domain; +} +exports.getTopLevelDomainForSameSiteResolution = getTopLevelDomainForSameSiteResolution; diff --git a/lib/build/version.d.ts b/lib/build/version.d.ts index 2835ff959..d1e5df58e 100644 --- a/lib/build/version.d.ts +++ b/lib/build/version.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck -export declare const version = "12.1.0"; +export declare const version = "13.0.1"; export declare const cdiSupported: string[]; -export declare const dashboardVersion = "0.2"; +export declare const dashboardVersion = "0.3"; diff --git a/lib/build/version.js b/lib/build/version.js index ab0b970e1..23c0eddb8 100644 --- a/lib/build/version.js +++ b/lib/build/version.js @@ -1,5 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +exports.dashboardVersion = exports.cdiSupported = exports.version = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the @@ -14,7 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); * License for the specific language governing permissions and limitations * under the License. */ -exports.version = "12.1.0"; +exports.version = "13.0.1"; exports.cdiSupported = ["2.8", "2.9", "2.10", "2.11", "2.12", "2.13", "2.14", "2.15"]; // Note: The actual script import for dashboard uses v{DASHBOARD_VERSION} -exports.dashboardVersion = "0.2"; +exports.dashboardVersion = "0.3"; diff --git a/lib/ts/framework/awsLambda/framework.ts b/lib/ts/framework/awsLambda/framework.ts index 59908bd7c..317d07792 100644 --- a/lib/ts/framework/awsLambda/framework.ts +++ b/lib/ts/framework/awsLambda/framework.ts @@ -189,6 +189,12 @@ export class AWSResponse extends BaseResponse { }); }; + removeHeader = (key: string) => { + this.event.supertokens.response.headers = this.event.supertokens.response.headers.filter( + (header) => header.key.toLowerCase() !== key.toLowerCase() + ); + }; + setCookie = ( key: string, value: string, @@ -216,7 +222,7 @@ export class AWSResponse extends BaseResponse { sendJSONResponse = (content: any) => { if (!this.responseSet) { this.content = JSON.stringify(content); - this.setHeader("Context-Type", "application/json", false); + this.setHeader("Content-Type", "application/json", false); this.responseSet = true; } }; diff --git a/lib/ts/framework/express/framework.ts b/lib/ts/framework/express/framework.ts index 26d6269d0..a838a0612 100644 --- a/lib/ts/framework/express/framework.ts +++ b/lib/ts/framework/express/framework.ts @@ -116,6 +116,10 @@ export class ExpressResponse extends BaseResponse { setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; + removeHeader = (key: string) => { + this.response.removeHeader(key); + }; + setCookie = ( key: string, value: string, diff --git a/lib/ts/framework/fastify/framework.ts b/lib/ts/framework/fastify/framework.ts index c0ef98c2f..c3709d802 100644 --- a/lib/ts/framework/fastify/framework.ts +++ b/lib/ts/framework/fastify/framework.ts @@ -110,6 +110,10 @@ export class FastifyResponse extends BaseResponse { } }; + removeHeader = (key: string) => { + this.response.removeHeader(key); + }; + setCookie = ( key: string, value: string, diff --git a/lib/ts/framework/hapi/framework.ts b/lib/ts/framework/hapi/framework.ts index 25e1e50a8..40cc92ee9 100644 --- a/lib/ts/framework/hapi/framework.ts +++ b/lib/ts/framework/hapi/framework.ts @@ -70,7 +70,12 @@ export class HapiRequest extends BaseRequest { } export interface ExtendedResponseToolkit extends ResponseToolkit { - lazyHeaderBindings: (h: ResponseToolkit, key: string, value: string, allowDuplicateKey: boolean) => void; + lazyHeaderBindings: ( + h: ResponseToolkit, + key: string, + value: string | undefined, + allowDuplicateKey: boolean + ) => void; } export class HapiResponse extends BaseResponse { @@ -105,6 +110,10 @@ export class HapiResponse extends BaseResponse { } }; + removeHeader = (key: string) => { + this.response.lazyHeaderBindings(this.response, key, undefined, false); + }; + setCookie = ( key: string, value: string, @@ -116,6 +125,7 @@ export class HapiResponse extends BaseResponse { sameSite: "strict" | "lax" | "none" ) => { let now = Date.now(); + if (expires > now) { this.response.state(key, value, { isHttpOnly: httpOnly, @@ -213,11 +223,18 @@ const plugin: Plugin<{}> = { server.decorate("toolkit", "lazyHeaderBindings", function ( h: ResponseToolkit, key: string, - value: string, + value: string | undefined, allowDuplicateKey: boolean ) { - (h.request.app as any).lazyHeaders = (h.request.app as any).lazyHeaders || []; - (h.request.app as any).lazyHeaders.push({ key, value, allowDuplicateKey }); + const anyApp = h.request.app as any; + anyApp.lazyHeaders = anyApp.lazyHeaders || []; + if (value === undefined) { + anyApp.lazyHeaders = anyApp.lazyHeaders.filter( + (header: { key: string }) => header.key.toLowerCase() !== key.toLowerCase() + ); + } else { + anyApp.lazyHeaders.push({ key, value, allowDuplicateKey }); + } }); let supportedRoutes: ServerRoute[] = []; let routeMethodSet = new Set(); diff --git a/lib/ts/framework/koa/framework.ts b/lib/ts/framework/koa/framework.ts index a1398b86f..721a57ae0 100644 --- a/lib/ts/framework/koa/framework.ts +++ b/lib/ts/framework/koa/framework.ts @@ -130,6 +130,10 @@ export class KoaResponse extends BaseResponse { } }; + removeHeader = (key: string) => { + this.ctx.remove(key); + }; + setCookie = ( key: string, value: string, diff --git a/lib/ts/framework/loopback/framework.ts b/lib/ts/framework/loopback/framework.ts index c0f08b372..86a740f79 100644 --- a/lib/ts/framework/loopback/framework.ts +++ b/lib/ts/framework/loopback/framework.ts @@ -110,6 +110,10 @@ export class LoopbackResponse extends BaseResponse { setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; + removeHeader = (key: string) => { + this.response.removeHeader(key); + }; + setCookie = ( key: string, value: string, diff --git a/lib/ts/framework/response.ts b/lib/ts/framework/response.ts index 5c5cc025a..e7e4312f7 100644 --- a/lib/ts/framework/response.ts +++ b/lib/ts/framework/response.ts @@ -20,6 +20,7 @@ export abstract class BaseResponse { this.wrapperUsed = true; } abstract setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; + abstract removeHeader: (key: string) => void; abstract setCookie: ( key: string, value: string, diff --git a/lib/ts/recipe/dashboard/api/userdetails/userGet.ts b/lib/ts/recipe/dashboard/api/userdetails/userGet.ts index 30be8c402..d11baa056 100644 --- a/lib/ts/recipe/dashboard/api/userdetails/userGet.ts +++ b/lib/ts/recipe/dashboard/api/userdetails/userGet.ts @@ -7,7 +7,7 @@ import { ThirdPartyUser, } from "../../types"; import STError from "../../../../error"; -import { getUserForRecipeId, isValidRecipeId } from "../../utils"; +import { getUserForRecipeId, isRecipeInitialised, isValidRecipeId } from "../../utils"; import UserMetaDataRecipe from "../../../usermetadata/recipe"; import UserMetaData from "../../../usermetadata"; @@ -15,6 +15,9 @@ type Response = | { status: "NO_USER_FOUND_ERROR"; } + | { + status: "RECIPE_NOT_INITIALISED"; + } | { status: "OK"; recipeId: "emailpassword"; @@ -56,6 +59,12 @@ export const userGet: APIFunction = async (_: APIInterface, options: APIOptions) }); } + if (!isRecipeInitialised(recipeId)) { + return { + status: "RECIPE_NOT_INITIALISED", + }; + } + let user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined = ( await getUserForRecipeId(userId, recipeId) ).user; diff --git a/lib/ts/recipe/dashboard/api/userdetails/userPut.ts b/lib/ts/recipe/dashboard/api/userdetails/userPut.ts index 3a9333f30..10240311a 100644 --- a/lib/ts/recipe/dashboard/api/userdetails/userPut.ts +++ b/lib/ts/recipe/dashboard/api/userdetails/userPut.ts @@ -1,7 +1,7 @@ import { APIInterface, APIOptions } from "../../types"; import STError from "../../../../error"; import EmailPasswordRecipe from "../../../emailpassword/recipe"; -import ThirdPartyEmailPasswordRecipe from "../../../emailpassword/recipe"; +import ThirdPartyEmailPasswordRecipe from "../../../thirdpartyemailpassword/recipe"; import PasswordlessRecipe from "../../../passwordless/recipe"; import ThirdPartyPasswordlessRecipe from "../../../thirdpartypasswordless/recipe"; import EmailPassword from "../../../emailpassword"; diff --git a/lib/ts/recipe/dashboard/utils.ts b/lib/ts/recipe/dashboard/utils.ts index 9b392e7c1..784de18b9 100644 --- a/lib/ts/recipe/dashboard/utils.ts +++ b/lib/ts/recipe/dashboard/utils.ts @@ -40,6 +40,11 @@ import { TypeNormalisedInput, } from "./types"; import Supertokens from "../.."; +import EmailPasswordRecipe from "../emailpassword/recipe"; +import ThirdPartyRecipe from "../thirdparty/recipe"; +import PasswordlessRecipe from "../passwordless/recipe"; +import ThirdPartyEmailPasswordRecipe from "../thirdpartyemailpassword/recipe"; +import ThirdPartyPasswordlessRecipe from "../thirdpartypasswordless/recipe"; export function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput { if (config.apiKey.trim().length === 0) { @@ -164,3 +169,54 @@ export async function getUserForRecipeId( recipe: userResponse.recipe, }; } + +export function isRecipeInitialised(recipeId: RecipeIdForUser): boolean { + let isRecipeInitialised = false; + + if (recipeId === "emailpassword") { + try { + EmailPasswordRecipe.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) {} + + if (!isRecipeInitialised) { + try { + ThirdPartyEmailPasswordRecipe.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) {} + } + } else if (recipeId === "passwordless") { + try { + PasswordlessRecipe.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) {} + + if (!isRecipeInitialised) { + try { + ThirdPartyPasswordlessRecipe.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) {} + } + } else if (recipeId === "thirdparty") { + try { + ThirdPartyRecipe.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) {} + + if (!isRecipeInitialised) { + try { + ThirdPartyEmailPasswordRecipe.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) {} + } + + if (!isRecipeInitialised) { + try { + ThirdPartyPasswordlessRecipe.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) {} + } + } + + return isRecipeInitialised; +} diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 4d5f36020..a65472f28 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -193,7 +193,7 @@ export default function getAPIImplementation(): APIInterface { } let user = response.user; - let session = await Session.createNewSession(options.res, user.id, user.recipeUserId, {}, {}, userContext); + let session = await Session.createNewSession(options.req, options.res, user.id, user.recipeUserId, {}, {}, userContext); return { status: "OK", session, @@ -237,7 +237,7 @@ export default function getAPIImplementation(): APIInterface { } let user = response.user; - let session = await Session.createNewSession(options.res, user.id, user.recipeUserId, {}, {}, userContext); + let session = await Session.createNewSession(options.req, options.res, user.id, user.recipeUserId, {}, {}, userContext); return { status: "OK", session, diff --git a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts index 7928535eb..060079c83 100644 --- a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts +++ b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts @@ -62,6 +62,10 @@ export default class BackwardCompatibilityService if (user === undefined) { throw Error("this should never come here"); } + // we add this here cause the user may have overridden the sendEmail function + // to change the input email and if we don't do this, the input email + // will get reset by the getUserById call above. + user.email = input.user.email; try { if (!this.isInServerlessEnv) { this.resetPasswordUsingTokenFeature diff --git a/lib/ts/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.ts b/lib/ts/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.ts index 648aeee52..ad04756ff 100644 --- a/lib/ts/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.ts +++ b/lib/ts/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.ts @@ -515,13 +515,6 @@ export function getPasswordResetEmailHTML(appName: string, email: string, resetL text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, diff --git a/lib/ts/recipe/emailverification/emaildelivery/services/smtp/emailVerify.ts b/lib/ts/recipe/emailverification/emaildelivery/services/smtp/emailVerify.ts index b242c5b9f..1844477c5 100644 --- a/lib/ts/recipe/emailverification/emaildelivery/services/smtp/emailVerify.ts +++ b/lib/ts/recipe/emailverification/emaildelivery/services/smtp/emailVerify.ts @@ -514,13 +514,6 @@ export function getEmailVerifyEmailHTML(appName: string, email: string, verifica text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, diff --git a/lib/ts/recipe/passwordless/api/implementation.ts b/lib/ts/recipe/passwordless/api/implementation.ts index 9a6344dc0..613b8919c 100644 --- a/lib/ts/recipe/passwordless/api/implementation.ts +++ b/lib/ts/recipe/passwordless/api/implementation.ts @@ -48,6 +48,7 @@ export default function getAPIImplementation(): APIInterface { } const session = await Session.createNewSession( + input.options.req, input.options.res, user.id, user.recipeUserId, diff --git a/lib/ts/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.ts b/lib/ts/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.ts index f4c6e7bd7..3823e56d3 100644 --- a/lib/ts/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.ts +++ b/lib/ts/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.ts @@ -520,13 +520,6 @@ function getPasswordlessLoginOTPBody(appName: string, email: string, codeLifetim text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, @@ -1441,13 +1434,6 @@ function getPasswordlessLoginURLLinkBody( text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, @@ -2378,13 +2364,6 @@ function getPasswordlessLoginOTPAndURLLinkBody( text-decoration: underline; } - @media only screen and (min-width:768px) { - .templateContainer { - width: 600px !important; - } - - } - @media only screen and (max-width: 480px) { body, diff --git a/lib/ts/recipe/session/accessToken.ts b/lib/ts/recipe/session/accessToken.ts index 0bd13ff16..244f596ba 100644 --- a/lib/ts/recipe/session/accessToken.ts +++ b/lib/ts/recipe/session/accessToken.ts @@ -14,10 +14,10 @@ */ import STError from "./error"; -import { verifyJWTAndGetPayload } from "./jwt"; +import { ParsedJWTInfo, verifyJWT } from "./jwt"; export async function getInfoFromAccessToken( - token: string, + jwtInfo: ParsedJWTInfo, jwtSigningPublicKey: string, doAntiCsrfCheck: boolean ): Promise<{ @@ -32,30 +32,27 @@ export async function getInfoFromAccessToken( timeCreated: number; }> { try { - let payload = verifyJWTAndGetPayload(token, jwtSigningPublicKey); + verifyJWT(jwtInfo, jwtSigningPublicKey); + const payload = jwtInfo.payload; - let sessionHandle = sanitizeStringInput(payload.sessionHandle); - let userId = sanitizeStringInput(payload.userId); - let recipeUserId = sanitizeStringInput(payload.recipeUserId); - let refreshTokenHash1 = sanitizeStringInput(payload.refreshTokenHash1); + // This should be called before this function, but the check is very quick, so we can also do them here + validateAccessTokenStructure(payload); + + // We can mark these as defined (the ! after the calls), since validateAccessTokenPayload checks this + let sessionHandle = sanitizeStringInput(payload.sessionHandle)!; + let userId = sanitizeStringInput(payload.userId)!; + let recipeUserId = sanitizeStringInput(payload.recipeUserId)!; + let refreshTokenHash1 = sanitizeStringInput(payload.refreshTokenHash1)!; let parentRefreshTokenHash1 = sanitizeStringInput(payload.parentRefreshTokenHash1); let userData = payload.userData; let antiCsrfToken = sanitizeStringInput(payload.antiCsrfToken); - let expiryTime = sanitizeNumberInput(payload.expiryTime); - let timeCreated = sanitizeNumberInput(payload.timeCreated); - if ( - sessionHandle === undefined || - userId === undefined || - recipeUserId === undefined || - refreshTokenHash1 === undefined || - userData === undefined || - (antiCsrfToken === undefined && doAntiCsrfCheck) || - expiryTime === undefined || - timeCreated === undefined - ) { - // it would come here if we change the structure of the JWT. - throw Error("Access token does not contain all the information. Maybe the structure has changed?"); + let expiryTime = sanitizeNumberInput(payload.expiryTime)!; + let timeCreated = sanitizeNumberInput(payload.timeCreated)!; + + if (antiCsrfToken === undefined && doAntiCsrfCheck) { + throw Error("Access token does not contain the anti-csrf token."); } + if (expiryTime < Date.now()) { throw Error("Access token expired"); } @@ -78,6 +75,21 @@ export async function getInfoFromAccessToken( } } +export function validateAccessTokenStructure(payload: any) { + if ( + typeof payload.sessionHandle !== "string" || + typeof payload.userId !== "string" || + typeof payload.recipeUserId !== "string" || + typeof payload.refreshTokenHash1 !== "string" || + payload.userData === undefined || + typeof payload.expiryTime !== "number" || + typeof payload.timeCreated !== "number" + ) { + // it would come here if we change the structure of the JWT. + throw Error("Access token does not contain all the information. Maybe the structure has changed?"); + } +} + function sanitizeStringInput(field: any): string | undefined { if (field === "") { return ""; diff --git a/lib/ts/recipe/session/constants.ts b/lib/ts/recipe/session/constants.ts index a2d5691d0..a8a5fb90e 100644 --- a/lib/ts/recipe/session/constants.ts +++ b/lib/ts/recipe/session/constants.ts @@ -13,5 +13,9 @@ * under the License. */ +import { TokenTransferMethod } from "./types"; + export const REFRESH_API_PATH = "/session/refresh"; export const SIGNOUT_API_PATH = "/signout"; + +export const availableTokenTransferMethods: TokenTransferMethod[] = ["cookie", "header"]; diff --git a/lib/ts/recipe/session/cookieAndHeaders.ts b/lib/ts/recipe/session/cookieAndHeaders.ts index c106db484..480fea2a2 100644 --- a/lib/ts/recipe/session/cookieAndHeaders.ts +++ b/lib/ts/recipe/session/cookieAndHeaders.ts @@ -12,94 +12,57 @@ * License for the specific language governing permissions and limitations * under the License. */ +import { HEADER_RID } from "../../constants"; import { BaseRequest, BaseResponse } from "../../framework"; -import { TypeNormalisedInput } from "./types"; +import { availableTokenTransferMethods } from "./constants"; +import { TokenTransferMethod, TokenType, TypeNormalisedInput } from "./types"; +const authorizationHeaderKey = "authorization"; const accessTokenCookieKey = "sAccessToken"; +const accessTokenHeaderKey = "st-access-token"; const refreshTokenCookieKey = "sRefreshToken"; - -// there are two of them because one is used by the server to check if the user is logged in and the other is checked by the frontend to see if the user is logged in. -const idRefreshTokenCookieKey = "sIdRefreshToken"; -const idRefreshTokenHeaderKey = "id-refresh-token"; +const refreshTokenHeaderKey = "st-refresh-token"; const antiCsrfHeaderKey = "anti-csrf"; -const ridHeaderKey = "rid"; - const frontTokenHeaderKey = "front-token"; -/** - * @description clears all the auth cookies from the response - */ -export function clearSessionFromCookie(config: TypeNormalisedInput, res: BaseResponse) { - setCookie(config, res, accessTokenCookieKey, "", 0, "accessTokenPath"); - setCookie(config, res, refreshTokenCookieKey, "", 0, "refreshTokenPath"); - setCookie(config, res, idRefreshTokenCookieKey, "", 0, "accessTokenPath"); - res.setHeader(idRefreshTokenHeaderKey, "remove", false); - res.setHeader("Access-Control-Expose-Headers", idRefreshTokenHeaderKey, true); -} - -/** - * @param expiry: must be time in milliseconds from epoch time. - */ -export function attachAccessTokenToCookie( - config: TypeNormalisedInput, - res: BaseResponse, - token: string, - expiry: number -) { - setCookie(config, res, accessTokenCookieKey, token, expiry, "accessTokenPath"); -} - -/** - * @param expiry: must be time in milliseconds from epoch time. - */ -export function attachRefreshTokenToCookie( - config: TypeNormalisedInput, - res: BaseResponse, - token: string, - expiry: number -) { - setCookie(config, res, refreshTokenCookieKey, token, expiry, "refreshTokenPath"); +const authModeHeaderKey = "st-auth-mode"; + +export function clearSessionFromAllTokenTransferMethods(config: TypeNormalisedInput, res: BaseResponse) { + // We are clearing the session in all transfermethods to be sure to override cookies in case they have been already added to the response. + // This is done to handle the following use-case: + // If the app overrides signInPOST to check the ban status of the user after the original implementation and throwing an UNAUTHORISED error + // In this case: the SDK has attached cookies to the response, but none was sent with the request + // We can't know which to clear since we can't reliably query or remove the set-cookie header added to the response (causes issues in some frameworks, i.e.: hapi) + // The safe solution in this case is to overwrite all the response cookies/headers with an empty value, which is what we are doing here + for (const transferMethod of availableTokenTransferMethods) { + clearSession(config, res, transferMethod); + } } -export function getAccessTokenFromCookie(req: BaseRequest): string | undefined { - return req.getCookieValue(accessTokenCookieKey); -} +export function clearSession(config: TypeNormalisedInput, res: BaseResponse, transferMethod: TokenTransferMethod) { + // If we can be specific about which transferMethod we want to clear, there is no reason to clear the other ones + const tokenTypes: TokenType[] = ["access", "refresh"]; + for (const token of tokenTypes) { + setToken(config, res, token, "", 0, transferMethod); + } -export function getRefreshTokenFromCookie(req: BaseRequest): string | undefined { - return req.getCookieValue(refreshTokenCookieKey); + res.removeHeader(antiCsrfHeaderKey); + // This can be added multiple times in some cases, but that should be OK + res.setHeader(frontTokenHeaderKey, "remove", false); + res.setHeader("Access-Control-Expose-Headers", frontTokenHeaderKey, true); } export function getAntiCsrfTokenFromHeaders(req: BaseRequest): string | undefined { return req.getHeaderValue(antiCsrfHeaderKey); } -export function getRidFromHeader(req: BaseRequest): string | undefined { - return req.getHeaderValue(ridHeaderKey); -} - -export function getIdRefreshTokenFromCookie(req: BaseRequest): string | undefined { - return req.getCookieValue(idRefreshTokenCookieKey); -} - export function setAntiCsrfTokenInHeaders(res: BaseResponse, antiCsrfToken: string) { res.setHeader(antiCsrfHeaderKey, antiCsrfToken, false); res.setHeader("Access-Control-Expose-Headers", antiCsrfHeaderKey, true); } -export function setIdRefreshTokenInHeaderAndCookie( - config: TypeNormalisedInput, - res: BaseResponse, - idRefreshToken: string, - expiry: number -) { - res.setHeader(idRefreshTokenHeaderKey, idRefreshToken + ";" + expiry, false); - res.setHeader("Access-Control-Expose-Headers", idRefreshTokenHeaderKey, true); - - setCookie(config, res, idRefreshTokenCookieKey, idRefreshToken, expiry, "accessTokenPath"); -} - export function setFrontTokenInHeaders(res: BaseResponse, userId: string, atExpiry: number, accessTokenPayload: any) { const tokenInfo = { uid: userId, @@ -111,7 +74,71 @@ export function setFrontTokenInHeaders(res: BaseResponse, userId: string, atExpi } export function getCORSAllowedHeaders(): string[] { - return [antiCsrfHeaderKey, ridHeaderKey]; + return [antiCsrfHeaderKey, HEADER_RID, authorizationHeaderKey, authModeHeaderKey]; +} + +function getCookieNameFromTokenType(tokenType: TokenType) { + switch (tokenType) { + case "access": + return accessTokenCookieKey; + case "refresh": + return refreshTokenCookieKey; + default: + throw new Error("Unknown token type, should never happen."); + } +} + +function getResponseHeaderNameForTokenType(tokenType: TokenType) { + switch (tokenType) { + case "access": + return accessTokenHeaderKey; + case "refresh": + return refreshTokenHeaderKey; + default: + throw new Error("Unknown token type, should never happen."); + } +} + +export function getToken(req: BaseRequest, tokenType: TokenType, transferMethod: TokenTransferMethod) { + if (transferMethod === "cookie") { + return req.getCookieValue(getCookieNameFromTokenType(tokenType)); + } else if (transferMethod === "header") { + const value = req.getHeaderValue(authorizationHeaderKey); + if (value === undefined || !value.startsWith("Bearer ")) { + return undefined; + } + + return value.replace(/^Bearer /, "").trim(); + } else { + throw new Error("Should never happen: Unknown transferMethod: " + transferMethod); + } +} + +export function setToken( + config: TypeNormalisedInput, + res: BaseResponse, + tokenType: TokenType, + value: string, + expires: number, + transferMethod: TokenTransferMethod +) { + if (transferMethod === "cookie") { + setCookie( + config, + res, + getCookieNameFromTokenType(tokenType), + value, + expires, + tokenType === "refresh" ? "refreshTokenPath" : "accessTokenPath" + ); + } else if (transferMethod === "header") { + setHeader(res, getResponseHeaderNameForTokenType(tokenType), value); + } +} + +export function setHeader(res: BaseResponse, name: string, value: string) { + res.setHeader(name, value, false); + res.setHeader("Access-Control-Expose-Headers", name, true); } /** @@ -146,3 +173,7 @@ export function setCookie( return res.setCookie(name, value, domain, secure, httpOnly, expires, path, sameSite); } + +export function getAuthModeFromHeader(req: BaseRequest): string | undefined { + return req.getHeaderValue(authModeHeaderKey)?.toLowerCase(); +} diff --git a/lib/ts/recipe/session/error.ts b/lib/ts/recipe/session/error.ts index bb239b512..c97ea7f36 100644 --- a/lib/ts/recipe/session/error.ts +++ b/lib/ts/recipe/session/error.ts @@ -28,7 +28,7 @@ export default class SessionError extends STError { message: string; type: "UNAUTHORISED"; payload?: { - clearCookies: boolean; + clearTokens: boolean; }; } | { @@ -55,7 +55,7 @@ export default class SessionError extends STError { ? { ...options, payload: { - clearCookies: true, + clearTokens: true, }, } : { ...options } diff --git a/lib/ts/recipe/session/index.ts b/lib/ts/recipe/session/index.ts index 1711a176b..cf8ff9a75 100644 --- a/lib/ts/recipe/session/index.ts +++ b/lib/ts/recipe/session/index.ts @@ -39,6 +39,7 @@ export default class SessionWrapper { static Error = SuperTokensError; static async createNewSession( + req: any, res: any, userId: string, recipeUserId?: string, @@ -58,10 +59,15 @@ export default class SessionWrapper { }; } + if (!req.wrapperUsed) { + req = frameworks[SuperTokens.getInstanceOrThrowError().framework].wrapRequest(req); + } + if (!res.wrapperUsed) { res = frameworks[SuperTokens.getInstanceOrThrowError().framework].wrapResponse(res); } return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.createNewSession({ + req, res, userId, recipeUserId, diff --git a/lib/ts/recipe/session/jwt.ts b/lib/ts/recipe/session/jwt.ts index 2855d6297..f8ebf1f2b 100644 --- a/lib/ts/recipe/session/jwt.ts +++ b/lib/ts/recipe/session/jwt.ts @@ -31,7 +31,15 @@ const HEADERS = new Set([ ).toString("base64"), ]); -export function verifyJWTAndGetPayload(jwt: string, jwtSigningPublicKey: string): { [key: string]: any } { +export type ParsedJWTInfo = { + rawTokenString: string; + rawPayload: string; + header: string; + payload: any; + signature: string; +}; + +export function parseJWTWithoutSignatureVerification(jwt: string): ParsedJWTInfo { const splittedInput = jwt.split("."); if (splittedInput.length !== 3) { throw new Error("Invalid JWT"); @@ -42,33 +50,29 @@ export function verifyJWTAndGetPayload(jwt: string, jwtSigningPublicKey: string) throw new Error("JWT header mismatch"); } - let payload = splittedInput[1]; + return { + rawTokenString: jwt, + rawPayload: splittedInput[1], + header: splittedInput[0], + // Ideally we would only parse this after the signature verification is done. + // We do this at the start, since we want to check if a token can be a supertokens access token or not + payload: JSON.parse(Buffer.from(splittedInput[1], "base64").toString()), + signature: splittedInput[2], + }; +} +export function verifyJWT({ header, rawPayload, signature }: ParsedJWTInfo, jwtSigningPublicKey: string): void { let verifier = crypto.createVerify("sha256"); // convert the jwtSigningPublicKey into .pem format - verifier.update(splittedInput[0] + "." + payload); + verifier.update(header + "." + rawPayload); if ( !verifier.verify( "-----BEGIN PUBLIC KEY-----\n" + jwtSigningPublicKey + "\n-----END PUBLIC KEY-----", - splittedInput[2], + signature, "base64" ) ) { throw new Error("JWT verification failed"); } - // sending payload - payload = Buffer.from(payload, "base64").toString(); - return JSON.parse(payload); -} - -export function getPayloadWithoutVerifiying(jwt: string): { [key: string]: any } { - const splittedInput = jwt.split("."); - if (splittedInput.length !== 3) { - throw new Error("Invalid JWT"); - } - - let payload = splittedInput[1]; - payload = Buffer.from(payload, "base64").toString(); - return JSON.parse(payload); } diff --git a/lib/ts/recipe/session/recipe.ts b/lib/ts/recipe/session/recipe.ts index cc0ccc0b1..afc115f46 100644 --- a/lib/ts/recipe/session/recipe.ts +++ b/lib/ts/recipe/session/recipe.ts @@ -31,7 +31,7 @@ import signOutAPI from "./api/signout"; import { REFRESH_API_PATH, SIGNOUT_API_PATH } from "./constants"; import NormalisedURLPath from "../../normalisedURLPath"; import { - clearSessionFromCookie, + clearSessionFromAllTokenTransferMethods, getCORSAllowedHeaders as getCORSAllowedHeadersFromCookiesAndHeaders, } from "./cookieAndHeaders"; import RecipeImplementation from "./recipeImplementation"; @@ -84,6 +84,7 @@ export default class SessionRecipe extends RecipeModule { RecipeImplementation( Querier.getNewInstanceOrThrowError(recipeId), this.config, + this.getAppInfo(), () => this.recipeInterfaceImpl ) ); @@ -104,6 +105,7 @@ export default class SessionRecipe extends RecipeModule { RecipeImplementation( Querier.getNewInstanceOrThrowError(recipeId), this.config, + this.getAppInfo(), () => this.recipeInterfaceImpl ) ); @@ -220,11 +222,11 @@ export default class SessionRecipe extends RecipeModule { logDebugMessage("errorHandler: returning UNAUTHORISED"); if ( err.payload === undefined || - err.payload.clearCookies === undefined || - err.payload.clearCookies === true + err.payload.clearTokens === undefined || + err.payload.clearTokens === true ) { - logDebugMessage("errorHandler: Clearing cookies because of UNAUTHORISED response"); - clearSessionFromCookie(this.config, response); + logDebugMessage("errorHandler: Clearing tokens because of UNAUTHORISED response"); + clearSessionFromAllTokenTransferMethods(this.config, response); } return await this.config.errorHandlers.onUnauthorised(err.message, request, response); } else if (err.type === STError.TRY_REFRESH_TOKEN) { @@ -232,8 +234,8 @@ export default class SessionRecipe extends RecipeModule { return await this.config.errorHandlers.onTryRefreshToken(err.message, request, response); } else if (err.type === STError.TOKEN_THEFT_DETECTED) { logDebugMessage("errorHandler: returning TOKEN_THEFT_DETECTED"); - logDebugMessage("errorHandler: Clearing cookies because of TOKEN_THEFT_DETECTED response"); - clearSessionFromCookie(this.config, response); + logDebugMessage("errorHandler: Clearing tokens because of TOKEN_THEFT_DETECTED response"); + clearSessionFromAllTokenTransferMethods(this.config, response); return await this.config.errorHandlers.onTokenTheftDetected( err.payload.sessionHandle, err.payload.userId, diff --git a/lib/ts/recipe/session/recipeImplementation.ts b/lib/ts/recipe/session/recipeImplementation.ts index 93cf9d0da..dca5e55d5 100644 --- a/lib/ts/recipe/session/recipeImplementation.ts +++ b/lib/ts/recipe/session/recipeImplementation.ts @@ -8,28 +8,31 @@ import { SessionClaimValidator, SessionClaim, ClaimValidationError, + TokenTransferMethod, } from "./types"; import * as SessionFunctions from "./sessionFunctions"; import { - attachAccessTokenToCookie, - getAccessTokenFromCookie, + clearSession, getAntiCsrfTokenFromHeaders, - getIdRefreshTokenFromCookie, - getRefreshTokenFromCookie, setFrontTokenInHeaders, - getRidFromHeader, + getToken, + setToken, + setCookie, } from "./cookieAndHeaders"; -import { attachCreateOrRefreshSessionResponseToExpressRes, validateClaimsInPayload } from "./utils"; +import { attachTokensToResponse, validateClaimsInPayload } from "./utils"; import Session from "./sessionClass"; import STError from "./error"; -import { normaliseHttpMethod, frontendHasInterceptor } from "../../utils"; +import { normaliseHttpMethod, getRidFromHeader, isAnIpAddress } from "../../utils"; import { Querier } from "../../querier"; import { PROCESS_STATE, ProcessState } from "../../processState"; import NormalisedURLPath from "../../normalisedURLPath"; -import { JSONObject } from "../../types"; +import { JSONObject, NormalisedAppinfo } from "../../types"; import { logDebugMessage } from "../../logger"; import { BaseResponse } from "../../framework/response"; import { BaseRequest } from "../../framework/request"; +import { availableTokenTransferMethods } from "./constants"; +import { ParsedJWTInfo, parseJWTWithoutSignatureVerification } from "./jwt"; +import { validateAccessTokenStructure } from "./accessToken"; export class HandshakeInfo { constructor( @@ -64,12 +67,17 @@ export type Helpers = { getHandshakeInfo: (forceRefetch?: boolean) => Promise; updateJwtSigningPublicKeyInfo: (keyList: KeyInfo[] | undefined, publicKey: string, expiryTime: number) => void; config: TypeNormalisedInput; + appInfo: NormalisedAppinfo; getRecipeImpl: () => RecipeInterface; }; +// We are defining this here to reduce the scope of legacy code +const LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME = "sIdRefreshToken"; + export default function getRecipeInterface( querier: Querier, config: TypeNormalisedInput, + appInfo: NormalisedAppinfo, getRecipeImplAfterOverrides: () => RecipeInterface ): RecipeInterface { let handshakeInfo: undefined | HandshakeInfo; @@ -110,12 +118,15 @@ export default function getRecipeInterface( let obj: RecipeInterface = { createNewSession: async function ({ + req, res, userId, recipeUserId, accessTokenPayload = {}, sessionData = {}, + userContext, }: { + req: BaseRequest; res: BaseResponse; userId: string; recipeUserId?: string; @@ -123,14 +134,49 @@ export default function getRecipeInterface( sessionData?: any; userContext: any; }): Promise { + logDebugMessage("createNewSession: Started"); + let outputTransferMethod = config.getTokenTransferMethod({ req, forCreateNewSession: true, userContext }); + if (outputTransferMethod === "any") { + outputTransferMethod = "header"; + } + logDebugMessage("createNewSession: using transfer method " + outputTransferMethod); + + if ( + outputTransferMethod === "cookie" && + helpers.config.cookieSameSite === "none" && + !helpers.config.cookieSecure && + !( + (helpers.appInfo.topLevelAPIDomain === "localhost" || + isAnIpAddress(helpers.appInfo.topLevelAPIDomain)) && + (helpers.appInfo.topLevelWebsiteDomain === "localhost" || + isAnIpAddress(helpers.appInfo.topLevelWebsiteDomain)) + ) + ) { + // We can allow insecure cookie when both website & API domain are localhost or an IP + // When either of them is a different domain, API domain needs to have https and a secure cookie to work + throw new Error( + "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." + ); + } + + const disableAntiCSRF = outputTransferMethod === "header"; + let response = await SessionFunctions.createNewSession( helpers, userId, + disableAntiCSRF, recipeUserId, accessTokenPayload, sessionData ); - attachCreateOrRefreshSessionResponseToExpressRes(config, res, response); + + for (const transferMethod of availableTokenTransferMethods) { + if (transferMethod !== outputTransferMethod && getToken(req, "access", transferMethod) !== undefined) { + clearSession(config, res, transferMethod); + } + } + + attachTokensToResponse(config, res, response, outputTransferMethod); return new Session( helpers, response.accessToken.token, @@ -138,7 +184,9 @@ export default function getRecipeInterface( response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, - res + res, + req, + outputTransferMethod ); }, @@ -148,10 +196,14 @@ export default function getRecipeInterface( return input.claimValidatorsAddedByOtherRecipes; }, + /* In all cases if sIdRefreshToken token exists (so it's a legacy session) we return TRY_REFRESH_TOKEN. The refresh endpoint will clear this cookie and try to upgrade the session. + Check https://supertokens.com/docs/contribute/decisions/session/0007 for further details and a table of expected behaviours + */ getSession: async function ({ req, res, options, + userContext, }: { req: BaseRequest; res: BaseResponse; @@ -159,63 +211,96 @@ export default function getRecipeInterface( userContext: any; }): Promise { logDebugMessage("getSession: Started"); - logDebugMessage("getSession: rid in header: " + frontendHasInterceptor(req)); - logDebugMessage("getSession: request method: " + req.getMethod()); - let doAntiCsrfCheck = options !== undefined ? options.antiCsrfCheck : undefined; - let idRefreshToken = getIdRefreshTokenFromCookie(req); - if (idRefreshToken === undefined) { - // we do not clear cookies here because of a - // race condition mentioned here: https://github.com/supertokens/supertokens-node/issues/17 + // This token isn't handled by getToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + // This could create a spike on refresh calls during the update of the backend SDK + throw new STError({ + message: "using legacy session, please call the refresh API", + type: STError.TRY_REFRESH_TOKEN, + }); + } - if (options !== undefined && typeof options !== "boolean" && options.sessionRequired === false) { + const sessionOptional = options?.sessionRequired === false; + logDebugMessage("getSession: optional validation: " + sessionOptional); + + const accessTokens: { + [key in TokenTransferMethod]?: ParsedJWTInfo; + } = {}; + + // We check all token transfer methods for available access tokens + for (const transferMethod of availableTokenTransferMethods) { + const tokenString = getToken(req, "access", transferMethod); + if (tokenString !== undefined) { + try { + const info = parseJWTWithoutSignatureVerification(tokenString); + validateAccessTokenStructure(info.payload); + logDebugMessage("getSession: got access token from " + transferMethod); + accessTokens[transferMethod] = info; + } catch { + logDebugMessage( + `getSession: ignoring token in ${transferMethod}, because it doesn't match our access token structure` + ); + } + } + } + + const allowedTransferMethod = config.getTokenTransferMethod({ + req, + forCreateNewSession: false, + userContext, + }); + let requestTransferMethod: TokenTransferMethod; + let accessToken: ParsedJWTInfo | undefined; + + if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "header") && + accessTokens["header"] !== undefined + ) { + logDebugMessage("getSession: using header transfer method"); + requestTransferMethod = "header"; + accessToken = accessTokens["header"]; + } else if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && + accessTokens["cookie"] !== undefined + ) { + logDebugMessage("getSession: using cookie transfer method"); + requestTransferMethod = "cookie"; + accessToken = accessTokens["cookie"]; + } else { + if (sessionOptional) { logDebugMessage( - "getSession: returning undefined because idRefreshToken is undefined and sessionRequired is false" + "getSession: returning undefined because accessToken is undefined and sessionRequired is false" ); // there is no session that exists here, and the user wants session verification // to be optional. So we return undefined. return undefined; } - logDebugMessage("getSession: UNAUTHORISED because idRefreshToken from cookies is undefined"); + logDebugMessage("getSession: UNAUTHORISED because accessToken in request is undefined"); throw new STError({ - message: "Session does not exist. Are you sending the session tokens in the request as cookies?", + message: + "Session does not exist. Are you sending the session tokens in the request with the appropriate token transfer method?", type: STError.UNAUTHORISED, payload: { - clearCookies: false, + // we do not clear the session here because of a + // race condition mentioned here: https://github.com/supertokens/supertokens-node/issues/17 + clearTokens: false, }, }); } - let accessToken = getAccessTokenFromCookie(req); - if (accessToken === undefined) { - // maybe the access token has expired. - /** - * Based on issue: #156 (spertokens-node) - * we throw TRY_REFRESH_TOKEN only if - * options.sessionRequired === true || (frontendHasInterceptor or request method is get), - * else we should return undefined - */ - if ( - options === undefined || - (options !== undefined && options.sessionRequired === true) || - frontendHasInterceptor(req) || - normaliseHttpMethod(req.getMethod()) === "get" - ) { - logDebugMessage( - "getSession: Returning try refresh token because access token from cookies is undefined" - ); - throw new STError({ - message: "Access token has expired. Please call the refresh API", - type: STError.TRY_REFRESH_TOKEN, - }); - } - return undefined; - } + let antiCsrfToken = getAntiCsrfTokenFromHeaders(req); + let doAntiCsrfCheck = options !== undefined ? options.antiCsrfCheck : undefined; if (doAntiCsrfCheck === undefined) { doAntiCsrfCheck = normaliseHttpMethod(req.getMethod()) !== "get"; } + + if (requestTransferMethod === "header") { + doAntiCsrfCheck = false; + } + logDebugMessage("getSession: Value of doAntiCsrfCheck is: " + doAntiCsrfCheck); let response = await SessionFunctions.getSession( @@ -225,6 +310,7 @@ export default function getRecipeInterface( doAntiCsrfCheck, getRidFromHeader(req) !== undefined ); + let accessTokenString = accessToken.rawTokenString; if (response.accessToken !== undefined) { setFrontTokenInHeaders( res, @@ -232,18 +318,31 @@ export default function getRecipeInterface( response.accessToken.expiry, response.session.userDataInJWT ); - attachAccessTokenToCookie(config, res, response.accessToken.token, response.accessToken.expiry); - accessToken = response.accessToken.token; + setToken( + config, + res, + "access", + response.accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, + requestTransferMethod + ); + accessTokenString = response.accessToken.token; } logDebugMessage("getSession: Success!"); const session = new Session( helpers, - accessToken, + accessTokenString, response.session.handle, response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, - res + res, + req, + requestTransferMethod ); return session; @@ -308,49 +407,122 @@ export default function getRecipeInterface( return SessionFunctions.getSessionInformation(helpers, sessionHandle); }, + /* + In all cases: if sIdRefreshToken token exists (so it's a legacy session) we clear it. + Check http://localhost:3002/docs/contribute/decisions/session/0008 for further details and a table of expected behaviours + */ refreshSession: async function ( this: RecipeInterface, - { req, res }: { req: BaseRequest; res: BaseResponse } + { req, res, userContext }: { req: BaseRequest; res: BaseResponse; userContext: any } ): Promise { logDebugMessage("refreshSession: Started"); - let inputIdRefreshToken = getIdRefreshTokenFromCookie(req); - if (inputIdRefreshToken === undefined) { - logDebugMessage("refreshSession: UNAUTHORISED because idRefreshToken from cookies is undefined"); - // we do not clear cookies here because of a - // race condition mentioned here: https://github.com/supertokens/supertokens-node/issues/17 - throw new STError({ - message: "Session does not exist. Are you sending the session tokens in the request as cookies?", - type: STError.UNAUTHORISED, - }); + const refreshTokens: { + [key in TokenTransferMethod]?: string; + } = {}; + + // We check all token transfer methods for available refresh tokens + // We do this so that we can later clear all we are not overwriting + for (const transferMethod of availableTokenTransferMethods) { + refreshTokens[transferMethod] = getToken(req, "refresh", transferMethod); + if (refreshTokens[transferMethod] !== undefined) { + logDebugMessage("refreshSession: got refresh token from " + transferMethod); + } } - let inputRefreshToken = getRefreshTokenFromCookie(req); - if (inputRefreshToken === undefined) { - logDebugMessage("refreshSession: UNAUTHORISED because refresh token from cookies is undefined"); + const allowedTransferMethod = config.getTokenTransferMethod({ + req, + forCreateNewSession: false, + userContext, + }); + logDebugMessage("refreshSession: getTokenTransferMethod returned " + allowedTransferMethod); + + let requestTransferMethod: TokenTransferMethod; + let refreshToken: string | undefined; + + if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "header") && + refreshTokens["header"] !== undefined + ) { + logDebugMessage("refreshSession: using header transfer method"); + requestTransferMethod = "header"; + refreshToken = refreshTokens["header"]; + } else if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && + refreshTokens["cookie"] + ) { + logDebugMessage("refreshSession: using cookie transfer method"); + requestTransferMethod = "cookie"; + refreshToken = refreshTokens["cookie"]; + } else { + // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + logDebugMessage( + "refreshSession: cleared legacy id refresh token because refresh token was not found" + ); + setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + } + + logDebugMessage("refreshSession: UNAUTHORISED because refresh token in request is undefined"); throw new STError({ - message: "Refresh token not found. Are you sending the refresh token in the request as a cookie?", + message: "Refresh token not found. Are you sending the refresh token in the request?", + payload: { + clearTokens: false, + }, type: STError.UNAUTHORISED, }); } - let antiCsrfToken = getAntiCsrfTokenFromHeaders(req); - let response = await SessionFunctions.refreshSession( - helpers, - inputRefreshToken, - antiCsrfToken, - getRidFromHeader(req) !== undefined - ); - attachCreateOrRefreshSessionResponseToExpressRes(config, res, response); - logDebugMessage("refreshSession: Success!"); - return new Session( - helpers, - response.accessToken.token, - response.session.handle, - response.session.userId, - response.session.recipeUserId, - response.session.userDataInJWT, - res - ); + + try { + let antiCsrfToken = getAntiCsrfTokenFromHeaders(req); + let response = await SessionFunctions.refreshSession( + helpers, + refreshToken, + antiCsrfToken, + getRidFromHeader(req) !== undefined, + requestTransferMethod + ); + logDebugMessage("refreshSession: Attaching refreshed session info as " + requestTransferMethod); + + // We clear the tokens in all token transfer methods we are not going to overwrite + for (const transferMethod of availableTokenTransferMethods) { + if (transferMethod !== requestTransferMethod && refreshTokens[transferMethod] !== undefined) { + clearSession(config, res, transferMethod); + } + } + + attachTokensToResponse(config, res, response, requestTransferMethod); + + logDebugMessage("refreshSession: Success!"); + // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + logDebugMessage("refreshSession: cleared legacy id refresh token after successful refresh"); + setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + } + + return new Session( + helpers, + response.accessToken.token, + response.session.handle, + response.session.userId, + response.session.recipeUserId, + response.session.userDataInJWT, + res, + req, + requestTransferMethod + ); + } catch (err) { + if (err.type === STError.TOKEN_THEFT_DETECTED || err.payload.clearTokens) { + // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code + if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { + logDebugMessage( + "refreshSession: cleared legacy id refresh token because refresh is clearing other tokens" + ); + setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + } + } + throw err; + } }, regenerateAccessToken: async function ( @@ -545,6 +717,7 @@ export default function getRecipeInterface( updateJwtSigningPublicKeyInfo, getHandshakeInfo, config, + appInfo, getRecipeImpl: getRecipeImplAfterOverrides, }; diff --git a/lib/ts/recipe/session/sessionClass.ts b/lib/ts/recipe/session/sessionClass.ts index 4dfded2db..f809fdc8b 100644 --- a/lib/ts/recipe/session/sessionClass.ts +++ b/lib/ts/recipe/session/sessionClass.ts @@ -12,38 +12,25 @@ * License for the specific language governing permissions and limitations * under the License. */ -import { BaseResponse } from "../../framework"; -import { attachAccessTokenToCookie, clearSessionFromCookie, setFrontTokenInHeaders } from "./cookieAndHeaders"; +import { BaseRequest, BaseResponse } from "../../framework"; +import { clearSession, setFrontTokenInHeaders, setToken } from "./cookieAndHeaders"; import STError from "./error"; -import { SessionClaim, SessionClaimValidator, SessionContainerInterface } from "./types"; +import { SessionClaim, SessionClaimValidator, SessionContainerInterface, TokenTransferMethod } from "./types"; import { Helpers } from "./recipeImplementation"; export default class Session implements SessionContainerInterface { - protected sessionHandle: string; - protected userId: string; - protected userDataInAccessToken: any; - protected res: BaseResponse; - protected accessToken: string; - protected helpers: Helpers; - protected recipeUserId: string; - constructor( - helpers: Helpers, - accessToken: string, - sessionHandle: string, - userId: string, - recipeUserId: string, - userDataInAccessToken: any, - res: BaseResponse - ) { - this.sessionHandle = sessionHandle; - this.userId = userId; - this.userDataInAccessToken = userDataInAccessToken; - this.res = res; - this.accessToken = accessToken; - this.helpers = helpers; - this.recipeUserId = recipeUserId; - } + protected helpers: Helpers, + protected accessToken: string, + protected sessionHandle: string, + protected userId: string, + protected recipeUserId: string, + protected userDataInAccessToken: any, + protected res: BaseResponse, + protected readonly req: BaseRequest, + protected readonly transferMethod: TokenTransferMethod + ) {} + getRecipeUserId(_userContext?: any): string { return this.recipeUserId; } @@ -60,7 +47,7 @@ export default class Session implements SessionContainerInterface { // If we instead clear the cookies only when revokeSession // returns true, it can cause this kind of a bug: // https://github.com/supertokens/supertokens-node/issues/343 - clearSessionFromCookie(this.helpers.config, this.res); + clearSession(this.helpers.config, this.res, this.transferMethod); } async getSessionData(userContext?: any): Promise { @@ -218,11 +205,17 @@ export default class Session implements SessionContainerInterface { response.accessToken.expiry, response.session.userDataInJWT ); - attachAccessTokenToCookie( + setToken( this.helpers.config, this.res, + "access", response.accessToken.token, - response.accessToken.expiry + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, + this.transferMethod ); } } diff --git a/lib/ts/recipe/session/sessionFunctions.ts b/lib/ts/recipe/session/sessionFunctions.ts index 08e82e478..a392cd805 100644 --- a/lib/ts/recipe/session/sessionFunctions.ts +++ b/lib/ts/recipe/session/sessionFunctions.ts @@ -13,10 +13,10 @@ * under the License. */ import { getInfoFromAccessToken, sanitizeNumberInput } from "./accessToken"; -import { getPayloadWithoutVerifiying } from "./jwt"; +import { ParsedJWTInfo } from "./jwt"; import STError from "./error"; import { PROCESS_STATE, ProcessState } from "../../processState"; -import { CreateOrRefreshAPIResponse, SessionInformation } from "./types"; +import { CreateOrRefreshAPIResponse, SessionInformation, TokenTransferMethod } from "./types"; import NormalisedURLPath from "../../normalisedURLPath"; import { Helpers } from "./recipeImplementation"; import { maxVersion } from "../../utils"; @@ -28,6 +28,7 @@ import { logDebugMessage } from "../../logger"; export async function createNewSession( helpers: Helpers, userId: string, + disableAntiCsrf: boolean, recipeUserId?: string, accessTokenPayload: any = {}, sessionData: any = {} @@ -49,7 +50,7 @@ export async function createNewSession( }; let handShakeInfo = await helpers.getHandshakeInfo(); - requestBody.enableAntiCsrf = handShakeInfo.antiCsrf === "VIA_TOKEN"; + requestBody.enableAntiCsrf = !disableAntiCsrf && handShakeInfo.antiCsrf === "VIA_TOKEN"; let response = await helpers.querier.sendPostRequest(new NormalisedURLPath("/recipe/session"), requestBody); helpers.updateJwtSigningPublicKeyInfo( response.jwtSigningPublicKeyList, @@ -69,7 +70,7 @@ export async function createNewSession( */ export async function getSession( helpers: Helpers, - accessToken: string, + parsedAccessToken: ParsedJWTInfo, antiCsrfToken: string | undefined, doAntiCsrfCheck: boolean, containsCustomHeader: boolean @@ -97,7 +98,7 @@ export async function getSession( * get access token info using existing signingKey */ accessTokenInfo = await getInfoFromAccessToken( - accessToken, + parsedAccessToken, key.publicKey, handShakeInfo.antiCsrf === "VIA_TOKEN" && doAntiCsrfCheck ); @@ -128,15 +129,7 @@ export async function getSession( * so if foundASigningKeyThatIsOlderThanTheAccessToken is still false after * the loop we just return TRY_REFRESH_TOKEN */ - let payload; - try { - payload = getPayloadWithoutVerifiying(accessToken); - } catch (_) { - throw err; - } - if (payload === undefined) { - throw err; - } + let payload = parsedAccessToken.payload; const timeCreated = sanitizeNumberInput(payload.timeCreated); const expiryTime = sanitizeNumberInput(payload.expiryTime); @@ -231,7 +224,7 @@ export async function getSession( doAntiCsrfCheck: boolean; enableAntiCsrf?: boolean; } = { - accessToken, + accessToken: parsedAccessToken.rawTokenString, antiCsrfToken, doAntiCsrfCheck, enableAntiCsrf: handShakeInfo.antiCsrf === "VIA_TOKEN", @@ -270,7 +263,7 @@ export async function getSession( // we force update the signing keys... await helpers.getHandshakeInfo(true); } - logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because of core response"); + logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because of core response."); throw new STError({ message: response.message, type: STError.TRY_REFRESH_TOKEN, @@ -318,7 +311,8 @@ export async function refreshSession( helpers: Helpers, refreshToken: string, antiCsrfToken: string | undefined, - containsCustomHeader: boolean + containsCustomHeader: boolean, + transferMethod: TokenTransferMethod ): Promise { let handShakeInfo = await helpers.getHandshakeInfo(); @@ -329,17 +323,17 @@ export async function refreshSession( } = { refreshToken, antiCsrfToken, - enableAntiCsrf: handShakeInfo.antiCsrf === "VIA_TOKEN", + enableAntiCsrf: transferMethod === "cookie" && handShakeInfo.antiCsrf === "VIA_TOKEN", }; - if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { + if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER" && transferMethod === "cookie") { if (!containsCustomHeader) { logDebugMessage("refreshSession: Returning UNAUTHORISED because custom header (rid) was not passed"); throw new STError({ message: "anti-csrf check failed. Please pass 'rid: \"session\"' header in the request.", type: STError.UNAUTHORISED, payload: { - clearCookies: false, // see https://github.com/supertokens/supertokens-node/issues/141 + clearTokens: false, // see https://github.com/supertokens/supertokens-node/issues/141 }, }); } diff --git a/lib/ts/recipe/session/types.ts b/lib/ts/recipe/session/types.ts index 05f89ed18..6dd69274a 100644 --- a/lib/ts/recipe/session/types.ts +++ b/lib/ts/recipe/session/types.ts @@ -62,11 +62,6 @@ export type CreateOrRefreshAPIResponse = { expiry: number; createdTime: number; }; - idRefreshToken: { - token: string; - expiry: number; - createdTime: number; - }; antiCsrfToken: string | undefined; }; @@ -76,14 +71,27 @@ export interface ErrorHandlers { onInvalidClaim?: InvalidClaimErrorHandlerMiddleware; } +export type TokenType = "access" | "refresh"; + +// When adding a new token transfer method, it's also necessary to update the related constant (availableTokenTransferMethods) +export type TokenTransferMethod = "header" | "cookie"; + export type TypeInput = { + sessionExpiredStatusCode?: number; + invalidClaimStatusCode?: number; + cookieSecure?: boolean; cookieSameSite?: "strict" | "lax" | "none"; - sessionExpiredStatusCode?: number; cookieDomain?: string; + + getTokenTransferMethod?: (input: { + req: BaseRequest; + forCreateNewSession: boolean; + userContext: any; + }) => TokenTransferMethod | "any"; + errorHandlers?: ErrorHandlers; antiCsrf?: "VIA_TOKEN" | "VIA_CUSTOM_HEADER" | "NONE"; - invalidClaimStatusCode?: number; jwt?: | { enable: true; @@ -129,6 +137,12 @@ export type TypeNormalisedInput = { errorHandlers: NormalisedErrorHandlers; antiCsrf: "VIA_TOKEN" | "VIA_CUSTOM_HEADER" | "NONE"; + getTokenTransferMethod: (input: { + req: BaseRequest; + forCreateNewSession: boolean; + userContext: any; + }) => TokenTransferMethod | "any"; + invalidClaimStatusCode: number; jwt: { enable: boolean; @@ -205,6 +219,7 @@ export interface VerifySessionOptions { export type RecipeInterface = { createNewSession(input: { + req: BaseRequest; res: BaseResponse; userId: string; recipeUserId?: string; diff --git a/lib/ts/recipe/session/utils.ts b/lib/ts/recipe/session/utils.ts index 7d291211d..528b4f8bb 100644 --- a/lib/ts/recipe/session/utils.ts +++ b/lib/ts/recipe/session/utils.ts @@ -22,20 +22,14 @@ import { SessionClaimValidator, SessionContainerInterface, VerifySessionOptions, + TokenTransferMethod, } from "./types"; -import { - setFrontTokenInHeaders, - attachAccessTokenToCookie, - attachRefreshTokenToCookie, - setIdRefreshTokenInHeaderAndCookie, - setAntiCsrfTokenInHeaders, -} from "./cookieAndHeaders"; +import { setFrontTokenInHeaders, setAntiCsrfTokenInHeaders, setToken, getAuthModeFromHeader } from "./cookieAndHeaders"; import { URL } from "url"; import SessionRecipe from "./recipe"; import { REFRESH_API_PATH } from "./constants"; import NormalisedURLPath from "../../normalisedURLPath"; import { NormalisedAppinfo } from "../../types"; -import * as psl from "psl"; import { isAnIpAddress } from "../../utils"; import { RecipeInterface, APIInterface } from "./types"; import { BaseRequest, BaseResponse } from "../../framework"; @@ -126,20 +120,6 @@ export function normaliseSessionScopeOrThrowError(sessionScope: string): string return noDotNormalised; } -export function getTopLevelDomainForSameSiteResolution(url: string): string { - let urlObj = new URL(url); - let hostname = urlObj.hostname; - if (hostname.startsWith("localhost") || hostname.startsWith("localhost.org") || isAnIpAddress(hostname)) { - // we treat these as the same TLDs since we can use sameSite lax for all of them. - return "localhost"; - } - let parsedURL = psl.parse(hostname) as psl.ParsedDomain; - if (parsedURL.domain === null) { - throw new Error("Please make sure that the apiDomain and websiteDomain have correct values"); - } - return parsedURL.domain; -} - export function getURLProtocol(url: string): string { let urlObj = new URL(url); return urlObj.protocol; @@ -155,14 +135,13 @@ export function validateAndNormaliseUserInput( ? undefined : normaliseSessionScopeOrThrowError(config.cookieDomain); - let topLevelAPIDomain = getTopLevelDomainForSameSiteResolution(appInfo.apiDomain.getAsStringDangerous()); - let topLevelWebsiteDomain = getTopLevelDomainForSameSiteResolution(appInfo.websiteDomain.getAsStringDangerous()); - let protocolOfAPIDomain = getURLProtocol(appInfo.apiDomain.getAsStringDangerous()); let protocolOfWebsiteDomain = getURLProtocol(appInfo.websiteDomain.getAsStringDangerous()); let cookieSameSite: "strict" | "lax" | "none" = - topLevelAPIDomain !== topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain ? "none" : "lax"; + appInfo.topLevelAPIDomain !== appInfo.topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain + ? "none" + : "lax"; cookieSameSite = config === undefined || config.cookieSameSite === undefined ? cookieSameSite @@ -233,21 +212,6 @@ export function validateAndNormaliseUserInput( } } - if ( - cookieSameSite === "none" && - !cookieSecure && - !( - (topLevelAPIDomain === "localhost" || isAnIpAddress(topLevelAPIDomain)) && - (topLevelWebsiteDomain === "localhost" || isAnIpAddress(topLevelWebsiteDomain)) - ) - ) { - // We can allow insecure cookie when both website & API domain are localhost or an IP - // When either of them is a different domain, API domain needs to have https and a secure cookie to work - throw new Error( - "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." - ); - } - let enableJWT = false; let accessTokenPayloadJWTPropertyName = "jwt"; let issuer: string | undefined; @@ -274,6 +238,10 @@ export function validateAndNormaliseUserInput( return { refreshTokenPath: appInfo.apiBasePath.appendPath(new NormalisedURLPath(REFRESH_API_PATH)), + getTokenTransferMethod: + config?.getTokenTransferMethod === undefined + ? defaultGetTokenTransferMethod + : config.getTokenTransferMethod, cookieDomain, cookieSameSite, cookieSecure, @@ -299,18 +267,28 @@ export function normaliseSameSiteOrThrowError(sameSite: string): "strict" | "lax return sameSite; } -export function attachCreateOrRefreshSessionResponseToExpressRes( +export function attachTokensToResponse( config: TypeNormalisedInput, res: BaseResponse, - response: CreateOrRefreshAPIResponse + response: CreateOrRefreshAPIResponse, + transferMethod: TokenTransferMethod ) { let accessToken = response.accessToken; let refreshToken = response.refreshToken; - let idRefreshToken = response.idRefreshToken; setFrontTokenInHeaders(res, response.session.userId, response.accessToken.expiry, response.session.userDataInJWT); - attachAccessTokenToCookie(config, res, accessToken.token, accessToken.expiry); - attachRefreshTokenToCookie(config, res, refreshToken.token, refreshToken.expiry); - setIdRefreshTokenInHeaderAndCookie(config, res, idRefreshToken.token, idRefreshToken.expiry); + setToken( + config, + res, + "access", + accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, + transferMethod + ); + setToken(config, res, "refresh", refreshToken.token, refreshToken.expiry, transferMethod); if (response.antiCsrfToken !== undefined) { setAntiCsrfTokenInHeaders(res, response.antiCsrfToken); } @@ -356,3 +334,26 @@ export async function validateClaimsInPayload( } return validationErrors; } + +function defaultGetTokenTransferMethod({ + req, + forCreateNewSession, +}: { + req: BaseRequest; + forCreateNewSession: boolean; +}): TokenTransferMethod | "any" { + // We allow fallback (checking headers then cookies) by default when validating + if (!forCreateNewSession) { + return "any"; + } + + // In create new session we respect the frontend preference by default + switch (getAuthModeFromHeader(req)) { + case "header": + return "header"; + case "cookie": + return "cookie"; + default: + return "any"; + } +} diff --git a/lib/ts/recipe/session/with-jwt/recipeImplementation.ts b/lib/ts/recipe/session/with-jwt/recipeImplementation.ts index 0745f883d..60aceb316 100644 --- a/lib/ts/recipe/session/with-jwt/recipeImplementation.ts +++ b/lib/ts/recipe/session/with-jwt/recipeImplementation.ts @@ -69,7 +69,7 @@ export default function ( let decodedPayload = JsonWebToken.decode(existingJwt, { json: true }); // JsonWebToken.decode possibly returns null - if (decodedPayload === null) { + if (decodedPayload === null || decodedPayload.exp === undefined) { throw new Error("Error reading JWT from session"); } @@ -105,6 +105,7 @@ export default function ( createNewSession: async function ( this: RecipeInterface, { + req, res, userId, recipeUserId, @@ -112,6 +113,7 @@ export default function ( sessionData, userContext, }: { + req: BaseRequest; res: BaseResponse; userId: string; recipeUserId?: string; @@ -134,6 +136,7 @@ export default function ( }); let sessionContainer = await originalImplementation.createNewSession({ + req, res, userId, recipeUserId, diff --git a/lib/ts/recipe/session/with-jwt/sessionClass.ts b/lib/ts/recipe/session/with-jwt/sessionClass.ts index 423975191..90fa9b330 100644 --- a/lib/ts/recipe/session/with-jwt/sessionClass.ts +++ b/lib/ts/recipe/session/with-jwt/sessionClass.ts @@ -147,7 +147,7 @@ export default class SessionClassWithJWT implements SessionContainerInterface { let decodedPayload = JsonWebToken.decode(existingJWT, { json: true }); // JsonWebToken.decode possibly returns null - if (decodedPayload === null) { + if (decodedPayload === null || decodedPayload.exp === undefined) { throw new Error("Error reading JWT from session"); } diff --git a/lib/ts/recipe/thirdparty/api/implementation.ts b/lib/ts/recipe/thirdparty/api/implementation.ts index 70fcb14ec..969f45c30 100644 --- a/lib/ts/recipe/thirdparty/api/implementation.ts +++ b/lib/ts/recipe/thirdparty/api/implementation.ts @@ -232,6 +232,7 @@ export default function getAPIInterface(): APIInterface { } let session = await Session.createNewSession( + options.req, options.res, response.user.id, response.user.recipeUserId, diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index 752046342..f470b115d 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -20,6 +20,7 @@ import { maxVersion, normaliseHttpMethod, sendNon200ResponseWithMessage, + getRidFromHeader, } from "./utils"; import { Querier } from "./querier"; import RecipeModule from "./recipeModule"; @@ -311,7 +312,7 @@ export default class SuperTokens { return false; } - let requestRID = request.getHeaderValue(HEADER_RID); + let requestRID = getRidFromHeader(request); logDebugMessage("middleware: requestRID is: " + requestRID); if (requestRID === "anti-csrf") { // see https://github.com/supertokens/supertokens-node/issues/202 diff --git a/lib/ts/types.ts b/lib/ts/types.ts index 2a1c82499..b9749a59e 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -32,6 +32,8 @@ export type NormalisedAppinfo = { appName: string; websiteDomain: NormalisedURLDomain; apiDomain: NormalisedURLDomain; + topLevelAPIDomain: string; + topLevelWebsiteDomain: string; apiBasePath: NormalisedURLPath; apiGatewayPath: NormalisedURLPath; websiteBasePath: NormalisedURLPath; diff --git a/lib/ts/utils.ts b/lib/ts/utils.ts index 200860a7f..d62e72a3a 100644 --- a/lib/ts/utils.ts +++ b/lib/ts/utils.ts @@ -1,9 +1,11 @@ +import * as psl from "psl"; + import type { AppInfo, NormalisedAppinfo, HTTPMethod, JSONObject } from "./types"; -import { HEADER_RID } from "./constants"; import NormalisedURLDomain from "./normalisedURLDomain"; import NormalisedURLPath from "./normalisedURLPath"; import type { BaseRequest, BaseResponse } from "./framework"; import { logDebugMessage } from "./logger"; +import { HEADER_RID } from "./constants"; export function getLargestVersionFromIntersection(v1: string[], v2: string[]): string | undefined { let intersection = v1.filter((value) => v2.indexOf(value) !== -1); @@ -53,10 +55,16 @@ export function normaliseInputAppInfoOrThrowError(appInfo: AppInfo): NormalisedA appInfo.apiGatewayPath !== undefined ? new NormalisedURLPath(appInfo.apiGatewayPath) : new NormalisedURLPath(""); + + const websiteDomain = new NormalisedURLDomain(appInfo.websiteDomain); + const apiDomain = new NormalisedURLDomain(appInfo.apiDomain); + const topLevelAPIDomain = getTopLevelDomainForSameSiteResolution(apiDomain.getAsStringDangerous()); + const topLevelWebsiteDomain = getTopLevelDomainForSameSiteResolution(websiteDomain.getAsStringDangerous()); + return { appName: appInfo.appName, - websiteDomain: new NormalisedURLDomain(appInfo.websiteDomain), - apiDomain: new NormalisedURLDomain(appInfo.apiDomain), + websiteDomain, + apiDomain, apiBasePath: apiGatewayPath.appendPath( appInfo.apiBasePath === undefined ? new NormalisedURLPath("/auth") @@ -67,13 +75,11 @@ export function normaliseInputAppInfoOrThrowError(appInfo: AppInfo): NormalisedA ? new NormalisedURLPath("/auth") : new NormalisedURLPath(appInfo.websiteBasePath), apiGatewayPath, + topLevelAPIDomain, + topLevelWebsiteDomain, }; } -export function getRIDFromRequest(req: BaseRequest): string | undefined { - return req.getHeaderValue(HEADER_RID); -} - export function normaliseHttpMethod(method: string): HTTPMethod { return method.toLowerCase() as HTTPMethod; } @@ -103,8 +109,12 @@ export function isAnIpAddress(ipaddress: string) { ); } +export function getRidFromHeader(req: BaseRequest): string | undefined { + return req.getHeaderValue(HEADER_RID); +} + export function frontendHasInterceptor(req: BaseRequest): boolean { - return getRIDFromRequest(req) !== undefined; + return getRidFromHeader(req) !== undefined; } export function humaniseMilliseconds(ms: number): string { @@ -132,3 +142,17 @@ export function makeDefaultUserContextFromAPI(request: BaseRequest): any { }, }; } + +export function getTopLevelDomainForSameSiteResolution(url: string): string { + let urlObj = new URL(url); + let hostname = urlObj.hostname; + if (hostname.startsWith("localhost") || hostname.startsWith("localhost.org") || isAnIpAddress(hostname)) { + // we treat these as the same TLDs since we can use sameSite lax for all of them. + return "localhost"; + } + let parsedURL = psl.parse(hostname) as psl.ParsedDomain; + if (parsedURL.domain === null) { + throw new Error("Please make sure that the apiDomain and websiteDomain have correct values"); + } + return parsedURL.domain; +} diff --git a/lib/ts/version.ts b/lib/ts/version.ts index fc3cc7355..50c6e9c2c 100644 --- a/lib/ts/version.ts +++ b/lib/ts/version.ts @@ -12,9 +12,9 @@ * License for the specific language governing permissions and limitations * under the License. */ -export const version = "12.1.0"; +export const version = "13.0.1"; export const cdiSupported = ["2.8", "2.9", "2.10", "2.11", "2.12", "2.13", "2.14", "2.15"]; // Note: The actual script import for dashboard uses v{DASHBOARD_VERSION} -export const dashboardVersion = "0.2"; +export const dashboardVersion = "0.3"; diff --git a/package-lock.json b/package-lock.json index 3eaeb2d2d..a88e221f1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,20 +1,20 @@ { "name": "supertokens-node", - "version": "12.1.0", + "version": "13.0.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "supertokens-node", - "version": "12.1.0", + "version": "13.0.1", "license": "Apache-2.0", "dependencies": { "axios": "0.21.4", - "body-parser": "1.19.0", + "body-parser": "1.20.1", "co-body": "6.1.0", "cookie": "0.4.0", "debug": "^4.3.3", - "jsonwebtoken": "^8.5.1", + "jsonwebtoken": "^9.0.0", "jwks-rsa": "^2.0.5", "libphonenumber-js": "^1.9.44", "nodemailer": "^6.7.2", @@ -42,7 +42,7 @@ "@types/validator": "10.11.0", "aws-sdk-mock": "^5.4.0", "cookie-parser": "^1.4.5", - "express": "4.17.1", + "express": "^4.18.2", "fastify": "3.18.1", "glob": "7.1.7", "koa": "^2.13.3", @@ -1431,6 +1431,54 @@ "node": ">= 10" } }, + "node_modules/@next/swc-darwin-x64": { + "version": "11.1.3", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-11.1.3.tgz", + "integrity": "sha512-ZSWmkg/PxccHFNUSeBdrfaH8KwSkoeUtewXKvuYYt7Ph0yRsbqSyNIvhUezDua96lApiXXq6EL2d1THfeWomvw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "11.1.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-11.1.3.tgz", + "integrity": "sha512-PrTBN0iZudAuj4jSbtXcdBdmfpaDCPIneG4Oms4zcs93KwMgLhivYW082Mvlgx9QVEiRm7+RkFpIVtG/i7JitA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "11.1.3", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-11.1.3.tgz", + "integrity": "sha512-mRwbscVjRoHk+tDY7XbkT5d9FCwujFIQJpGp0XNb1i5OHCSDO8WW/C9cLEWS4LxKRbIZlTLYg1MTXqLQkvva8w==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, "node_modules/@node-rs/helper": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@node-rs/helper/-/helper-1.2.1.tgz", @@ -2296,21 +2344,32 @@ "dev": true }, "node_modules/body-parser": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", - "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", + "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", "dependencies": { - "bytes": "3.1.0", + "bytes": "3.1.2", "content-type": "~1.0.4", "debug": "2.6.9", - "depd": "~1.1.2", - "http-errors": "1.7.2", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", "iconv-lite": "0.4.24", - "on-finished": "~2.3.0", - "qs": "6.7.0", - "raw-body": "2.4.0", - "type-is": "~1.6.17" + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", "engines": { "node": ">= 0.8" } @@ -2323,45 +2382,45 @@ "ms": "2.0.0" } }, + "node_modules/body-parser/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/body-parser/node_modules/http-errors": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", - "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dependencies": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" }, "engines": { - "node": ">= 0.6" + "node": ">= 0.8" } }, - "node_modules/body-parser/node_modules/inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, "node_modules/body-parser/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" }, - "node_modules/body-parser/node_modules/qs": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", - "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==", - "engines": { - "node": ">=0.6" - } + "node_modules/body-parser/node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, - "node_modules/body-parser/node_modules/toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", + "node_modules/body-parser/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "engines": { - "node": ">=0.6" + "node": ">= 0.8" } }, "node_modules/brace-expansion": { @@ -2546,6 +2605,7 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", + "dev": true, "engines": { "node": ">= 0.8" } @@ -2752,9 +2812,9 @@ } }, "node_modules/cliui/node_modules/ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", "dev": true, "engines": { "node": ">=4" @@ -2891,17 +2951,37 @@ "dev": true }, "node_modules/content-disposition": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", - "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", "dev": true, "dependencies": { - "safe-buffer": "5.1.2" + "safe-buffer": "5.2.1" }, "engines": { "node": ">= 0.6" } }, + "node_modules/content-disposition/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/content-type": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", @@ -3237,6 +3317,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true, "engines": { "node": ">= 0.6" } @@ -3252,10 +3333,9 @@ } }, "node_modules/destroy": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.1.0.tgz", - "integrity": "sha512-R5QZrOXxSs0JDUIU/VANvRJlQVMts9C0L76HToQdPdlftfZCE7W6dyH0G4GZ5UW9fRqUOhAoCE2aGekuu+3HjQ==", - "dev": true, + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", "engines": { "node": ">= 0.8", "npm": "1.2.8000 || >= 1.4.16" @@ -3338,12 +3418,12 @@ "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" }, "node_modules/ejs": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.6.tgz", - "integrity": "sha512-9lt9Zse4hPucPkoP7FHDF0LQAlGyF9JVpnClFLFH3aSSbxmyoqINRpp/9wePWJTUl4KOQwRL72Iw3InHPDkoGw==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.8.tgz", + "integrity": "sha512-/sXZeMlhS0ArkfX2Aw780gJzXSMPnKjtspYZv+f3NiKLlubezAHDU5+9xz6gd3/NhG3txQCo6xlglmTS+oTGEQ==", "dev": true, "dependencies": { - "jake": "^10.6.1" + "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" @@ -3597,38 +3677,39 @@ } }, "node_modules/express": { - "version": "4.17.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", - "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", + "version": "4.18.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", + "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", "dev": true, "dependencies": { - "accepts": "~1.3.7", + "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.19.0", - "content-disposition": "0.5.3", + "body-parser": "1.20.1", + "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.4.0", + "cookie": "0.5.0", "cookie-signature": "1.0.6", "debug": "2.6.9", - "depd": "~1.1.2", + "depd": "2.0.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "~1.1.2", + "finalhandler": "1.2.0", "fresh": "0.5.2", + "http-errors": "2.0.0", "merge-descriptors": "1.0.1", "methods": "~1.1.2", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.5", - "qs": "6.7.0", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", "range-parser": "~1.2.1", - "safe-buffer": "5.1.2", - "send": "0.17.1", - "serve-static": "1.14.1", - "setprototypeof": "1.1.1", - "statuses": "~1.5.0", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" @@ -3637,6 +3718,15 @@ "node": ">= 0.10.0" } }, + "node_modules/express/node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -3646,10 +3736,35 @@ "ms": "2.0.0" } }, + "node_modules/express/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/express/node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dev": true, + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/express/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true }, "node_modules/express/node_modules/path-to-regexp": { @@ -3658,13 +3773,39 @@ "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", "dev": true }, - "node_modules/express/node_modules/qs": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", - "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==", + "node_modules/express/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/express/node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, + "node_modules/express/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true, "engines": { - "node": ">=0.6" + "node": ">= 0.8" } }, "node_modules/extend": { @@ -3768,12 +3909,33 @@ } }, "node_modules/filelist": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.2.tgz", - "integrity": "sha512-z7O0IS8Plc39rTCq6i6iHxk43duYOn8uFJiWSewIq0Bww1RNybVHSCjahmcC87ZqAm4OTvFzlzeGu3XAzG1ctQ==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", "dev": true, "dependencies": { - "minimatch": "^3.0.4" + "minimatch": "^5.0.1" + } + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.1.tgz", + "integrity": "sha512-362NP+zlprccbEt/SkxKfRMHnNY85V74mVnpUpNyr3F35covl09Kec7/sEFLt3RA4oXmewtoaanoIf67SE5Y5g==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" } }, "node_modules/fill-range": { @@ -3789,17 +3951,17 @@ } }, "node_modules/finalhandler": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", - "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", "dev": true, "dependencies": { "debug": "2.6.9", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "parseurl": "~1.3.3", - "statuses": "~1.5.0", + "statuses": "2.0.1", "unpipe": "~1.0.0" }, "engines": { @@ -3818,9 +3980,18 @@ "node_modules/finalhandler/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true }, + "node_modules/finalhandler/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/find-cache-dir": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.1.tgz", @@ -4432,8 +4603,7 @@ "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/internal-slot": { "version": "1.0.3", @@ -4788,13 +4958,13 @@ } }, "node_modules/jake": { - "version": "10.8.2", - "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.2.tgz", - "integrity": "sha512-eLpKyrfG3mzvGE2Du8VoPbeSkRry093+tyNjdYaBbJS9v17knImYGNXQCUV0gLxQtF82m3E8iRb/wdSQZLoq7A==", + "version": "10.8.5", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.5.tgz", + "integrity": "sha512-sVpxYeuAhWt0OTWITwT98oyV0GsXyMlXCF+3L1SuafBVUIr/uILGRB+NqwkzhgXKvoJpDIpQvqkUALgdmQsQxw==", "dev": true, "dependencies": { - "async": "0.9.x", - "chalk": "^2.4.2", + "async": "^3.2.3", + "chalk": "^4.0.2", "filelist": "^1.0.1", "minimatch": "^3.0.4" }, @@ -4802,15 +4972,79 @@ "jake": "bin/cli.js" }, "engines": { - "node": "*" + "node": ">=10" + } + }, + "node_modules/jake/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/jake/node_modules/async": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", - "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=", + "node_modules/jake/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/jake/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/jake/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, + "node_modules/jake/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jake/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/jest-worker": { "version": "27.0.0-next.5", "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.0.0-next.5.tgz", @@ -4872,9 +5106,9 @@ } }, "node_modules/jose": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/jose/-/jose-2.0.5.tgz", - "integrity": "sha512-BAiDNeDKTMgk4tvD0BbxJ8xHEHBZgpeRZ1zGPPsitSyMgjoMWiLGYAE7H7NpP5h0lPppQajQs871E8NHUrzVPA==", + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/jose/-/jose-2.0.6.tgz", + "integrity": "sha512-FVoPY7SflDodE4lknJmbAHSUjLCzE2H1F6MS0RYKMQ8SR+lNccpMf8R4eqkNYyyUjR5qZReOzZo5C5YiHOCjjg==", "dependencies": { "@panva/asn1.js": "^1.0.0" }, @@ -4972,11 +5206,14 @@ } }, "node_modules/json5/node_modules/minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", "dev": true, - "peer": true + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/jsonc-parser": { "version": "3.0.0", @@ -4985,32 +5222,18 @@ "dev": true }, "node_modules/jsonwebtoken": { - "version": "8.5.1", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", - "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz", + "integrity": "sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw==", "dependencies": { "jws": "^3.2.2", - "lodash.includes": "^4.3.0", - "lodash.isboolean": "^3.0.3", - "lodash.isinteger": "^4.0.4", - "lodash.isnumber": "^3.0.3", - "lodash.isplainobject": "^4.0.6", - "lodash.isstring": "^4.0.1", - "lodash.once": "^4.0.0", + "lodash": "^4.17.21", "ms": "^2.1.1", - "semver": "^5.6.0" + "semver": "^7.3.8" }, "engines": { - "node": ">=4", - "npm": ">=1.4.28" - } - }, - "node_modules/jsonwebtoken/node_modules/semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "bin": { - "semver": "bin/semver" + "node": ">=12", + "npm": ">=6" } }, "node_modules/just-extend": { @@ -5297,10 +5520,13 @@ } }, "node_modules/loader-utils/node_modules/minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "dev": true + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/locate-path": { "version": "3.0.0", @@ -5334,37 +5560,37 @@ "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", - "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" }, "node_modules/lodash.isboolean": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" }, "node_modules/lodash.isinteger": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", - "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" }, "node_modules/lodash.isnumber": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", - "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" }, "node_modules/lodash.isplainobject": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" }, "node_modules/lodash.isstring": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" }, "node_modules/lodash.once": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", - "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" }, "node_modules/lodash.sortby": { "version": "4.7.0", @@ -5687,13 +5913,13 @@ "node_modules/minimist": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "integrity": "sha512-miQKw5Hv4NS1Psg2517mV4e4dYNaO3++hjAvLOAzKqZ61rH8NS1SK+vbfBWZ5PY/Me/bEWhUwqMghEW5Fb9T7Q==", "dev": true }, "node_modules/mkdirp": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "integrity": "sha512-SknJC52obPfGQPnjIkXbmA6+5H15E+fR+E4iR2oQ3zzCLbd7/ONua69R/Gw7AgkTLsRG+r5fzksYwWe1AgTyWA==", "deprecated": "Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)", "dev": true, "dependencies": { @@ -5777,6 +6003,18 @@ "node": "*" } }, + "node_modules/mocha/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/mocha/node_modules/js-yaml": { "version": "3.13.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", @@ -6018,15 +6256,6 @@ "node": ">= 0.6" } }, - "node_modules/next/node_modules/node-fetch": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", - "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", - "dev": true, - "engines": { - "node": "4.x || >=6.0.0" - } - }, "node_modules/next/node_modules/raw-body": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.1.tgz", @@ -6131,6 +6360,15 @@ "semver": "bin/semver" } }, + "node_modules/node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", + "dev": true, + "engines": { + "node": "4.x || >=6.0.0" + } + }, "node_modules/node-html-parser": { "version": "1.4.9", "resolved": "https://registry.npmjs.org/node-html-parser/-/node-html-parser-1.4.9.tgz", @@ -6445,9 +6683,9 @@ } }, "node_modules/on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "dependencies": { "ee-first": "1.1.1" }, @@ -7176,9 +7414,9 @@ } }, "node_modules/qs": { - "version": "6.10.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.3.tgz", - "integrity": "sha512-wr7M2E0OFRfIfJZjKGieI8lBKb7fRCH4Fv5KNPEs7gJ8jadvotdsS08PzOKR7opXhZ/Xkjtt3WF9g38drmyRqQ==", + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", "dependencies": { "side-channel": "^1.0.4" }, @@ -7277,12 +7515,12 @@ } }, "node_modules/raw-body": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", - "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", "dependencies": { - "bytes": "3.1.0", - "http-errors": "1.7.2", + "bytes": "3.1.2", + "http-errors": "2.0.0", "iconv-lite": "0.4.24", "unpipe": "1.0.0" }, @@ -7290,32 +7528,48 @@ "node": ">= 0.8" } }, + "node_modules/raw-body/node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/raw-body/node_modules/http-errors": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", - "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dependencies": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" }, "engines": { - "node": ">= 0.6" + "node": ">= 0.8" } }, - "node_modules/raw-body/node_modules/inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + "node_modules/raw-body/node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, - "node_modules/raw-body/node_modules/toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", + "node_modules/raw-body/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "engines": { - "node": ">=0.6" + "node": ">= 0.8" } }, "node_modules/react": { @@ -7516,10 +7770,9 @@ "dev": true }, "node_modules/semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", - "dev": true, + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", "dependencies": { "lru-cache": "^6.0.0" }, @@ -7540,7 +7793,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, "dependencies": { "yallist": "^4.0.0" }, @@ -7551,28 +7803,27 @@ "node_modules/semver/node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/send": { - "version": "0.17.1", - "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", - "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", "dev": true, "dependencies": { "debug": "2.6.9", - "depd": "~1.1.2", - "destroy": "~1.0.4", + "depd": "2.0.0", + "destroy": "1.2.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "0.5.2", - "http-errors": "~1.7.2", + "http-errors": "2.0.0", "mime": "1.6.0", - "ms": "2.1.1", - "on-finished": "~2.3.0", + "ms": "2.1.3", + "on-finished": "2.4.1", "range-parser": "~1.2.1", - "statuses": "~1.5.0" + "statuses": "2.0.1" }, "engines": { "node": ">= 0.8.0" @@ -7590,44 +7841,53 @@ "node_modules/send/node_modules/debug/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true }, - "node_modules/send/node_modules/destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", - "dev": true + "node_modules/send/node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "engines": { + "node": ">= 0.8" + } }, "node_modules/send/node_modules/http-errors": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.3.tgz", - "integrity": "sha512-ZTTX0MWrsQ2ZAhA1cejAwDLycFsd7I7nVtnkT3Ol0aqodaKW+0CTZDQ1uBv5whptCnc8e8HeRRJxRs0kmm/Qfw==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dev": true, "dependencies": { - "depd": "~1.1.2", + "depd": "2.0.0", "inherits": "2.0.4", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" }, "engines": { - "node": ">= 0.6" + "node": ">= 0.8" } }, "node_modules/send/node_modules/ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true }, - "node_modules/send/node_modules/toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", + "node_modules/send/node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, + "node_modules/send/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true, "engines": { - "node": ">=0.6" + "node": ">= 0.8" } }, "node_modules/sentence-case": { @@ -7642,15 +7902,15 @@ } }, "node_modules/serve-static": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", - "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", "dev": true, "dependencies": { "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.17.1" + "send": "0.18.0" }, "engines": { "node": ">= 0.8.0" @@ -7677,7 +7937,8 @@ "node_modules/setprototypeof": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", - "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" + "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==", + "dev": true }, "node_modules/sha.js": { "version": "2.4.11", @@ -7919,6 +8180,7 @@ "version": "1.5.0", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "dev": true, "engines": { "node": ">= 0.6" } @@ -8034,9 +8296,9 @@ } }, "node_modules/string-width/node_modules/ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", "dev": true, "engines": { "node": ">=4" @@ -8357,7 +8619,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "dev": true, "engines": { "node": ">=0.6" } @@ -8438,6 +8699,35 @@ "follow-redirects": "^1.14.8" } }, + "node_modules/twilio/node_modules/jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=4", + "npm": ">=1.4.28" + } + }, + "node_modules/twilio/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "bin": { + "semver": "bin/semver" + } + }, "node_modules/twilio/node_modules/xmlbuilder": { "version": "13.0.2", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-13.0.2.tgz", @@ -8698,6 +8988,35 @@ "jwks-rsa": "^2.0.2" } }, + "node_modules/verify-apple-id-token/node_modules/jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=4", + "npm": ">=1.4.28" + } + }, + "node_modules/verify-apple-id-token/node_modules/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "bin": { + "semver": "bin/semver" + } + }, "node_modules/vm-browserify": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", @@ -9181,9 +9500,9 @@ } }, "node_modules/yargs/node_modules/ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", "dev": true, "engines": { "node": ">=6" @@ -10539,6 +10858,27 @@ "dev": true, "optional": true }, + "@next/swc-darwin-x64": { + "version": "11.1.3", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-11.1.3.tgz", + "integrity": "sha512-ZSWmkg/PxccHFNUSeBdrfaH8KwSkoeUtewXKvuYYt7Ph0yRsbqSyNIvhUezDua96lApiXXq6EL2d1THfeWomvw==", + "dev": true, + "optional": true + }, + "@next/swc-linux-x64-gnu": { + "version": "11.1.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-11.1.3.tgz", + "integrity": "sha512-PrTBN0iZudAuj4jSbtXcdBdmfpaDCPIneG4Oms4zcs93KwMgLhivYW082Mvlgx9QVEiRm7+RkFpIVtG/i7JitA==", + "dev": true, + "optional": true + }, + "@next/swc-win32-x64-msvc": { + "version": "11.1.3", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-11.1.3.tgz", + "integrity": "sha512-mRwbscVjRoHk+tDY7XbkT5d9FCwujFIQJpGp0XNb1i5OHCSDO8WW/C9cLEWS4LxKRbIZlTLYg1MTXqLQkvva8w==", + "dev": true, + "optional": true + }, "@node-rs/helper": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@node-rs/helper/-/helper-1.2.1.tgz", @@ -11313,22 +11653,29 @@ "dev": true }, "body-parser": { - "version": "1.19.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", - "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", + "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", "requires": { - "bytes": "3.1.0", + "bytes": "3.1.2", "content-type": "~1.0.4", "debug": "2.6.9", - "depd": "~1.1.2", - "http-errors": "1.7.2", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", "iconv-lite": "0.4.24", - "on-finished": "~2.3.0", - "qs": "6.7.0", - "raw-body": "2.4.0", - "type-is": "~1.6.17" + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" }, "dependencies": { + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==" + }, "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -11337,37 +11684,37 @@ "ms": "2.0.0" } }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" + }, "http-errors": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", - "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "requires": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" } }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" - }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" }, - "qs": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", - "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, - "toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==" + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" } } }, @@ -11527,7 +11874,8 @@ "bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", - "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" + "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", + "dev": true }, "cache-content-type": { "version": "1.0.1", @@ -11700,9 +12048,9 @@ }, "dependencies": { "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", "dev": true }, "strip-ansi": { @@ -11822,12 +12170,20 @@ "dev": true }, "content-disposition": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", - "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", "dev": true, "requires": { - "safe-buffer": "5.1.2" + "safe-buffer": "5.2.1" + }, + "dependencies": { + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + } } }, "content-type": { @@ -12099,7 +12455,8 @@ "depd": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true }, "des.js": { "version": "1.0.1", @@ -12112,10 +12469,9 @@ } }, "destroy": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.1.0.tgz", - "integrity": "sha512-R5QZrOXxSs0JDUIU/VANvRJlQVMts9C0L76HToQdPdlftfZCE7W6dyH0G4GZ5UW9fRqUOhAoCE2aGekuu+3HjQ==", - "dev": true + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==" }, "diff": { "version": "3.5.0", @@ -12184,12 +12540,12 @@ "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" }, "ejs": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.6.tgz", - "integrity": "sha512-9lt9Zse4hPucPkoP7FHDF0LQAlGyF9JVpnClFLFH3aSSbxmyoqINRpp/9wePWJTUl4KOQwRL72Iw3InHPDkoGw==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.8.tgz", + "integrity": "sha512-/sXZeMlhS0ArkfX2Aw780gJzXSMPnKjtspYZv+f3NiKLlubezAHDU5+9xz6gd3/NhG3txQCo6xlglmTS+oTGEQ==", "dev": true, "requires": { - "jake": "^10.6.1" + "jake": "^10.8.5" } }, "electron-to-chromium": { @@ -12391,43 +12747,50 @@ } }, "express": { - "version": "4.17.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", - "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", + "version": "4.18.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", + "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", "dev": true, "requires": { - "accepts": "~1.3.7", + "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.19.0", - "content-disposition": "0.5.3", + "body-parser": "1.20.1", + "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.4.0", + "cookie": "0.5.0", "cookie-signature": "1.0.6", "debug": "2.6.9", - "depd": "~1.1.2", + "depd": "2.0.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "~1.1.2", + "finalhandler": "1.2.0", "fresh": "0.5.2", + "http-errors": "2.0.0", "merge-descriptors": "1.0.1", "methods": "~1.1.2", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.5", - "qs": "6.7.0", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", "range-parser": "~1.2.1", - "safe-buffer": "5.1.2", - "send": "0.17.1", - "serve-static": "1.14.1", - "setprototypeof": "1.1.1", - "statuses": "~1.5.0", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" }, "dependencies": { + "cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "dev": true + }, "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -12437,10 +12800,29 @@ "ms": "2.0.0" } }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true + }, + "http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dev": true, + "requires": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + } + }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true }, "path-to-regexp": { @@ -12449,10 +12831,22 @@ "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", "dev": true }, - "qs": { - "version": "6.7.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", - "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==", + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true + }, + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true } } @@ -12551,12 +12945,32 @@ } }, "filelist": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.2.tgz", - "integrity": "sha512-z7O0IS8Plc39rTCq6i6iHxk43duYOn8uFJiWSewIq0Bww1RNybVHSCjahmcC87ZqAm4OTvFzlzeGu3XAzG1ctQ==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", "dev": true, "requires": { - "minimatch": "^3.0.4" + "minimatch": "^5.0.1" + }, + "dependencies": { + "brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0" + } + }, + "minimatch": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.1.tgz", + "integrity": "sha512-362NP+zlprccbEt/SkxKfRMHnNY85V74mVnpUpNyr3F35covl09Kec7/sEFLt3RA4oXmewtoaanoIf67SE5Y5g==", + "dev": true, + "requires": { + "brace-expansion": "^2.0.1" + } + } } }, "fill-range": { @@ -12569,17 +12983,17 @@ } }, "finalhandler": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", - "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", "dev": true, "requires": { "debug": "2.6.9", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", - "on-finished": "~2.3.0", + "on-finished": "2.4.1", "parseurl": "~1.3.3", - "statuses": "~1.5.0", + "statuses": "2.0.1", "unpipe": "~1.0.0" }, "dependencies": { @@ -12595,7 +13009,13 @@ "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true } } @@ -13038,8 +13458,7 @@ "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "internal-slot": { "version": "1.0.3", @@ -13274,22 +13693,65 @@ "dev": true }, "jake": { - "version": "10.8.2", - "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.2.tgz", - "integrity": "sha512-eLpKyrfG3mzvGE2Du8VoPbeSkRry093+tyNjdYaBbJS9v17knImYGNXQCUV0gLxQtF82m3E8iRb/wdSQZLoq7A==", + "version": "10.8.5", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.5.tgz", + "integrity": "sha512-sVpxYeuAhWt0OTWITwT98oyV0GsXyMlXCF+3L1SuafBVUIr/uILGRB+NqwkzhgXKvoJpDIpQvqkUALgdmQsQxw==", "dev": true, "requires": { - "async": "0.9.x", - "chalk": "^2.4.2", + "async": "^3.2.3", + "chalk": "^4.0.2", "filelist": "^1.0.1", "minimatch": "^3.0.4" }, "dependencies": { - "async": { - "version": "0.9.2", - "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", - "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=", + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "requires": { + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } } } }, @@ -13341,9 +13803,9 @@ } }, "jose": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/jose/-/jose-2.0.5.tgz", - "integrity": "sha512-BAiDNeDKTMgk4tvD0BbxJ8xHEHBZgpeRZ1zGPPsitSyMgjoMWiLGYAE7H7NpP5h0lPppQajQs871E8NHUrzVPA==", + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/jose/-/jose-2.0.6.tgz", + "integrity": "sha512-FVoPY7SflDodE4lknJmbAHSUjLCzE2H1F6MS0RYKMQ8SR+lNccpMf8R4eqkNYyyUjR5qZReOzZo5C5YiHOCjjg==", "requires": { "@panva/asn1.js": "^1.0.0" } @@ -13420,9 +13882,9 @@ }, "dependencies": { "minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", "dev": true, "peer": true } @@ -13435,27 +13897,14 @@ "dev": true }, "jsonwebtoken": { - "version": "8.5.1", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", - "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz", + "integrity": "sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw==", "requires": { "jws": "^3.2.2", - "lodash.includes": "^4.3.0", - "lodash.isboolean": "^3.0.3", - "lodash.isinteger": "^4.0.4", - "lodash.isnumber": "^3.0.3", - "lodash.isplainobject": "^4.0.6", - "lodash.isstring": "^4.0.1", - "lodash.once": "^4.0.0", + "lodash": "^4.17.21", "ms": "^2.1.1", - "semver": "^5.6.0" - }, - "dependencies": { - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" - } + "semver": "^7.3.8" } }, "just-extend": { @@ -13699,9 +14148,9 @@ } }, "minimist": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", "dev": true } } @@ -13735,37 +14184,37 @@ "lodash.includes": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", - "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" }, "lodash.isboolean": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==" }, "lodash.isinteger": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", - "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==" }, "lodash.isnumber": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", - "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==" }, "lodash.isplainobject": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==" }, "lodash.isstring": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==" }, "lodash.once": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", - "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" }, "lodash.sortby": { "version": "4.7.0", @@ -14031,13 +14480,13 @@ "minimist": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "integrity": "sha512-miQKw5Hv4NS1Psg2517mV4e4dYNaO3++hjAvLOAzKqZ61rH8NS1SK+vbfBWZ5PY/Me/bEWhUwqMghEW5Fb9T7Q==", "dev": true }, "mkdirp": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", - "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "integrity": "sha512-SknJC52obPfGQPnjIkXbmA6+5H15E+fR+E4iR2oQ3zzCLbd7/ONua69R/Gw7AgkTLsRG+r5fzksYwWe1AgTyWA==", "dev": true, "requires": { "minimist": "0.0.8" @@ -14104,6 +14553,17 @@ "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" + }, + "dependencies": { + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + } } }, "js-yaml": { @@ -14301,12 +14761,6 @@ "toidentifier": "1.0.0" } }, - "node-fetch": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", - "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", - "dev": true - }, "raw-body": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.1.tgz", @@ -14405,6 +14859,12 @@ } } }, + "node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==", + "dev": true + }, "node-html-parser": { "version": "1.4.9", "resolved": "https://registry.npmjs.org/node-html-parser/-/node-html-parser-1.4.9.tgz", @@ -14677,9 +15137,9 @@ } }, "on-finished": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", - "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", "requires": { "ee-first": "1.1.1" } @@ -15243,9 +15703,9 @@ } }, "qs": { - "version": "6.10.3", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.3.tgz", - "integrity": "sha512-wr7M2E0OFRfIfJZjKGieI8lBKb7fRCH4Fv5KNPEs7gJ8jadvotdsS08PzOKR7opXhZ/Xkjtt3WF9g38drmyRqQ==", + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", "requires": { "side-channel": "^1.0.4" } @@ -15314,37 +15774,47 @@ "dev": true }, "raw-body": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", - "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", "requires": { - "bytes": "3.1.0", - "http-errors": "1.7.2", + "bytes": "3.1.2", + "http-errors": "2.0.0", "iconv-lite": "0.4.24", "unpipe": "1.0.0" }, "dependencies": { + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==" + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" + }, "http-errors": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", - "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "requires": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" } }, - "inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, - "toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==" + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" } } }, @@ -15518,10 +15988,9 @@ "dev": true }, "semver": { - "version": "7.3.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", - "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", - "dev": true, + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", "requires": { "lru-cache": "^6.0.0" }, @@ -15530,7 +15999,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, "requires": { "yallist": "^4.0.0" } @@ -15538,8 +16006,7 @@ "yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" } } }, @@ -15550,24 +16017,24 @@ "dev": true }, "send": { - "version": "0.17.1", - "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", - "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", "dev": true, "requires": { "debug": "2.6.9", - "depd": "~1.1.2", - "destroy": "~1.0.4", + "depd": "2.0.0", + "destroy": "1.2.0", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "0.5.2", - "http-errors": "~1.7.2", + "http-errors": "2.0.0", "mime": "1.6.0", - "ms": "2.1.1", - "on-finished": "~2.3.0", + "ms": "2.1.3", + "on-finished": "2.4.1", "range-parser": "~1.2.1", - "statuses": "~1.5.0" + "statuses": "2.0.1" }, "dependencies": { "debug": { @@ -15582,40 +16049,46 @@ "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true } } }, - "destroy": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", "dev": true }, "http-errors": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.3.tgz", - "integrity": "sha512-ZTTX0MWrsQ2ZAhA1cejAwDLycFsd7I7nVtnkT3Ol0aqodaKW+0CTZDQ1uBv5whptCnc8e8HeRRJxRs0kmm/Qfw==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dev": true, "requires": { - "depd": "~1.1.2", + "depd": "2.0.0", "inherits": "2.0.4", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" } }, "ms": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", - "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true }, - "toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true } } @@ -15632,15 +16105,15 @@ } }, "serve-static": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", - "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", "dev": true, "requires": { "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.17.1" + "send": "0.18.0" } }, "set-blocking": { @@ -15664,7 +16137,8 @@ "setprototypeof": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", - "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" + "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==", + "dev": true }, "sha.js": { "version": "2.4.11", @@ -15877,7 +16351,8 @@ "statuses": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "dev": true }, "stoppable": { "version": "1.1.0", @@ -15973,9 +16448,9 @@ }, "dependencies": { "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", "dev": true }, "strip-ansi": { @@ -16229,8 +16704,7 @@ "toidentifier": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "dev": true + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" }, "toposort": { "version": "2.0.2", @@ -16294,6 +16768,28 @@ "follow-redirects": "^1.14.8" } }, + "jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "requires": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, "xmlbuilder": { "version": "13.0.2", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-13.0.2.tgz", @@ -16500,6 +16996,30 @@ "requires": { "jsonwebtoken": "^8.5.1", "jwks-rsa": "^2.0.2" + }, + "dependencies": { + "jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "requires": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + } } }, "vm-browserify": { @@ -16725,9 +17245,9 @@ }, "dependencies": { "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz", + "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==", "dev": true }, "cross-spawn": { diff --git a/package.json b/package.json index 45343ba36..116fe6fc6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "supertokens-node", - "version": "12.1.0", + "version": "13.0.1", "description": "NodeJS driver for SuperTokens core", "main": "index.js", "scripts": { @@ -35,11 +35,11 @@ "homepage": "https://github.com/supertokens/supertokens-node#readme", "dependencies": { "axios": "0.21.4", - "body-parser": "1.19.0", + "body-parser": "1.20.1", "co-body": "6.1.0", "cookie": "0.4.0", "debug": "^4.3.3", - "jsonwebtoken": "^8.5.1", + "jsonwebtoken": "^9.0.0", "jwks-rsa": "^2.0.5", "libphonenumber-js": "^1.9.44", "nodemailer": "^6.7.2", @@ -59,7 +59,7 @@ "@types/cookie": "0.3.3", "@types/express": "4.16.1", "@types/hapi__hapi": "20.0.8", - "@types/jsonwebtoken": "8.5.0", + "@types/jsonwebtoken": "9.0.0", "@types/koa": "^2.13.4", "@types/koa-bodyparser": "^4.3.3", "@types/nodemailer": "^6.4.4", @@ -67,7 +67,7 @@ "@types/validator": "10.11.0", "aws-sdk-mock": "^5.4.0", "cookie-parser": "^1.4.5", - "express": "4.17.1", + "express": "^4.18.2", "fastify": "3.18.1", "glob": "7.1.7", "koa": "^2.13.3", diff --git a/test/auth-modes.test.js b/test/auth-modes.test.js new file mode 100644 index 000000000..1011ab08e --- /dev/null +++ b/test/auth-modes.test.js @@ -0,0 +1,1139 @@ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +const { + printPath, + setupST, + startST, + killAllST, + cleanST, + extractInfoFromResponse, + setKeyValueInConfig, + delay, +} = require("./utils"); +const assert = require("assert"); +const { ProcessState } = require("../lib/build/processState"); +const SuperTokens = require("../"); +const Session = require("../recipe/session"); +const { verifySession } = require("../recipe/session/framework/express"); +const { middleware, errorHandler } = require("../framework/express"); +const express = require("express"); +const request = require("supertest"); +const sinon = require("sinon"); + +const exampleJWT = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; + +describe(`auth-modes: ${printPath("[test/auth-modes.test.js]")}`, function () { + beforeEach(async function () { + await killAllST(); + await setupST(); + ProcessState.getInstance().reset(); + }); + + afterEach(function () { + sinon.restore(); + }); + + after(async function () { + await killAllST(); + await cleanST(); + }); + + describe("with default getTokenTransferMethod", () => { + describe("createNewSession", () => { + describe("with default getTokenTransferMethod", () => { + it("should default to header based session w/ no auth-mode header", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN" })], + }); + + const app = getTestApp(); + + const resp = await createSession(app); + assert.strictEqual(resp.accessToken, undefined); + assert.strictEqual(resp.refreshToken, undefined); + assert.strictEqual(resp.antiCsrf, undefined); + assert.notStrictEqual(resp.accessTokenFromHeader, undefined); + assert.notStrictEqual(resp.refreshTokenFromHeader, undefined); + }); + + it("should default to header based session w/ bad auth-mode header", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN" })], + }); + + const app = getTestApp(); + + const resp = await createSession(app, "lol"); + assert.strictEqual(resp.accessToken, undefined); + assert.strictEqual(resp.refreshToken, undefined); + assert.strictEqual(resp.antiCsrf, undefined); + assert.notStrictEqual(resp.accessTokenFromHeader, undefined); + assert.notStrictEqual(resp.refreshTokenFromHeader, undefined); + }); + + it("should use headers if auth-mode specifies it", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN" })], + }); + + const app = getTestApp(); + + const resp = await createSession(app, "header"); + assert.strictEqual(resp.accessToken, undefined); + assert.strictEqual(resp.refreshToken, undefined); + assert.strictEqual(resp.antiCsrf, undefined); + assert.notStrictEqual(resp.accessTokenFromHeader, undefined); + assert.notStrictEqual(resp.refreshTokenFromHeader, undefined); + }); + + it("should use cookies if auth-mode specifies it", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN" })], + }); + + const app = getTestApp(); + + const resp = await createSession(app, "cookie"); + assert.notStrictEqual(resp.accessToken, undefined); + assert.notStrictEqual(resp.refreshToken, undefined); + assert.notStrictEqual(resp.antiCsrf, undefined); + assert.strictEqual(resp.accessTokenFromHeader, undefined); + assert.strictEqual(resp.refreshTokenFromHeader, undefined); + + // We check that we will have access token at least as long as we have a refresh token + // so verify session can return TRY_REFRESH_TOKEN + assert(Date.parse(resp.accessTokenExpiry) >= Date.parse(resp.refreshTokenExpiry)); + }); + }); + + describe("with user provided getTokenTransferMethod", () => { + it("should use headers if getTokenTransferMethod returns any", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN", getTokenTransferMethod: () => "any" })], + }); + + const app = getTestApp(); + + const resp = await createSession(app, "cookie"); + assert.strictEqual(resp.accessToken, undefined); + assert.strictEqual(resp.refreshToken, undefined); + assert.strictEqual(resp.antiCsrf, undefined); + assert.notStrictEqual(resp.accessTokenFromHeader, undefined); + assert.notStrictEqual(resp.refreshTokenFromHeader, undefined); + }); + + it("should use headers if getTokenTransferMethod returns header", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN", getTokenTransferMethod: () => "header" })], + }); + + const app = getTestApp(); + + const resp = await createSession(app, "cookie"); + assert.strictEqual(resp.accessToken, undefined); + assert.strictEqual(resp.refreshToken, undefined); + assert.strictEqual(resp.antiCsrf, undefined); + assert.notStrictEqual(resp.accessTokenFromHeader, undefined); + assert.notStrictEqual(resp.refreshTokenFromHeader, undefined); + }); + + it("should use clear cookies (if present) if getTokenTransferMethod returns header", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN", getTokenTransferMethod: () => "header" })], + }); + + const app = getTestApp(); + + const resp = extractInfoFromResponse( + await new Promise((resolve, reject) => { + const req = request(app).post("/create"); + req.set("st-auth-mode", "header"); + return req + .set("Cookie", ["sAccessToken=" + exampleJWT]) + .send(undefined) + .expect(200) + .end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }) + ); + assert.strictEqual(resp.accessToken, ""); + assert.strictEqual(resp.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(resp.refreshToken, ""); + assert.strictEqual(resp.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(resp.antiCsrf, undefined); + }); + + it("should use cookies if getTokenTransferMethod returns cookie", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN", getTokenTransferMethod: () => "cookie" })], + }); + + const app = getTestApp(); + + const resp = await createSession(app, "header"); + assert.notStrictEqual(resp.accessToken, undefined); + assert.notStrictEqual(resp.refreshToken, undefined); + assert.notStrictEqual(resp.antiCsrf, undefined); + assert.strictEqual(resp.accessTokenFromHeader, undefined); + assert.strictEqual(resp.refreshTokenFromHeader, undefined); + + // We check that we will have access token at least as long as we have a refresh token + // so verify session can return TRY_REFRESH_TOKEN + assert(Date.parse(resp.accessTokenExpiry) >= Date.parse(resp.refreshTokenExpiry)); + }); + + it("should clear headers (if present) if getTokenTransferMethod returns cookie", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN", getTokenTransferMethod: () => "cookie" })], + }); + + const app = getTestApp(); + + const resp = extractInfoFromResponse( + await new Promise((resolve, reject) => { + const req = request(app).post("/create"); + req.set("st-auth-mode", "header"); + return req + .set("Authorization", `Bearer ${exampleJWT}`) + .send(undefined) + .expect(200) + .end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }) + ); + + assert.strictEqual(resp.accessTokenFromHeader, ""); + assert.strictEqual(resp.refreshTokenFromHeader, ""); + }); + }); + }); + + describe("verifySession", () => { + describe("from behaviour table", () => { + // prettier-ignore + const behaviourTable = [ + { getTokenTransferMethodRes: "any", sessionRequired: false, authHeader: false, authCookie: false, output: "undefined" }, + { getTokenTransferMethodRes: "header", sessionRequired: false, authHeader: false, authCookie: false, output: "undefined" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: false, authHeader: false, authCookie: false, output: "undefined" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: false, authHeader: true, authCookie: false, output: "undefined" }, + { getTokenTransferMethodRes: "header", sessionRequired: false, authHeader: false, authCookie: true, output: "undefined" }, + { getTokenTransferMethodRes: "any", sessionRequired: true, authHeader: false, authCookie: false, output: "UNAUTHORISED" }, + { getTokenTransferMethodRes: "header", sessionRequired: true, authHeader: false, authCookie: false, output: "UNAUTHORISED" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: true, authHeader: false, authCookie: false, output: "UNAUTHORISED" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: true, authHeader: true, authCookie: false, output: "UNAUTHORISED" }, + { getTokenTransferMethodRes: "header", sessionRequired: true, authHeader: false, authCookie: true, output: "UNAUTHORISED" }, + { getTokenTransferMethodRes: "any", sessionRequired: true, authHeader: true, authCookie: true, output: "validateheader" }, + { getTokenTransferMethodRes: "any", sessionRequired: false, authHeader: true, authCookie: true, output: "validateheader" }, + { getTokenTransferMethodRes: "header", sessionRequired: true, authHeader: true, authCookie: true, output: "validateheader" }, + { getTokenTransferMethodRes: "header", sessionRequired: false, authHeader: true, authCookie: true, output: "validateheader" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: true, authHeader: true, authCookie: true, output: "validatecookie" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: false, authHeader: true, authCookie: true, output: "validatecookie" }, + { getTokenTransferMethodRes: "any", sessionRequired: true, authHeader: true, authCookie: false, output: "validateheader" }, + { getTokenTransferMethodRes: "any", sessionRequired: false, authHeader: true, authCookie: false, output: "validateheader" }, + { getTokenTransferMethodRes: "header", sessionRequired: true, authHeader: true, authCookie: false, output: "validateheader" }, + { getTokenTransferMethodRes: "header", sessionRequired: false, authHeader: true, authCookie: false, output: "validateheader" }, + { getTokenTransferMethodRes: "any", sessionRequired: true, authHeader: false, authCookie: true, output: "validatecookie" }, + { getTokenTransferMethodRes: "any", sessionRequired: false, authHeader: false, authCookie: true, output: "validatecookie" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: true, authHeader: false, authCookie: true, output: "validatecookie" }, + { getTokenTransferMethodRes: "cookie", sessionRequired: false, authHeader: false, authCookie: true, output: "validatecookie" }, + ]; + + for (let i = 0; i < behaviourTable.length; ++i) { + const conf = behaviourTable[i]; + it(`should match line ${i + 1} with a valid token`, async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: () => conf.getTokenTransferMethodRes, + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfo = await createSession(app, "cookie"); + + const authMode = + conf.authCookie && conf.authHeader + ? "both" + : conf.authCookie + ? "cookie" + : conf.authHeader + ? "header" + : "none"; + + const res = await testGet( + app, + createInfo, + conf.sessionRequired ? "/verify" : "/verify-optional", + conf.output === "UNAUTHORISED" ? 401 : 200, + authMode + ); + switch (conf.output) { + case "undefined": + assert.strictEqual(res.body.sessionExists, false); + break; + case "UNAUTHORISED": + assert.deepStrictEqual(res.body, { message: "unauthorised" }); + break; + case "validatecookie": + case "validateheader": + assert.strictEqual(res.body.sessionExists, true); + } + }); + + it(`should match line ${i + 1} with a expired token`, async () => { + await setKeyValueInConfig("access_token_validity", 2); + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: () => conf.getTokenTransferMethodRes, + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfo = await createSession(app, "cookie"); + await delay(3); + const authMode = + conf.authCookie && conf.authHeader + ? "both" + : conf.authCookie + ? "cookie" + : conf.authHeader + ? "header" + : "none"; + + const res = await testGet( + app, + createInfo, + conf.sessionRequired ? "/verify" : "/verify-optional", + conf.output !== "undefined" ? 401 : 200, + authMode + ); + switch (conf.output) { + case "undefined": + assert.strictEqual(res.body.sessionExists, false); + break; + case "UNAUTHORISED": + assert.deepStrictEqual(res.body, { message: "unauthorised" }); + break; + case "validatecookie": + case "validateheader": + assert.deepStrictEqual(res.body, { message: "try refresh token" }); + } + }); + } + }); + + describe("with access tokens in both headers and cookies", () => { + it("should use the value from headers if getTokenTransferMethod returns any", async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: () => "any", + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfoCookie = await createSession(app, "header"); + const createInfoHeader = await createSession(app, "header"); + + const resp = await new Promise((resolve, reject) => { + const req = request(app).get("/verify"); + + req.set("Cookie", ["sAccessToken=" + createInfoCookie.accessTokenFromHeader]); + if (createInfoCookie.antiCsrf) { + req.set("anti-csrf", info.antiCsrf); + } + req.set( + "Authorization", + `Bearer ${decodeURIComponent(createInfoHeader.accessTokenFromHeader)}` + ); + req.expect(200).end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + + assert.strictEqual(resp.body.sessionHandle, createInfoHeader.body.sessionHandle); + }); + + it("should use the value from headers if getTokenTransferMethod returns header", async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: ({ forCreateNewSession }) => + forCreateNewSession ? "any" : "header", + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfoCookie = await createSession(app, "header"); + const createInfoHeader = await createSession(app, "header"); + + const resp = await new Promise((resolve, reject) => { + const req = request(app).get("/verify"); + + req.set("Cookie", ["sAccessToken=" + createInfoCookie.accessTokenFromHeader]); + if (createInfoCookie.antiCsrf) { + req.set("anti-csrf", info.antiCsrf); + } + req.set( + "Authorization", + `Bearer ${decodeURIComponent(createInfoHeader.accessTokenFromHeader)}` + ); + req.expect(200).end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + + assert.strictEqual(resp.body.sessionHandle, createInfoHeader.body.sessionHandle); + }); + + it("should use the value from cookies if getTokenTransferMethod returns cookie", async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: ({ forCreateNewSession }) => + forCreateNewSession ? "any" : "cookie", + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfoCookie = await createSession(app, "header"); + const createInfoHeader = await createSession(app, "header"); + + const resp = await new Promise((resolve, reject) => { + const req = request(app).get("/verify"); + + req.set("Cookie", ["sAccessToken=" + createInfoCookie.accessTokenFromHeader]); + if (createInfoCookie.antiCsrf) { + req.set("anti-csrf", info.antiCsrf); + } + req.set( + "Authorization", + `Bearer ${decodeURIComponent(createInfoHeader.accessTokenFromHeader)}` + ); + req.expect(200).end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + + assert.strictEqual(resp.body.sessionHandle, createInfoCookie.body.sessionHandle); + }); + }); + + it("should reject requests with sIdRefreshToken", async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfo = await createSession(app, "cookie"); + + const res = await new Promise((resolve, reject) => + request(app) + .get("/verify") + .set("Cookie", [ + "sAccessToken=" + createInfo.accessToken, + "sIdRefreshToken=" + createInfo.refreshToken, // The value doesn't actually matter + ]) + .set("anti-csrf", createInfo.antiCsrf) + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ); + assert.strictEqual(res.status, 401); + assert.deepStrictEqual(res.body, { message: "try refresh token" }); + }); + + describe("with non ST in Authorize header", () => { + it("should use the value from cookies if present and getTokenTransferMethod returns any", async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: () => "any", + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfoCookie = await createSession(app, "header"); + + const resp = await new Promise((resolve, reject) => { + const req = request(app).get("/verify"); + + req.set("Cookie", ["sAccessToken=" + createInfoCookie.accessTokenFromHeader]); + if (createInfoCookie.antiCsrf) { + req.set("anti-csrf", info.antiCsrf); + } + req.set("Authorization", `Bearer ${exampleJWT}`); + req.expect(200).end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + + assert.strictEqual(resp.body.sessionHandle, createInfoCookie.body.sessionHandle); + }); + + it("should reject with UNAUTHORISED if getTokenTransferMethod returns header", async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: ({ forCreateNewSession }) => + forCreateNewSession ? "any" : "header", + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const createInfoCookie = await createSession(app, "header"); + + const resp = await new Promise((resolve, reject) => { + const req = request(app).get("/verify"); + + req.set("Cookie", ["sAccessToken=" + createInfoCookie.accessTokenFromHeader]); + if (createInfoCookie.antiCsrf) { + req.set("anti-csrf", info.antiCsrf); + } + req.set("Authorization", `Bearer ${exampleJWT}`); + req.end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + assert.strictEqual(resp.status, 401); + assert.deepStrictEqual(resp.body, { message: "unauthorised" }); + }); + + it("should reject with UNAUTHORISED if cookies are not present", async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: ({}) => "any", + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const resp = await new Promise((resolve, reject) => { + const req = request(app).get("/verify"); + + req.set("Authorization", `Bearer ${exampleJWT}`); + req.end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + + assert.strictEqual(resp.status, 401); + assert.deepStrictEqual(resp.body, { message: "unauthorised" }); + }); + }); + }); + + describe("mergeIntoAccessTokenPayload", () => { + it("should update cookies if the session was cookie based", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN" })], + }); + + const app = getTestApp(); + + const createInfo = await createSession(app, "header"); + + const updateInfo = extractInfoFromResponse( + await testGet(app, createInfo, "/update-payload", 200, "cookie", undefined) + ); + + // Didn't update + assert.strictEqual(updateInfo.refreshToken, undefined); + assert.strictEqual(updateInfo.antiCsrf, undefined); + assert.strictEqual(updateInfo.accessTokenFromHeader, undefined); + assert.strictEqual(updateInfo.refreshTokenFromHeader, undefined); + + // Updated access token + assert.notStrictEqual(updateInfo.accessToken, undefined); + assert.notStrictEqual(updateInfo.accessToken, createInfo.accessTokenFromHeader); + + // Updated front token + assert.notStrictEqual(updateInfo.frontToken, undefined); + assert.notStrictEqual(updateInfo.frontToken, createInfo.frontToken); + }); + + it("should allow headers if the session was header based", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ antiCsrf: "VIA_TOKEN" })], + }); + + const app = getTestApp(); + + const createInfo = await createSession(app, "cookie"); + + const updateInfo = extractInfoFromResponse( + await testGet(app, createInfo, "/update-payload", 200, "header", undefined) + ); + + // Didn't update + assert.strictEqual(updateInfo.accessToken, undefined); + assert.strictEqual(updateInfo.refreshToken, undefined); + assert.strictEqual(updateInfo.antiCsrf, undefined); + assert.strictEqual(updateInfo.refreshTokenFromHeader, undefined); + + // Updated access token + assert.notStrictEqual(updateInfo.accessTokenFromHeader, undefined); + assert.notStrictEqual(updateInfo.accessTokenFromHeader, createInfo.accessToken); + + // Updated front token + assert.notStrictEqual(updateInfo.frontToken, undefined); + assert.notStrictEqual(updateInfo.frontToken, createInfo.frontToken); + }); + }); + + describe("refreshSession", () => { + describe("from behaviour table", () => { + // prettier-ignore + const behaviourTable = [ + { getTokenTransferMethodRes: "any", authHeader: false, authCookie: false, output: "unauthorised", setTokens: "none", clearedTokens: "none" }, + { getTokenTransferMethodRes: "header", authHeader: false, authCookie: false, output: "unauthorised", setTokens: "none", clearedTokens: "none" }, + { getTokenTransferMethodRes: "cookie", authHeader: false, authCookie: false, output: "unauthorised", setTokens: "none", clearedTokens: "none" }, + { getTokenTransferMethodRes: "any", authHeader: false, authCookie: true, output: "validatecookie", setTokens: "cookies", clearedTokens: "none" }, + { getTokenTransferMethodRes: "header", authHeader: false, authCookie: true, output: "unauthorised", setTokens: "none", clearedTokens: "none" }, // 5 + { getTokenTransferMethodRes: "cookie", authHeader: false, authCookie: true, output: "validatecookie", setTokens: "cookies", clearedTokens: "none" }, + { getTokenTransferMethodRes: "any", authHeader: true, authCookie: false, output: "validateheader", setTokens: "headers", clearedTokens: "none" }, + { getTokenTransferMethodRes: "header", authHeader: true, authCookie: false, output: "validateheader", setTokens: "headers", clearedTokens: "none" }, + { getTokenTransferMethodRes: "cookie", authHeader: true, authCookie: false, output: "unauthorised", setTokens: "none", clearedTokens: "none" }, // 9 + { getTokenTransferMethodRes: "any", authHeader: true, authCookie: true, output: "validateheader", setTokens: "headers", clearedTokens: "cookies" }, + { getTokenTransferMethodRes: "header", authHeader: true, authCookie: true, output: "validateheader", setTokens: "headers", clearedTokens: "cookies" }, + { getTokenTransferMethodRes: "cookie", authHeader: true, authCookie: true, output: "validatecookie", setTokens: "cookies", clearedTokens: "headers" }, // 12 + ]; + + for (let i = 0; i < behaviourTable.length; ++i) { + const conf = behaviourTable[i]; + it(`should match line ${i + 1} with a valid token`, async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: () => conf.getTokenTransferMethodRes, + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + // Which we create doesn't really matter, since the token is the same + const createInfo = await createSession(app, "header"); + + const authMode = + conf.authCookie && conf.authHeader + ? "both" + : conf.authCookie + ? "cookie" + : conf.authHeader + ? "header" + : "none"; + + const refreshRes = await refreshSession( + app, + conf.getTokenTransferMethodRes, + authMode, + createInfo + ); + + if (conf.output === "unauthorised") { + assert.strictEqual(refreshRes.status, 401); + assert.deepStrictEqual(refreshRes.body, { message: "unauthorised" }); + } else { + assert.strictEqual(refreshRes.status, 200); + } + + if (conf.clearedTokens === "headers") { + assert.strictEqual(refreshRes.accessTokenFromHeader, ""); + assert.strictEqual(refreshRes.refreshTokenFromHeader, ""); + } else if (conf.clearedTokens === "cookies") { + assert.strictEqual(refreshRes.accessToken, ""); + assert.strictEqual(refreshRes.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(refreshRes.refreshToken, ""); + assert.strictEqual(refreshRes.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + } + + switch (conf.setTokens) { + case "headers": + assert.ok(refreshRes.accessTokenFromHeader); + assert.notStrictEqual(refreshRes.accessTokenFromHeader, ""); + assert.ok(refreshRes.refreshTokenFromHeader); + assert.notStrictEqual(refreshRes.refreshTokenFromHeader, ""); + break; + case "cookies": + assert.notStrictEqual(refreshRes.accessToken, ""); + assert.notStrictEqual(refreshRes.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.notStrictEqual(refreshRes.refreshToken, ""); + assert.notStrictEqual(refreshRes.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + break; + case "none": + if (conf.clearedTokens === "none") { + assert.strictEqual(refreshRes.frontToken, undefined); + } + break; + } + if (conf.setTokens !== "cookies" && conf.clearedTokens !== "cookies") { + assert.strictEqual(refreshRes.accessToken, undefined); + assert.strictEqual(refreshRes.accessTokenExpiry, undefined); + assert.strictEqual(refreshRes.refreshToken, undefined); + assert.strictEqual(refreshRes.refreshTokenExpiry, undefined); + } + if (conf.setTokens !== "headers" && conf.clearedTokens !== "headers") { + assert.strictEqual(refreshRes.accessTokenFromHeader, undefined); + assert.strictEqual(refreshRes.refreshTokenFromHeader, undefined); + } + }); + } + + for (let i = 0; i < behaviourTable.length; ++i) { + const conf = behaviourTable[i]; + + it(`should match line ${i + 1} with a invalid token`, async () => { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: () => conf.getTokenTransferMethodRes, + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + const app = getTestApp(); + + const infoWithInvalidRefreshToken = { + refreshToken: "asdf", + }; + + const authMode = + conf.authCookie && conf.authHeader + ? "both" + : conf.authCookie + ? "cookie" + : conf.authHeader + ? "header" + : "none"; + + const refreshRes = await refreshSession( + app, + conf.getTokenTransferMethodRes, + authMode, + infoWithInvalidRefreshToken + ); + + assert.strictEqual(refreshRes.status, 401); + assert.deepStrictEqual(refreshRes.body, { message: "unauthorised" }); + if (conf.output === "validateheader") { + assert.strictEqual(refreshRes.accessTokenFromHeader, ""); + assert.strictEqual(refreshRes.refreshTokenFromHeader, ""); + } else if (conf.output === "validatecookie") { + assert.strictEqual(refreshRes.accessToken, ""); + assert.strictEqual(refreshRes.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(refreshRes.refreshToken, ""); + assert.strictEqual(refreshRes.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + } + }); + } + }); + }); + }); +}); + +async function createSession(app, authModeHeader, body) { + return extractInfoFromResponse( + await new Promise((resolve, reject) => { + const req = request(app).post("/create"); + if (authModeHeader) { + req.set("st-auth-mode", authModeHeader); + } + return req + .send(body) + .expect(200) + .end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }) + ); +} + +async function refreshSession(app, authModeHeader, authMode, info) { + return extractInfoFromResponse( + await new Promise((resolve, reject) => { + const req = request(app).post("/auth/session/refresh"); + if (authModeHeader) { + req.set("st-auth-mode", authModeHeader); + } + + const accessToken = info.accessToken || info.accessTokenFromHeader; + const refreshToken = info.refreshToken || info.refreshTokenFromHeader; + + if (authMode === "both" || authMode === "cookie") { + req.set("Cookie", ["sAccessToken=" + accessToken, "sRefreshToken=" + refreshToken]); + if (info.antiCsrf) { + req.set("anti-csrf", info.antiCsrf); + } + } + if (authMode === "both" || authMode === "header") { + req.set("Authorization", `Bearer ${decodeURIComponent(refreshToken)}`); + } + return req.send().end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }) + ); +} + +function testGet(app, info, url, expectedStatus, authMode, authModeHeader) { + return new Promise((resolve, reject) => { + const req = request(app).get(url); + const accessToken = info.accessToken || info.accessTokenFromHeader; + + if (authModeHeader) { + req.set("st-auth-mode", authModeHeader); + } + if (authMode === "cookie" || authMode === "both") { + req.set("Cookie", ["sAccessToken=" + accessToken]); + if (info.antiCsrf) { + req.set("anti-csrf", info.antiCsrf); + } + } + if (authMode === "header" || authMode === "both") { + req.set("Authorization", `Bearer ${decodeURIComponent(accessToken)}`); + } + return req.expect(expectedStatus).end((err, res) => { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); +} + +function getTestApp(endpoints) { + const app = express(); + + app.use(middleware()); + + app.use(express.json()); + + app.post("/create", async (req, res) => { + const session = await Session.createNewSession(req, res, "testing-userId", req.body, {}); + res.status(200).json({ message: true, sessionHandle: session.getHandle() }); + }); + + app.get("/update-payload", verifySession(), async (req, res) => { + await req.session.mergeIntoAccessTokenPayload({ newValue: "test" }); + res.status(200).json({ message: true }); + }); + + app.get("/verify", verifySession(), async (req, res) => { + res.status(200).json({ message: true, sessionHandle: req.session.getHandle(), sessionExists: true }); + }); + + app.get("/verify-optional", verifySession({ sessionRequired: false }), async (req, res) => { + res.status(200).json({ + message: true, + sessionHandle: req.session && req.session.getHandle(), + sessionExists: !!req.session, + }); + }); + + if (endpoints !== undefined) { + for (const { path, overrideGlobalClaimValidators } of endpoints) { + app.get(path, verifySession({ overrideGlobalClaimValidators }), async (req, res) => { + res.status(200).json({ message: req.session.getHandle() }); + }); + } + } + + app.post("/logout", verifySession(), async (req, res) => { + await req.session.revokeSession(); + res.status(200).json({ message: true }); + }); + + app.use(errorHandler()); + return app; +} diff --git a/test/config.test.js b/test/config.test.js index 5e586be49..e16dbdc4a 100644 --- a/test/config.test.js +++ b/test/config.test.js @@ -21,6 +21,8 @@ const { cleanST, resetAll, extractInfoFromResponse, + mockResponse, + mockRequest, } = require("./utils"); const request = require("supertest"); const express = require("express"); @@ -37,8 +39,8 @@ let SuperTokens = require("../lib/build/supertokens").default; let ST = require("../"); let EmailPassword = require("../lib/build/recipe/emailpassword"); let EmailPasswordRecipe = require("../lib/build/recipe/emailpassword/recipe").default; -const { getTopLevelDomainForSameSiteResolution } = require("../lib/build/recipe/session/utils"); -let { middleware, errorHandler } = require("../framework/express"); +const { getTopLevelDomainForSameSiteResolution } = require("../lib/build/utils"); +const { middleware } = require("../framework/express"); describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { beforeEach(async function () { @@ -67,7 +69,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SuperTokens.getInstanceOrThrowError().appInfo.apiBasePath.getAsStringDangerous() === "/auth"); assert(SuperTokens.getInstanceOrThrowError().appInfo.websiteBasePath.getAsStringDangerous() === "/auth"); @@ -87,7 +89,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SuperTokens.getInstanceOrThrowError().appInfo.apiBasePath.getAsStringDangerous() === "/test"); @@ -110,7 +112,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(false); } catch (err) { @@ -135,7 +137,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiDomain: "api.supertokens.io", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(false); } catch (err) { @@ -160,7 +162,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiDomain: "api.supertokens.io", appName: "SuperTokens", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(false); } catch (err) { @@ -214,7 +216,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); SessionRecipe.getInstanceOrThrowError(); assert(SuperTokens.getInstanceOrThrowError().recipeModules.length === 1); @@ -231,7 +233,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init(), EmailPassword.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" }), EmailPassword.init()], }); SessionRecipe.getInstanceOrThrowError(); EmailPasswordRecipe.getInstanceOrThrowError(); @@ -255,6 +257,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", cookieDomain: "testDomain", sessionExpiredStatusCode: 111, cookieSecure: true, @@ -279,11 +282,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: " Lax ", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: " Lax " })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "lax"); @@ -301,11 +300,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: "None ", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "None " })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "none"); @@ -323,11 +318,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: " STRICT ", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: " STRICT " })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "strict"); @@ -346,11 +337,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: "random ", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "random " })], }); assert(false); } catch (err) { @@ -373,11 +360,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: " ", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: " " })], }); assert(false); } catch (err) { @@ -399,11 +382,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: "lax", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "lax" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "lax"); @@ -421,11 +400,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: "none", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "none" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "none"); @@ -443,11 +418,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - cookieSameSite: "strict", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "strict" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "strict"); @@ -465,7 +436,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "lax"); @@ -484,25 +455,28 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { ]; for (const domainCombination of domainCombinations) { + let err; + STExpress.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + appName: "SuperTokens", + websiteDomain: domainCombination[0], + apiDomain: domainCombination[1], + }, + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "none" })], + }); try { - STExpress.init({ - supertokens: { - connectionURI: "http://localhost:8080", - }, - appInfo: { - appName: "SuperTokens", - websiteDomain: domainCombination[0], - apiDomain: domainCombination[1], - }, - recipeList: [Session.init({ cookieSameSite: "none" })], - }); - assert(false); + await Session.createNewSession(mockRequest(), mockResponse(), "asdf"); } catch (e) { - assert( - e.message === - "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." - ); + err = e; } + assert.ok(err); + assert.strictEqual( + err.message, + "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." + ); resetAll(); } }); @@ -537,7 +511,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { websiteDomain: domainCombination[0], apiDomain: domainCombination[1], }, - recipeList: [Session.init({ cookieSameSite: "none" })], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "none" })], }); } catch (e) { assert(false); @@ -718,7 +692,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { websiteDomain: "supertokens.io", apiBasePath: "/custom/a", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert( SessionRecipe.getInstanceOrThrowError().config.refreshTokenPath.getAsStringDangerous() === @@ -738,7 +712,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { websiteDomain: "supertokens.io", apiBasePath: "/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert( SessionRecipe.getInstanceOrThrowError().config.refreshTokenPath.getAsStringDangerous() === @@ -757,7 +731,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert( SessionRecipe.getInstanceOrThrowError().config.refreshTokenPath.getAsStringDangerous() === @@ -777,7 +751,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(Querier.apiKey === "haha"); resetAll(); @@ -794,11 +768,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { websiteDomain: "supertokens.io", apiBasePath: "/custom", }, - recipeList: [ - Session.init({ - sessionExpiredStatusCode: 402, - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", sessionExpiredStatusCode: 402 })], }); assert(SessionRecipe.getInstanceOrThrowError().config.sessionExpiredStatusCode === 402); resetAll(); @@ -814,7 +784,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); let hosts = Querier.hosts; assert(hosts.length === 4); @@ -837,11 +807,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { websiteDomain: "supertokens.io", apiBasePath: "/", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_CUSTOM_HEADER", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_CUSTOM_HEADER" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "VIA_CUSTOM_HEADER"); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "lax"); @@ -861,7 +827,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "NONE"); @@ -883,7 +849,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "NONE"); @@ -904,7 +870,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "NONE"); @@ -925,7 +891,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "VIA_CUSTOM_HEADER"); @@ -946,7 +912,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "NONE"); @@ -967,7 +933,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "NONE"); @@ -988,11 +954,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_CUSTOM_HEADER", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_CUSTOM_HEADER" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "VIA_CUSTOM_HEADER"); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "lax"); @@ -1012,7 +974,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "VIA_CUSTOM_HEADER"); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "none"); @@ -1032,7 +994,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "NONE"); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite === "lax"); @@ -1052,11 +1014,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [ - Session.init({ - antiCsrf: "NONE", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "NONE" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.antiCsrf === "NONE"); resetAll(); @@ -1075,11 +1033,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [ - Session.init({ - antiCsrf: "RANDOM", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "RANDOM" })], }); assert(false); } catch (err) { @@ -1103,16 +1057,15 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); + await Session.createNewSession(mockRequest(), mockResponse(), "userId"); assert(false); } catch (err) { - if ( - err.message !== + assert.strictEqual( + err.message, "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." - ) { - throw err; - } + ); } resetAll(); } @@ -1130,24 +1083,43 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "test/", websiteBasePath: "test1/", }, - recipeList: [ - Session.init({ - cookieSecure: false, - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", cookieSecure: false })], }); + await Session.createNewSession(mockRequest(), mockResponse(), "userId"); assert(false); } catch (err) { - if ( - err.message !== + assert.strictEqual( + err.message, "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." - ) { - throw err; - } + ); } resetAll(); } + { + STExpress.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "https://api.test.com:3000", + appName: "SuperTokens", + websiteDomain: "google.com", + apiBasePath: "test/", + websiteBasePath: "test1/", + }, + recipeList: [ + Session.init({ + getTokenTransferMethod: () => "cookie", + getTokenTransferMethod: () => "header", + cookieSecure: false, + }), + ], + }); + await Session.createNewSession(mockRequest(), mockResponse(), "userId"); + resetAll(); + } + { STExpress.init({ supertokens: { @@ -1158,7 +1130,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "Supertokens", websiteDomain: "http://localhost:3000", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert(SessionRecipe.getInstanceOrThrowError().config.cookieSecure); @@ -1179,7 +1151,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert.equal(SessionRecipe.getInstanceOrThrowError().config.cookieDomain, undefined); assert.equal(SessionRecipe.getInstanceOrThrowError().config.cookieSameSite, "lax"); @@ -1202,7 +1174,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert.notStrictEqual(SessionRecipe.getInstanceOrThrowError().config.jwt, undefined); assert.strictEqual(SessionRecipe.getInstanceOrThrowError().config.jwt.enable, false); @@ -1219,7 +1191,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init({ jwt: { enable: false } })], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", jwt: { enable: false } })], }); assert.notStrictEqual(SessionRecipe.getInstanceOrThrowError().config.jwt, undefined); assert.strictEqual(SessionRecipe.getInstanceOrThrowError().config.jwt.enable, false); @@ -1236,7 +1208,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init({ jwt: { enable: true } })], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", jwt: { enable: true } })], }); assert.notStrictEqual(SessionRecipe.getInstanceOrThrowError().config.jwt, undefined); @@ -1254,7 +1226,12 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init({ jwt: { enable: true, propertyNameInAccessTokenPayload: "customJWTKey" } })], + recipeList: [ + Session.init({ + getTokenTransferMethod: () => "cookie", + jwt: { enable: true, propertyNameInAccessTokenPayload: "customJWTKey" }, + }), + ], }); assert.notStrictEqual(SessionRecipe.getInstanceOrThrowError().config.jwt, undefined); @@ -1275,7 +1252,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init({ jwt: { enable: true } })], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", jwt: { enable: true } })], }); assert.notStrictEqual(SessionRecipe.getInstanceOrThrowError().config.jwt, undefined); @@ -1294,7 +1271,12 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init({ jwt: { enable: true, propertyNameInAccessTokenPayload: "_jwtPName" } })], + recipeList: [ + Session.init({ + getTokenTransferMethod: () => "cookie", + jwt: { enable: true, propertyNameInAccessTokenPayload: "_jwtPName" }, + }), + ], }); throw new Error("Init succeeded when it should have failed"); @@ -1334,11 +1316,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { websiteDomain: "supertokens.io", apiGatewayPath: "/gateway", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); @@ -1346,7 +1324,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -1368,10 +1346,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -1401,11 +1376,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { apiBasePath: "hello", apiGatewayPath: "/gateway", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); @@ -1413,7 +1384,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -1435,10 +1406,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { let res2 = await new Promise((resolve) => request(app) .post("/hello/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -1468,11 +1436,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { websiteDomain: "supertokens.io", apiBasePath: "hello", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); @@ -1480,7 +1444,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -1502,10 +1466,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { let res2 = await new Promise((resolve) => request(app) .post("/hello/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -1536,7 +1497,7 @@ describe(`configTest: ${printPath("[test/config.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init(), , EmailPassword.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" }), , EmailPassword.init()], }); errorCaught = false; } catch (err) { diff --git a/test/emailpassword/deleteUser.test.js b/test/emailpassword/deleteUser.test.js index 0fee53889..d1c3feeb7 100644 --- a/test/emailpassword/deleteUser.test.js +++ b/test/emailpassword/deleteUser.test.js @@ -64,7 +64,7 @@ describe(`deleteUser: ${printPath("[test/emailpassword/deleteUser.test.js]")}`, appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); let querier = Querier.getNewInstanceOrThrowError(undefined); diff --git a/test/emailpassword/emailDelivery.test.js b/test/emailpassword/emailDelivery.test.js index 3741335b1..0205da7cb 100644 --- a/test/emailpassword/emailDelivery.test.js +++ b/test/emailpassword/emailDelivery.test.js @@ -49,7 +49,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], telemetry: false, }); @@ -105,7 +105,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], telemetry: false, }); @@ -175,7 +175,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -225,7 +225,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -299,7 +299,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -403,7 +403,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -446,7 +446,11 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailVerification.init({ mode: "OPTIONAL" }), EmailPassword.init(), Session.init()], + recipeList: [ + EmailVerification.init({ mode: "OPTIONAL" }), + EmailPassword.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), + ], telemetry: false, }); @@ -454,7 +458,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -480,7 +484,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -501,7 +505,11 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailVerification.init({ mode: "OPTIONAL" }), EmailPassword.init(), Session.init()], + recipeList: [ + EmailVerification.init({ mode: "OPTIONAL" }), + EmailPassword.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), + ], telemetry: false, }); @@ -509,7 +517,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -535,7 +543,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] let result = await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -569,7 +577,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] }, }), EmailPassword.init(), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -578,7 +586,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -589,7 +597,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); assert.strictEqual(email, "test@example.com"); @@ -629,7 +637,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] }, }), EmailPassword.init(), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -638,7 +646,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -658,7 +666,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -734,7 +742,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] }, }), EmailPassword.init(), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -743,7 +751,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -754,7 +762,7 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); @@ -764,4 +772,69 @@ describe(`emailDelivery: ${printPath("[test/emailpassword/emailDelivery.test.js] assert(sendRawEmailCalled); assert.notStrictEqual(emailVerifyURL, undefined); }); + + it("test backward compatibility: reset password and sendEmail override", async function () { + await startST(); + let email = undefined; + let passwordResetURL = undefined; + let timeJoined = undefined; + STExpress.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [ + EmailPassword.init({ + emailDelivery: { + override: (oI) => { + return { + ...oI, + sendEmail: async function (input) { + input.user.email = "override@example.com"; + return oI.sendEmail(input); + }, + }; + }, + }, + resetPasswordUsingTokenFeature: { + createAndSendCustomEmail: async (input, passwordResetLink) => { + email = input.email; + passwordResetURL = passwordResetLink; + timeJoined = input.timeJoined; + }, + }, + }), + Session.init(), + ], + telemetry: false, + }); + + const app = express(); + app.use(middleware()); + app.use(errorHandler()); + + await EmailPassword.signUp("test@example.com", "1234abcd"); + + await supertest(app) + .post("/auth/user/password/reset/token") + .set("rid", "emailpassword") + .send({ + formFields: [ + { + id: "email", + value: "test@example.com", + }, + ], + }) + .expect(200); + + await delay(2); + assert.strictEqual(email, "override@example.com"); + assert.notStrictEqual(passwordResetURL, undefined); + assert.notStrictEqual(timeJoined, undefined); + }); }); diff --git a/test/emailpassword/emailExists.test.js b/test/emailpassword/emailExists.test.js index 6305273fa..642fa3f31 100644 --- a/test/emailpassword/emailExists.test.js +++ b/test/emailpassword/emailExists.test.js @@ -78,7 +78,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -118,7 +118,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -164,7 +164,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -206,7 +206,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -252,7 +252,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -298,7 +298,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -335,7 +335,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -378,7 +378,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -427,7 +427,7 @@ describe(`emailExists: ${printPath("[test/emailpassword/emailExists.test.js]")}` appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); diff --git a/test/emailpassword/emailverify.test.js b/test/emailpassword/emailverify.test.js index 9cf1777da..c9c4a58f9 100644 --- a/test/emailpassword/emailverify.test.js +++ b/test/emailpassword/emailverify.test.js @@ -78,9 +78,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL" }), ], }); @@ -98,13 +96,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = JSON.parse(response.text).user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "OK"); assert(Object.keys(JSON.parse(response.text)).length === 1); @@ -124,9 +116,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL" }), ], }); @@ -147,13 +137,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let verifyToken = await EmailVerification.createEmailVerificationToken(userId); await EmailVerification.verifyEmailUsingToken(verifyToken.token); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "EMAIL_ALREADY_VERIFIED_ERROR"); assert(response.status === 200); @@ -174,9 +158,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL" }), ], }); @@ -220,9 +202,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL" }), ], }); @@ -245,7 +225,6 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let response2 = await emailVerifyTokenRequest( app, infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, infoFromResponse.antiCsrf, userId ); @@ -259,10 +238,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + infoFromResponse.refreshToken, - "sIdRefreshToken=" + infoFromResponse.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + infoFromResponse.refreshToken]) .set("anti-csrf", infoFromResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -278,7 +254,6 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let response3 = (response = await emailVerifyTokenRequest( app, refreshedResponse.accessToken, - refreshedResponse.idRefreshTokenFromCookie, refreshedResponse.antiCsrf, userId )); @@ -313,9 +288,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -335,7 +308,6 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let response2 = await emailVerifyTokenRequest( app, infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, infoFromResponse.antiCsrf, userId ); @@ -383,9 +355,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init({}), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -402,13 +372,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = JSON.parse(response.text).user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "OK"); assert(Object.keys(JSON.parse(response.text)).length === 1); @@ -451,9 +415,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` mode: "OPTIONAL", }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -501,9 +463,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` mode: "OPTIONAL", }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -571,9 +531,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -590,13 +548,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = JSON.parse(response.text).user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "OK"); let response2 = await new Promise((resolve) => @@ -649,9 +601,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -668,13 +618,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = JSON.parse(response.text).user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "OK"); let response2 = await new Promise((resolve) => @@ -699,12 +643,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let response3 = await new Promise((resolve) => request(app) .get("/auth/user/email/verify") - .set("Cookie", [ - "sAccessToken=" + - infoFromResponse.accessToken + - ";sIdRefreshToken=" + - infoFromResponse.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + infoFromResponse.accessToken]) .set("anti-csrf", infoFromResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -738,9 +677,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` mode: "OPTIONAL", }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -791,9 +728,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -810,13 +745,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = JSON.parse(response.text).user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "OK"); let response2 = await new Promise((resolve) => @@ -843,12 +772,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let response3 = await new Promise((resolve) => request(app) .get("/auth/user/email/verify") - .set("Cookie", [ - "sAccessToken=" + - infoFromResponse.accessToken + - ";sIdRefreshToken=" + - infoFromResponse.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + infoFromResponse.accessToken]) .set("anti-csrf", infoFromResponse.antiCsrf) .end((err, res) => { if (err) { @@ -867,10 +791,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + infoFromResponse.refreshToken, - "sIdRefreshToken=" + infoFromResponse.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + infoFromResponse.refreshToken]) .set("anti-csrf", infoFromResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -886,12 +807,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let response4 = await new Promise((resolve) => request(app) .get("/auth/user/email/verify") - .set("Cookie", [ - "sAccessToken=" + - refreshedResponse.accessToken + - ";sIdRefreshToken=" + - refreshedResponse.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + refreshedResponse.accessToken]) .set("anti-csrf", refreshedResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -941,9 +857,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -960,13 +874,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = response.body.user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(response.body.status === "OK"); assert(Object.keys(response.body).length === 1); @@ -1027,9 +935,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -1046,13 +952,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = response.body.user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(response.body.status === "OK"); assert(Object.keys(response.body).length === 1); @@ -1115,9 +1015,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }), EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -1141,13 +1039,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = response.body.user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(response.body.status === "OK"); assert(Object.keys(response.body).length === 1); @@ -1209,9 +1101,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, }, }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -1235,13 +1125,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = response.body.user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(response.body.status === "OK"); assert(Object.keys(response.body).length === 1); @@ -1280,9 +1164,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL" }), ], }); @@ -1328,9 +1210,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL" }), ], }); @@ -1410,13 +1290,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let userId = response.body.user.id; let infoFromResponse = extractInfoFromResponse(response); await STExpress.deleteUser(userId); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert.strictEqual(response.statusCode, 401); assert.deepStrictEqual(response.body, { message: "unauthorised" }); }); @@ -1439,7 +1313,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` ? { status: "EMAIL_DOES_NOT_EXIST_ERROR" } : { status: "UNKNOWN_USER_ID_ERROR" }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -1501,13 +1375,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` let antiCsrfToken = infoFromResponse.antiCsrf; let token = await EmailVerification.createEmailVerificationToken(userId); await EmailVerification.verifyEmailUsingToken(token.token); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - antiCsrfToken, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, antiCsrfToken, userId); infoFromResponse = extractInfoFromResponse(response); assert.strictEqual(response.statusCode, 200); assert.deepStrictEqual(response.body.status, "EMAIL_ALREADY_VERIFIED_ERROR"); @@ -1515,13 +1383,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` assert.strictEqual(frontendInfo.up["st-ev"].v, true); // calling the API again should not modify the access token again - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - antiCsrfToken, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, antiCsrfToken, userId); let infoFromResponse2 = extractInfoFromResponse(response); assert.strictEqual(response.statusCode, 200); assert.deepStrictEqual(response.body.status, "EMAIL_ALREADY_VERIFIED_ERROR"); @@ -1529,13 +1391,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` // now we mark the email as unverified and try again await EmailVerification.unverifyEmail(userId); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - antiCsrfToken, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, antiCsrfToken, userId); infoFromResponse = extractInfoFromResponse(response); assert.strictEqual(response.statusCode, 200); assert.deepStrictEqual(response.body.status, "OK"); @@ -1543,13 +1399,7 @@ describe(`emailverify: ${printPath("[test/emailpassword/emailverify.test.js]")}` assert.strictEqual(frontendInfo.up["st-ev"].v, false); // calling the API again should not modify the access token again - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - antiCsrfToken, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, antiCsrfToken, userId); infoFromResponse2 = extractInfoFromResponse(response); assert.strictEqual(response.statusCode, 200); assert.deepStrictEqual(response.body.status, "OK"); diff --git a/test/emailpassword/override.test.js b/test/emailpassword/override.test.js index c9aea9096..191d314e7 100644 --- a/test/emailpassword/override.test.js +++ b/test/emailpassword/override.test.js @@ -82,7 +82,7 @@ describe(`overrideTest: ${printPath("[test/emailpassword/override.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -198,7 +198,7 @@ describe(`overrideTest: ${printPath("[test/emailpassword/override.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -326,7 +326,7 @@ describe(`overrideTest: ${printPath("[test/emailpassword/override.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -446,7 +446,7 @@ describe(`overrideTest: ${printPath("[test/emailpassword/override.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/emailpassword/passwordreset.test.js b/test/emailpassword/passwordreset.test.js index c66377af9..f993d2d3e 100644 --- a/test/emailpassword/passwordreset.test.js +++ b/test/emailpassword/passwordreset.test.js @@ -132,7 +132,7 @@ describe(`passwordreset: ${printPath("[test/emailpassword/passwordreset.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -366,7 +366,7 @@ describe(`passwordreset: ${printPath("[test/emailpassword/passwordreset.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/emailpassword/signinFeature.test.js b/test/emailpassword/signinFeature.test.js index 5d9c8a0ad..637d808ef 100644 --- a/test/emailpassword/signinFeature.test.js +++ b/test/emailpassword/signinFeature.test.js @@ -135,7 +135,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -192,7 +192,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -247,7 +247,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -308,7 +308,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -352,7 +352,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -395,7 +395,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -442,9 +442,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); const app = express(); @@ -486,15 +484,11 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] assert(cookies.accessToken !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.antiCsrf !== undefined); - assert(cookies.idRefreshTokenFromHeader !== undefined); - assert(cookies.idRefreshTokenFromCookie !== undefined); assert(cookies.accessTokenExpiry !== undefined); assert(cookies.refreshTokenExpiry !== undefined); - assert(cookies.idRefreshTokenExpiry !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); assert(cookies.frontToken !== undefined); }); @@ -539,7 +533,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -618,7 +612,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -680,7 +674,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -734,7 +728,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -789,7 +783,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -838,7 +832,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -889,7 +883,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -948,7 +942,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); let emailpassword = EmailPasswordRecipe.getInstanceOrThrowError(); @@ -989,7 +983,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); let emailpassword = EmailPasswordRecipe.getInstanceOrThrowError(); @@ -1043,7 +1037,7 @@ describe(`signinFeature: ${printPath("[test/emailpassword/signinFeature.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); diff --git a/test/emailpassword/signoutFeature.test.js b/test/emailpassword/signoutFeature.test.js index cfcf49355..b1c3918b7 100644 --- a/test/emailpassword/signoutFeature.test.js +++ b/test/emailpassword/signoutFeature.test.js @@ -69,9 +69,7 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -91,9 +89,7 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -105,18 +101,14 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j }) ) ); - assert(response2.antiCsrf === undefined); - assert(response2.accessToken === ""); - assert(response2.refreshToken === ""); - assert(response2.idRefreshTokenFromHeader === "remove"); - assert(response2.idRefreshTokenFromCookie === ""); - assert(response2.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(response2.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(response2.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(response2.accessTokenDomain === undefined); - assert(response2.refreshTokenDomain === undefined); - assert(response2.idRefreshTokenDomain === undefined); - assert(response2.frontToken === undefined); + assert.strictEqual(response2.antiCsrf, undefined); + assert.strictEqual(response2.accessToken, ""); + assert.strictEqual(response2.refreshToken, ""); + assert.strictEqual(response2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(response2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(response2.accessTokenDomain, undefined); + assert.strictEqual(response2.refreshTokenDomain, undefined); + assert.strictEqual(response2.frontToken, "remove"); }); // Disable default route and test that that API returns 404 @@ -143,7 +135,7 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -181,7 +173,7 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -224,9 +216,7 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -247,7 +237,8 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j let signOutResponse = await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -257,18 +248,15 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j } }) ); - assert(signOutResponse.status === 401); - assert(JSON.parse(signOutResponse.text).message === "try refresh token"); + assert.strictEqual(signOutResponse.status, 401); + assert.strictEqual(signOutResponse.body.message, "try refresh token"); let refreshedResponse = extractInfoFromResponse( await new Promise((resolve) => request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -285,12 +273,8 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + - refreshedResponse.accessToken + - ";sIdRefreshToken=" + - refreshedResponse.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + refreshedResponse.accessToken]) .set("anti-csrf", refreshedResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -306,13 +290,9 @@ describe(`signoutFeature: ${printPath("[test/emailpassword/signoutFeature.test.j assert(signOutResponse.antiCsrf === undefined); assert(signOutResponse.accessToken === ""); assert(signOutResponse.refreshToken === ""); - assert(signOutResponse.idRefreshTokenFromHeader === "remove"); - assert(signOutResponse.idRefreshTokenFromCookie === ""); assert(signOutResponse.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(signOutResponse.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(signOutResponse.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(signOutResponse.accessTokenDomain === undefined); assert(signOutResponse.refreshTokenDomain === undefined); - assert(signOutResponse.idRefreshTokenDomain === undefined); }); }); diff --git a/test/emailpassword/signupFeature.test.js b/test/emailpassword/signupFeature.test.js index 1482aded6..37fdf3071 100644 --- a/test/emailpassword/signupFeature.test.js +++ b/test/emailpassword/signupFeature.test.js @@ -76,7 +76,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -108,7 +108,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -138,7 +138,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -177,7 +177,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -219,7 +219,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -256,7 +256,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -292,7 +292,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -331,7 +331,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -372,7 +372,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -420,9 +420,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] }, recipeList: [ EmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); const app = express(); @@ -439,15 +437,11 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] assert(cookies.accessToken !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.antiCsrf !== undefined); - assert(cookies.idRefreshTokenFromHeader !== undefined); - assert(cookies.idRefreshTokenFromCookie !== undefined); assert(cookies.accessTokenExpiry !== undefined); assert(cookies.refreshTokenExpiry !== undefined); - assert(cookies.idRefreshTokenExpiry !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); assert(cookies.frontToken !== undefined); }); @@ -482,7 +476,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -563,7 +557,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -642,7 +636,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -716,7 +710,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -753,7 +747,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -818,7 +812,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -884,7 +878,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -939,7 +933,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -982,7 +976,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -1039,7 +1033,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -1105,7 +1099,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -1188,7 +1182,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); @@ -1247,7 +1241,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -1297,7 +1291,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -1347,7 +1341,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -1422,7 +1416,7 @@ describe(`signupFeature: ${printPath("[test/emailpassword/signupFeature.test.js] }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); diff --git a/test/emailpassword/updateEmailPass.test.js b/test/emailpassword/updateEmailPass.test.js index 4fbc3a366..227da56c4 100644 --- a/test/emailpassword/updateEmailPass.test.js +++ b/test/emailpassword/updateEmailPass.test.js @@ -46,7 +46,7 @@ describe(`updateEmailPassTest: ${printPath("[test/emailpassword/updateEmailPass. appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); let apiVersion = await Querier.getNewInstanceOrThrowError(undefined).getAPIVersion(); diff --git a/test/emailpassword/users.test.js b/test/emailpassword/users.test.js index 2f3fc001d..886c2060e 100644 --- a/test/emailpassword/users.test.js +++ b/test/emailpassword/users.test.js @@ -46,7 +46,7 @@ describe(`usersTest: ${printPath("[test/emailpassword/users.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const express = require("express"); @@ -110,7 +110,7 @@ describe(`usersTest: ${printPath("[test/emailpassword/users.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const express = require("express"); @@ -174,7 +174,7 @@ describe(`usersTest: ${printPath("[test/emailpassword/users.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailPassword.init(), Session.init()], + recipeList: [EmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); let userCount = await getUserCount(); diff --git a/test/framework/awsLambda.test.js b/test/framework/awsLambda.test.js index 3138292f1..20bf1524b 100644 --- a/test/framework/awsLambda.test.js +++ b/test/framework/awsLambda.test.js @@ -56,15 +56,11 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct websiteDomain: "supertokens.io", apiGatewayPath: "/dev", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let createSession = async (awsEvent, _) => { - await Session.createNewSession(awsEvent, "userId", {}, {}); + await Session.createNewSession(awsEvent, awsEvent, "userId", {}, {}); return { body: JSON.stringify(""), statusCode: 200, @@ -101,8 +97,6 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let verifySessionEvent = mockLambdaProxyEvent("/session/verify", "POST", null, null, proxy); @@ -113,7 +107,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct "/session/verify", "POST", { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, null, proxy @@ -125,7 +119,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct "/session/verify", "POST", { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, null, @@ -138,7 +132,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct "/session/verify", "POST", { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, null, proxy @@ -156,7 +150,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct "/auth/session/refresh", "POST", { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, null, @@ -172,15 +166,13 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); verifySessionEvent = mockLambdaProxyEvent( "/session/verify", "POST", { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, null, @@ -199,7 +191,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct "/session/revoke", "POST", { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, null, @@ -214,11 +206,8 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct let sessionRevokedResponseExtracted = extractInfoFromResponse(result); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); //check basic usage of session @@ -235,15 +224,11 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct websiteDomain: "supertokens.io", apiGatewayPath: "/dev", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let createSession = async (awsEvent, _) => { - await Session.createNewSession(awsEvent, "userId", {}, {}); + await Session.createNewSession(awsEvent, awsEvent, "userId", {}, {}); return { body: JSON.stringify(""), statusCode: 200, @@ -280,8 +265,6 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let verifySessionEvent = mockLambdaProxyEventV2("/session/verify", "POST", null, null, proxy); @@ -290,7 +273,6 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct verifySessionEvent = mockLambdaProxyEventV2("/session/verify", "POST", null, null, proxy, [ `sAccessToken=${res.accessToken}`, - `sIdRefreshToken=${res.idRefreshTokenFromCookie}`, ]); result = await verifySession(verifyLambdaSession)(verifySessionEvent, undefined); assert.deepStrictEqual(JSON.parse(result.body), { message: "try refresh token" }); @@ -303,14 +285,13 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct }, null, proxy, - [`sAccessToken=${res.accessToken}`, `sIdRefreshToken=${res.idRefreshTokenFromCookie}`] + [`sAccessToken=${res.accessToken}`] ); result = await verifySession(verifyLambdaSession)(verifySessionEvent, undefined); assert.deepStrictEqual(JSON.parse(result.body), { user: "userId" }); verifySessionEvent = mockLambdaProxyEventV2("/session/verify", "POST", null, null, proxy, [ `sAccessToken=${res.accessToken}`, - `sIdRefreshToken=${res.idRefreshTokenFromCookie}`, ]); result = await verifySession(verifyLambdaSession, { antiCsrfCheck: false, @@ -329,7 +310,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct }, null, proxy, - [`sRefreshToken=${res.refreshToken}`, `sIdRefreshToken=${res.idRefreshTokenFromCookie}`] + [`sRefreshToken=${res.refreshToken}`] ); result = await middleware()(refreshSessionEvent, undefined); result.headers = { @@ -341,8 +322,6 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); verifySessionEvent = mockLambdaProxyEventV2( @@ -353,7 +332,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct }, null, proxy, - [`sAccessToken=${res2.accessToken}`, `sIdRefreshToken=${res2.idRefreshTokenFromCookie}`] + [`sAccessToken=${res2.accessToken}`] ); result = await verifySession(verifyLambdaSession)(verifySessionEvent, undefined); assert.deepStrictEqual(JSON.parse(result.body), { user: "userId" }); @@ -372,7 +351,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct }, null, proxy, - [`sAccessToken=${res3.accessToken}`, `sIdRefreshToken=${res2.idRefreshTokenFromCookie}`] + [`sAccessToken=${res3.accessToken}`] ); result = await verifySession(revokeSession)(revokeSessionEvent, undefined); result.headers = { @@ -383,11 +362,8 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct let sessionRevokedResponseExtracted = extractInfoFromResponse(result); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("sending custom response awslambda", async function () { @@ -420,7 +396,7 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -432,4 +408,174 @@ describe(`AWS Lambda: ${printPath("[test/framework/awsLambda.test.js]")}`, funct assert(result.statusCode === 203); assert(JSON.parse(result.body).custom); }); + + for (const tokenTransferMethod of ["header", "cookie"]) { + describe(`Throwing UNATHORISED w/ auth-mode=${tokenTransferMethod}`, () => { + it("should clear all response cookies during refresh", async () => { + await startST(); + SuperTokens.init({ + framework: "awsLambda", + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "http://api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "http://supertokens.io", + }, + recipeList: [ + Session.init({ + antiCsrf: "VIA_TOKEN", + override: { + apis: (oI) => { + return { + ...oI, + refreshPOST: async function (input) { + await oI.refreshPOST(input); + throw new Session.Error({ + message: "unauthorised", + type: Session.Error.UNAUTHORISED, + clearTokens: true, + }); + }, + }; + }, + }, + }), + ], + }); + + let createSession = async (awsEvent, _) => { + await Session.createNewSession(awsEvent, awsEvent, "userId", {}, {}); + return { + body: JSON.stringify(""), + statusCode: 200, + }; + }; + + let proxy = "/dev"; + let createAccountEvent = mockLambdaProxyEventV2( + "/create", + "POST", + { "st-auth-mode": tokenTransferMethod }, + null, + proxy + ); + let result = await middleware(createSession)(createAccountEvent, undefined); + result.headers = { + ...result.headers, + "set-cookie": result.cookies, + }; + + let res = extractInfoFromResponse(result); + + assert.notStrictEqual(res.accessTokenFromAny, undefined); + assert.notStrictEqual(res.refreshTokenFromAny, undefined); + + const refreshHeaders = + tokenTransferMethod === "header" + ? { authorization: `Bearer ${res.refreshTokenFromAny}` } + : { + cookie: `sRefreshToken=${encodeURIComponent( + res.refreshTokenFromAny + )}; sIdRefreshToken=asdf`, + }; + if (res.antiCsrf) { + refreshHeaders.antiCsrf = res.antiCsrf; + } + + refreshSessionEvent = mockLambdaProxyEventV2( + "/auth/session/refresh", + "POST", + refreshHeaders, + null, + proxy, + null + ); + result = await middleware()(refreshSessionEvent, undefined); + result.headers = { + ...result.headers, + "set-cookie": result.cookies, + }; + + let res2 = extractInfoFromResponse(result); + + assert.strictEqual(res2.status, 401); + if (tokenTransferMethod === "cookie") { + assert.strictEqual(res2.accessToken, ""); + assert.strictEqual(res2.refreshToken, ""); + assert.strictEqual(res2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res2.accessTokenDomain, undefined); + assert.strictEqual(res2.refreshTokenDomain, undefined); + } else { + assert.strictEqual(res2.accessTokenFromHeader, ""); + assert.strictEqual(res2.refreshTokenFromHeader, ""); + } + assert.strictEqual(res2.frontToken, "remove"); + assert.strictEqual(res2.antiCsrf, undefined); + }); + + it("test revoking a session after createNewSession with throwing unauthorised error", async function () { + await startST(); + SuperTokens.init({ + framework: "awsLambda", + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "http://api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "http://supertokens.io", + apiBasePath: "/", + }, + recipeList: [ + Session.init({ + antiCsrf: "VIA_TOKEN", + }), + ], + }); + + let createSession = async (awsEvent, _) => { + await Session.createNewSession(awsEvent, awsEvent, "userId", {}, {}); + throw new Session.Error({ + message: "unauthorised", + type: Session.Error.UNAUTHORISED, + clearTokens: true, + }); + }; + + let proxy = "/dev"; + let createAccountEvent = mockLambdaProxyEventV2( + "/create", + "POST", + { "st-auth-mode": tokenTransferMethod }, + null, + proxy + ); + let result = await middleware(createSession)(createAccountEvent, undefined); + result.headers = { + ...result.headers, + "set-cookie": result.cookies, + }; + + let res = extractInfoFromResponse(result); + + assert.strictEqual(res.status, 401); + if (tokenTransferMethod === "cookie") { + assert.strictEqual(res.accessToken, ""); + assert.strictEqual(res.refreshToken, ""); + assert.strictEqual(res.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res.accessTokenDomain, undefined); + assert.strictEqual(res.refreshTokenDomain, undefined); + } else { + assert.strictEqual(res.accessTokenFromHeader, ""); + assert.strictEqual(res.refreshTokenFromHeader, ""); + } + assert.strictEqual(res.frontToken, "remove"); + assert.strictEqual(res.antiCsrf, undefined); + }); + }); + } }); diff --git a/test/framework/crossFramework.testgen.js b/test/framework/crossFramework.testgen.js new file mode 100644 index 000000000..d7e98307b --- /dev/null +++ b/test/framework/crossFramework.testgen.js @@ -0,0 +1,406 @@ +const SuperTokens = require("../../"); +const { ProcessState } = require("../../lib/build/processState"); +const { setupST, startST, killAllST, cleanST } = require("../utils"); + +const express = require("express"); +const request = require("supertest"); +const { verifySession: expressVerifySession } = require("../../recipe/session/framework/express"); +const ExpressFramework = require("../../framework/express"); + +const Fastify = require("fastify"); +const FastifyFramework = require("../../framework/fastify"); +const { verifySession: fastifyVerifySession } = require("../../recipe/session/framework/fastify"); + +const HapiFramework = require("../../framework/hapi"); +const Hapi = require("@hapi/hapi"); +const { verifySession: hapiVerifySession } = require("../../recipe/session/framework/hapi"); + +const Koa = require("koa"); +const KoaFramework = require("../../framework/koa"); +const Router = require("@koa/router"); +const { verifySession: koaVerifySession } = require("../../recipe/session/framework/koa"); + +const loopbackRoutes = [ + { + path: "/create", + method: "post", + verifySession: false, + }, + { + path: "/create-throw", + method: "post", + verifySession: false, + }, + { + path: "/session/verify", + method: "post", + verifySession: true, + }, + { + path: "/session/verify/optionalCSRF", + method: "post", + verifySession: true, + verifySessionOpts: { antiCsrfCheck: false }, + }, + { + path: "/session/revoke", + method: "post", + verifySession: true, + }, +]; + +module.exports.addCrossFrameworkTests = (getTestCases, { allTokenTransferMethods } = {}) => { + if (allTokenTransferMethods) { + addTestCases("header"); + addTestCases("cookie"); + } else { + addTestCases("cookie"); + } + + function addTestCases(tokenTransferMethod) { + describe(`express w/ auth-mode=${tokenTransferMethod}`, () => { + let app; + beforeEach(async () => { + await killAllST(); + await setupST(); + ProcessState.getInstance().reset(); + app = undefined; + }); + + after(async function () { + await killAllST(); + await cleanST(); + }); + + getTestCases( + async ({ stConfig, routes }) => { + await startST(); + + SuperTokens.init(stConfig); + + app = express(); + + app.use(ExpressFramework.middleware()); + + for (const route of routes) { + const handlers = [ + (req, res, next) => + route.handler( + ExpressFramework.wrapRequest(req), + ExpressFramework.wrapResponse(res), + next + ), + ]; + if (route.verifySession) { + handlers.unshift(expressVerifySession(route.verifySessionOpts)); + } + if (route.method === "get") { + app.get(route.path, ...handlers); + } else if (route.method === "post") { + app.post(route.path, ...handlers); + } else { + throw new Error("UNKNOWN METHOD"); + } + } + + app.use(ExpressFramework.errorHandler()); + }, + ({ method, path, headers }) => { + const req = method === "post" ? request(app).post(path) : request(app).get(path); + for (const key of Object.keys(headers)) { + req.set(key, headers[key]); + } + return new Promise((resolve) => + req.end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ); + }, + tokenTransferMethod + ); + }); + + describe(`fastify w/ auth-mode=${tokenTransferMethod}`, () => { + let server; + beforeEach(async () => { + await killAllST(); + await setupST(); + ProcessState.getInstance().reset(); + server = undefined; + }); + + afterEach(async function () { + try { + await server.close(); + } catch (err) {} + }); + + after(async function () { + await killAllST(); + await cleanST(); + }); + + getTestCases( + async ({ stConfig, routes }) => { + await startST(); + + SuperTokens.init({ + framework: "fastify", + ...stConfig, + }); + + server = Fastify(); + + await server.register(FastifyFramework.plugin); + server.setErrorHandler(FastifyFramework.errorHandler()); + for (const route of routes) { + const handlers = [ + (req, res) => + route.handler( + FastifyFramework.wrapRequest(req), + FastifyFramework.wrapResponse(res), + (err) => { + throw err; + } + ), + ]; + if (route.verifySession) { + handlers.unshift(fastifyVerifySession(route.verifySessionOpts)); + } + if (route.method === "get") { + server.get(route.path, ...handlers); + } else if (route.method === "post") { + server.post(route.path, ...handlers); + } else { + throw new Error("UNKNOWN METHOD"); + } + } + }, + ({ method, path, headers }) => { + return server.inject({ + method, + url: path, + headers, + }); + }, + tokenTransferMethod + ); + }); + + describe(`hapi w/ auth-mode=${tokenTransferMethod}`, () => { + let server; + beforeEach(async () => { + await killAllST(); + await setupST(); + ProcessState.getInstance().reset(); + server = undefined; + }); + + afterEach(async function () { + try { + await server.close(); + } catch (err) {} + }); + + after(async function () { + await killAllST(); + await cleanST(); + }); + + getTestCases( + async ({ stConfig, routes }) => { + await startST(); + + SuperTokens.init({ + framework: "hapi", + ...stConfig, + }); + + server = Hapi.server({ + port: 3000, + host: "localhost", + }); + + for (const route of routes) { + server.route({ + method: route.method, + path: route.path, + handler: async (req, res) => { + await route.handler( + HapiFramework.wrapRequest(req), + HapiFramework.wrapResponse(res), + (err) => { + throw err; + } + ); + return ""; + }, + + options: { + pre: route.verifySession ? [{ method: hapiVerifySession() }] : [], + }, + }); + } + await server.register(HapiFramework.plugin); + + await server.initialize(); + }, + ({ method, path, headers }) => { + return server.inject({ + method, + url: path, + headers, + }); + }, + tokenTransferMethod + ); + }); + + describe(`koa w/ auth-mode=${tokenTransferMethod}`, () => { + let app, server; + beforeEach(async () => { + await killAllST(); + await setupST(); + ProcessState.getInstance().reset(); + app = undefined; + server = undefined; + }); + + afterEach(async function () { + try { + await server.close(); + } catch (err) {} + }); + + after(async function () { + await killAllST(); + await cleanST(); + }); + + getTestCases( + async ({ stConfig, routes }) => { + await startST(); + + SuperTokens.init({ + framework: "koa", + ...stConfig, + }); + + app = new Koa(); + const router = new Router(); + app.use(KoaFramework.middleware()); + + for (const route of routes) { + const handlers = [ + (ctx) => + route.handler(KoaFramework.wrapRequest(ctx), KoaFramework.wrapResponse(ctx), (err) => { + throw err; + }), + ]; + if (route.verifySession) { + handlers.unshift(koaVerifySession(route.verifySessionOpts)); + } + if (route.method === "get") { + router.get(route.path, ...handlers); + } else if (route.method === "post") { + router.post(route.path, ...handlers); + } else { + throw new Error("UNKNOWN METHOD"); + } + } + + app.use(router.routes()); + server = app.listen(9999); + }, + ({ method, path, headers }) => { + const req = method === "post" ? request(server).post(path) : request(server).get(path); + for (const key of Object.keys(headers)) { + req.set(key, headers[key]); + } + return new Promise((resolve) => + req.end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ); + }, + tokenTransferMethod + ); + }); + + describe(`loopback w/ auth-mode=${tokenTransferMethod}`, () => { + let app; + beforeEach(async () => { + await killAllST(); + await setupST(); + ProcessState.getInstance().reset(); + app = require("./loopback-server/index.js"); + }); + + afterEach(async function () { + try { + await app.stop(); + } catch (err) {} + }); + + after(async function () { + await killAllST(); + await cleanST(); + }); + + getTestCases( + async ({ stConfig, routes }) => { + await startST(); + + SuperTokens.init({ + framework: "loopback", + ...stConfig, + }); + + for (const route of routes) { + const matchingRoute = loopbackRoutes.find((r) => r.path === route.path); + if ( + matchingRoute === undefined || + matchingRoute.method !== route.method || + !!matchingRoute.verifySession !== !!route.verifySession || + JSON.stringify(matchingRoute.verifySessionOpts) !== + JSON.stringify(matchingRoute.verifySessionOpts) + ) { + throw new Error( + "No matching route in loopback-server. Please implement it or skip this test" + ); + } + } + + await app.start(); + }, + ({ method, path, headers }) => { + const req = + method === "post" + ? request("http://localhost:9876").post(path) + : request("http://localhost:9876").get(path); + for (const key of Object.keys(headers)) { + req.set(key, headers[key]); + } + return new Promise((resolve) => + req.end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ); + }, + tokenTransferMethod + ); + }); + } +}; diff --git a/test/framework/crossframework/unauthorised.test.js b/test/framework/crossframework/unauthorised.test.js new file mode 100644 index 000000000..7f1c53112 --- /dev/null +++ b/test/framework/crossframework/unauthorised.test.js @@ -0,0 +1,168 @@ +const { addCrossFrameworkTests } = require("../crossFramework.testgen"); +let Session = require("../../../recipe/session"); +const { extractInfoFromResponse } = require("../../utils"); +let assert = require("assert"); + +addCrossFrameworkTests( + (setup, callServer, tokenTransferMethod) => { + describe("Throwing UNATHORISED", () => { + it("should clear all response cookies during refresh", async () => { + await setup({ + stConfig: { + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "http://api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "http://supertokens.io", + apiBasePath: "/", + }, + recipeList: [ + Session.init({ + antiCsrf: "VIA_TOKEN", + override: { + apis: (oI) => { + return { + ...oI, + refreshPOST: async function (input) { + await oI.refreshPOST(input); + throw new Session.Error({ + message: "unauthorised", + type: Session.Error.UNAUTHORISED, + clearTokens: true, + }); + }, + }; + }, + }, + }), + ], + }, + routes: [ + { + path: "/create", + method: "post", + handler: async (req, res, next) => { + await Session.createNewSession(req, res, "id1", {}, {}); + res.setStatusCode(200); + res.sendJSONResponse(""); + return res.response; + }, + }, + ], + }); + + let res = extractInfoFromResponse( + await callServer({ + method: "post", + path: "/create", + headers: { + "st-auth-mode": tokenTransferMethod, + }, + }) + ); + + assert.notStrictEqual(res.accessTokenFromAny, undefined); + assert.notStrictEqual(res.refreshTokenFromAny, undefined); + + const refreshHeaders = + tokenTransferMethod === "header" + ? { authorization: `Bearer ${res.refreshTokenFromAny}` } + : { + cookie: `sRefreshToken=${encodeURIComponent( + res.refreshTokenFromAny + )}; sIdRefreshToken=asdf`, + }; + if (res.antiCsrf) { + refreshHeaders.antiCsrf = res.antiCsrf; + } + + let resp = await callServer({ + method: "post", + path: "/session/refresh", + headers: refreshHeaders, + }); + + let res2 = extractInfoFromResponse(resp); + + assert.strictEqual(res2.status, 401); + if (tokenTransferMethod === "cookie") { + assert.strictEqual(res2.accessToken, ""); + assert.strictEqual(res2.refreshToken, ""); + assert.strictEqual(res2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res2.accessTokenDomain, undefined); + assert.strictEqual(res2.refreshTokenDomain, undefined); + } else { + assert.strictEqual(res2.accessTokenFromHeader, ""); + assert.strictEqual(res2.refreshTokenFromHeader, ""); + } + assert.strictEqual(res2.frontToken, "remove"); + assert.strictEqual(res2.antiCsrf, undefined); + }); + + it("test revoking a session after createNewSession with throwing unauthorised error", async function () { + await setup({ + stConfig: { + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "http://api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "http://supertokens.io", + apiBasePath: "/", + }, + recipeList: [ + Session.init({ + antiCsrf: "VIA_TOKEN", + }), + ], + }, + routes: [ + { + path: "/create-throw", + method: "post", + handler: async (req, res, next) => { + await Session.createNewSession(req, res, "id1", {}, {}); + next( + new Session.Error({ + message: "unauthorised", + type: Session.Error.UNAUTHORISED, + }) + ); + }, + }, + ], + }); + + let res = extractInfoFromResponse( + await callServer({ + method: "post", + path: "/create-throw", + headers: { + "st-auth-mode": tokenTransferMethod, + }, + }) + ); + + assert.strictEqual(res.status, 401); + if (tokenTransferMethod === "cookie") { + assert.strictEqual(res.accessToken, ""); + assert.strictEqual(res.refreshToken, ""); + assert.strictEqual(res.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res.accessTokenDomain, undefined); + assert.strictEqual(res.refreshTokenDomain, undefined); + } else { + assert.strictEqual(res.accessTokenFromHeader, ""); + assert.strictEqual(res.refreshTokenFromHeader, ""); + } + assert.strictEqual(res.frontToken, "remove"); + assert.strictEqual(res.antiCsrf, undefined); + }); + }); + }, + { allTokenTransferMethods: true } +); diff --git a/test/framework/fastify.test.js b/test/framework/fastify.test.js index 21372e342..df6151cb9 100644 --- a/test/framework/fastify.test.js +++ b/test/framework/fastify.test.js @@ -41,7 +41,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( afterEach(async function () { try { - await this.sever.close(); + await this.server.close(); } catch (err) {} }); after(async function () { @@ -64,6 +64,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -78,7 +79,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); @@ -95,7 +96,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -117,6 +118,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -131,7 +133,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); @@ -172,6 +174,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( }); }, }, + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { apis: (oI) => { @@ -188,12 +191,12 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( this.server.setErrorHandler(FastifyFramework.errorHandler()); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); this.server.post("/session/verify", async (req, res) => { - await Session.getSession(req, res, true); + await Session.getSession(req, res); return res.send("").code(200); }); @@ -216,7 +219,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) @@ -226,7 +229,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -235,7 +238,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -245,14 +248,10 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( assert.strictEqual(cookies.antiCsrf, undefined); assert.strictEqual(cookies.accessToken, ""); assert.strictEqual(cookies.refreshToken, ""); - assert.strictEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(cookies.idRefreshTokenFromCookie, ""); assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); }); // - check for token theft detection @@ -268,22 +267,18 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.setErrorHandler(FastifyFramework.errorHandler()); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); this.server.post("/session/verify", async (req, res) => { - await Session.getSession(req, res, true); + await Session.getSession(req, res); return res.send("").code(200); }); @@ -301,7 +296,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) @@ -311,7 +306,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -320,7 +315,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -331,10 +326,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( assert.strictEqual(cookies.antiCsrf, undefined); assert.strictEqual(cookies.accessToken, ""); assert.strictEqual(cookies.refreshToken, ""); - assert.strictEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(cookies.idRefreshTokenFromCookie, ""); assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); }); @@ -351,20 +343,16 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); this.server.post("/session/verify", async (req, res) => { - await Session.getSession(req, res, true); + await Session.getSession(req, res); return res.send("").code(200); }); @@ -382,7 +370,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) @@ -392,7 +380,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -401,7 +389,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -412,10 +400,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( assert.strictEqual(cookies.antiCsrf, undefined); assert.strictEqual(cookies.accessToken, ""); assert.strictEqual(cookies.refreshToken, ""); - assert.strictEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(cookies.idRefreshTokenFromCookie, ""); assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); }); @@ -432,11 +417,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post( @@ -473,25 +454,21 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); this.server.post("/session/verify", async (req, res) => { - await Session.getSession(req, res, true); + await Session.getSession(req, res); return res.send("").code(200); }); this.server.post("/session/revoke", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.revokeSession(); return res.send("").code(200); }); @@ -507,15 +484,13 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await this.server.inject({ method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -528,7 +503,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) @@ -536,8 +511,6 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( @@ -545,7 +518,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }) @@ -560,7 +533,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -571,18 +544,15 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/revoke", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test signout API works", async function () { @@ -597,15 +567,11 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); @@ -622,7 +588,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/signout", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -630,11 +596,8 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); // check basic usage of session @@ -651,25 +614,21 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( websiteDomain: "supertokens.io", apiBasePath: "/", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); this.server.post("/session/verify", async (req, res) => { - await Session.getSession(req, res, true); + await Session.getSession(req, res); return res.send("").code(200); }); this.server.post("/session/revoke", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.revokeSession(); return res.send("").code(200); }); @@ -685,15 +644,13 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await this.server.inject({ method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -706,15 +663,13 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) ); assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( @@ -722,7 +677,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }) @@ -737,7 +692,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -748,18 +703,15 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/revoke", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); // check session verify for with / without anti-csrf present @@ -775,20 +727,16 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); return res.send("").code(200); }); this.server.post("/session/verify", async (req, res) => { - let sessionResponse = await Session.getSession(req, res, true); + let sessionResponse = await Session.getSession(req, res); return res.send({ userId: sessionResponse.userId }).code(200); }); @@ -810,7 +758,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -820,7 +768,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verifyAntiCsrfFalse", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -840,17 +788,13 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); await this.server.register(FastifyFramework.plugin); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); return res.send("").code(200); }); @@ -882,7 +826,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verifyAntiCsrfFalse", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, }); assert.strictEqual(response2.json().userId, "id1"); @@ -891,7 +835,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, }); assert.strictEqual(response.json().success, true); @@ -910,29 +854,25 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); this.server.post("/usercreate", async (req, res) => { - await Session.createNewSession(res, "someUniqueUserId", {}, {}); + await Session.createNewSession(req, res, "someUniqueUserId", {}, {}); return res.send("").code(200); }); this.server.post("/session/revoke", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.revokeSession(); return res.send("").code(200); }); this.server.post("/session/revokeUserid", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await Session.revokeAllSessionsForUser(session.getUserId()); return res.send("").code(200); }); @@ -954,18 +894,15 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/revoke", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); await this.server.inject({ method: "post", @@ -982,7 +919,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/session/revokeUserid", headers: { - Cookie: `sAccessToken=${userCreateResponse.accessToken}; sIdRefreshToken=${userCreateResponse.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${userCreateResponse.accessToken}`, "anti-csrf": userCreateResponse.antiCsrf, }, }); @@ -1006,15 +943,11 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.send("").code(200); }); @@ -1071,7 +1004,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/updateSessionData", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1081,7 +1014,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/getSessionData", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1094,7 +1027,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/updateSessionData2", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1104,7 +1037,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/getSessionData", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1117,7 +1050,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/updateSessionDataInvalidSessionHandle", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1137,15 +1070,11 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "user1", {}, {}); + await Session.createNewSession(req, res, "user1", {}, {}); return res.send("").code(200); }); @@ -1212,7 +1141,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/updateAccessTokenPayload", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }) @@ -1227,7 +1156,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/getAccessTokenPayload", headers: { - Cookie: `sAccessToken=${updatedResponse.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${updatedResponse.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1240,7 +1169,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${response.refreshToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${response.refreshToken}`, "anti-csrf": response.antiCsrf, }, }) @@ -1256,7 +1185,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/updateAccessTokenPayload2", headers: { - Cookie: `sAccessToken=${response2.accessToken}; sIdRefreshToken=${response2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response2.accessToken}`, "anti-csrf": response2.antiCsrf, }, }) @@ -1271,7 +1200,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/getAccessTokenPayload", headers: { - Cookie: `sAccessToken=${updatedResponse2.accessToken}; sIdRefreshToken=${response2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${updatedResponse2.accessToken}`, "anti-csrf": response2.antiCsrf, }, }); @@ -1283,7 +1212,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( method: "post", url: "/updateAccessTokenPayloadInvalidSessionHandle", headers: { - Cookie: `sAccessToken=${updatedResponse2.accessToken}; sIdRefreshToken=${response2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${updatedResponse2.accessToken}`, "anti-csrf": response2.antiCsrf, }, }); @@ -1319,7 +1248,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -1348,7 +1277,11 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailVerification.init({ mode: "OPTIONAL" }), EmailPassword.init(), Session.init()], + recipeList: [ + EmailVerification.init({ mode: "OPTIONAL" }), + EmailPassword.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), + ], }); await this.server.register(FastifyFramework.plugin); @@ -1379,7 +1312,7 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( url: "/auth/user/email/verify/token", payload: {}, headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "Content-Type": "application/json", }, }); @@ -1399,17 +1332,13 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); await this.server.register(FastifyFramework.plugin); this.server.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); return res.send("").code(200); }); @@ -1421,6 +1350,5 @@ describe(`Fastify: ${printPath("[test/framework/fastify.test.js]")}`, function ( ); assert.strictEqual(res.accessToken, 1); assert.strictEqual(res.refreshToken, 1); - assert.strictEqual(res.idRefreshToken, 1); }); }); diff --git a/test/framework/hapi.test.js b/test/framework/hapi.test.js index 6e0849d7a..5dad9e56e 100644 --- a/test/framework/hapi.test.js +++ b/test/framework/hapi.test.js @@ -58,6 +58,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -75,7 +76,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", path: "/create", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -95,7 +96,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -117,6 +118,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -134,7 +136,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -178,6 +180,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { }); }, }, + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { apis: (oI) => { @@ -195,7 +198,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -234,7 +237,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) @@ -244,7 +247,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -253,7 +256,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -263,14 +266,10 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { assert.strictEqual(cookies.antiCsrf, undefined); assert.strictEqual(cookies.accessToken, ""); assert.strictEqual(cookies.refreshToken, ""); - assert.strictEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(cookies.idRefreshTokenFromCookie, ""); assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); }); //- check for token theft detection @@ -286,18 +285,14 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -327,7 +322,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) @@ -337,7 +332,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -346,7 +341,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -358,10 +353,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { assert.strictEqual(cookies.antiCsrf, undefined); assert.strictEqual(cookies.accessToken, ""); assert.strictEqual(cookies.refreshToken, ""); - assert.strictEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(cookies.idRefreshTokenFromCookie, ""); assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); }); @@ -378,18 +370,14 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -426,15 +414,13 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await this.server.inject({ method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -447,7 +433,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) @@ -455,8 +441,6 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( @@ -464,7 +448,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }) @@ -479,7 +463,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -490,18 +474,15 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/revoke", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test signout API works", async function () { @@ -516,17 +497,13 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -546,7 +523,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/signout", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -554,11 +531,8 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); //check basic usage of session @@ -575,18 +549,14 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { websiteDomain: "supertokens.io", apiBasePath: "/", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -623,15 +593,13 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await this.server.inject({ method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -644,15 +612,13 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/refresh", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }) ); assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( @@ -660,7 +626,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }) @@ -675,7 +641,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -686,18 +652,15 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/revoke", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res3.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); // check session verify for with / without anti-csrf present @@ -713,18 +676,14 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); return res.response("").code(200); }, }); @@ -762,7 +721,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -772,7 +731,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verifyAntiCsrfFalse", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -792,11 +751,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); await this.server.register(HapiFramework.plugin); @@ -805,7 +760,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); return res.response("").code(200); }, }); @@ -849,7 +804,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verifyAntiCsrfFalse", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, }); assert.strictEqual(response2.result.userId, "id1"); @@ -858,7 +813,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/verify", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, }); assert.strictEqual(response.result.success, true); @@ -877,17 +832,13 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -895,7 +846,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { path: "/usercreate", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "someUniqueUserId", {}, {}); + await Session.createNewSession(req, res, "someUniqueUserId", {}, {}); return res.response("").code(200); }, }); @@ -942,18 +893,15 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/revoke", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); await this.server.inject({ method: "post", @@ -970,7 +918,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/session/revokeUserid", headers: { - Cookie: `sAccessToken=${userCreateResponse.accessToken}; sIdRefreshToken=${userCreateResponse.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${userCreateResponse.accessToken}`, "anti-csrf": userCreateResponse.antiCsrf, }, }); @@ -994,18 +942,14 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); return res.response("").code(200); }, }); @@ -1072,7 +1016,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/updateSessionData", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1082,7 +1026,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/getSessionData", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1095,7 +1039,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/updateSessionData2", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1105,7 +1049,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/getSessionData", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1118,7 +1062,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/updateSessionDataInvalidSessionHandle", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1138,18 +1082,14 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); this.server.route({ path: "/create", method: "post", handler: async (req, res) => { - await Session.createNewSession(res, "user1", {}, {}); + await Session.createNewSession(req, res, "user1", {}, {}); return res.response("").code(200); }, }); @@ -1232,7 +1172,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/updateAccessTokenPayload", headers: { - Cookie: `sAccessToken=${response.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response.accessToken}`, "anti-csrf": response.antiCsrf, }, }) @@ -1247,7 +1187,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/getAccessTokenPayload", headers: { - Cookie: `sAccessToken=${updatedResponse.accessToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${updatedResponse.accessToken}`, "anti-csrf": response.antiCsrf, }, }); @@ -1260,7 +1200,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/auth/session/refresh", headers: { - Cookie: `sRefreshToken=${response.refreshToken}; sIdRefreshToken=${response.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${response.refreshToken}`, "anti-csrf": response.antiCsrf, }, }) @@ -1276,7 +1216,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/updateAccessTokenPayload2", headers: { - Cookie: `sAccessToken=${response2.accessToken}; sIdRefreshToken=${response2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${response2.accessToken}`, "anti-csrf": response2.antiCsrf, }, }) @@ -1291,7 +1231,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/getAccessTokenPayload", headers: { - Cookie: `sAccessToken=${updatedResponse2.accessToken}; sIdRefreshToken=${response2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${updatedResponse2.accessToken}`, "anti-csrf": response2.antiCsrf, }, }); @@ -1303,7 +1243,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { method: "post", url: "/updateAccessTokenPayloadInvalidSessionHandle", headers: { - Cookie: `sAccessToken=${updatedResponse2.accessToken}; sIdRefreshToken=${response2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${updatedResponse2.accessToken}`, "anti-csrf": response2.antiCsrf, }, }); @@ -1339,7 +1279,7 @@ describe(`Hapi: ${printPath("[test/framework/hapi.test.js]")}`, function () { }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/framework/koa.test.js b/test/framework/koa.test.js index d4cc9b4fb..7a6c85c6f 100644 --- a/test/framework/koa.test.js +++ b/test/framework/koa.test.js @@ -58,6 +58,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -76,7 +77,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); @@ -101,7 +102,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let res2 = await new Promise((resolve) => request(this.server) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -130,6 +131,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -148,7 +150,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); @@ -205,6 +207,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { }); }, }, + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { apis: (oI) => { @@ -222,7 +225,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { const router = new Router(); app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); @@ -258,10 +261,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -276,9 +276,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { resolve(); @@ -288,7 +286,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let res3 = await new Promise((resolve) => request(this.server) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -304,14 +302,10 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { assert.strictEqual(cookies.antiCsrf, undefined); assert.strictEqual(cookies.accessToken, ""); assert.strictEqual(cookies.refreshToken, ""); - assert.strictEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(cookies.idRefreshTokenFromCookie, ""); assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); }); //- check for token theft detection @@ -327,11 +321,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); @@ -339,7 +329,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { app.use(KoaFramework.middleware()); router.post("/create", async (ctx, _) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); @@ -369,10 +359,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -387,9 +374,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { resolve(); @@ -399,7 +384,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let res3 = await new Promise((resolve) => request(this.server) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -416,10 +401,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { assert.strictEqual(cookies.antiCsrf, undefined); assert.strictEqual(cookies.accessToken, ""); assert.strictEqual(cookies.refreshToken, ""); - assert.strictEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(cookies.idRefreshTokenFromCookie, ""); assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); }); @@ -436,11 +418,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); @@ -448,7 +426,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); @@ -486,14 +464,12 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -511,10 +487,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -528,17 +501,13 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -558,9 +527,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -576,9 +543,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponse = await new Promise((resolve) => request(this.server) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -592,11 +557,8 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test signout API works", async function () { @@ -611,18 +573,14 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); const router = new Router(); app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); @@ -647,7 +605,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponse = await new Promise((resolve) => request(this.server) .post("/auth/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -661,11 +619,8 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); //check basic usage of session @@ -683,11 +638,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { websiteDomain: "http://supertokens.io", apiBasePath: "/", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); @@ -695,7 +646,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); @@ -729,14 +680,12 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -754,10 +703,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -771,17 +717,13 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -801,9 +743,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -819,9 +759,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponse = await new Promise((resolve) => request(this.server) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -835,11 +773,8 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); //check session verify for with / without anti-csrf present @@ -855,18 +790,14 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); const router = new Router(); app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "id1", {}, {}); + await Session.createNewSession(ctx, ctx, "id1", {}, {}); ctx.body = ""; }); @@ -901,7 +832,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let res2 = await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -916,7 +847,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let res3 = await new Promise((resolve) => request(this.server) .post("/session/verifyAntiCsrfFalse") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -942,11 +873,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); @@ -954,7 +881,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { app.use(KoaFramework.middleware()); router.post("/create", async (ctx, next) => { - await Session.createNewSession(ctx, "id1", {}, {}); + await Session.createNewSession(ctx, ctx, "id1", {}, {}); ctx.body = ""; }); @@ -994,7 +921,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let response2 = await new Promise((resolve) => request(this.server) .post("/session/verifyAntiCsrfFalse") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1008,7 +935,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let response = await new Promise((resolve) => request(this.server) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1033,21 +960,17 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); const router = new Router(); app.use(KoaFramework.middleware()); router.post("/create", async (ctx, _) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); router.post("/usercreate", async (ctx, _) => { - await Session.createNewSession(ctx, "someUniqueUserId", {}, {}); + await Session.createNewSession(ctx, ctx, "someUniqueUserId", {}, {}); ctx.body = ""; }); router.post("/session/revoke", async (ctx, _) => { @@ -1087,9 +1010,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponse = await new Promise((resolve) => request(this.server) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1103,11 +1024,8 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); await new Promise((resolve) => request(this.server) @@ -1139,12 +1057,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/session/revokeUserid") - .set("Cookie", [ - "sAccessToken=" + - userCreateResponse.accessToken + - ";sIdRefreshToken=" + - userCreateResponse.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + userCreateResponse.accessToken]) .set("anti-csrf", userCreateResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -1183,18 +1096,14 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); const router = new Router(); app.use(KoaFramework.middleware()); router.post("/create", async (ctx, _) => { - await Session.createNewSession(ctx, "", {}, {}); + await Session.createNewSession(ctx, ctx, "", {}, {}); ctx.body = ""; }); router.post("/updateSessionData", async (ctx, _) => { @@ -1241,9 +1150,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/updateSessionData") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1259,9 +1166,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let response2 = await new Promise((resolve) => request(this.server) .post("/getSessionData") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1280,9 +1185,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/updateSessionData2") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1297,9 +1200,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { response2 = await new Promise((resolve) => request(this.server) .post("/getSessionData") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1318,9 +1219,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let invalidSessionResponse = await new Promise((resolve) => request(this.server) .post("/updateSessionDataInvalidSessionHandle") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1347,17 +1246,13 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "http://supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let app = new Koa(); const router = new Router(); app.use(KoaFramework.middleware()); router.post("/create", async (ctx, _) => { - await Session.createNewSession(ctx, "user1", {}, {}); + await Session.createNewSession(ctx, ctx, "user1", {}, {}); ctx.body = ""; }); router.post("/updateAccessTokenPayload", async (ctx, _) => { @@ -1415,12 +1310,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/updateAccessTokenPayload") - .set("Cookie", [ - "sAccessToken=" + - response.accessToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1441,12 +1331,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let response2 = await new Promise((resolve) => request(this.server) .post("/getAccessTokenPayload") - .set("Cookie", [ - "sAccessToken=" + - updatedResponse.accessToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + updatedResponse.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1465,12 +1350,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + - response.refreshToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + response.refreshToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1492,12 +1372,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { await new Promise((resolve) => request(this.server) .post("/updateAccessTokenPayload2") - .set("Cookie", [ - "sAccessToken=" + - response2.accessToken + - ";sIdRefreshToken=" + - response2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response2.accessToken]) .set("anti-csrf", response2.antiCsrf) .expect(200) .end((err, res) => { @@ -1518,12 +1393,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { response2 = await new Promise((resolve) => request(this.server) .post("/getAccessTokenPayload") - .set("Cookie", [ - "sAccessToken=" + - updatedResponse2.accessToken + - ";sIdRefreshToken=" + - response2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + updatedResponse2.accessToken]) .set("anti-csrf", response2.antiCsrf) .expect(200) .end((err, res) => { @@ -1541,12 +1411,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { let invalidSessionResponse = await new Promise((resolve) => request(this.server) .post("/updateAccessTokenPayloadInvalidSessionHandle") - .set("Cookie", [ - "sAccessToken=" + - updatedResponse2.accessToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + updatedResponse2.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1589,7 +1454,7 @@ describe(`Koa: ${printPath("[test/framework/koa.test.js]")}`, function () { }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/framework/loopback-server/index.js b/test/framework/loopback-server/index.js index 511fbe51c..15256a6c9 100644 --- a/test/framework/loopback-server/index.js +++ b/test/framework/loopback-server/index.js @@ -35,12 +35,26 @@ let Create = class Create { this.ctx = ctx; } async handler() { - await session_1.default.createNewSession(this.ctx, "userId", {}, {}); + await session_1.default.createNewSession(this.ctx, this.ctx, "userId", {}, {}); return {}; } }; __decorate([rest_1.post("/create"), rest_1.response(200)], Create.prototype, "handler", null); Create = __decorate([__param(0, core_1.inject(rest_1.RestBindings.Http.CONTEXT))], Create); +let CreateThrowing = class CreateThrowing { + constructor(ctx) { + this.ctx = ctx; + } + async handler() { + await session_1.default.createNewSession(this.ctx, this.ctx, "userId", {}, {}); + throw new session_1.default.Error({ + message: "unauthorised", + type: session_1.default.Error.UNAUTHORISED, + }); + } +}; +__decorate([rest_1.post("/create-throw"), rest_1.response(200)], CreateThrowing.prototype, "handler", null); +CreateThrowing = __decorate([__param(0, core_1.inject(rest_1.RestBindings.Http.CONTEXT))], CreateThrowing); let Verify = class Verify { constructor(ctx) { this.ctx = ctx; @@ -102,6 +116,7 @@ let app = new rest_1.RestApplication({ }); app.middleware(loopback_1.middleware); app.controller(Create); +app.controller(CreateThrowing); app.controller(Verify); app.controller(Revoke); app.controller(VerifyOptionalCSRF); diff --git a/test/framework/loopback-server/index.ts b/test/framework/loopback-server/index.ts index f4e8e1989..6bbc40a87 100644 --- a/test/framework/loopback-server/index.ts +++ b/test/framework/loopback-server/index.ts @@ -9,11 +9,23 @@ class Create { @post("/create") @response(200) async handler() { - await Session.createNewSession(this.ctx, "userId", {}, {}); + await Session.createNewSession(this.ctx, this.ctx, "userId", {}, {}); return {}; } } +class CreateThrowing { + constructor(@inject(RestBindings.Http.CONTEXT) private ctx: MiddlewareContext) {} + @post("/create-throw") + @response(200) + async handler() { + await Session.createNewSession(this.ctx, this.ctx, "userId", {}, {}); + throw new Session.Error({ + message: "unauthorised", + type: Session.Error.UNAUTHORISED, + }); + } +} class Verify { constructor(@inject(RestBindings.Http.CONTEXT) private ctx: MiddlewareContext) {} @post("/session/verify") @@ -57,6 +69,7 @@ let app = new RestApplication({ app.middleware(middleware); app.controller(Create); +app.controller(CreateThrowing); app.controller(Verify); app.controller(Revoke); app.controller(VerifyOptionalCSRF); diff --git a/test/framework/loopback.test.js b/test/framework/loopback.test.js index ba1a7a4ff..784ffa375 100644 --- a/test/framework/loopback.test.js +++ b/test/framework/loopback.test.js @@ -23,7 +23,7 @@ let { verifySession } = require("../../recipe/session/framework/awsLambda"); const request = require("supertest"); const axios = require("axios").default; -describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, function () { +describe(`Loopback: ${printPath("[test/framework/loopback.test.js]")}`, function () { beforeEach(async function () { await killAllST(); await setupST(); @@ -55,11 +55,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); await this.app.start(); @@ -73,8 +69,6 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); try { @@ -98,7 +92,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, baseURL: "http://localhost:9876", method: "post", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, }); } catch (err) { @@ -115,7 +109,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, baseURL: "http://localhost:9876", method: "post", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -126,7 +120,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, baseURL: "http://localhost:9876", method: "post", headers: { - Cookie: `sAccessToken=${res.accessToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res.accessToken}`, }, }); assert.deepStrictEqual(result.data, { user: "userId" }); @@ -151,7 +145,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, baseURL: "http://localhost:9876", method: "post", headers: { - Cookie: `sRefreshToken=${res.refreshToken}; sIdRefreshToken=${res.idRefreshTokenFromCookie}`, + Cookie: `sRefreshToken=${res.refreshToken}`, "anti-csrf": res.antiCsrf, }, }); @@ -160,8 +154,6 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); result = await axios({ @@ -169,7 +161,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, baseURL: "http://localhost:9876", method: "post", headers: { - Cookie: `sAccessToken=${res2.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res2.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -183,7 +175,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, baseURL: "http://localhost:9876", method: "post", headers: { - Cookie: `sAccessToken=${res3.accessToken}; sIdRefreshToken=${res2.idRefreshTokenFromCookie}`, + Cookie: `sAccessToken=${res3.accessToken}`, "anti-csrf": res2.antiCsrf, }, }); @@ -191,11 +183,8 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, let sessionRevokedResponseExtracted = extractInfoFromResponse(result); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("sending custom response", async function () { @@ -227,7 +216,7 @@ describe(`Loopback: ${printPath("[test/framework/loopback/loopback.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/frontendIntegration/index.html b/test/frontendIntegration/index.html index 0770b1fb0..b7a77f524 100644 --- a/test/frontendIntegration/index.html +++ b/test/frontendIntegration/index.html @@ -68,6 +68,17 @@ return Promise.all(loadPromises); } + + function deleteAllCookies() { + var cookies = document.cookie.split(";"); + + for (var i = 0; i < cookies.length; i++) { + var cookie = cookies[i]; + var eqPos = cookie.indexOf("="); + var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; + document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; + } + } diff --git a/test/frontendIntegration/index.js b/test/frontendIntegration/index.js index 1aa145291..f913a2c0c 100644 --- a/test/frontendIntegration/index.js +++ b/test/frontendIntegration/index.js @@ -70,6 +70,7 @@ function getConfig(enableAntiCsrf, enableJWT, jwtPropertyName) { }, recipeList: [ Session.init({ + getTokenTransferMethod: process.env.TRANSFER_METHOD ? () => process.env.TRANSFER_METHOD : undefined, jwt: { enable: true, propertyNameInAccessTokenPayload: jwtPropertyName, @@ -91,13 +92,25 @@ function getConfig(enableAntiCsrf, enableJWT, jwtPropertyName) { functions: function (oI) { return { ...oI, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oI.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oI.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -118,6 +131,7 @@ function getConfig(enableAntiCsrf, enableJWT, jwtPropertyName) { }, recipeList: [ Session.init({ + getTokenTransferMethod: process.env.TRANSFER_METHOD ? () => process.env.TRANSFER_METHOD : undefined, errorHandlers: { onUnauthorised: (err, req, res) => { res.setStatusCode(401); @@ -201,7 +215,7 @@ app.post("/reinitialiseBackendConfig", async (req, res) => { app.post("/login", async (req, res) => { let userId = req.body.userId; - let session = await Session.createNewSession(res, userId); + let session = await Session.createNewSession(req, res, userId); res.send(session.getUserId()); }); diff --git a/test/handshake.test.js b/test/handshake.test.js index 89551b73e..bf9db8e5a 100644 --- a/test/handshake.test.js +++ b/test/handshake.test.js @@ -44,7 +44,7 @@ describe(`Handshake: ${printPath("[test/handshake.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); let sessionRecipeInstance = SessionRecipe.getInstanceOrThrowError(); @@ -75,7 +75,7 @@ describe(`Handshake: ${printPath("[test/handshake.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); try { await Session.revokeSession(""); @@ -98,7 +98,7 @@ describe(`Handshake: ${printPath("[test/handshake.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); let info = await SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.getHandshakeInfo(); assert(info.getJwtSigningPublicKeyList() instanceof Array); @@ -130,7 +130,7 @@ describe(`Handshake: ${printPath("[test/handshake.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); let info = await SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.getHandshakeInfo(); assert(info.getJwtSigningPublicKeyList() instanceof Array); @@ -146,6 +146,6 @@ describe(`Handshake: ${printPath("[test/handshake.test.js]")}`, function () { expiryTime ); let info2 = await SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.getHandshakeInfo(); - assert.deepEqual(info2.getJwtSigningPublicKeyList(), [{ publicKey: "hello2", expiryTime }]); + assert.deepStrictEqual(info2.getJwtSigningPublicKeyList(), [{ publicKey: "hello2", expiryTime }]); }); }); diff --git a/test/middleware.test.js b/test/middleware.test.js index 356f69cf7..c85d52491 100644 --- a/test/middleware.test.js +++ b/test/middleware.test.js @@ -20,6 +20,7 @@ const { cleanST, setKeyValueInConfig, extractInfoFromResponse, + delay, } = require("./utils"); let assert = require("assert"); const express = require("express"); @@ -62,6 +63,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -107,6 +109,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", errorHandlers: { onTokenTheftDetected: (sessionHandle, userId, req, res) => { res.setStatusCode(403); @@ -121,7 +124,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", {}, {}); + await Session.createNewSession(req, res, "testing-userId", {}, {}); res.status(200).json({ message: true }); }); @@ -181,9 +184,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r1 = await new Promise((resolve) => request(app) .get("/user/id") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -199,9 +200,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -216,9 +215,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V0 = await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -233,9 +230,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V1 = await new Promise((resolve) => request(app) .get("/user/handleV1") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -250,9 +245,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2Optional = await new Promise((resolve) => request(app) .get("/user/handleOptional") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(200) .end((err, res) => { if (err) { @@ -278,48 +271,12 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ); assert(r2Optional === false); - // not passing id refresh token - let r3V0 = await new Promise((resolve) => - request(app) - .get("/user/handleV0") - .expect(401) - .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r3V0 === "unauthorised"); - - let r3V1 = await new Promise((resolve) => - request(app) - .get("/user/handleV1") - .expect(401) - .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r3V1 === "unauthorised"); - let res2 = extractInfoFromResponse( await new Promise((resolve) => request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { @@ -335,9 +292,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/id") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -352,9 +307,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -368,10 +321,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r4 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .expect(403) .end((err, res) => { @@ -388,9 +338,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .post("/logout") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -403,21 +351,16 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ) ); - assert.deepEqual(res4.antiCsrf, undefined); - assert.deepEqual(res4.accessToken, ""); - assert.deepEqual(res4.refreshToken, ""); - assert.deepEqual(res4.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res4.idRefreshTokenFromCookie, ""); - assert.deepEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.antiCsrf, undefined); + assert.strictEqual(res4.accessToken, ""); + assert.strictEqual(res4.refreshToken, ""); + assert.strictEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); let r5 = await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res4.accessToken + ";sIdRefreshToken=" + res4.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res4.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -427,10 +370,11 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { } }) ); - assert(r5 === "try refresh token"); + assert.strictEqual(r5, "unauthorised"); }); it("test session verify middleware with auto refresh", async function () { + await setKeyValueInConfig(2); await startST(); SuperTokens.init({ supertokens: { @@ -443,6 +387,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", errorHandlers: { onTokenTheftDetected: (sessionHandle, userId, req, res) => { @@ -461,7 +406,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", {}, {}); + await Session.createNewSession(req, res, "testing-userId", {}, {}); res.status(200).json({ message: true }); }); @@ -517,9 +462,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r1 = await new Promise((resolve) => request(app) .get("/user/id") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -535,9 +478,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -552,9 +493,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V0 = await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -569,43 +508,8 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V1 = await new Promise((resolve) => request(app) .get("/user/handleV1") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) - .expect(401) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r2V1 === "try refresh token"); - - // not passing id refresh token - let r3V0 = await new Promise((resolve) => - request(app) - .get("/user/handleV0") - .expect(401) .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r3V0 === "unauthorised"); - - let r3V1 = await new Promise((resolve) => - request(app) - .get("/user/handleV1") .expect(401) - .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { resolve(undefined); @@ -614,14 +518,12 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { } }) ); - assert(r3V1 === "unauthorised"); + assert(r2V1 === "try refresh token"); let rOptionalSession = await new Promise((resolve) => request(app) .get("/user/handleOptional") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(200) .end((err, res) => { if (err) { @@ -652,10 +554,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { @@ -671,9 +570,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/id") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -688,9 +585,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -704,10 +599,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r4 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .expect(403) .end((err, res) => { @@ -728,9 +620,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .post("/logout") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -743,21 +633,17 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ) ); - assert.deepEqual(res4.antiCsrf, undefined); - assert.deepEqual(res4.accessToken, ""); - assert.deepEqual(res4.refreshToken, ""); - assert.deepEqual(res4.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res4.idRefreshTokenFromCookie, ""); - assert.deepEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.antiCsrf, undefined); + assert.strictEqual(res4.accessToken, ""); + assert.strictEqual(res4.refreshToken, ""); + assert.strictEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + await delay(2); let r5 = await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res4.accessToken + ";sIdRefreshToken=" + res4.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -767,10 +653,11 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { } }) ); - assert(r5 === "try refresh token"); + assert.strictEqual(r5, "try refresh token"); }); it("test session verify middleware with driver config", async function () { + await setKeyValueInConfig(2); await startST(); SuperTokens.init({ supertokens: { @@ -784,6 +671,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", cookieDomain: "test-driver", cookieSecure: true, cookieSameSite: "strict", @@ -802,7 +690,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", {}, {}); + await Session.createNewSession(req, res, "testing-userId", {}, {}); res.status(200).json({ message: true }); }); @@ -863,9 +751,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r1 = await new Promise((resolve) => request(app) .get("/custom/user/id") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -882,9 +768,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -900,9 +784,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V0 = await new Promise((resolve) => request(app) .get("/custom/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -917,43 +799,8 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V1 = await new Promise((resolve) => request(app) .get("/custom/user/handleV1") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) - .expect(401) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r2V1 === "try refresh token"); - - // not passing id refresh token - let r3V0 = await new Promise((resolve) => - request(app) - .get("/custom/user/handleV0") - .expect(401) .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r3V0 === "unauthorised"); - - let r3V1 = await new Promise((resolve) => - request(app) - .get("/custom/user/handleV1") .expect(401) - .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { resolve(undefined); @@ -962,14 +809,12 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { } }) ); - assert(r3V1 === "unauthorised"); + assert(r2V1 === "try refresh token"); let rOptionalSession = await new Promise((resolve) => request(app) .get("/custom/user/handleOptional") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(200) .end((err, res) => { if (err) { @@ -1000,10 +845,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { request(app) .post("/custom/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { @@ -1019,9 +861,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/custom/user/id") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1037,9 +877,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/custom/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1054,10 +892,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r4 = await new Promise((resolve) => request(app) .post("/custom/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .expect(403) .end((err, res) => { @@ -1074,9 +909,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .post("/custom/logout") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1089,21 +922,16 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ) ); - assert.deepEqual(res4.antiCsrf, undefined); - assert.deepEqual(res4.accessToken, ""); - assert.deepEqual(res4.refreshToken, ""); - assert.deepEqual(res4.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res4.idRefreshTokenFromCookie, ""); - assert.deepEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - + assert.strictEqual(res4.antiCsrf, undefined); + assert.strictEqual(res4.accessToken, ""); + assert.strictEqual(res4.refreshToken, ""); + assert.strictEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + await delay(2); let r5 = await new Promise((resolve) => request(app) .get("/custom/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res4.accessToken + ";sIdRefreshToken=" + res4.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -1113,7 +941,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { } }) ); - assert(r5 === "try refresh token"); + assert.strictEqual(r5, "try refresh token"); }); it("test session verify middleware with driver config with auto refresh", async function () { @@ -1131,6 +959,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", cookieDomain: "test-driver", cookieSecure: true, cookieSameSite: "strict", @@ -1152,7 +981,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", {}, {}); + await Session.createNewSession(req, res, "testing-userId", {}, {}); res.status(200).json({ message: true }); }); @@ -1207,15 +1036,13 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ); assert(res1.accessTokenHttpOnly); - assert(res1.idRefreshTokenHttpOnly); + assert(res1.refreshTokenHttpOnly); let r1 = await new Promise((resolve) => request(app) .get("/custom/user/id") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -1232,9 +1059,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -1250,9 +1075,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V0 = await new Promise((resolve) => request(app) .get("/custom/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -1267,43 +1090,8 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2V1 = await new Promise((resolve) => request(app) .get("/custom/user/handleV1") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) - .expect(401) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r2V1 === "try refresh token"); - - // not passing id refresh token - let r3V0 = await new Promise((resolve) => - request(app) - .get("/custom/user/handleV0") - .expect(401) .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res.body.message); - } - }) - ); - assert(r3V0 === "unauthorised"); - - let r3V1 = await new Promise((resolve) => - request(app) - .get("/custom/user/handleV1") .expect(401) - .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { resolve(undefined); @@ -1312,14 +1100,12 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { } }) ); - assert(r3V1 === "unauthorised"); + assert(r2V1 === "try refresh token"); let rOptionalSession = await new Promise((resolve) => request(app) .get("/custom/user/handleOptional") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(200) .end((err, res) => { if (err) { @@ -1349,10 +1135,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { request(app) .post("/custom/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { @@ -1368,9 +1151,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/custom/user/id") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1386,9 +1167,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/custom/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1403,10 +1182,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r4 = await new Promise((resolve) => request(app) .post("/custom/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .expect(403) .end((err, res) => { @@ -1423,9 +1199,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .post("/custom/logout") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1438,21 +1212,17 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ) ); - assert.deepEqual(res4.antiCsrf, undefined); - assert.deepEqual(res4.accessToken, ""); - assert.deepEqual(res4.refreshToken, ""); - assert.deepEqual(res4.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res4.idRefreshTokenFromCookie, ""); - assert.deepEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.antiCsrf, undefined); + assert.strictEqual(res4.accessToken, ""); + assert.strictEqual(res4.refreshToken, ""); + assert.strictEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + await delay(2); let r5 = await new Promise((resolve) => request(app) .get("/custom/user/handleV0") - .set("Cookie", [ - "sAccessToken=" + res4.accessToken + ";sIdRefreshToken=" + res4.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -1483,6 +1253,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", cookieDomain: "test-driver", cookieSecure: true, cookieSameSite: "strict", @@ -1504,7 +1275,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", {}, {}); + await Session.createNewSession(req, res, "testing-userId", {}, {}); res.status(200).json({ message: true }); }); @@ -1545,15 +1316,13 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ); assert(res1.accessTokenHttpOnly); - assert(res1.idRefreshTokenHttpOnly); + assert(res1.refreshTokenHttpOnly); let r1 = await new Promise((resolve) => request(app) .get("/custom/user/id") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -1570,9 +1339,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handle") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -1589,9 +1356,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let r2 = await new Promise((resolve) => request(app) .get("/custom/user/handle") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -1622,6 +1387,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", cookieDomain: "test-driver", cookieSecure: true, cookieSameSite: "strict", @@ -1643,7 +1409,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", {}, {}); + await Session.createNewSession(req, res, "testing-userId", {}, {}); res.status(200).json({ message: true }); }); @@ -1684,15 +1450,13 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ); assert(res1.accessTokenHttpOnly); - assert(res1.idRefreshTokenHttpOnly); + assert(res1.refreshTokenHttpOnly); let r1 = await new Promise((resolve) => request(app) .get("/custom/user/id") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -1709,9 +1473,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/user/handle") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -1728,10 +1490,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { request(app) .post("/custom/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { @@ -1747,9 +1506,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/custom/user/id") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1765,9 +1522,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .get("/custom/user/handle") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1783,9 +1538,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { await new Promise((resolve) => request(app) .post("/custom/logout") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -1798,21 +1551,16 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { ) ); - assert.deepEqual(res4.antiCsrf, undefined); - assert.deepEqual(res4.accessToken, ""); - assert.deepEqual(res4.refreshToken, ""); - assert.deepEqual(res4.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res4.idRefreshTokenFromCookie, ""); - assert.deepEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.antiCsrf, undefined); + assert.strictEqual(res4.accessToken, ""); + assert.strictEqual(res4.refreshToken, ""); + assert.strictEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); let r2 = await new Promise((resolve) => request(app) .get("/custom/user/handle") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401) .end((err, res) => { if (err) { @@ -1842,6 +1590,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", cookieDomain: "test-driver", cookieSecure: true, cookieSameSite: "strict", @@ -1890,6 +1639,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }); it("test session verify middleware without error handler added", async function () { + await setKeyValueInConfig("access_token_validity", 2); await startST(); SuperTokens.init({ supertokens: { @@ -1902,6 +1652,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", errorHandlers: { onTokenTheftDetected: (sessionHandle, userId, req, res) => { res.setStatusCode(403); @@ -1920,7 +1671,7 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", {}, {}); + await Session.createNewSession(req, res, "testing-userId", {}, {}); res.status(200).json({ message: true }); }); @@ -1960,82 +1711,62 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let res1 = extractInfoFromResponse(await request(app).post("/create").expect(200)); let r1 = await request(app) .get("/user/id") - .set("Cookie", ["sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200); assert.strictEqual(r1.body.message, "testing-userId"); await request(app) .get("/user/handleV0") - .set("Cookie", ["sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200); // not passing anti csrf even if requried let r2V0 = await request(app) .get("/user/handleV0") - .set("Cookie", ["sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401); assert.strictEqual(r2V0.body.message, "try refresh token"); let r2V1 = await request(app) .get("/user/handleV1") - .set("Cookie", ["sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(401); assert.strictEqual(r2V1.body.message, "try refresh token"); let r2Optional = await request(app) .get("/user/handleOptional") - .set("Cookie", ["sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .expect(200); assert.strictEqual(r2Optional.body.message, true); r2Optional = await request(app).get("/user/handleOptional").expect(200); assert.strictEqual(r2Optional.body.message, false); - // not passing id refresh token - let r3V0 = await request(app) - .get("/user/handleV0") - .expect(401) - .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf); - assert.strictEqual(r3V0.body.message, "unauthorised"); - - let r3V1 = await request(app) - .get("/user/handleV1") - .expect(401) - .set("Cookie", ["sAccessToken=" + res1.accessToken]) - .set("anti-csrf", res1.antiCsrf); - assert.strictEqual(r3V1.body.message, "unauthorised"); - let res2 = extractInfoFromResponse( await request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) ); let res3 = extractInfoFromResponse( await request(app) .get("/user/id") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) ); await request(app) .get("/user/handleV0") - .set("Cookie", ["sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200); let r4 = await request(app) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res1.refreshToken, "sIdRefreshToken=" + res1.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .expect(403); assert.strictEqual(r4.body.message, "token theft detected"); @@ -2043,25 +1774,21 @@ describe(`middleware: ${printPath("[test/middleware.test.js]")}`, function () { let res4 = extractInfoFromResponse( await request(app) .post("/logout") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) ); - assert.deepEqual(res4.antiCsrf, undefined); - assert.deepEqual(res4.accessToken, ""); - assert.deepEqual(res4.refreshToken, ""); - assert.deepEqual(res4.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res4.idRefreshTokenFromCookie, ""); - assert.deepEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.antiCsrf, undefined); + assert.strictEqual(res4.accessToken, ""); + assert.strictEqual(res4.refreshToken, ""); + assert.strictEqual(res4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + await delay(2); let r5 = await request(app) .get("/user/handleV0") - .set("Cookie", ["sAccessToken=" + res4.accessToken + ";sIdRefreshToken=" + res4.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .expect(401); assert.strictEqual(r5.body.message, "try refresh token"); }); diff --git a/test/middleware2.test.js b/test/middleware2.test.js index 9169dc8db..ef704c795 100644 --- a/test/middleware2.test.js +++ b/test/middleware2.test.js @@ -56,7 +56,7 @@ describe(`middleware2: ${printPath("[test/middleware2.test.js]")}`, function () appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init(), EmailPassword.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" }), EmailPassword.init()], }); const app = express(); @@ -90,7 +90,7 @@ describe(`middleware2: ${printPath("[test/middleware2.test.js]")}`, function () appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init(), EmailPassword.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" }), EmailPassword.init()], }); const app = express(); @@ -123,7 +123,7 @@ describe(`middleware2: ${printPath("[test/middleware2.test.js]")}`, function () appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init(), EmailPassword.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" }), EmailPassword.init()], }); const app = express(); @@ -157,7 +157,7 @@ describe(`middleware2: ${printPath("[test/middleware2.test.js]")}`, function () appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init(), EmailPassword.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" }), EmailPassword.init()], }); const app = express(); @@ -192,7 +192,7 @@ describe(`middleware2: ${printPath("[test/middleware2.test.js]")}`, function () websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), EmailPassword.init({ override: { apis: (oI) => { diff --git a/test/nextjs.test.js b/test/nextjs.test.js index 6c90ed6ca..de7a885cb 100644 --- a/test/nextjs.test.js +++ b/test/nextjs.test.js @@ -48,6 +48,7 @@ describe(`NextJS Middleware Test: ${printPath("[test/nextjs.test.js]")}`, functi recipeList: [ EmailPassword.init(), Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => { return { @@ -396,7 +397,7 @@ describe(`NextJS Middleware Test: ${printPath("[test/nextjs.test.js]")}`, functi const session = await superTokensNextWrapper( async () => { - return await Session.createNewSession(response, "1", {}, {}); + return await Session.createNewSession(request, response, "1", {}, {}); }, request, response @@ -448,6 +449,7 @@ describe(`NextJS Middleware Test: ${printPath("[test/nextjs.test.js]")}`, functi ], }), Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => { return { @@ -561,6 +563,7 @@ describe(`NextJS Middleware Test: ${printPath("[test/nextjs.test.js]")}`, functi recipeList: [ EmailPassword.init(), Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => { return { @@ -634,8 +637,5 @@ function getSessionCookiesFromResponse(response) { sRefreshToken: decodeURIComponent( response._getHeaders()["set-cookie"][1].split("sRefreshToken=")[1].split(";")[0] ), - sIdRefreshToken: decodeURIComponent( - response._getHeaders()["set-cookie"][2].split("sIdRefreshToken=")[1].split(";")[0] - ), }; } diff --git a/test/passwordless/apis.test.js b/test/passwordless/apis.test.js index e932ee0cd..43e2ddf5f 100644 --- a/test/passwordless/apis.test.js +++ b/test/passwordless/apis.test.js @@ -55,7 +55,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -150,7 +150,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -245,7 +245,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -332,7 +332,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -418,7 +418,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -503,7 +503,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -632,7 +632,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -692,7 +692,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -782,7 +782,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -901,7 +901,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -968,7 +968,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1049,7 +1049,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1131,7 +1131,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1195,7 +1195,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1284,7 +1284,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1375,7 +1375,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1459,7 +1459,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1499,7 +1499,7 @@ describe(`apisFunctions: ${printPath("[test/passwordless/apis.test.js]")}`, func websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", diff --git a/test/passwordless/config.test.js b/test/passwordless/config.test.js index 61deb2332..16085d55e 100644 --- a/test/passwordless/config.test.js +++ b/test/passwordless/config.test.js @@ -25,7 +25,7 @@ let { middleware, errorHandler } = require("../../framework/express"); let { isCDIVersionCompatible, generateRandomCode } = require("../utils"); let PasswordlessRecipe = require("../../lib/build/recipe/passwordless/recipe").default; -describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, function () { +describe(`config tests: ${printPath("[test/passwordless/config.test.js]")}`, function () { beforeEach(async function () { await killAllST(); await setupST(); @@ -54,7 +54,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -98,7 +98,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -196,7 +196,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -266,7 +266,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -332,7 +332,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -373,7 +373,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -439,7 +439,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -499,7 +499,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE", @@ -571,7 +571,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "MAGIC_LINK", @@ -633,7 +633,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -696,7 +696,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "MAGIC_LINK", @@ -761,7 +761,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -803,7 +803,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -869,7 +869,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -930,7 +930,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", @@ -1002,7 +1002,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "MAGIC_LINK", @@ -1064,7 +1064,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1127,7 +1127,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "MAGIC_LINK", @@ -1197,7 +1197,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", }), @@ -1227,7 +1227,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ flowType: "USER_INPUT_CODE", }), @@ -1265,7 +1265,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", @@ -1351,7 +1351,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", @@ -1439,7 +1439,7 @@ describe(`config tests: ${printPath("[test/passwordless/apis.test.js]")}`, funct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", diff --git a/test/passwordless/emailDelivery.test.js b/test/passwordless/emailDelivery.test.js index 72dd70ba4..17b957ad4 100644 --- a/test/passwordless/emailDelivery.test.js +++ b/test/passwordless/emailDelivery.test.js @@ -54,7 +54,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -132,7 +132,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" userInputCode = input.userInputCode; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -198,7 +198,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -310,7 +310,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -358,7 +358,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -433,7 +433,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -537,7 +537,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" sendCustomEmailCalled = true; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -627,7 +627,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -769,7 +769,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -833,7 +833,7 @@ describe(`emailDelivery: ${printPath("[test/passwordless/emailDelivery.test.js]" contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); diff --git a/test/passwordless/recipeFunctions.test.js b/test/passwordless/recipeFunctions.test.js index c862e1edc..dbd0393b6 100644 --- a/test/passwordless/recipeFunctions.test.js +++ b/test/passwordless/recipeFunctions.test.js @@ -46,7 +46,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -148,7 +148,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -211,7 +211,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -310,7 +310,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -396,7 +396,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -446,7 +446,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -516,7 +516,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -583,7 +583,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -647,7 +647,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -712,7 +712,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -763,7 +763,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -814,7 +814,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -867,7 +867,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -910,7 +910,7 @@ describe(`recipeFunctions: ${printPath("[test/passwordless/recipeFunctions.test. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", diff --git a/test/passwordless/smsDelivery.test.js b/test/passwordless/smsDelivery.test.js index 84a4679ea..5a5afe333 100644 --- a/test/passwordless/smsDelivery.test.js +++ b/test/passwordless/smsDelivery.test.js @@ -55,7 +55,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -136,7 +136,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, userInputCode = input.userInputCode; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -202,7 +202,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -307,7 +307,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -363,7 +363,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -456,7 +456,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -518,7 +518,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -587,7 +587,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -694,7 +694,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, sendCustomSMSCalled = true; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -784,7 +784,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -922,7 +922,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1003,7 +1003,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1121,7 +1121,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1203,7 +1203,7 @@ describe(`smsDelivery: ${printPath("[test/passwordless/smsDelivery.test.js]")}`, contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); diff --git a/test/querier.test.js b/test/querier.test.js index 4d376f2f8..fb7852033 100644 --- a/test/querier.test.js +++ b/test/querier.test.js @@ -50,11 +50,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); await q.getAPIVersion(); @@ -87,11 +83,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let querier = Querier.getNewInstanceOrThrowError(SessionRecipe.getInstanceOrThrowError().getRecipeId()); @@ -140,11 +132,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); try { let q = Querier.getNewInstanceOrThrowError(undefined); @@ -170,11 +158,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); assert.equal(await q.sendGetRequest(new NormalisedURLPath("/hello"), {}), "Hello\n"); @@ -201,11 +185,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); assert.equal(await q.sendGetRequest(new NormalisedURLPath("/hello"), {}), "Hello\n"); @@ -228,11 +208,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); try { @@ -256,6 +232,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => { @@ -298,7 +275,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); // we query the core now @@ -330,7 +307,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); try { @@ -369,7 +346,7 @@ describe(`Querier: ${printPath("[test/querier.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); { diff --git a/test/recipeModuleManager.test.js b/test/recipeModuleManager.test.js index 775c672b3..0f055c9c6 100644 --- a/test/recipeModuleManager.test.js +++ b/test/recipeModuleManager.test.js @@ -62,9 +62,7 @@ describe(`recipeModuleManagerTest: ${printPath("[test/recipeModuleManager.test.j websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailPassword.init(), ], }); @@ -79,9 +77,7 @@ describe(`recipeModuleManagerTest: ${printPath("[test/recipeModuleManager.test.j websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailPassword.init(), ], }); @@ -110,11 +106,7 @@ describe(`recipeModuleManagerTest: ${printPath("[test/recipeModuleManager.test.j appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); await Querier.getNewInstanceOrThrowError(undefined); @@ -153,9 +145,7 @@ describe(`recipeModuleManagerTest: ${printPath("[test/recipeModuleManager.test.j websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailPassword.init(), ], }); @@ -619,11 +609,12 @@ describe(`recipeModuleManagerTest: ${printPath("[test/recipeModuleManager.test.j recipeList: [TestRecipe1.init(), TestRecipe2.init(), TestRecipe3.init(), TestRecipe3Duplicate.init()], }); let headers = await ST.getAllCORSHeaders(); - assert(headers.length === 5); - assert(headers.includes("rid") && headers.includes("fdi-version")); - assert( - headers.includes("test-recipe-1") && headers.includes("test-recipe-2") && headers.includes("test-recipe-3") - ); + assert.strictEqual(headers.length, 5); + assert(headers.includes("rid")); + assert(headers.includes("fdi-version")); + assert(headers.includes("test-recipe-1")); + assert(headers.includes("test-recipe-2")); + assert(headers.includes("test-recipe-3")); }); }); diff --git a/test/session.test.js b/test/session.test.js index 2e1003a14..dfb504be4 100644 --- a/test/session.test.js +++ b/test/session.test.js @@ -22,6 +22,7 @@ const { setKeyValueInConfig, killAllSTCoresOnly, mockResponse, + mockRequest, } = require("./utils"); let assert = require("assert"); let { Querier } = require("../lib/build/querier"); @@ -32,6 +33,7 @@ let { ProcessState, PROCESS_STATE } = require("../lib/build/processState"); let SuperTokens = require("../"); let Session = require("../recipe/session"); let SessionFunctions = require("../lib/build/recipe/session/sessionFunctions"); +let { parseJWTWithoutSignatureVerification } = require("../lib/build/recipe/session/jwt"); let SessionRecipe = require("../lib/build/recipe/session/recipe").default; const { maxVersion } = require("../lib/build/utils"); const { fail } = require("assert"); @@ -42,7 +44,6 @@ let { middleware, errorHandler } = require("../framework/express"); - calling createNewSession twice, should overwrite the first call (in terms of cookies) - calling createNewSession in the case of unauthorised error, should create a proper session - revoking old session after create new session, should not remove new session's cookies. -- check that if idRefreshToken is not passed to express, verify throws UNAUTHORISED - check that Access-Control-Expose-Headers header is being set properly during create, use and destroy session**** only for express */ @@ -70,11 +71,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); @@ -82,7 +79,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -100,21 +97,17 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { } }) ); - assert(res.header["access-control-expose-headers"] === "front-token, id-refresh-token, anti-csrf"); + assert(res.header["access-control-expose-headers"] === "front-token, anti-csrf"); let cookies = extractInfoFromResponse(res); assert(cookies.accessToken !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.antiCsrf !== undefined); - assert(cookies.idRefreshTokenFromHeader !== undefined); - assert(cookies.idRefreshTokenFromCookie !== undefined); assert(cookies.accessTokenExpiry !== undefined); assert(cookies.refreshTokenExpiry !== undefined); - assert(cookies.idRefreshTokenExpiry !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); assert(cookies.frontToken !== undefined); }); @@ -130,18 +123,14 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -165,7 +154,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -175,21 +164,17 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { } }) ); - assert(res2.header["access-control-expose-headers"] === "front-token, id-refresh-token, anti-csrf"); + assert(res2.header["access-control-expose-headers"] === "front-token, anti-csrf"); let cookies = extractInfoFromResponse(res2); assert(cookies.accessToken !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.antiCsrf !== undefined); - assert(cookies.idRefreshTokenFromHeader !== undefined); - assert(cookies.idRefreshTokenFromCookie !== undefined); assert(cookies.accessTokenExpiry !== undefined); assert(cookies.refreshTokenExpiry !== undefined); - assert(cookies.idRefreshTokenExpiry !== undefined); assert(cookies.refreshToken !== undefined); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); assert(cookies.frontToken !== undefined); }); @@ -206,18 +191,14 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -264,18 +245,14 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -297,7 +274,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -322,16 +299,13 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let response = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -339,22 +313,26 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let response2 = await SessionFunctions.refreshSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, response.refreshToken.token, - response.antiCsrfToken + response.antiCsrfToken, + true, + "cookie" ); await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response2.accessToken.token, + parseJWTWithoutSignatureVerification(response2.accessToken.token), response2.antiCsrfToken, - true, - response2.idRefreshToken.token + true ); try { await SessionFunctions.refreshSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, response.refreshToken.token, - response.antiCsrfToken + response.antiCsrfToken, + true, + "cookie", + "cookie" ); throw new Error("should not have come here"); } catch (err) { @@ -377,16 +355,13 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let response = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -394,22 +369,27 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let response2 = await SessionFunctions.refreshSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, response.refreshToken.token, - response.antiCsrfToken + response.antiCsrfToken, + true, + "cookie", + "cookie" ); await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response2.accessToken.token, + parseJWTWithoutSignatureVerification(response2.accessToken.token), response2.antiCsrfToken, - true, - response2.idRefreshToken.token + true ); try { await SessionFunctions.refreshSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, response.refreshToken.token, - response.antiCsrfToken + response.antiCsrfToken, + true, + "cookie", + "cookie" ); throw new Error("should not have come here"); } catch (err) { @@ -431,11 +411,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); try { @@ -463,29 +439,24 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError(); - let response = await SessionFunctions.createNewSession(s.recipeInterfaceImpl.helpers, "", {}, {}); + let response = await SessionFunctions.createNewSession(s.recipeInterfaceImpl.helpers, "", false, {}, {}); assert(response.session !== undefined); assert(response.accessToken !== undefined); assert(response.refreshToken !== undefined); - assert(response.idRefreshToken !== undefined); assert(response.antiCsrfToken !== undefined); assert(Object.keys(response).length === 5); await SessionFunctions.getSession( s.recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), response.antiCsrfToken, true, - response.idRefreshToken.token + true ); let verifyState3 = await ProcessState.getInstance().waitForEvent(PROCESS_STATE.CALLING_SERVICE_IN_VERIFY, 1500); assert(verifyState3 === undefined); @@ -493,21 +464,23 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let response2 = await SessionFunctions.refreshSession( s.recipeInterfaceImpl.helpers, response.refreshToken.token, - response.antiCsrfToken + response.antiCsrfToken, + true, + "cookie", + "cookie" ); assert(response2.session !== undefined); assert(response2.accessToken !== undefined); assert(response2.refreshToken !== undefined); - assert(response2.idRefreshToken !== undefined); assert(response2.antiCsrfToken !== undefined); assert(Object.keys(response2).length === 5); let response3 = await SessionFunctions.getSession( s.recipeInterfaceImpl.helpers, - response2.accessToken.token, + parseJWTWithoutSignatureVerification(response2.accessToken.token), response2.antiCsrfToken, true, - response.idRefreshToken.token + true ); let verifyState = await ProcessState.getInstance().waitForEvent(PROCESS_STATE.CALLING_SERVICE_IN_VERIFY); assert(verifyState !== undefined); @@ -519,10 +492,10 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let response4 = await SessionFunctions.getSession( s.recipeInterfaceImpl.helpers, - response3.accessToken.token, + parseJWTWithoutSignatureVerification(response3.accessToken.token), response2.antiCsrfToken, true, - response.idRefreshToken.token + true ); let verifyState2 = await ProcessState.getInstance().waitForEvent(PROCESS_STATE.CALLING_SERVICE_IN_VERIFY, 1000); assert(verifyState2 === undefined); @@ -546,33 +519,29 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError(); - let response = await SessionFunctions.createNewSession(s.recipeInterfaceImpl.helpers, "", {}, {}); + let response = await SessionFunctions.createNewSession(s.recipeInterfaceImpl.helpers, "", false, {}, {}); let response2 = await SessionFunctions.getSession( s.recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), response.antiCsrfToken, true, - response.idRefreshToken.token + true ); assert(response2.session != undefined); assert(Object.keys(response2.session).length === 3); let response3 = await SessionFunctions.getSession( s.recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), response.antiCsrfToken, false, - response.idRefreshToken.token + true ); assert(response3.session != undefined); assert(Object.keys(response3.session).length === 3); @@ -590,24 +559,20 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError(); - let response = await SessionFunctions.createNewSession(s.recipeInterfaceImpl.helpers, "", {}, {}); + let response = await SessionFunctions.createNewSession(s.recipeInterfaceImpl.helpers, "", false, {}, {}); //passing anti-csrf token as undefined and anti-csrf check as false let response2 = await SessionFunctions.getSession( s.recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), undefined, false, - response.idRefreshToken + true ); assert(response2.session != undefined); assert(Object.keys(response2.session).length === 3); @@ -616,10 +581,10 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { try { await SessionFunctions.getSession( s.recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), undefined, true, - response.idRefreshToken + true ); throw new Error("should not have come here"); } catch (err) { @@ -641,16 +606,12 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //create a single session and revoke using the session handle - let res = await SessionFunctions.createNewSession(s.helpers, "someUniqueUserId", {}, {}); + let res = await SessionFunctions.createNewSession(s.helpers, "someUniqueUserId", false, {}, {}); let res2 = await SessionFunctions.revokeSession(s.helpers, res.session.handle); assert(res2 === true); @@ -658,8 +619,8 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { assert(res3.length === 0); //create multiple sessions with the same userID and use revokeAllSessionsForUser to revoke sessions - await SessionFunctions.createNewSession(s.helpers, "someUniqueUserId", {}, {}); - await SessionFunctions.createNewSession(s.helpers, "someUniqueUserId", {}, {}); + await SessionFunctions.createNewSession(s.helpers, "someUniqueUserId", false, {}, {}); + await SessionFunctions.createNewSession(s.helpers, "someUniqueUserId", false, {}, {}); let sessionIdResponse = await SessionFunctions.getAllSessionHandlesForUser(s.helpers, "someUniqueUserId"); assert(sessionIdResponse.length === 2); @@ -691,26 +652,22 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding session data - let res = await SessionFunctions.createNewSession(s.helpers, "", {}, {}); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, {}, {}); await SessionFunctions.updateSessionData(s.helpers, res.session.handle, { key: "value" }); let res2 = (await SessionFunctions.getSessionInformation(s.helpers, res.session.handle)).sessionData; - assert.deepEqual(res2, { key: "value" }); + assert.deepStrictEqual(res2, { key: "value" }); //changing the value of session data with the same key await SessionFunctions.updateSessionData(s.helpers, res.session.handle, { key: "value 2" }); let res3 = (await SessionFunctions.getSessionInformation(s.helpers, res.session.handle)).sessionData; - assert.deepEqual(res3, { key: "value 2" }); + assert.deepStrictEqual(res3, { key: "value 2" }); //passing invalid session handle when updating session data assert(!(await SessionFunctions.updateSessionData(s.helpers, "random", { key2: "value2" }))); @@ -727,11 +684,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -744,17 +697,17 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding session data - let res = await SessionFunctions.createNewSession(s.helpers, "", {}, {}); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, {}, {}); await SessionFunctions.updateSessionData(s.helpers, res.session.handle, { key: "value" }); let res2 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); - assert.deepEqual(res2.sessionData, { key: "value" }); + assert.deepStrictEqual(res2.sessionData, { key: "value" }); //changing the value of session data with the same key await SessionFunctions.updateSessionData(s.helpers, res.session.handle, { key: "value 2" }); let res3 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); - assert.deepEqual(res3.sessionData, { key: "value 2" }); + assert.deepStrictEqual(res3.sessionData, { key: "value 2" }); //passing invalid session handle when updating session data assert(!(await SessionFunctions.updateSessionData(s.helpers, "random", { key2: "value2" }))); @@ -771,16 +724,12 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding session data - let res = await SessionFunctions.createNewSession(s.helpers, "", {}, null); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, {}, null); let res2 = (await SessionFunctions.getSessionInformation(s.helpers, res.session.handle)).sessionData; assert.deepStrictEqual(res2, {}); @@ -817,11 +766,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -834,7 +779,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding session data - let res = await SessionFunctions.createNewSession(s.helpers, "", {}, null); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, {}, null); let res2 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); assert.deepStrictEqual(res2.sessionData, {}); @@ -872,27 +817,23 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding jwt payload - let res = await SessionFunctions.createNewSession(s.helpers, "", {}, {}); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, {}, {}); await SessionFunctions.updateAccessTokenPayload(s.helpers, res.session.handle, { key: "value" }); let res2 = (await SessionFunctions.getSessionInformation(s.helpers, res.session.handle)).accessTokenPayload; - assert.deepEqual(res2, { key: "value" }); + assert.deepStrictEqual(res2, { key: "value" }); //changing the value of jwt payload with the same key await SessionFunctions.updateAccessTokenPayload(s.helpers, res.session.handle, { key: "value 2" }); let res3 = (await SessionFunctions.getSessionInformation(s.helpers, res.session.handle)).accessTokenPayload; - assert.deepEqual(res3, { key: "value 2" }); + assert.deepStrictEqual(res3, { key: "value 2" }); //passing invalid session handle when updating jwt payload assert(!(await SessionFunctions.updateAccessTokenPayload(s.helpers, "random", { key2: "value2" }))); @@ -909,11 +850,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -926,18 +863,18 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding jwt payload - let res = await SessionFunctions.createNewSession(s.helpers, "", {}, {}); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, {}, {}); await SessionFunctions.updateAccessTokenPayload(s.helpers, res.session.handle, { key: "value" }); let res2 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); - assert.deepEqual(res2.accessTokenPayload, { key: "value" }); + assert.deepStrictEqual(res2.accessTokenPayload, { key: "value" }); //changing the value of jwt payload with the same key await SessionFunctions.updateAccessTokenPayload(s.helpers, res.session.handle, { key: "value 2" }); let res3 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); - assert.deepEqual(res3.accessTokenPayload, { key: "value 2" }); + assert.deepStrictEqual(res3.accessTokenPayload, { key: "value 2" }); //passing invalid session handle when updating jwt payload assert(!(await SessionFunctions.updateAccessTokenPayload(s.helpers, "random", { key2: "value2" }))); @@ -954,16 +891,12 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding jwt payload - let res = await SessionFunctions.createNewSession(s.helpers, "", null, {}); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, null, {}); let res2 = (await SessionFunctions.getSessionInformation(s.helpers, res.session.handle)).accessTokenPayload; assert.deepStrictEqual(res2, {}); @@ -1001,11 +934,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -1018,7 +947,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding jwt payload - let res = await SessionFunctions.createNewSession(s.helpers, "", null, {}); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, null, {}); let res2 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); assert.deepStrictEqual(res2.accessTokenPayload, {}); @@ -1056,23 +985,19 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "NONE", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "NONE" })], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; - let response = await SessionFunctions.createNewSession(s.helpers, "", {}, {}); + let response = await SessionFunctions.createNewSession(s.helpers, "", false, {}, {}); //passing anti-csrf token as undefined and anti-csrf check as false let response2 = await SessionFunctions.getSession( s, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), undefined, false, - response.idRefreshToken + true ); assert(response2.session != undefined); assert(Object.keys(response2.session).length === 3); @@ -1080,10 +1005,10 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { //passing anti-csrf token as undefined and anti-csrf check as true let response3 = await SessionFunctions.getSession( s, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), undefined, true, - response.idRefreshToken + true ); assert(response3.session != undefined); assert(Object.keys(response3.session).length === 3); @@ -1102,10 +1027,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - cookieSameSite: "none", - antiCsrf: "NONE", - }), + Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "none", antiCsrf: "NONE" }), ], }); }); @@ -1122,15 +1044,12 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - cookieSameSite: "lax", - antiCsrf: "NONE", - }), + Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "lax", antiCsrf: "NONE" }), ], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; - await SessionFunctions.createNewSession(s.helpers, "", {}, {}); + await SessionFunctions.createNewSession(s.helpers, "", false, {}, {}); }); it("test that anti-csrf disabled and sameSite strict does now throw an error", async function () { @@ -1145,15 +1064,12 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - cookieSameSite: "strict", - antiCsrf: "NONE", - }), + Session.init({ getTokenTransferMethod: () => "cookie", cookieSameSite: "strict", antiCsrf: "NONE" }), ], }); let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; - await SessionFunctions.createNewSession(s.helpers, "", {}, {}); + await SessionFunctions.createNewSession(s.helpers, "", false, {}, {}); }); it("test that custom user id is returned correctly", async function () { @@ -1167,11 +1083,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -1184,7 +1096,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding session data - let res = await SessionFunctions.createNewSession(s.helpers, "customuserid", {}, null); + let res = await SessionFunctions.createNewSession(s.helpers, "customuserid", false, {}, null); let res2 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); @@ -1202,11 +1114,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -1219,7 +1127,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding session data - let res = await SessionFunctions.createNewSession(s.helpers, "", {}, null); + let res = await SessionFunctions.createNewSession(s.helpers, "", false, {}, null); let res2 = await SessionFunctions.getSessionInformation(s.helpers, res.session.handle); assert(typeof res2.status === "string"); @@ -1242,11 +1150,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -1259,7 +1163,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { let s = SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl; //adding session data - let res = await SessionFunctions.createNewSession(s.helpers, "someid", {}, null); + let res = await SessionFunctions.createNewSession(s.helpers, "someid", false, {}, null); let response = await SessionFunctions.revokeAllSessionsForUser(s.helpers, "someid"); assert(response.length === 1); @@ -1280,6 +1184,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -1295,7 +1200,7 @@ describe(`session: ${printPath("[test/session.test.js]")}`, function () { ], }); - const session = await Session.createNewSession(mockResponse(), "testId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "testId"); const data = await session.getSessionData(); diff --git a/test/session/claims/createNewSession.test.js b/test/session/claims/createNewSession.test.js index 759eabc2c..18917cbd8 100644 --- a/test/session/claims/createNewSession.test.js +++ b/test/session/claims/createNewSession.test.js @@ -12,7 +12,7 @@ * License for the specific language governing permissions and limitations * under the License. */ -const { printPath, setupST, startST, killAllST, cleanST, mockResponse } = require("../../utils"); +const { printPath, setupST, startST, killAllST, cleanST, mockResponse, mockRequest } = require("../../utils"); const assert = require("assert"); const { ProcessState } = require("../../../lib/build/processState"); const SuperTokens = require("../../.."); @@ -48,6 +48,7 @@ describe(`sessionClaims/createNewSession: ${printPath("[test/session/claims/crea }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -71,7 +72,7 @@ describe(`sessionClaims/createNewSession: ${printPath("[test/session/claims/crea return; } const response = mockResponse(); - const res = await Session.createNewSession(response, "someId"); + const res = await Session.createNewSession(mockRequest(), response, "someId"); const payload = res.getAccessTokenPayload(); assert.equal(Object.keys(payload).length, 1); @@ -93,6 +94,7 @@ describe(`sessionClaims/createNewSession: ${printPath("[test/session/claims/crea }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -120,7 +122,7 @@ describe(`sessionClaims/createNewSession: ${printPath("[test/session/claims/crea return; } const response = mockResponse(); - const res = await Session.createNewSession(response, "someId"); + const res = await Session.createNewSession(mockRequest(), response, "someId"); const payload = res.getAccessTokenPayload(); assert.equal(Object.keys(payload).length, 0); }); @@ -145,6 +147,7 @@ describe(`sessionClaims/createNewSession: ${printPath("[test/session/claims/crea }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -170,7 +173,7 @@ describe(`sessionClaims/createNewSession: ${printPath("[test/session/claims/crea } const includesNullInPayload = maxVersion(apiVersion, "2.14") !== "2.14"; const response = mockResponse(); - const res = await Session.createNewSession(response, "someId", payloadParam); + const res = await Session.createNewSession(mockRequest(), response, "someId", payloadParam); // The passed object should be unchanged assert.strictEqual(Object.keys(payloadParam).length, 1); diff --git a/test/session/claims/fetchAndSetClaim.test.js b/test/session/claims/fetchAndSetClaim.test.js index 3d05b6b22..cf4d0864f 100644 --- a/test/session/claims/fetchAndSetClaim.test.js +++ b/test/session/claims/fetchAndSetClaim.test.js @@ -12,7 +12,7 @@ * License for the specific language governing permissions and limitations * under the License. */ -const { printPath, startST, killAllST, setupST, cleanST, mockResponse } = require("../../utils"); +const { printPath, startST, killAllST, setupST, cleanST, mockResponse, mockRequest } = require("../../utils"); const assert = require("assert"); const { default: SessionClass } = require("../../../lib/build/recipe/session/sessionClass"); const sinon = require("sinon"); @@ -75,11 +75,11 @@ describe(`sessionClaims/fetchAndSetClaim: ${printPath("[test/session/claims/fetc appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); const response = mockResponse(); - const res = await Session.createNewSession(response, "someId"); + const res = await Session.createNewSession(mockRequest(), response, "someId"); await Session.fetchAndSetClaim(res.getHandle(), TrueClaim); diff --git a/test/session/claims/getClaimValue.test.js b/test/session/claims/getClaimValue.test.js index 3e7fda710..e88cfa419 100644 --- a/test/session/claims/getClaimValue.test.js +++ b/test/session/claims/getClaimValue.test.js @@ -12,7 +12,7 @@ * License for the specific language governing permissions and limitations * under the License. */ -const { printPath, startST, killAllST, setupST, cleanST, mockResponse } = require("../../utils"); +const { printPath, startST, killAllST, setupST, cleanST, mockResponse, mockRequest } = require("../../utils"); const assert = require("assert"); const SuperTokens = require("../../.."); const Session = require("../../../recipe/session"); @@ -51,6 +51,7 @@ describe(`sessionClaims/getClaimValue: ${printPath("[test/session/claims/getClai }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -68,7 +69,7 @@ describe(`sessionClaims/getClaimValue: ${printPath("[test/session/claims/getClai }); const response = mockResponse(); - const session = await Session.createNewSession(response, "someId"); + const session = await Session.createNewSession(mockRequest(), response, "someId"); const res = await session.getClaimValue(TrueClaim); assert.equal(res, true); @@ -88,6 +89,7 @@ describe(`sessionClaims/getClaimValue: ${printPath("[test/session/claims/getClai }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -105,7 +107,7 @@ describe(`sessionClaims/getClaimValue: ${printPath("[test/session/claims/getClai }); const response = mockResponse(); - const session = await Session.createNewSession(response, "someId"); + const session = await Session.createNewSession(mockRequest(), response, "someId"); const res = await Session.getClaimValue(session.getHandle(), TrueClaim); assert.deepStrictEqual(res, { @@ -126,7 +128,7 @@ describe(`sessionClaims/getClaimValue: ${printPath("[test/session/claims/getClai appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert.deepStrictEqual(await Session.getClaimValue("asfd", TrueClaim), { diff --git a/test/session/claims/removeClaim.test.js b/test/session/claims/removeClaim.test.js index cde3a2761..9dd9e68b6 100644 --- a/test/session/claims/removeClaim.test.js +++ b/test/session/claims/removeClaim.test.js @@ -12,7 +12,7 @@ * License for the specific language governing permissions and limitations * under the License. */ -const { printPath, startST, killAllST, setupST, cleanST, mockResponse } = require("../../utils"); +const { printPath, startST, killAllST, setupST, cleanST, mockResponse, mockRequest } = require("../../utils"); const assert = require("assert"); const SuperTokens = require("../../.."); const Session = require("../../../recipe/session"); @@ -62,6 +62,7 @@ describe(`sessionClaims/removeClaim: ${printPath("[test/session/claims/removeCla }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -79,7 +80,7 @@ describe(`sessionClaims/removeClaim: ${printPath("[test/session/claims/removeCla }); const response = mockResponse(); - const res = await Session.createNewSession(response, "someId"); + const res = await Session.createNewSession(mockRequest(), response, "someId"); const payload = res.getAccessTokenPayload(); assert.equal(Object.keys(payload).length, 1); @@ -107,6 +108,7 @@ describe(`sessionClaims/removeClaim: ${printPath("[test/session/claims/removeCla }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -124,7 +126,7 @@ describe(`sessionClaims/removeClaim: ${printPath("[test/session/claims/removeCla }); const response = mockResponse(); - const session = await Session.createNewSession(response, "someId"); + const session = await Session.createNewSession(mockRequest(), response, "someId"); const payload = session.getAccessTokenPayload(); assert.equal(Object.keys(payload).length, 1); @@ -153,6 +155,7 @@ describe(`sessionClaims/removeClaim: ${printPath("[test/session/claims/removeCla }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, diff --git a/test/session/claims/setClaimValue.test.js b/test/session/claims/setClaimValue.test.js index 16506c019..cee0e94e8 100644 --- a/test/session/claims/setClaimValue.test.js +++ b/test/session/claims/setClaimValue.test.js @@ -12,7 +12,7 @@ * License for the specific language governing permissions and limitations * under the License. */ -const { printPath, startST, killAllST, setupST, cleanST, mockResponse } = require("../../utils"); +const { printPath, startST, killAllST, setupST, cleanST, mockResponse, mockRequest } = require("../../utils"); const assert = require("assert"); const SuperTokens = require("../../.."); const Session = require("../../../recipe/session"); @@ -69,6 +69,7 @@ describe(`sessionClaims/setClaimValue: ${printPath("[test/session/claims/setClai }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -86,7 +87,7 @@ describe(`sessionClaims/setClaimValue: ${printPath("[test/session/claims/setClai }); const response = mockResponse(); - const res = await Session.createNewSession(response, "someId"); + const res = await Session.createNewSession(mockRequest(), response, "someId"); const payload = res.getAccessTokenPayload(); assert.equal(Object.keys(payload).length, 1); @@ -117,6 +118,7 @@ describe(`sessionClaims/setClaimValue: ${printPath("[test/session/claims/setClai }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -134,7 +136,7 @@ describe(`sessionClaims/setClaimValue: ${printPath("[test/session/claims/setClai }); const response = mockResponse(); - const res = await Session.createNewSession(response, "someId"); + const res = await Session.createNewSession(mockRequest(), response, "someId"); const payload = res.getAccessTokenPayload(); assert.equal(Object.keys(payload).length, 1); @@ -163,7 +165,7 @@ describe(`sessionClaims/setClaimValue: ${printPath("[test/session/claims/setClai appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); const res = await Session.setClaimValue("asfd", TrueClaim, false); diff --git a/test/session/claims/validateClaimsForSessionHandle.test.js b/test/session/claims/validateClaimsForSessionHandle.test.js index 45ccd4399..bb736c7e7 100644 --- a/test/session/claims/validateClaimsForSessionHandle.test.js +++ b/test/session/claims/validateClaimsForSessionHandle.test.js @@ -12,7 +12,7 @@ * License for the specific language governing permissions and limitations * under the License. */ -const { printPath, startST, killAllST, setupST, cleanST, mockResponse } = require("../../utils"); +const { printPath, startST, killAllST, setupST, cleanST, mockResponse, mockRequest } = require("../../utils"); const assert = require("assert"); const SuperTokens = require("../../.."); const Session = require("../../../recipe/session"); @@ -53,6 +53,7 @@ describe(`sessionClaims/validateClaimsForSessionHandle: ${printPath( }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -70,7 +71,7 @@ describe(`sessionClaims/validateClaimsForSessionHandle: ${printPath( }); const response = mockResponse(); - const session = await Session.createNewSession(response, "someId"); + const session = await Session.createNewSession(mockRequest(), response, "someId"); const failingValidator = UndefinedClaim.validators.hasValue(true); assert.deepStrictEqual( @@ -106,7 +107,7 @@ describe(`sessionClaims/validateClaimsForSessionHandle: ${printPath( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [Session.init()], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie" })], }); assert.deepStrictEqual(await Session.validateClaimsForSessionHandle("asfd"), { diff --git a/test/session/claims/verifySession.test.js b/test/session/claims/verifySession.test.js index 83066f2ff..6a7197cc7 100644 --- a/test/session/claims/verifySession.test.js +++ b/test/session/claims/verifySession.test.js @@ -56,11 +56,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = getTestApp(); @@ -82,6 +78,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -115,6 +112,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -162,6 +160,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -199,6 +198,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -238,6 +238,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -297,6 +298,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -350,6 +352,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -385,6 +388,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -423,6 +427,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -461,6 +466,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -507,6 +513,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -555,6 +562,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -602,6 +610,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => ({ @@ -638,7 +647,7 @@ describe(`sessionClaims/verifySession: ${printPath("[test/session/claims/verifyS function validateErrorResp(resp, errors) { assert.ok(resp.body); assert.strictEqual(resp.body.message, "invalid claim"); - assert.deepEqual(resp.body.claimValidationErrors, errors); + assert.deepStrictEqual(resp.body.claimValidationErrors, errors); } async function createSession(app, body) { @@ -663,7 +672,7 @@ function testGet(app, info, url, expectedStatus) { return new Promise((resolve, reject) => request(app) .get(url) - .set("Cookie", ["sAccessToken=" + info.accessToken + ";sIdRefreshToken=" + info.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + info.accessToken]) .set("anti-csrf", info.antiCsrf) .expect(expectedStatus) .end((err, res) => { @@ -684,7 +693,7 @@ function getTestApp(endpoints) { app.use(express.json()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "testing-userId", req.body, {}); + await Session.createNewSession(req, res, "testing-userId", req.body, {}); res.status(200).json({ message: true }); }); diff --git a/test/session/claims/withJWT.test.js b/test/session/claims/withJWT.test.js index 277eed934..b10c9fa02 100644 --- a/test/session/claims/withJWT.test.js +++ b/test/session/claims/withJWT.test.js @@ -52,6 +52,7 @@ describe(`sessionClaims/withJWT: ${printPath("[test/session/claims/withJWT.test. }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => ({ ...oI, @@ -82,7 +83,7 @@ describe(`sessionClaims/withJWT: ${printPath("[test/session/claims/withJWT.test. app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", undefined, {}); + let session = await Session.createNewSession(req, res, "userId", undefined, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); diff --git a/test/session/with-jwt/jwt.override.test.js b/test/session/with-jwt/jwt.override.test.js index 323b24374..7da217e01 100644 --- a/test/session/with-jwt/jwt.override.test.js +++ b/test/session/with-jwt/jwt.override.test.js @@ -56,6 +56,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/jwt.override.tes }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { openIdFeature: { @@ -103,7 +104,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/jwt.override.tes app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "", {}, {}); + let session = await Session.createNewSession(req, res, "", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -160,6 +161,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/jwt.override.tes }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { openIdFeature: { diff --git a/test/session/with-jwt/jwtFunctions.test.js b/test/session/with-jwt/jwtFunctions.test.js index 11f039e58..8a78e92f9 100644 --- a/test/session/with-jwt/jwtFunctions.test.js +++ b/test/session/with-jwt/jwtFunctions.test.js @@ -44,18 +44,31 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/jwtFunction }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -109,19 +122,32 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/jwtFunction }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, diff --git a/test/session/with-jwt/session.override.test.js b/test/session/with-jwt/session.override.test.js index d302b0e3b..a414c1724 100644 --- a/test/session/with-jwt/session.override.test.js +++ b/test/session/with-jwt/session.override.test.js @@ -67,6 +67,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", jwt: { enable: true }, override: { @@ -110,7 +111,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -146,15 +147,13 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] assert(res.accessToken !== undefined); assert.strictEqual(session.getAccessToken(), decodeURIComponent(res.accessToken)); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); session = undefined; await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -172,10 +171,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] await new Promise((resolve) => request(app) .post("/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -192,8 +188,6 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] assert(res2.accessToken !== undefined); assert.strictEqual(session.getAccessToken(), decodeURIComponent(res2.accessToken)); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); session = undefined; @@ -201,9 +195,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -226,9 +218,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -244,9 +234,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -260,11 +248,8 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test overriding of sessions functions, error thrown", async function () { @@ -284,6 +269,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", jwt: { enable: true }, override: { @@ -318,7 +304,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] app.post("/create", async (req, res, next) => { try { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); } catch (err) { next(err); @@ -368,6 +354,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", jwt: { enable: true }, override: { @@ -398,7 +385,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -425,14 +412,12 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -447,11 +432,8 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] assert.strictEqual(signoutCalled, true); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test overriding of sessions apis, error thrown", async function () { @@ -470,6 +452,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", jwt: { enable: true }, override: { @@ -502,7 +485,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -536,14 +519,12 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -571,6 +552,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { apis: function (oI) { @@ -596,7 +578,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -618,7 +600,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -645,6 +627,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { apis: function (oI) { @@ -670,7 +653,7 @@ describe(`session: ${printPath("[test/session/with-jwt/session.override.test.js] app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); diff --git a/test/session/with-jwt/sessionClass.test.js b/test/session/with-jwt/sessionClass.test.js index 468a19d88..6fb3e2fb6 100644 --- a/test/session/with-jwt/sessionClass.test.js +++ b/test/session/with-jwt/sessionClass.test.js @@ -51,19 +51,32 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -85,7 +98,7 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); await session.updateAccessTokenPayload({ newKey: "newValue" }); @@ -140,14 +153,14 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { - accessTokenPayload = { - ...accessTokenPayload, + createNewSession: async function (input) { + const accessTokenPayload = { + ...input.accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ ...input, accessTokenPayload }); }, }; }, @@ -169,7 +182,7 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); await session.mergeIntoAccessTokenPayload({ newKey: "newValue" }); @@ -219,18 +232,19 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { - accessTokenPayload = { - ...accessTokenPayload, + createNewSession: async function (input) { + const accessTokenPayload = { + ...input.accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ ...input, accessTokenPayload }); }, }; }, @@ -252,7 +266,7 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); await session.updateAccessTokenPayload(undefined); @@ -307,14 +321,14 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { - accessTokenPayload = { - ...accessTokenPayload, + createNewSession: async function (input) { + const accessTokenPayload = { + ...input.accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ ...input, accessTokenPayload }); }, }; }, @@ -336,7 +350,7 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); await session.fetchAndSetClaim(TrueClaim); @@ -391,14 +405,14 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { - accessTokenPayload = { - ...accessTokenPayload, + createNewSession: async function (input) { + const accessTokenPayload = { + ...input.accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ ...input, accessTokenPayload }); }, }; }, @@ -420,7 +434,7 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); await session.setClaimValue(TrueClaim, false); @@ -475,14 +489,14 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { - accessTokenPayload = { - ...accessTokenPayload, + createNewSession: async function (input) { + const accessTokenPayload = { + ...input.accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ ...input, accessTokenPayload }); }, }; }, @@ -504,7 +518,7 @@ describe(`session-jwt-functions: ${printPath("[test/session/with-jwt/sessionClas app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); await session.setClaimValue(TrueClaim, true); await session.removeClaim(TrueClaim); diff --git a/test/session/with-jwt/withjwt.test.js b/test/session/with-jwt/withjwt.test.js index f84b95b29..e7d045e6d 100644 --- a/test/session/with-jwt/withjwt.test.js +++ b/test/session/with-jwt/withjwt.test.js @@ -63,19 +63,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -97,7 +110,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -144,19 +157,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -178,7 +204,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "", {}, {}); + let session = await Session.createNewSession(req, res, "", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -198,7 +224,11 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] ); let responseInfo = extractInfoFromResponse(createJWTResponse); - let accessTokenExpiryInSeconds = new Date(responseInfo.accessTokenExpiry).getTime() / 1000; + + let accessTokenExpiryInSeconds = + JSON.parse( + Buffer.from(decodeURIComponent(responseInfo.accessToken).split(".")[1], "base64").toString("utf-8") + ).expiryTime / 1000; let sessionHandle = createJWTResponse.body.sessionHandle; let sessionInformation = await Session.getSessionInformation(sessionHandle); @@ -206,8 +236,9 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] let jwtExpiryInSeconds = JSON.parse(Buffer.from(jwtPayload, "base64").toString("utf-8")).exp; let expiryDiff = jwtExpiryInSeconds - accessTokenExpiryInSeconds; - // We check that JWT expiry is 30 seconds more than access token expiry. Accounting for a 5ms skew - assert(27 <= expiryDiff && expiryDiff <= 32); + // We check that JWT expiry is 30 seconds more than access token expiry. Accounting for a 5s skew + assert(27 <= expiryDiff); + assert(expiryDiff <= 32); }); it("Test that when a session is refreshed, the JWT expiry is updated correctly", async function () { @@ -223,19 +254,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -257,7 +301,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -298,10 +342,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] let refreshResponse = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + responseInfo.refreshToken, - "sIdRefreshToken=" + responseInfo.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + responseInfo.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -345,14 +386,14 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { - accessTokenPayload = { - ...accessTokenPayload, + createNewSession: async function (input) { + const accessTokenPayload = { + ...input.accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ ...input, accessTokenPayload }); }, }; }, @@ -374,7 +415,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -430,19 +471,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -464,7 +518,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -519,18 +573,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -552,7 +619,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "", {}, {}); + let session = await Session.createNewSession(req, res, "", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -594,19 +661,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -638,18 +718,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -671,7 +764,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -714,19 +807,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -738,10 +844,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + responseInfo.refreshToken, - "sIdRefreshToken=" + responseInfo.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + responseInfo.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -772,19 +875,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -806,7 +922,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -849,18 +965,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, sub: "customsub", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -882,7 +1011,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -924,19 +1053,32 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customKey: "customValue", customKey2: "customValue2", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -958,7 +1100,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1001,18 +1143,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, iss: "customIss", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1034,7 +1189,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1074,18 +1229,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1107,7 +1275,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1167,18 +1335,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1200,7 +1381,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1236,10 +1417,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + responseInfo.refreshToken, - "sIdRefreshToken=" + responseInfo.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + responseInfo.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1273,18 +1451,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true, propertyNameInAccessTokenPayload: "customPropertyName" }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1306,7 +1497,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1348,18 +1539,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1381,7 +1585,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1412,10 +1616,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] let refreshResponse = await new Promise((resolve) => request(app) .post("/refreshsession") - .set("Cookie", [ - "sRefreshToken=" + responseInfo.refreshToken, - "sIdRefreshToken=" + responseInfo.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + responseInfo.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1445,18 +1646,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1478,7 +1692,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1520,10 +1734,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + responseInfo.refreshToken, - "sIdRefreshToken=" + responseInfo.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + responseInfo.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1554,18 +1765,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1587,7 +1811,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1621,18 +1845,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true, propertyNameInAccessTokenPayload: "jwtProperty" }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1665,18 +1902,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1698,7 +1948,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1733,18 +1983,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true, propertyNameInAccessTokenPayload: "jwtProperty" }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1756,10 +2019,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + responseInfo.refreshToken, - "sIdRefreshToken=" + responseInfo.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + responseInfo.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1794,18 +2054,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1827,7 +2100,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1866,10 +2139,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + responseInfo.refreshToken, - "sIdRefreshToken=" + responseInfo.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + responseInfo.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1905,18 +2175,31 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", jwt: { enable: true }, override: { functions: function (oi) { return { ...oi, - createNewSession: async function ({ res, userId, accessTokenPayload, sessionData }) { + createNewSession: async function ({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }) { accessTokenPayload = { ...accessTokenPayload, customClaim: "customValue", }; - return await oi.createNewSession({ res, userId, accessTokenPayload, sessionData }); + return await oi.createNewSession({ + req, + res, + userId, + accessTokenPayload, + sessionData, + }); }, }; }, @@ -1938,7 +2221,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", {}, {}); + let session = await Session.createNewSession(req, res, "userId", {}, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); @@ -1999,11 +2282,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - jwt: { enable: true }, - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", jwt: { enable: true } })], }); // Only run for version >= 2.9 @@ -2019,7 +2298,7 @@ describe(`session-with-jwt: ${printPath("[test/session/with-jwt/withjwt.test.js] app.use(express.json()); app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "userId", undefined, {}); + let session = await Session.createNewSession(req, res, "userId", undefined, {}); res.status(200).json({ sessionHandle: session.getHandle() }); }); diff --git a/test/sessionAccessTokenSigningKeyUpdate.test.js b/test/sessionAccessTokenSigningKeyUpdate.test.js index 5006678a5..4ac04e95b 100644 --- a/test/sessionAccessTokenSigningKeyUpdate.test.js +++ b/test/sessionAccessTokenSigningKeyUpdate.test.js @@ -31,6 +31,7 @@ let { ProcessState, PROCESS_STATE } = require("../lib/build/processState"); let SuperTokens = require("../"); let Session = require("../recipe/session"); let SessionFunctions = require("../lib/build/recipe/session/sessionFunctions"); +let { parseJWTWithoutSignatureVerification } = require("../lib/build/recipe/session/jwt"); let SessionRecipe = require("../lib/build/recipe/session/recipe").default; const { maxVersion } = require("../lib/build/utils"); const { fail } = require("assert"); @@ -40,7 +41,6 @@ const { fail } = require("assert"); - calling createNewSession twice, should overwrite the first call (in terms of cookies) - calling createNewSession in the case of unauthorised error, should create a proper session - revoking old session after create new session, should not remove new session's cookies. -- check that if idRefreshToken is not passed to express, verify throws UNAUTHORISED - check that Access-Control-Expose-Headers header is being set properly during create, use and destroy session**** only for express */ @@ -70,11 +70,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const currCDIVersion = await Querier.getNewInstanceOrThrowError(undefined).getAPIVersion(); @@ -83,6 +79,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( let response = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -90,10 +87,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), response.antiCsrfToken, true, - response.idRefreshToken.token + true ); let verifyState = await ProcessState.getInstance().waitForEvent( @@ -108,10 +105,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( try { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), response.antiCsrfToken, true, - response.idRefreshToken.token + true ); // Old core versions should throw here because the signing key was updated if (!coreSupportsMultipleSignigKeys) { @@ -137,15 +134,18 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( const response2 = await SessionFunctions.refreshSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, response.refreshToken.token, - response.antiCsrfToken + response.antiCsrfToken, + true, + "cookie", + "cookie" ); await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response2.accessToken.token, + parseJWTWithoutSignatureVerification(response2.accessToken.token), response2.antiCsrfToken, true, - response2.idRefreshToken.token + true ); // We call verify, since refresh does not refresh the signing key info @@ -168,11 +168,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const currCDIVersion = await Querier.getNewInstanceOrThrowError(undefined).getAPIVersion(); @@ -181,6 +177,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( const oldSession = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -188,6 +185,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -200,6 +198,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( const newSession = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -209,10 +208,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - newSession.accessToken.token, + parseJWTWithoutSignatureVerification(newSession.accessToken.token), newSession.antiCsrfToken, true, - newSession.idRefreshToken.token + true ); let verifyState = await ProcessState.getInstance().waitForEvent( @@ -234,10 +233,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( try { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - oldSession.accessToken.token, + parseJWTWithoutSignatureVerification(oldSession.accessToken.token), oldSession.antiCsrfToken, true, - oldSession.idRefreshToken.token + true ); // Old core versions should throw here because the signing key was updated if (!coreSupportsMultipleSignigKeys) { @@ -272,11 +271,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const currCDIVersion = await Querier.getNewInstanceOrThrowError(undefined).getAPIVersion(); @@ -285,6 +280,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( let response2 = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -294,6 +290,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( let response = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -301,10 +298,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), response.antiCsrfToken, true, - response.idRefreshToken.token + true ); let verifyState = await ProcessState.getInstance().waitForEvent( @@ -320,10 +317,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( try { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response2.accessToken.token, + parseJWTWithoutSignatureVerification(response2.accessToken.token), response2.antiCsrfToken, true, - response2.idRefreshToken.token + true ); // Old core versions should throw here because the signing key was updated if (!coreSupportsMultipleSignigKeys) { @@ -358,11 +355,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const currCDIVersion = await Querier.getNewInstanceOrThrowError(undefined).getAPIVersion(); @@ -371,6 +364,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( let response2 = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -384,6 +378,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( let response = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -395,10 +390,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response.accessToken.token, + parseJWTWithoutSignatureVerification(response.accessToken.token), response.antiCsrfToken, true, - response.idRefreshToken.token + true ); let verifyState = await ProcessState.getInstance().waitForEvent( @@ -418,10 +413,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( try { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - response2.accessToken.token, + parseJWTWithoutSignatureVerification(response2.accessToken.token), response2.antiCsrfToken, true, - response2.idRefreshToken.token + true ); // Old core versions should throw here because the signing key was updated @@ -457,16 +452,13 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let session = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -474,10 +466,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - session.accessToken.token, + parseJWTWithoutSignatureVerification(session.accessToken.token), session.antiCsrfToken, true, - session.idRefreshToken.token + true ); let verifyState3 = await ProcessState.getInstance().waitForEvent( @@ -497,10 +489,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - session.accessToken.token, + parseJWTWithoutSignatureVerification(session.accessToken.token), session.antiCsrfToken, true, - session.idRefreshToken.token + true ); let verifyState3 = await ProcessState.getInstance().waitForEvent( @@ -519,6 +511,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( let session2 = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -532,10 +525,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( // jwt signing key has not expired, according to the SDK, so it should succeed await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - session2.accessToken.token, + parseJWTWithoutSignatureVerification(session2.accessToken.token), session2.antiCsrfToken, true, - session2.idRefreshToken.token + true ); let verifyState3 = await ProcessState.getInstance().waitForEvent( @@ -552,10 +545,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( // jwt signing key has not expired, according to the SDK, so it should succeed await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - session2.accessToken.token, + parseJWTWithoutSignatureVerification(session2.accessToken.token), session2.antiCsrfToken, true, - session2.idRefreshToken.token + true ); let verifyState3 = await ProcessState.getInstance().waitForEvent( @@ -570,10 +563,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( try { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - session.accessToken.token, + parseJWTWithoutSignatureVerification(session.accessToken.token), session.antiCsrfToken, true, - session.idRefreshToken.token + true ); fail(); } catch (err) { @@ -603,11 +596,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); let q = Querier.getNewInstanceOrThrowError(undefined); @@ -621,6 +610,7 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( let session = await SessionFunctions.createNewSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, "", + false, {}, {} ); @@ -628,10 +618,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - session.accessToken.token, + parseJWTWithoutSignatureVerification(session.accessToken.token), session.antiCsrfToken, true, - session.idRefreshToken.token + true ); let verifyState3 = await ProcessState.getInstance().waitForEvent( @@ -648,10 +638,10 @@ describe(`sessionAccessTokenSigningKeyUpdate: ${printPath( { await SessionFunctions.getSession( SessionRecipe.getInstanceOrThrowError().recipeInterfaceImpl.helpers, - session.accessToken.token, + parseJWTWithoutSignatureVerification(session.accessToken.token), session.antiCsrfToken, true, - session.idRefreshToken.token + true ); let verifyState3 = await ProcessState.getInstance().waitForEvent( diff --git a/test/sessionExpress.test.js b/test/sessionExpress.test.js index 7c1938549..4a25c75b7 100644 --- a/test/sessionExpress.test.js +++ b/test/sessionExpress.test.js @@ -20,6 +20,7 @@ const { cleanST, extractInfoFromResponse, setKeyValueInConfig, + delay, } = require("./utils"); let assert = require("assert"); const express = require("express"); @@ -59,6 +60,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -75,7 +77,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -83,6 +85,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/create") + .set("st-auth-mode", "cookie") .expect(200) .end((err, res) => { if (err) { @@ -97,7 +100,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -124,6 +127,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", override: { apis: (oI) => { return { @@ -140,7 +144,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -148,6 +152,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/create") + .set("st-auth-mode", "cookie") .expect(200) .end((err, res) => { if (err) { @@ -188,6 +193,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", errorHandlers: { onTokenTheftDetected: async (sessionHandle, userId, request, response) => { response.sendJSONResponse({ @@ -202,12 +208,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); app.post("/session/verify", async (req, res) => { - await Session.getSession(req, res, true); + await Session.getSession(req, res); res.status(200).send(""); }); @@ -241,10 +247,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -259,9 +262,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { resolve(); @@ -271,7 +272,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res3 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -281,20 +282,16 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(res3.body.success, true); + assert.strictEqual(res3.body.success, true); let cookies = extractInfoFromResponse(res3); - assert.deepEqual(cookies.antiCsrf, undefined); - assert.deepEqual(cookies.accessToken, ""); - assert.deepEqual(cookies.refreshToken, ""); - assert.deepEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(cookies.idRefreshTokenFromCookie, ""); - assert.deepEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(cookies.antiCsrf, undefined); + assert.strictEqual(cookies.accessToken, ""); + assert.strictEqual(cookies.refreshToken, ""); + assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert(cookies.accessTokenDomain === undefined); assert(cookies.refreshTokenDomain === undefined); - assert(cookies.idRefreshTokenDomain === undefined); }); //- check for token theft detection @@ -309,11 +306,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); @@ -321,7 +314,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -350,10 +343,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -368,9 +358,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { resolve(); @@ -380,7 +368,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res3 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -391,17 +379,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }) ); assert(res3.status === 401); - assert.deepEqual(res3.text, '{"message":"token theft detected"}'); + assert.deepStrictEqual(res3.text, '{"message":"token theft detected"}'); let cookies = extractInfoFromResponse(res3); - assert.deepEqual(cookies.antiCsrf, undefined); - assert.deepEqual(cookies.accessToken, ""); - assert.deepEqual(cookies.refreshToken, ""); - assert.deepEqual(cookies.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(cookies.idRefreshTokenFromCookie, ""); - assert.deepEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(cookies.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(cookies.antiCsrf, undefined); + assert.strictEqual(cookies.accessToken, ""); + assert.strictEqual(cookies.refreshToken, ""); + assert.strictEqual(cookies.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(cookies.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); }); //check basic usage of session @@ -416,22 +401,18 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); app.post("/session/verify", async (req, res) => { - await Session.getSession(req, res, true); + await Session.getSession(req, res); res.status(200).send(""); }); app.post("/auth/session/refresh", async (req, res) => { @@ -439,7 +420,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi res.status(200).send(""); }); app.post("/session/revoke", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.revokeSession(); res.status(200).send(""); }); @@ -461,14 +442,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -486,10 +465,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -503,17 +479,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -533,9 +505,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -551,9 +521,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -567,14 +535,11 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); - it("test signout API works", async function () { + it("test basic usage of express sessions with headers", async function () { await startST(); SuperTokens.init({ supertokens: { @@ -588,14 +553,168 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi recipeList: [ Session.init({ antiCsrf: "VIA_TOKEN", + getTokenTransferMethod: () => "header", }), ], }); + + const app = express(); + + app.post("/create", async (req, res) => { + await Session.createNewSession(req, res, "", {}, {}); + res.status(200).send(""); + }); + + app.post("/session/verify", async (req, res) => { + await Session.getSession(req, res); + res.status(200).send(""); + }); + app.post("/auth/session/refresh", async (req, res) => { + await Session.refreshSession(req, res); + res.status(200).send(""); + }); + app.post("/session/revoke", async (req, res) => { + let session = await Session.getSession(req, res); + await session.revokeSession(); + res.status(200).send(""); + }); + app.use(errorHandler()); + + let res = extractInfoFromResponse( + await new Promise((resolve) => + request(app) + .post("/create") + .expect(200) + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ) + ); + + assert(res.antiCsrf === undefined); + + assert.ok(res.accessTokenFromHeader); + assert.strictEqual(res.accessToken, undefined); + + assert.ok(res.refreshTokenFromHeader); + assert.strictEqual(res.refreshToken, undefined); + + await new Promise((resolve) => + request(app) + .post("/session/verify") + .set("Authorization", `Bearer ${res.accessTokenFromHeader}`) + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ); + + let verifyState3 = await ProcessState.getInstance().waitForEvent(PROCESS_STATE.CALLING_SERVICE_IN_VERIFY, 1500); + assert(verifyState3 === undefined); + + let res2 = extractInfoFromResponse( + await new Promise((resolve) => + request(app) + .post("/auth/session/refresh") + .set("Authorization", `Bearer ${res.refreshTokenFromHeader}`) + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ) + ); + + assert(res2.antiCsrf === undefined); + assert.ok(res2.accessTokenFromHeader); + assert.strictEqual(res2.accessToken, undefined); + + assert.ok(res2.refreshTokenFromHeader); + assert.strictEqual(res2.refreshToken, undefined); + + let res3 = extractInfoFromResponse( + await new Promise((resolve) => + request(app) + .post("/session/verify") + .set("Authorization", `Bearer ${res2.accessTokenFromHeader}`) + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ) + ); + let verifyState = await ProcessState.getInstance().waitForEvent(PROCESS_STATE.CALLING_SERVICE_IN_VERIFY); + assert(verifyState !== undefined); + assert(res3.accessTokenFromHeader !== undefined); + + ProcessState.getInstance().reset(); + + await new Promise((resolve) => + request(app) + .post("/session/verify") + .set("Authorization", `Bearer ${res3.accessTokenFromHeader}`) + + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ); + let verifyState2 = await ProcessState.getInstance().waitForEvent(PROCESS_STATE.CALLING_SERVICE_IN_VERIFY, 1000); + assert(verifyState2 === undefined); + + let sessionRevokedResponse = await new Promise((resolve) => + request(app) + .post("/session/revoke") + .set("Authorization", `Bearer ${res3.accessTokenFromHeader}`) + + .expect(200) + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + ); + let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); + + assert.strictEqual(sessionRevokedResponseExtracted.accessTokenFromHeader, ""); + assert.strictEqual(sessionRevokedResponseExtracted.refreshTokenFromHeader, ""); + }); + + it("test signout API works", async function () { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io", + }, + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], + }); const app = express(); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -617,7 +736,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -631,11 +750,8 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test signout API works if even session is deleted on the backend after creation", async function () { @@ -649,11 +765,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.use(middleware()); @@ -661,7 +773,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionHandle = ""; app.post("/create", async (req, res) => { - let session = await Session.createNewSession(res, "", {}, {}); + let session = await Session.createNewSession(req, res, "", {}, {}); sessionHandle = session.getHandle(); res.status(200).send(""); }); @@ -686,7 +798,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -700,11 +812,8 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); //check basic usage of session @@ -721,11 +830,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi websiteDomain: "supertokens.io", apiBasePath: "/", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); @@ -733,7 +838,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -766,14 +871,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -791,10 +894,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -808,17 +908,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res2.accessToken !== undefined); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); let res3 = extractInfoFromResponse( await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -838,9 +934,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -856,9 +950,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -872,11 +964,8 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); //check session verify for with / without anti-csrf present @@ -891,21 +980,17 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); res.status(200).send(""); }); app.post("/session/verify", async (req, res) => { - let sessionResponse = await Session.getSession(req, res, true); + let sessionResponse = await Session.getSession(req, res); res.status(200).json({ userId: sessionResponse.userId }); }); @@ -932,7 +1017,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -942,12 +1027,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(res2.body.userId, "id1"); + assert.strictEqual(res2.body.userId, "id1"); let res3 = await new Promise((resolve) => request(app) .post("/session/verifyAntiCsrfFalse") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -957,7 +1042,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(res3.body.userId, "id1"); + assert.strictEqual(res3.body.userId, "id1"); }); // check session verify for with / without anti-csrf present @@ -972,17 +1057,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); res.status(200).send(""); }); @@ -1020,7 +1101,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let response2 = await new Promise((resolve) => request(app) .post("/session/verifyAntiCsrfFalse") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1029,12 +1110,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(response2.body.userId, "id1"); + assert.strictEqual(response2.body.userId, "id1"); let response = await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1043,7 +1124,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(response.body.success, true); + assert.strictEqual(response.body.success, true); }); //check revoking session(s)** @@ -1058,29 +1139,25 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); app.post("/usercreate", async (req, res) => { - await Session.createNewSession(res, "someUniqueUserId", {}, {}); + await Session.createNewSession(req, res, "someUniqueUserId", {}, {}); res.status(200).send(""); }); app.post("/session/revoke", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.revokeSession(); res.status(200).send(""); }); app.post("/session/revokeUserid", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await Session.revokeAllSessionsForUser(session.getUserId()); res.status("200").send(""); }); @@ -1108,9 +1185,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1124,11 +1199,8 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); await new Promise((resolve) => request(app) @@ -1160,12 +1232,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/revokeUserid") - .set("Cookie", [ - "sAccessToken=" + - userCreateResponse.accessToken + - ";sIdRefreshToken=" + - userCreateResponse.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + userCreateResponse.accessToken]) .set("anti-csrf", userCreateResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -1203,31 +1270,27 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); app.post("/updateSessionData", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.updateSessionData({ key: "value" }); res.status(200).send(""); }); app.post("/getSessionData", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); let sessionData = await session.getSessionData(); res.status(200).json(sessionData); }); app.post("/updateSessionData2", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.updateSessionData(null); res.status(200).send(""); }); @@ -1256,9 +1319,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/updateSessionData") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1274,9 +1335,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let response2 = await new Promise((resolve) => request(app) .post("/getSessionData") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1289,15 +1348,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi ); //check that the session data returned is valid - assert.deepEqual(response2.body.key, "value"); + assert.strictEqual(response2.body.key, "value"); // change the value of the inserted session data await new Promise((resolve) => request(app) .post("/updateSessionData2") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1312,9 +1369,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi response2 = await new Promise((resolve) => request(app) .post("/getSessionData") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1333,9 +1388,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let invalidSessionResponse = await new Promise((resolve) => request(app) .post("/updateSessionDataInvalidSessionHandle") - .set("Cookie", [ - "sAccessToken=" + response.accessToken + ";sIdRefreshToken=" + response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1346,7 +1399,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(invalidSessionResponse.body.success, true); + assert.strictEqual(invalidSessionResponse.body.success, true); }); //check manipulating jwt payload @@ -1361,19 +1414,15 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "user1", {}, {}); + await Session.createNewSession(req, res, "user1", {}, {}); res.status(200).send(""); }); app.post("/updateAccessTokenPayload", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); let accessTokenBefore = session.accessToken; await session.updateAccessTokenPayload({ key: "value" }); let accessTokenAfter = session.accessToken; @@ -1385,13 +1434,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi res.status(200).send(""); }); app.post("/getAccessTokenPayload", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); let jwtPayload = session.getAccessTokenPayload(); res.status(200).json(jwtPayload); }); app.post("/updateAccessTokenPayload2", async (req, res) => { - let session = await Session.getSession(req, res, true); + let session = await Session.getSession(req, res); await session.updateAccessTokenPayload(null); res.status(200).send(""); }); @@ -1420,19 +1469,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let frontendInfo = JSON.parse(new Buffer.from(response.frontToken, "base64").toString()); assert(frontendInfo.uid === "user1"); - assert.deepEqual(frontendInfo.up, {}); + assert.deepStrictEqual(frontendInfo.up, {}); //call the updateAccessTokenPayload api to add jwt payload let updatedResponse = extractInfoFromResponse( await new Promise((resolve) => request(app) .post("/updateAccessTokenPayload") - .set("Cookie", [ - "sAccessToken=" + - response.accessToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1447,18 +1491,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi frontendInfo = JSON.parse(new Buffer.from(updatedResponse.frontToken, "base64").toString()); assert(frontendInfo.uid === "user1"); - assert.deepEqual(frontendInfo.up, { key: "value" }); + assert.deepStrictEqual(frontendInfo.up, { key: "value" }); //call the getAccessTokenPayload api to get jwt payload let response2 = await new Promise((resolve) => request(app) .post("/getAccessTokenPayload") - .set("Cookie", [ - "sAccessToken=" + - updatedResponse.accessToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + updatedResponse.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1470,19 +1509,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }) ); //check that the jwt payload returned is valid - assert.deepEqual(response2.body.key, "value"); + assert.strictEqual(response2.body.key, "value"); // refresh session response2 = extractInfoFromResponse( await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + - response.refreshToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + response.refreshToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1497,19 +1531,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi frontendInfo = JSON.parse(new Buffer.from(response2.frontToken, "base64").toString()); assert(frontendInfo.uid === "user1"); - assert.deepEqual(frontendInfo.up, { key: "value" }); + assert.deepStrictEqual(frontendInfo.up, { key: "value" }); // change the value of the inserted jwt payload let updatedResponse2 = extractInfoFromResponse( await new Promise((resolve) => request(app) .post("/updateAccessTokenPayload2") - .set("Cookie", [ - "sAccessToken=" + - response2.accessToken + - ";sIdRefreshToken=" + - response2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + response2.accessToken]) .set("anti-csrf", response2.antiCsrf) .expect(200) .end((err, res) => { @@ -1530,12 +1559,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi response2 = await new Promise((resolve) => request(app) .post("/getAccessTokenPayload") - .set("Cookie", [ - "sAccessToken=" + - updatedResponse2.accessToken + - ";sIdRefreshToken=" + - response2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + updatedResponse2.accessToken]) .set("anti-csrf", response2.antiCsrf) .expect(200) .end((err, res) => { @@ -1553,12 +1577,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let invalidSessionResponse = await new Promise((resolve) => request(app) .post("/updateAccessTokenPayloadInvalidSessionHandle") - .set("Cookie", [ - "sAccessToken=" + - updatedResponse2.accessToken + - ";sIdRefreshToken=" + - response.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + updatedResponse2.accessToken]) .set("anti-csrf", response.antiCsrf) .expect(200) .end((err, res) => { @@ -1569,7 +1588,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(invalidSessionResponse.body.success, true); + assert.strictEqual(invalidSessionResponse.body.success, true); }); // test with existing header params being there and that the lib appends to those and not overrides those @@ -1584,17 +1603,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/create", async (req, res) => { res.header("testHeader", "testValue"); res.header("Access-Control-Expose-Headers", "customValue"); - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -1612,18 +1627,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(response.headers.testheader, "testValue"); - assert.deepEqual( - response.headers["access-control-expose-headers"], - "customValue, front-token, id-refresh-token, anti-csrf" - ); + assert.strictEqual(response.headers.testheader, "testValue"); + assert.deepEqual(response.headers["access-control-expose-headers"], "customValue, front-token, anti-csrf"); //normal session headers let extractInfo = extractInfoFromResponse(response); assert(extractInfo.accessToken !== undefined); assert(extractInfo.refreshToken != undefined); - assert(extractInfo.idRefreshTokenFromCookie !== undefined); - assert(extractInfo.idRefreshTokenFromHeader !== undefined); assert(extractInfo.antiCsrf !== undefined); }); @@ -1639,21 +1649,17 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "NONE", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "NONE" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); res.status(200).send(""); }); app.post("/session/verify", async (req, res) => { - let sessionResponse = await Session.getSession(req, res, true); + let sessionResponse = await Session.getSession(req, res); res.status(200).json({ userId: sessionResponse.userId }); }); app.post("/session/verifyAntiCsrfFalse", async (req, res) => { @@ -1679,7 +1685,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1688,12 +1694,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(res2.body.userId, "id1"); + assert.strictEqual(res2.body.userId, "id1"); let res3 = await new Promise((resolve) => request(app) .post("/session/verifyAntiCsrfFalse") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1702,7 +1708,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi } }) ); - assert.deepEqual(res3.body.userId, "id1"); + assert.strictEqual(res3.body.userId, "id1"); }); it("test that getSession does not clear cookies if a session does not exist in the first place", async function () { @@ -1716,18 +1722,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.post("/session/verify", async (req, res) => { try { - await Session.getSession(req, res, true); + await Session.getSession(req, res); } catch (err) { if (err.type === Session.Error.UNAUTHORISED) { res.status(200).json({ success: true }); @@ -1749,17 +1751,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }) ); - assert.deepEqual(res.body.success, true); + assert.strictEqual(res.body.success, true); let cookies = extractInfoFromResponse(res); - assert.deepEqual(cookies.antiCsrf, undefined); - assert.deepEqual(cookies.accessToken, undefined); - assert.deepEqual(cookies.refreshToken, undefined); - assert.deepEqual(cookies.idRefreshTokenFromHeader, undefined); - assert.deepEqual(cookies.idRefreshTokenFromCookie, undefined); - assert.deepEqual(cookies.accessTokenExpiry, undefined); - assert.deepEqual(cookies.idRefreshTokenExpiry, undefined); - assert.deepEqual(cookies.refreshTokenExpiry, undefined); + assert.strictEqual(cookies.antiCsrf, undefined); + assert.strictEqual(cookies.accessToken, undefined); + assert.strictEqual(cookies.refreshToken, undefined); + assert.strictEqual(cookies.accessTokenExpiry, undefined); + assert.strictEqual(cookies.refreshTokenExpiry, undefined); }); it("test that refreshSession does not clear cookies if a session does not exist in the first place", async function () { @@ -1773,11 +1772,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); @@ -1806,17 +1801,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }) ); - assert.deepEqual(res.body.success, true); + assert.strictEqual(res.body.success, true); let cookies = extractInfoFromResponse(res); - assert.deepEqual(cookies.antiCsrf, undefined); - assert.deepEqual(cookies.accessToken, undefined); - assert.deepEqual(cookies.refreshToken, undefined); - assert.deepEqual(cookies.idRefreshTokenFromHeader, undefined); - assert.deepEqual(cookies.idRefreshTokenFromCookie, undefined); - assert.deepEqual(cookies.accessTokenExpiry, undefined); - assert.deepEqual(cookies.idRefreshTokenExpiry, undefined); - assert.deepEqual(cookies.refreshTokenExpiry, undefined); + assert.strictEqual(cookies.antiCsrf, undefined); + assert.strictEqual(cookies.accessToken, undefined); + assert.strictEqual(cookies.refreshToken, undefined); + assert.strictEqual(cookies.accessTokenExpiry, undefined); + assert.strictEqual(cookies.refreshTokenExpiry, undefined); }); it("test that when anti-csrf is enabled with custom header, and we don't provide that in verifySession, we get try refresh token", async function () { @@ -1830,16 +1822,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_CUSTOM_HEADER", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_CUSTOM_HEADER" })], }); const app = express(); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); res.status(200).send(""); }); @@ -1873,9 +1861,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1890,9 +1876,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res3 = await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("rid", "session") .end((err, res) => { if (err) { @@ -1909,9 +1893,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/session/verifyAntiCsrfFalse") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -1925,9 +1907,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res3 = await new Promise((resolve) => request(app) .post("/session/verifyAntiCsrfFalse") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("rid", "session") .end((err, res) => { if (err) { @@ -1952,17 +1932,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_CUSTOM_HEADER", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_CUSTOM_HEADER" })], }); const app = express(); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -1987,10 +1963,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -2008,10 +1981,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("rid", "session") .end((err, res) => { if (err) { @@ -2034,7 +2004,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); + await Session.createNewSession(req, res, "id1", {}, {}); res.status(200).send(""); }); @@ -2058,11 +2028,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_CUSTOM_HEADER", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_CUSTOM_HEADER" })], }); let res = extractInfoFromResponse( @@ -2084,9 +2050,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -2101,9 +2065,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res3 = await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("rid", "session") .end((err, res) => { if (err) { @@ -2136,6 +2098,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => { @@ -2171,7 +2134,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -2207,15 +2170,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert.strictEqual(session.getAccessToken(), decodeURIComponent(res.accessToken)); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); session = undefined; await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -2233,10 +2194,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -2253,8 +2211,6 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res2.accessToken !== undefined); assert.strictEqual(session.getAccessToken(), decodeURIComponent(res2.accessToken)); assert(res2.antiCsrf !== undefined); - assert(res2.idRefreshTokenFromCookie !== undefined); - assert(res2.idRefreshTokenFromHeader !== undefined); assert(res2.refreshToken !== undefined); session = undefined; @@ -2262,9 +2218,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -2287,9 +2241,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/session/verify") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -2305,9 +2257,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/session/revoke") - .set("Cookie", [ - "sAccessToken=" + res3.accessToken + ";sIdRefreshToken=" + res3.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res3.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -2321,11 +2271,8 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let sessionRevokedResponseExtracted = extractInfoFromResponse(sessionRevokedResponse); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test overriding of sessions apis", async function () { @@ -2344,6 +2291,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { apis: (oI) => { @@ -2366,7 +2314,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -2393,14 +2341,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -2415,11 +2361,8 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert.strictEqual(signoutCalled, true); assert(sessionRevokedResponseExtracted.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(sessionRevokedResponseExtracted.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(sessionRevokedResponseExtracted.accessToken === ""); assert(sessionRevokedResponseExtracted.refreshToken === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromCookie === ""); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); }); it("test overriding of sessions functions, error thrown", async function () { @@ -2439,6 +2382,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { functions: (oI) => { @@ -2465,7 +2409,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.post("/create", async (req, res, next) => { try { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); } catch (err) { next(err); @@ -2515,6 +2459,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", override: { apis: (oI) => { @@ -2539,7 +2484,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -2573,14 +2518,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let sessionRevokedResponse = await new Promise((resolve) => request(app) .post("/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -2606,17 +2549,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_CUSTOM_HEADER", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_CUSTOM_HEADER" })], }); const app = express(); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -2641,10 +2580,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -2657,7 +2593,6 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert.deepStrictEqual(res2.status, 401); assert.deepStrictEqual(res2.text, '{"message":"unauthorised"}'); let sessionRevokedResponseExtracted = extractInfoFromResponse(res2); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader !== "remove"); } }); @@ -2672,17 +2607,13 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], + recipeList: [Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" })], }); const app = express(); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -2707,10 +2638,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .end((err, res) => { if (err) { resolve(undefined); @@ -2722,169 +2650,9 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert.deepStrictEqual(res2.status, 401); assert.deepStrictEqual(res2.text, '{"message":"unauthorised"}'); - let sessionRevokedResponseExtracted = extractInfoFromResponse(res2); - assert(sessionRevokedResponseExtracted.idRefreshTokenFromHeader === "remove"); } }); - // check session verify for with session optional and no rid pass - it("check session verify for with session optional and no rid pass", async function () { - await startST(); - SuperTokens.init({ - supertokens: { - connectionURI: "http://localhost:8080", - }, - appInfo: { - apiDomain: "api.supertokens.io", - appName: "SuperTokens", - websiteDomain: "supertokens.io", - }, - recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), - ], - }); - - const app = express(); - - app.post("/create", async (req, res) => { - await Session.createNewSession(res, "id1", {}, {}); - res.status(200).send(""); - }); - - app.post( - "/session/verify", - verifySession({ - sessionRequired: false, - antiCsrfCheck: false, - }), - async (req, res) => { - res.status(200).json({ success: true, session: req.session !== undefined }); - } - ); - - app.get( - "/session/verify", - verifySession({ - sessionRequired: false, - antiCsrfCheck: false, - }), - async (req, res) => { - res.status(200).json({ success: true, session: req.session !== undefined }); - } - ); - - app.use(errorHandler()); - - let res = extractInfoFromResponse( - await new Promise((resolve) => - request(app) - .post("/create") - .expect(200) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - ) - ); - - let response = await new Promise((resolve) => - request(app) - .post("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - ); - assert.strictEqual(response.body.success, true); - assert.strictEqual(response.body.session, true); - - response = await new Promise((resolve) => - request(app) - .post("/session/verify") - .set("Cookie", ["sIdRefreshToken=" + res.idRefreshTokenFromCookie]) - .set("rid", "session") - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - ); - assert.strictEqual(response.body.message, "try refresh token"); - assert.strictEqual(response.status, 401); - - response = await new Promise((resolve) => - request(app) - .post("/session/verify") - .set("Cookie", ["sIdRefreshToken=" + res.idRefreshTokenFromCookie]) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - ); - assert.strictEqual(response.body.success, true); - assert.strictEqual(response.body.session, false); - - response = await new Promise((resolve) => - request(app) - .get("/session/verify") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - ); - assert.strictEqual(response.body.success, true); - assert.strictEqual(response.body.session, true); - - response = await new Promise((resolve) => - request(app) - .get("/session/verify") - .set("Cookie", ["sIdRefreshToken=" + res.idRefreshTokenFromCookie]) - .set("rid", "session") - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - ); - assert.strictEqual(response.body.message, "try refresh token"); - assert.strictEqual(response.status, 401); - - response = await new Promise((resolve) => - request(app) - .get("/session/verify") - .set("Cookie", ["sIdRefreshToken=" + res.idRefreshTokenFromCookie]) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - ); - assert.strictEqual(response.body.message, "try refresh token"); - assert.strictEqual(response.status, 401); - }); - it("test session error handler overriding", async function () { await startST(); let testpass = false; @@ -2899,6 +2667,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, recipeList: [ Session.init({ + getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN", errorHandlers: { onUnauthorised: async (message, request, response) => { @@ -2919,7 +2688,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.post("/session/verify", async (req, res, next) => { try { - await Session.getSession(req, res, true); + await Session.getSession(req, res); res.status(200).send(""); } catch (err) { next(err); @@ -2987,7 +2756,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -2997,6 +2766,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/create") + .set("st-auth-mode", "cookie") .expect(200) .end((err, res) => { if (err) { @@ -3008,16 +2778,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi ) ); - assert(res.accessToken !== undefined); - assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); - assert(res.refreshToken !== undefined); + assert.notStrictEqual(res.accessToken, undefined); + assert.notStrictEqual(res.antiCsrf, undefined); + assert.notStrictEqual(res.refreshToken, undefined); let resp = await new Promise((resolve) => request(app) .post("/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -3032,18 +2800,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = extractInfoFromResponse(resp); - assert(res2.antiCsrf.length > 1); assert.deepEqual(res2.accessToken, ""); assert.deepEqual(res2.refreshToken, ""); - assert.deepEqual(res2.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res2.idRefreshTokenFromCookie, ""); assert.deepEqual(res2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res2.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.deepEqual(res2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert(res2.accessTokenDomain === undefined); assert(res2.refreshTokenDomain === undefined); - assert(res2.idRefreshTokenDomain === undefined); - assert(res2.frontToken.length > 1); + assert.strictEqual(res2.frontToken, "remove"); + assert.strictEqual(res2.antiCsrf, undefined); }); it("test revoking a session during refresh with revokeSession function and sending 401", async function () { @@ -3084,7 +2848,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -3094,6 +2858,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/create") + .set("st-auth-mode", "cookie") .expect(200) .end((err, res) => { if (err) { @@ -3107,14 +2872,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let resp = await new Promise((resolve) => request(app) .post("/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -3129,18 +2892,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = extractInfoFromResponse(resp); - assert(res2.antiCsrf.length > 1); assert.deepEqual(res2.accessToken, ""); assert.deepEqual(res2.refreshToken, ""); - assert.deepEqual(res2.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res2.idRefreshTokenFromCookie, ""); assert.deepEqual(res2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res2.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.deepEqual(res2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert(res2.accessTokenDomain === undefined); assert(res2.refreshTokenDomain === undefined); - assert(res2.idRefreshTokenDomain === undefined); - assert(res2.frontToken.length > 1); + assert.strictEqual(res2.frontToken, "remove"); + assert.strictEqual(res2.antiCsrf, undefined); }); it("test revoking a session during refresh with throwing unauthorised error", async function () { @@ -3164,10 +2923,11 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi return { ...oI, refreshPOST: async function (input) { - let session = await oI.refreshPOST(input); + await oI.refreshPOST(input); throw new Session.Error({ message: "unauthorised", type: Session.Error.UNAUTHORISED, + clearTokens: true, }); }, }; @@ -3182,7 +2942,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -3192,6 +2952,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/create") + .set("st-auth-mode", "cookie") .expect(200) .end((err, res) => { if (err) { @@ -3205,14 +2966,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let resp = await new Promise((resolve) => request(app) .post("/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -3227,18 +2986,14 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi let res2 = extractInfoFromResponse(resp); - assert(res2.antiCsrf.length > 1); - assert.deepEqual(res2.accessToken, ""); - assert.deepEqual(res2.refreshToken, ""); - assert.deepEqual(res2.idRefreshTokenFromHeader, "remove"); - assert.deepEqual(res2.idRefreshTokenFromCookie, ""); - assert.deepEqual(res2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res2.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.deepEqual(res2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(res2.accessTokenDomain === undefined); - assert(res2.refreshTokenDomain === undefined); - assert(res2.idRefreshTokenDomain === undefined); - assert(res2.frontToken.length > 1); + assert.strictEqual(res2.accessToken, ""); + assert.strictEqual(res2.refreshToken, ""); + assert.strictEqual(res2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(res2.accessTokenDomain, undefined); + assert.strictEqual(res2.refreshTokenDomain, undefined); + assert.strictEqual(res2.frontToken, "remove"); + assert.strictEqual(res2.antiCsrf, undefined); }); it("test revoking a session during refresh fails if just sending 401", async function () { @@ -3278,7 +3033,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, "", {}, {}); + await Session.createNewSession(req, res, "", {}, {}); res.status(200).send(""); }); @@ -3288,6 +3043,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi await new Promise((resolve) => request(app) .post("/create") + .set("st-auth-mode", "cookie") .expect(200) .end((err, res) => { if (err) { @@ -3301,14 +3057,12 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res.accessToken !== undefined); assert(res.antiCsrf !== undefined); - assert(res.idRefreshTokenFromCookie !== undefined); - assert(res.idRefreshTokenFromHeader !== undefined); assert(res.refreshToken !== undefined); let resp = await new Promise((resolve) => request(app) .post("/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -3325,8 +3079,6 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi assert(res2.accessToken.length > 1); assert(res2.antiCsrf.length > 1); - assert(res2.idRefreshTokenFromCookie.length > 1); - assert(res2.idRefreshTokenFromHeader !== "remove"); assert(res2.refreshToken.length > 1); }); }); diff --git a/test/thirdparty/authorisationUrlFeature.test.js b/test/thirdparty/authorisationUrlFeature.test.js index b609dff2f..d7d521282 100644 --- a/test/thirdparty/authorisationUrlFeature.test.js +++ b/test/thirdparty/authorisationUrlFeature.test.js @@ -91,9 +91,7 @@ describe(`authorisationTest: ${printPath("[test/thirdparty/authorisationFeature. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirPartyRecipe.init({ signInAndUpFeature: { providers: [ @@ -146,9 +144,7 @@ describe(`authorisationTest: ${printPath("[test/thirdparty/authorisationFeature. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider1], @@ -194,9 +190,7 @@ describe(`authorisationTest: ${printPath("[test/thirdparty/authorisationFeature. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider2], @@ -245,7 +239,7 @@ describe(`authorisationTest: ${printPath("[test/thirdparty/authorisationFeature. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider1], @@ -290,7 +284,7 @@ describe(`authorisationTest: ${printPath("[test/thirdparty/authorisationFeature. websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider1], diff --git a/test/thirdparty/override.test.js b/test/thirdparty/override.test.js index b721c5026..3272da69c 100644 --- a/test/thirdparty/override.test.js +++ b/test/thirdparty/override.test.js @@ -101,7 +101,7 @@ describe(`overrideTest: ${printPath("[test/thirdparty/override.test.js]")}`, fun }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -220,7 +220,7 @@ describe(`overrideTest: ${printPath("[test/thirdparty/override.test.js]")}`, fun }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -327,7 +327,7 @@ describe(`overrideTest: ${printPath("[test/thirdparty/override.test.js]")}`, fun }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -453,7 +453,7 @@ describe(`overrideTest: ${printPath("[test/thirdparty/override.test.js]")}`, fun }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/thirdparty/signinupFeature.test.js b/test/thirdparty/signinupFeature.test.js index c97330463..895bc6fc9 100644 --- a/test/thirdparty/signinupFeature.test.js +++ b/test/thirdparty/signinupFeature.test.js @@ -233,9 +233,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider6], @@ -279,16 +277,12 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") assert.notStrictEqual(cookies1.accessToken, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.notStrictEqual(cookies1.antiCsrf, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies1.accessTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.strictEqual(cookies1.accessTokenDomain, undefined); assert.strictEqual(cookies1.refreshTokenDomain, undefined); - assert.strictEqual(cookies1.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies1.frontToken, undefined); + assert.notStrictEqual(cookies1.frontToken, "remove"); let response2 = await new Promise((resolve) => request(app) @@ -320,16 +314,12 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") assert.notStrictEqual(cookies2.accessToken, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.notStrictEqual(cookies2.antiCsrf, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies2.accessTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.strictEqual(cookies2.accessTokenDomain, undefined); assert.strictEqual(cookies2.refreshTokenDomain, undefined); - assert.strictEqual(cookies2.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies2.frontToken, undefined); + assert.notStrictEqual(cookies2.frontToken, "remove"); }); it("test missing code and authCodeResponse", async function () { @@ -344,9 +334,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider6], @@ -392,9 +380,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") }, recipeList: [ EmailVerification.init({ mode: "OPTIONAL" }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider1], @@ -438,16 +424,12 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") assert.notStrictEqual(cookies1.accessToken, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.notStrictEqual(cookies1.antiCsrf, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies1.accessTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.strictEqual(cookies1.accessTokenDomain, undefined); assert.strictEqual(cookies1.refreshTokenDomain, undefined); - assert.strictEqual(cookies1.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies1.frontToken, undefined); + assert.notStrictEqual(cookies1.frontToken, "remove"); assert.strictEqual(await EmailVerification.isEmailVerified(response1.body.user.id), true); @@ -481,16 +463,12 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") assert.notStrictEqual(cookies2.accessToken, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.notStrictEqual(cookies2.antiCsrf, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies2.accessTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.strictEqual(cookies2.accessTokenDomain, undefined); assert.strictEqual(cookies2.refreshTokenDomain, undefined); - assert.strictEqual(cookies2.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies2.frontToken, undefined); + assert.notStrictEqual(cookies2.frontToken, "remove"); }); it("test minimum config for thirdparty module, email unverified", async function () { @@ -506,9 +484,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") }, recipeList: [ EmailVerification.init({ mode: "OPTIONAL" }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider5], @@ -552,16 +528,12 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") assert.notStrictEqual(cookies1.accessToken, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.notStrictEqual(cookies1.antiCsrf, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies1.accessTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.strictEqual(cookies1.accessTokenDomain, undefined); assert.strictEqual(cookies1.refreshTokenDomain, undefined); - assert.strictEqual(cookies1.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies1.frontToken, undefined); + assert.notStrictEqual(cookies1.frontToken, "remove"); assert.strictEqual(await EmailVerification.isEmailVerified(response1.body.user.id), false); }); @@ -578,7 +550,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider1], @@ -628,7 +600,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider2], @@ -681,7 +653,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider3], @@ -730,7 +702,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider4], @@ -785,7 +757,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyRecipe.init({ signInAndUpFeature: { providers: [this.customProvider1], @@ -962,7 +934,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") providers: [this.customProvider1], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -1021,7 +993,7 @@ describe(`signinupTest: ${printPath("[test/thirdparty/signinupFeature.test.js]") providers: [this.customProvider1], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/thirdparty/signoutFeature.test.js b/test/thirdparty/signoutFeature.test.js index 6a68b3729..1c235af41 100644 --- a/test/thirdparty/signoutFeature.test.js +++ b/test/thirdparty/signoutFeature.test.js @@ -88,9 +88,7 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` providers: [this.customProvider1], }, }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -127,9 +125,7 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -144,15 +140,11 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` assert.strictEqual(response2.antiCsrf, undefined); assert.strictEqual(response2.accessToken, ""); assert.strictEqual(response2.refreshToken, ""); - assert.strictEqual(response2.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(response2.idRefreshTokenFromCookie, ""); assert.strictEqual(response2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(response2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(response2.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(response2.accessTokenDomain, undefined); assert.strictEqual(response2.refreshTokenDomain, undefined); - assert.strictEqual(response2.idRefreshTokenDomain, undefined); - assert.strictEqual(response2.frontToken, undefined); + assert.strictEqual(response2.frontToken, "remove"); }); it("test that disabling default route and calling the API returns 404", async function () { @@ -181,7 +173,7 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -224,7 +216,7 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` providers: [this.customProvider1], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -271,9 +263,7 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` providers: [this.customProvider1], }, }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -311,7 +301,8 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` let signOutResponse = await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -329,10 +320,8 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -349,12 +338,8 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + - refreshedResponse.accessToken + - ";sIdRefreshToken=" + - refreshedResponse.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + refreshedResponse.accessToken]) .set("anti-csrf", refreshedResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -370,13 +355,9 @@ describe(`signoutTest: ${printPath("[test/thirdparty/signoutFeature.test.js]")}` assert.strictEqual(signOutResponse.antiCsrf, undefined); assert.strictEqual(signOutResponse.accessToken, ""); assert.strictEqual(signOutResponse.refreshToken, ""); - assert.strictEqual(signOutResponse.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(signOutResponse.idRefreshTokenFromCookie, ""); assert.strictEqual(signOutResponse.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(signOutResponse.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(signOutResponse.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(signOutResponse.accessTokenDomain, undefined); assert.strictEqual(signOutResponse.refreshTokenDomain, undefined); - assert.strictEqual(signOutResponse.idRefreshTokenDomain, undefined); }); }); diff --git a/test/thirdparty/users.test.js b/test/thirdparty/users.test.js index 15f23f82a..c715bdbca 100644 --- a/test/thirdparty/users.test.js +++ b/test/thirdparty/users.test.js @@ -78,7 +78,7 @@ describe(`usersTest: ${printPath("[test/thirdparty/users.test.js]")}`, function providers: [this.customProvider1], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -149,7 +149,7 @@ describe(`usersTest: ${printPath("[test/thirdparty/users.test.js]")}`, function providers: [this.customProvider1], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -220,7 +220,7 @@ describe(`usersTest: ${printPath("[test/thirdparty/users.test.js]")}`, function providers: [this.customProvider1], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/thirdpartyemailpassword/authorisationUrlFeature.test.js b/test/thirdpartyemailpassword/authorisationUrlFeature.test.js index 3e804ce2a..3e5c8ad17 100644 --- a/test/thirdpartyemailpassword/authorisationUrlFeature.test.js +++ b/test/thirdpartyemailpassword/authorisationUrlFeature.test.js @@ -88,9 +88,7 @@ describe(`authorisationTest: ${printPath("[test/thirdpartyemailpassword/authoris websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyEmailPasswordRecipe.init({ providers: [this.customProvider1], }), @@ -132,9 +130,7 @@ describe(`authorisationTest: ${printPath("[test/thirdpartyemailpassword/authoris websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyEmailPasswordRecipe.init({ providers: [this.customProvider2], }), @@ -182,7 +178,7 @@ describe(`authorisationTest: ${printPath("[test/thirdpartyemailpassword/authoris websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyEmailPasswordRecipe.init({ providers: [this.customProvider1], }), diff --git a/test/thirdpartyemailpassword/emailDelivery.test.js b/test/thirdpartyemailpassword/emailDelivery.test.js index 1606bbe41..4c7e31815 100644 --- a/test/thirdpartyemailpassword/emailDelivery.test.js +++ b/test/thirdpartyemailpassword/emailDelivery.test.js @@ -49,7 +49,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], telemetry: false, }); @@ -105,7 +105,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], telemetry: false, }); @@ -175,7 +175,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -229,7 +229,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -296,7 +296,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -354,7 +354,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -458,7 +458,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -501,7 +501,11 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailVerification.init({ mode: "OPTIONAL" }), ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ + EmailVerification.init({ mode: "OPTIONAL" }), + ThirdPartyEmailPassword.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), + ], telemetry: false, }); @@ -509,7 +513,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -535,7 +539,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -556,7 +560,11 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [EmailVerification.init({ mode: "OPTIONAL" }), ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ + EmailVerification.init({ mode: "OPTIONAL" }), + ThirdPartyEmailPassword.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), + ], telemetry: false, }); @@ -564,7 +572,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -590,7 +598,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver let result = await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -625,7 +633,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }), ThirdPartyEmailPassword.init(), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -634,7 +642,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -645,7 +653,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); assert.strictEqual(idInCallback, user.user.id); @@ -680,7 +688,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver // We need to add something to the providers array to make the thirdparty recipe initialize providers: [/** @type {any} */ {}], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -689,7 +697,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -704,7 +712,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); assert.strictEqual(idInCallback, user.user.id); @@ -744,7 +752,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }), ThirdPartyEmailPassword.init(), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -753,7 +761,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -773,7 +781,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -849,7 +857,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver }, }), ThirdPartyEmailPassword.init(), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -858,7 +866,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -869,7 +877,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartyemailpassword/emailDeliver await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); diff --git a/test/thirdpartyemailpassword/emailExists.test.js b/test/thirdpartyemailpassword/emailExists.test.js index 5269a27b3..780cb25bc 100644 --- a/test/thirdpartyemailpassword/emailExists.test.js +++ b/test/thirdpartyemailpassword/emailExists.test.js @@ -59,7 +59,7 @@ describe(`emailExists: ${printPath("[test/thirdpartyemailpassword/emailExists.te }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -99,7 +99,7 @@ describe(`emailExists: ${printPath("[test/thirdpartyemailpassword/emailExists.te appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -145,7 +145,7 @@ describe(`emailExists: ${printPath("[test/thirdpartyemailpassword/emailExists.te appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -187,7 +187,7 @@ describe(`emailExists: ${printPath("[test/thirdpartyemailpassword/emailExists.te appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); diff --git a/test/thirdpartyemailpassword/emailverify.test.js b/test/thirdpartyemailpassword/emailverify.test.js index 11c07cc7a..3da225599 100644 --- a/test/thirdpartyemailpassword/emailverify.test.js +++ b/test/thirdpartyemailpassword/emailverify.test.js @@ -88,9 +88,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te recipeList: [ EmailVerification.init({ mode: "OPTIONAL" }), ThirdPartyEmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -107,13 +105,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te let userId = JSON.parse(response.text).user.id; let infoFromResponse = extractInfoFromResponse(response); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "OK"); assert(Object.keys(JSON.parse(response.text)).length === 1); @@ -133,9 +125,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te recipeList: [ EmailVerification.init({ mode: "OPTIONAL" }), ThirdPartyEmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -155,13 +145,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te let verifyToken = await EmailVerification.createEmailVerificationToken(userId); await EmailVerification.verifyEmailUsingToken(verifyToken.token); - response = await emailVerifyTokenRequest( - app, - infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, - infoFromResponse.antiCsrf, - userId - ); + response = await emailVerifyTokenRequest(app, infoFromResponse.accessToken, infoFromResponse.antiCsrf, userId); assert(JSON.parse(response.text).status === "EMAIL_ALREADY_VERIFIED_ERROR"); assert(response.status === 200); @@ -182,9 +166,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te recipeList: [ EmailVerification.init({ mode: "OPTIONAL" }), ThirdPartyEmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -235,9 +217,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te }, }), ThirdPartyEmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -257,7 +237,6 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te let response2 = await emailVerifyTokenRequest( app, infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, infoFromResponse.antiCsrf, userId ); @@ -298,9 +277,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te ThirdPartyEmailPassword.init({ providers: [this.customProvider1], }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -320,7 +297,6 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te let response2 = await emailVerifyTokenRequest( app, infoFromResponse.accessToken, - infoFromResponse.idRefreshTokenFromCookie, infoFromResponse.antiCsrf, userId ); @@ -352,9 +328,7 @@ describe(`emailverify: ${printPath("[test/thirdpartyemailpassword/emailverify.te mode: "OPTIONAL", }), ThirdPartyEmailPassword.init(), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); diff --git a/test/thirdpartyemailpassword/override.test.js b/test/thirdpartyemailpassword/override.test.js index 74d09a5b1..9d83581b4 100644 --- a/test/thirdpartyemailpassword/override.test.js +++ b/test/thirdpartyemailpassword/override.test.js @@ -77,7 +77,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartyemailpassword/override.test }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -199,7 +199,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartyemailpassword/override.test }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -331,7 +331,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartyemailpassword/override.test }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -468,7 +468,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartyemailpassword/override.test }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/thirdpartyemailpassword/signinFeature.test.js b/test/thirdpartyemailpassword/signinFeature.test.js index 7e0c28f6f..7e1bf1be3 100644 --- a/test/thirdpartyemailpassword/signinFeature.test.js +++ b/test/thirdpartyemailpassword/signinFeature.test.js @@ -207,9 +207,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyEmailPassword.init({ providers: [this.customProvider1], override: { @@ -271,7 +269,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -325,7 +323,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -380,7 +378,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -435,7 +433,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -491,7 +489,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -546,7 +544,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -601,7 +599,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -657,7 +655,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -683,7 +681,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -709,7 +707,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -736,7 +734,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -763,7 +761,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -789,7 +787,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -815,7 +813,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -846,7 +844,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -917,7 +915,7 @@ describe(`signinFeature: ${printPath("[test/thirdpartyemailpassword/signinFeatur ], }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); const app = express(); diff --git a/test/thirdpartyemailpassword/signoutFeature.test.js b/test/thirdpartyemailpassword/signoutFeature.test.js index ca8e6ee09..0921aec06 100644 --- a/test/thirdpartyemailpassword/signoutFeature.test.js +++ b/test/thirdpartyemailpassword/signoutFeature.test.js @@ -87,9 +87,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature ThirdPartyEmailPasswordRecipe.init({ providers: [this.customProvider1], }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -126,9 +124,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -143,15 +139,11 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature assert.strictEqual(response2.antiCsrf, undefined); assert.strictEqual(response2.accessToken, ""); assert.strictEqual(response2.refreshToken, ""); - assert.strictEqual(response2.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(response2.idRefreshTokenFromCookie, ""); assert.strictEqual(response2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(response2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(response2.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(response2.accessTokenDomain, undefined); assert.strictEqual(response2.refreshTokenDomain, undefined); - assert.strictEqual(response2.idRefreshTokenDomain, undefined); - assert.strictEqual(response2.frontToken, undefined); + assert.strictEqual(response2.frontToken, "remove"); let response3 = await signUPRequest(app, "random@gmail.com", "validpass123"); assert(JSON.parse(response3.text).status === "OK"); @@ -163,9 +155,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -177,18 +167,14 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature }) ) ); - assert(response4.antiCsrf === undefined); - assert(response4.accessToken === ""); - assert(response4.refreshToken === ""); - assert(response4.idRefreshTokenFromHeader === "remove"); - assert(response4.idRefreshTokenFromCookie === ""); - assert(response4.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(response4.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(response4.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(response4.accessTokenDomain === undefined); - assert(response4.refreshTokenDomain === undefined); - assert(response4.idRefreshTokenDomain === undefined); - assert(response4.frontToken === undefined); + assert.strictEqual(response4.antiCsrf, undefined); + assert.strictEqual(response4.accessToken, ""); + assert.strictEqual(response4.refreshToken, ""); + assert.strictEqual(response4.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(response4.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); + assert.strictEqual(response4.accessTokenDomain, undefined); + assert.strictEqual(response4.refreshTokenDomain, undefined); + assert.strictEqual(response4.frontToken, "remove"); }); it("test that disabling default route and calling the API returns 404", async function () { @@ -215,7 +201,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -256,7 +242,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature ThirdPartyEmailPasswordRecipe.init({ providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -301,9 +287,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature ThirdPartyEmailPasswordRecipe.init({ providers: [this.customProvider1], }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -341,9 +325,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature let signOutResponse = await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + res1.accessToken + ";sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + res1.accessToken]) .set("anti-csrf", res1.antiCsrf) .end((err, res) => { if (err) { @@ -361,10 +344,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature request(app) .post("/auth/session/refresh") .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res1.refreshToken, - "sIdRefreshToken=" + res1.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sRefreshToken=" + res1.refreshToken]) .set("anti-csrf", res1.antiCsrf) .expect(200) .end((err, res) => { @@ -381,12 +362,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + - refreshedResponse.accessToken + - ";sIdRefreshToken=" + - refreshedResponse.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + refreshedResponse.accessToken]) .set("anti-csrf", refreshedResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -402,15 +379,10 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature assert.strictEqual(signOutResponse.antiCsrf, undefined); assert.strictEqual(signOutResponse.accessToken, ""); assert.strictEqual(signOutResponse.refreshToken, ""); - assert.strictEqual(signOutResponse.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(signOutResponse.idRefreshTokenFromCookie, ""); assert.strictEqual(signOutResponse.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(signOutResponse.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(signOutResponse.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(signOutResponse.accessTokenDomain, undefined); assert.strictEqual(signOutResponse.refreshTokenDomain, undefined); - assert.strictEqual(signOutResponse.idRefreshTokenDomain, undefined); - let response2 = await signUPRequest(app, "random@gmail.com", "validpass123"); assert(JSON.parse(response2.text).status === "OK"); assert(response2.status === 200); @@ -422,9 +394,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature signOutResponse = await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + res2.accessToken + ";sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + res2.accessToken]) .set("anti-csrf", res2.antiCsrf) .end((err, res) => { if (err) { @@ -441,11 +412,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res2.refreshToken, - "sIdRefreshToken=" + res2.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sRefreshToken=" + res2.refreshToken]) .set("anti-csrf", res2.antiCsrf) .expect(200) .end((err, res) => { @@ -462,12 +430,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + - refreshedResponse.accessToken + - ";sIdRefreshToken=" + - refreshedResponse.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + refreshedResponse.accessToken]) .set("anti-csrf", refreshedResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -483,13 +447,9 @@ describe(`signoutTest: ${printPath("[test/thirdpartyemailpassword/signoutFeature assert(signOutResponse.antiCsrf === undefined); assert(signOutResponse.accessToken === ""); assert(signOutResponse.refreshToken === ""); - assert(signOutResponse.idRefreshTokenFromHeader === "remove"); - assert(signOutResponse.idRefreshTokenFromCookie === ""); assert(signOutResponse.accessTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(signOutResponse.refreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); - assert(signOutResponse.idRefreshTokenExpiry === "Thu, 01 Jan 1970 00:00:00 GMT"); assert(signOutResponse.accessTokenDomain === undefined); assert(signOutResponse.refreshTokenDomain === undefined); - assert(signOutResponse.idRefreshTokenDomain === undefined); }); }); diff --git a/test/thirdpartyemailpassword/signupFeature.test.js b/test/thirdpartyemailpassword/signupFeature.test.js index d1aab128e..c8336c228 100644 --- a/test/thirdpartyemailpassword/signupFeature.test.js +++ b/test/thirdpartyemailpassword/signupFeature.test.js @@ -216,7 +216,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -243,9 +243,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t }, recipeList: [ EmailVerification.init({ mode: "OPTIONAL" }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyEmailPassword.init({ providers: [this.customProvider1], }), @@ -298,7 +296,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -335,9 +333,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyEmailPassword.init({ providers: [this.customProvider1], override: { @@ -424,7 +420,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -457,7 +453,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); const app = express(); @@ -497,7 +493,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyEmailPassword.init({ providers: [this.customProvider2], }), @@ -549,7 +545,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyEmailPassword.init({ providers: [this.customProvider3], }), @@ -596,7 +592,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyEmailPassword.init({ providers: [this.customProvider4], }), @@ -653,7 +649,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t ThirdPartyEmailPassword.init({ providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -710,7 +706,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t ThirdPartyEmailPassword.init({ providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -763,7 +759,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [ThirdPartyEmailPassword.init(), Session.init()], + recipeList: [ThirdPartyEmailPassword.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); let currCDIVersion = await Querier.getNewInstanceOrThrowError(undefined).getAPIVersion(); @@ -835,7 +831,7 @@ describe(`signupTest: ${printPath("[test/thirdpartyemailpassword/signupFeature.t ThirdPartyEmailPassword.init({ providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/thirdpartypasswordless/api.test.js b/test/thirdpartypasswordless/api.test.js index 2c63bbe95..55e8b85d7 100644 --- a/test/thirdpartypasswordless/api.test.js +++ b/test/thirdpartypasswordless/api.test.js @@ -55,7 +55,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -150,7 +150,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -245,7 +245,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -332,7 +332,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -418,7 +418,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -503,7 +503,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -632,7 +632,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -692,7 +692,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -782,7 +782,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -901,7 +901,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -968,7 +968,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1049,7 +1049,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1131,7 +1131,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1195,7 +1195,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1284,7 +1284,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1375,7 +1375,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1459,7 +1459,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1499,7 +1499,7 @@ describe(`apisFunctions: ${printPath("[test/thirdpartypasswordless/apis.test.js] websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", diff --git a/test/thirdpartypasswordless/authorisationUrlFeature.test.js b/test/thirdpartypasswordless/authorisationUrlFeature.test.js index dcb3c14b7..72a7d88bc 100644 --- a/test/thirdpartypasswordless/authorisationUrlFeature.test.js +++ b/test/thirdpartypasswordless/authorisationUrlFeature.test.js @@ -88,9 +88,7 @@ describe(`authorisationTest: ${printPath("[test/thirdpartyemailpassword/authoris websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyPasswordlessRecipe.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -142,9 +140,7 @@ describe(`authorisationTest: ${printPath("[test/thirdpartyemailpassword/authoris websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyPasswordlessRecipe.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -202,7 +198,7 @@ describe(`authorisationTest: ${printPath("[test/thirdpartyemailpassword/authoris websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordlessRecipe.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { diff --git a/test/thirdpartypasswordless/config.test.js b/test/thirdpartypasswordless/config.test.js index ebb22c23e..938e69921 100644 --- a/test/thirdpartypasswordless/config.test.js +++ b/test/thirdpartypasswordless/config.test.js @@ -54,7 +54,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -98,7 +98,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -196,7 +196,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -266,7 +266,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -332,7 +332,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -373,7 +373,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -439,7 +439,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -499,7 +499,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE", @@ -571,7 +571,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "MAGIC_LINK", @@ -633,7 +633,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -696,7 +696,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "MAGIC_LINK", @@ -762,7 +762,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -804,7 +804,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -870,7 +870,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -931,7 +931,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", @@ -1003,7 +1003,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "MAGIC_LINK", @@ -1065,7 +1065,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1128,7 +1128,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "MAGIC_LINK", @@ -1198,7 +1198,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", }), @@ -1228,7 +1228,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ flowType: "USER_INPUT_CODE", }), @@ -1266,7 +1266,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", @@ -1352,7 +1352,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", @@ -1440,7 +1440,7 @@ describe(`config tests: ${printPath("[test/thirdpartypasswordless/config.test.js websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE", diff --git a/test/thirdpartypasswordless/emailDelivery.test.js b/test/thirdpartypasswordless/emailDelivery.test.js index b0ee052ba..79a72b331 100644 --- a/test/thirdpartypasswordless/emailDelivery.test.js +++ b/test/thirdpartypasswordless/emailDelivery.test.js @@ -85,7 +85,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -99,7 +99,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -125,7 +125,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -153,7 +153,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -167,7 +167,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -193,7 +193,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery let result = await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -233,7 +233,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -247,7 +247,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -258,7 +258,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); assert.strictEqual(email, "test@example.com"); @@ -294,7 +294,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -308,7 +308,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -321,7 +321,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); assert.strictEqual(functionCalled, false); @@ -365,7 +365,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -379,7 +379,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -399,7 +399,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); process.env.TEST_MODE = "testing"; @@ -479,7 +479,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -493,7 +493,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery app.use(express.json()); app.use(middleware()); app.post("/create", async (req, res) => { - await Session.createNewSession(res, req.body.id, {}, {}); + await Session.createNewSession(req, res, req.body.id, {}, {}); res.status(200).send(""); }); app.use(errorHandler()); @@ -504,7 +504,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery await supertest(app) .post("/auth/user/email/verify/token") .set("rid", "emailverification") - .set("Cookie", ["sAccessToken=" + res.accessToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .expect(200); await delay(2); @@ -531,7 +531,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -609,7 +609,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery userInputCode = input.userInputCode; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -675,7 +675,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -788,7 +788,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -836,7 +836,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -911,7 +911,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1015,7 +1015,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery sendCustomEmailCalled = true; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1105,7 +1105,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1247,7 +1247,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1311,7 +1311,7 @@ describe(`emailDelivery: ${printPath("[test/thirdpartypasswordless/emailDelivery contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); diff --git a/test/thirdpartypasswordless/override.test.js b/test/thirdpartypasswordless/override.test.js index 9430c6feb..81bde8791 100644 --- a/test/thirdpartypasswordless/override.test.js +++ b/test/thirdpartypasswordless/override.test.js @@ -114,7 +114,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartypasswordless/override.test. }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -241,7 +241,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartypasswordless/override.test. }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -356,7 +356,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartypasswordless/override.test. }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -490,7 +490,7 @@ describe(`overrideTest: ${printPath("[test/thirdpartypasswordless/override.test. }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/thirdpartypasswordless/recipeFunctions.test.js b/test/thirdpartypasswordless/recipeFunctions.test.js index 8ca01ca09..b71117b14 100644 --- a/test/thirdpartypasswordless/recipeFunctions.test.js +++ b/test/thirdpartypasswordless/recipeFunctions.test.js @@ -47,7 +47,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), EmailVerification.init({ mode: "OPTIONAL" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", @@ -105,7 +105,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), EmailVerification.init({ mode: "OPTIONAL" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL_OR_PHONE", @@ -171,7 +171,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -273,7 +273,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -336,7 +336,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -435,7 +435,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -521,7 +521,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -571,7 +571,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -639,7 +639,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -704,7 +704,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -768,7 +768,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -833,7 +833,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -884,7 +884,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -935,7 +935,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -988,7 +988,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", @@ -1031,7 +1031,7 @@ describe(`recipeFunctions: ${printPath("[test/thirdpartypasswordless/recipeFunct websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", diff --git a/test/thirdpartypasswordless/signinupFeature.test.js b/test/thirdpartypasswordless/signinupFeature.test.js index af421b056..48bde4760 100644 --- a/test/thirdpartypasswordless/signinupFeature.test.js +++ b/test/thirdpartypasswordless/signinupFeature.test.js @@ -248,9 +248,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL", createAndSendCustomEmail: () => {} }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", @@ -302,16 +300,12 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur assert.notStrictEqual(cookies1.accessToken, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.notStrictEqual(cookies1.antiCsrf, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies1.accessTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.strictEqual(cookies1.accessTokenDomain, undefined); assert.strictEqual(cookies1.refreshTokenDomain, undefined); - assert.strictEqual(cookies1.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies1.frontToken, undefined); + assert.notStrictEqual(cookies1.frontToken, "remove"); assert.strictEqual( await EmailVerification.isEmailVerified(response1.body.user.id, response1.body.user.email), @@ -348,16 +342,12 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur assert.notStrictEqual(cookies2.accessToken, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.notStrictEqual(cookies2.antiCsrf, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies2.accessTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.strictEqual(cookies2.accessTokenDomain, undefined); assert.strictEqual(cookies2.refreshTokenDomain, undefined); - assert.strictEqual(cookies2.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies2.frontToken, undefined); + assert.notStrictEqual(cookies2.frontToken, "remove"); }); it("test with thirdPartyPasswordless, missing code and authCodeResponse", async function () { @@ -372,9 +362,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -427,9 +415,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), EmailVerification.init({ mode: "OPTIONAL", createAndSendCustomEmail: () => {} }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", @@ -482,16 +468,12 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur assert.notStrictEqual(cookies1.accessToken, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.notStrictEqual(cookies1.antiCsrf, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies1.accessTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.strictEqual(cookies1.accessTokenDomain, undefined); assert.strictEqual(cookies1.refreshTokenDomain, undefined); - assert.strictEqual(cookies1.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies1.frontToken, undefined); + assert.notStrictEqual(cookies1.frontToken, "remove"); assert.strictEqual( await EmailVerification.isEmailVerified(response1.body.user.id, response1.body.user.email), @@ -528,16 +510,12 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur assert.notStrictEqual(cookies2.accessToken, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.notStrictEqual(cookies2.antiCsrf, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies2.accessTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies2.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies2.refreshToken, undefined); assert.strictEqual(cookies2.accessTokenDomain, undefined); assert.strictEqual(cookies2.refreshTokenDomain, undefined); - assert.strictEqual(cookies2.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies2.frontToken, undefined); + assert.notStrictEqual(cookies2.frontToken, "remove"); }); it("test with thirdPartyPasswordless, with minimum config for thirdparty module, email unverified", async function () { @@ -552,9 +530,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -607,16 +583,12 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur assert.notStrictEqual(cookies1.accessToken, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.notStrictEqual(cookies1.antiCsrf, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromHeader, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenFromCookie, undefined); assert.notStrictEqual(cookies1.accessTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshTokenExpiry, undefined); - assert.notStrictEqual(cookies1.idRefreshTokenExpiry, undefined); assert.notStrictEqual(cookies1.refreshToken, undefined); assert.strictEqual(cookies1.accessTokenDomain, undefined); assert.strictEqual(cookies1.refreshTokenDomain, undefined); - assert.strictEqual(cookies1.idRefreshTokenDomain, undefined); - assert.notStrictEqual(cookies1.frontToken, undefined); + assert.notStrictEqual(cookies1.frontToken, "remove"); assert.strictEqual( await EmailVerification.isEmailVerified(response1.body.user.id, response1.body.user.email), @@ -636,7 +608,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -694,7 +666,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -755,7 +727,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -812,7 +784,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -875,7 +847,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur websiteDomain: "supertokens.io", }, recipeList: [ - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ThirdPartyPasswordless.init({ contactMethod: "EMAIL", createAndSendCustomEmail: (input) => { @@ -1063,7 +1035,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -1128,7 +1100,7 @@ describe(`signinupTest: ${printPath("[test/thirdpartypasswordless/signinupFeatur flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/thirdpartypasswordless/signoutFeature.test.js b/test/thirdpartypasswordless/signoutFeature.test.js index e022e3a35..f4550e095 100644 --- a/test/thirdpartypasswordless/signoutFeature.test.js +++ b/test/thirdpartypasswordless/signoutFeature.test.js @@ -92,9 +92,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -136,9 +134,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -153,15 +149,11 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. assert.strictEqual(response2.antiCsrf, undefined); assert.strictEqual(response2.accessToken, ""); assert.strictEqual(response2.refreshToken, ""); - assert.strictEqual(response2.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(response2.idRefreshTokenFromCookie, ""); assert.strictEqual(response2.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(response2.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(response2.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(response2.accessTokenDomain, undefined); assert.strictEqual(response2.refreshTokenDomain, undefined); - assert.strictEqual(response2.idRefreshTokenDomain, undefined); - assert.strictEqual(response2.frontToken, undefined); + assert.strictEqual(response2.frontToken, "remove"); }); it("test that disabling default route and calling the API returns 404", async function () { @@ -193,7 +185,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -244,7 +236,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -298,9 +290,7 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init({ - antiCsrf: "VIA_TOKEN", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "VIA_TOKEN" }), ], }); @@ -343,7 +333,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. let signOutResponse = await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", ["sAccessToken=" + res.accessToken + ";sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + res.accessToken]) .set("anti-csrf", res.antiCsrf) .end((err, res) => { if (err) { @@ -360,11 +351,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. await new Promise((resolve) => request(app) .post("/auth/session/refresh") - .expect(200) - .set("Cookie", [ - "sRefreshToken=" + res.refreshToken, - "sIdRefreshToken=" + res.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sRefreshToken=" + res.refreshToken]) .set("anti-csrf", res.antiCsrf) .expect(200) .end((err, res) => { @@ -381,12 +369,8 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. await new Promise((resolve) => request(app) .post("/auth/signout") - .set("Cookie", [ - "sAccessToken=" + - refreshedResponse.accessToken + - ";sIdRefreshToken=" + - refreshedResponse.idRefreshTokenFromCookie, - ]) + .set("rid", "session") + .set("Cookie", ["sAccessToken=" + refreshedResponse.accessToken]) .set("anti-csrf", refreshedResponse.antiCsrf) .expect(200) .end((err, res) => { @@ -402,13 +386,9 @@ describe(`signoutTest: ${printPath("[test/thirdpartypasswordless/signoutFeature. assert.strictEqual(signOutResponse.antiCsrf, undefined); assert.strictEqual(signOutResponse.accessToken, ""); assert.strictEqual(signOutResponse.refreshToken, ""); - assert.strictEqual(signOutResponse.idRefreshTokenFromHeader, "remove"); - assert.strictEqual(signOutResponse.idRefreshTokenFromCookie, ""); assert.strictEqual(signOutResponse.accessTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(signOutResponse.refreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); - assert.strictEqual(signOutResponse.idRefreshTokenExpiry, "Thu, 01 Jan 1970 00:00:00 GMT"); assert.strictEqual(signOutResponse.accessTokenDomain, undefined); assert.strictEqual(signOutResponse.refreshTokenDomain, undefined); - assert.strictEqual(signOutResponse.idRefreshTokenDomain, undefined); }); }); diff --git a/test/thirdpartypasswordless/smsDelivery.test.js b/test/thirdpartypasswordless/smsDelivery.test.js index 342b0e94e..d464794cd 100644 --- a/test/thirdpartypasswordless/smsDelivery.test.js +++ b/test/thirdpartypasswordless/smsDelivery.test.js @@ -55,7 +55,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -136,7 +136,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes userInputCode = input.userInputCode; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -202,7 +202,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -308,7 +308,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -364,7 +364,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -457,7 +457,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -519,7 +519,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -588,7 +588,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -695,7 +695,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes sendCustomSMSCalled = true; }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -785,7 +785,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -923,7 +923,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1004,7 +1004,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1122,7 +1122,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes }, }, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); @@ -1204,7 +1204,7 @@ describe(`smsDelivery: ${printPath("[test/thirdpartypasswordless/smsDelivery.tes contactMethod: "PHONE", flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], telemetry: false, }); diff --git a/test/thirdpartypasswordless/users.test.js b/test/thirdpartypasswordless/users.test.js index f259d41ac..ac4dd3ec1 100644 --- a/test/thirdpartypasswordless/users.test.js +++ b/test/thirdpartypasswordless/users.test.js @@ -89,7 +89,7 @@ describe(`usersTest: ${printPath("[test/thirdpartypasswordless/users.test.js]")} flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -168,7 +168,7 @@ describe(`usersTest: ${printPath("[test/thirdpartypasswordless/users.test.js]")} flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -247,7 +247,7 @@ describe(`usersTest: ${printPath("[test/thirdpartypasswordless/users.test.js]")} flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", providers: [this.customProvider1], }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); diff --git a/test/userContext.test.js b/test/userContext.test.js index 418ab7615..3205e9fb6 100644 --- a/test/userContext.test.js +++ b/test/userContext.test.js @@ -35,7 +35,7 @@ const { default: next } = require("next"); let { middleware, errorHandler } = require("../framework/express"); let STExpress = require("../"); -describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, function () { +describe(`userContext: ${printPath("[test/userContext.test.js]")}`, function () { beforeEach(async function () { await killAllST(); await setupST(); @@ -112,6 +112,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, }), Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => { return { @@ -227,6 +228,7 @@ describe(`sessionExpress: ${printPath("[test/sessionExpress.test.js]")}`, functi }, }), Session.init({ + getTokenTransferMethod: () => "cookie", override: { functions: (oI) => { return { diff --git a/test/userroles/claims.test.js b/test/userroles/claims.test.js index b1ee1d9c2..241e92a31 100644 --- a/test/userroles/claims.test.js +++ b/test/userroles/claims.test.js @@ -1,5 +1,5 @@ const assert = require("assert"); -const { printPath, setupST, startST, killAllST, cleanST, mockResponse } = require("../utils"); +const { printPath, setupST, startST, killAllST, cleanST, mockResponse, mockRequest } = require("../utils"); const { ProcessState } = require("../../lib/build/processState"); const STExpress = require("../.."); const UserRoles = require("../../lib/build/recipe/userroles").default; @@ -31,7 +31,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [UserRoles.init(), Session.init()], + recipeList: [UserRoles.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); // Only run for version >= 2.14 @@ -41,7 +41,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function return this.skip(); } - const session = await Session.createNewSession(mockResponse(), "userId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "userId"); assert.deepStrictEqual(await session.getClaimValue(UserRoles.UserRoleClaim), []); assert.deepStrictEqual(await session.getClaimValue(UserRoles.PermissionClaim), []); }); @@ -62,7 +62,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function skipAddingPermissionsToAccessToken: true, skipAddingRolesToAccessToken: true, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -73,7 +73,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function return this.skip(); } - const session = await Session.createNewSession(mockResponse(), "userId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "userId"); assert.strictEqual(await session.getClaimValue(UserRoles.UserRoleClaim), undefined); assert.strictEqual(await session.getClaimValue(UserRoles.PermissionClaim), undefined); }); @@ -89,7 +89,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [UserRoles.init(), Session.init()], + recipeList: [UserRoles.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); // Only run for version >= 2.14 @@ -101,7 +101,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function await UserRoles.createNewRoleOrAddPermissions("test", ["a", "b"]); await UserRoles.addRoleToUser("userId", "test"); - const session = await Session.createNewSession(mockResponse(), "userId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "userId"); assert.deepStrictEqual(await session.getClaimValue(UserRoles.UserRoleClaim), ["test"]); assert.deepStrictEqual(await session.getClaimValue(UserRoles.PermissionClaim), ["a", "b"]); }); @@ -119,7 +119,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [UserRoles.init(), Session.init()], + recipeList: [UserRoles.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); // Only run for version >= 2.14 @@ -131,7 +131,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function await UserRoles.createNewRoleOrAddPermissions("test", ["a", "b"]); await UserRoles.addRoleToUser("userId", "test"); - const session = await Session.createNewSession(mockResponse(), "userId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "userId"); await session.assertClaims([UserRoles.UserRoleClaim.validators.includes("test")]); @@ -167,7 +167,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function UserRoles.init({ skipAddingRolesToAccessToken: true, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -178,7 +178,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function return this.skip(); } - const session = await Session.createNewSession(mockResponse(), "userId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "userId"); await UserRoles.createNewRoleOrAddPermissions("test", ["a", "b"]); await UserRoles.addRoleToUser("userId", "test"); @@ -195,7 +195,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function appName: "SuperTokens", websiteDomain: "supertokens.io", }, - recipeList: [UserRoles.init(), Session.init()], + recipeList: [UserRoles.init(), Session.init({ getTokenTransferMethod: () => "cookie" })], }); // Only run for version >= 2.14 @@ -207,7 +207,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function await UserRoles.createNewRoleOrAddPermissions("test", ["a", "b"]); await UserRoles.addRoleToUser("userId", "test"); - const session = await Session.createNewSession(mockResponse(), "userId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "userId"); await session.assertClaims([UserRoles.PermissionClaim.validators.includes("a")]); @@ -243,7 +243,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function UserRoles.init({ skipAddingPermissionsToAccessToken: true, }), - Session.init(), + Session.init({ getTokenTransferMethod: () => "cookie" }), ], }); @@ -254,7 +254,7 @@ describe(`claimsTest: ${printPath("[test/userroles/claims.test.js]")}`, function return this.skip(); } - const session = await Session.createNewSession(mockResponse(), "userId"); + const session = await Session.createNewSession(mockRequest(), mockResponse(), "userId"); await UserRoles.createNewRoleOrAddPermissions("test", ["a", "b"]); await UserRoles.addRoleToUser("userId", "test"); diff --git a/test/utils.js b/test/utils.js index 1b87b8596..e4fbde65f 100644 --- a/test/utils.js +++ b/test/utils.js @@ -32,6 +32,7 @@ let { ProcessState } = require("../lib/build/processState"); let { Querier } = require("../lib/build/querier"); let { maxVersion } = require("../lib/build/utils"); const { default: OpenIDRecipe } = require("../lib/build/recipe/openid/recipe"); +const { wrapRequest } = require("../framework/express"); module.exports.printPath = function (path) { return `${createFormat([consoleOptions.yellow, consoleOptions.italic, consoleOptions.dim])}${path}${createFormat([ @@ -75,10 +76,8 @@ module.exports.setKeyValueInConfig = async function (key, value) { module.exports.extractInfoFromResponse = function (res) { let antiCsrf = res.headers["anti-csrf"]; - let idRefreshTokenFromHeader = res.headers["id-refresh-token"]; let accessToken = undefined; let refreshToken = undefined; - let idRefreshTokenFromCookie = undefined; let accessTokenExpiry = undefined; let refreshTokenExpiry = undefined; let idRefreshTokenExpiry = undefined; @@ -100,7 +99,7 @@ module.exports.extractInfoFromResponse = function (res) { * if token is sAccessToken=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsInZlcnNpb24iOiIyIn0=.eyJzZXNzaW9uSGFuZGxlIjoiMWI4NDBhOTAtMjVmYy00ZjQ4LWE2YWMtMDc0MDIzZjNjZjQwIiwidXNlcklkIjoiIiwicmVmcmVzaFRva2VuSGFzaDEiOiJjYWNhZDNlMGNhMDVkNzRlNWYzNTc4NmFlMGQ2MzJjNDhmMTg1YmZmNmUxNThjN2I2OThkZDYwMzA1NzAyYzI0IiwidXNlckRhdGEiOnt9LCJhbnRpQ3NyZlRva2VuIjoiYTA2MjRjYWItZmIwNy00NTFlLWJmOTYtNWQ3YzU2MjMwZTE4IiwiZXhwaXJ5VGltZSI6MTYyNjUxMjM3NDU4NiwidGltZUNyZWF0ZWQiOjE2MjY1MDg3NzQ1ODYsImxtcnQiOjE2MjY1MDg3NzQ1ODZ9.f1sCkjt0OduS6I6FBQDBLV5zhHXpCU2GXnbe+8OCU6HKG00TX5CM8AyFlOlqzSHABZ7jES/+5k0Ff/rdD34cczlNqICcC4a23AjJg2a097rFrh8/8V7J5fr4UrHLIM4ojZNFz1NyVyDK/ooE6I7soHshEtEVr2XsnJ4q3d+fYs2wwx97PIT82hfHqgbRAzvlv952GYt+OH4bWQE4vTzDqGN7N2OKpn9l2fiCB1Ytzr3ocHRqKuQ8f6xW1n575Q1sSs9F9TtD7lrKfFQH+//6lyKFe2Q1SDc7YU4pE5Cy9Kc/LiqiTU+gsGIJL5qtMzUTG4lX38ugF4QDyNjDBMqCKw==; Max-Age=3599; Expires=Sat, 17 Jul 2021 08:59:34 GMT; Secure; HttpOnly; SameSite=Lax; Path=/' * i.split(";")[0].split("=")[1] will result in eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsInZlcnNpb24iOiIyIn0 */ - accessToken = i.split(";")[0].split("=").slice(1).join("="); + accessToken = decodeURIComponent(i.split(";")[0].split("=").slice(1).join("=")); if (i.split(";")[2].includes("Expires=")) { accessTokenExpiry = i.split(";")[2].split("=")[1]; } else if (i.split(";")[2].includes("expires=")) { @@ -125,27 +124,25 @@ module.exports.extractInfoFromResponse = function (res) { refreshTokenDomain = i.split(";")[1].split("=").slice(1).join("="); } refreshTokenHttpOnly = i.split(";").findIndex((j) => j.includes("HttpOnly")) !== -1; - } else { - idRefreshTokenFromCookie = i.split(";")[0].split("=")[1]; - if (i.split(";")[2].includes("Expires=")) { - idRefreshTokenExpiry = i.split(";")[2].split("=")[1]; - } else if (i.split(";")[2].includes("expires=")) { - idRefreshTokenExpiry = i.split(";")[2].split("=")[1]; - } else { - idRefreshTokenExpiry = i.split(";")[3].split("=")[1]; - } - if (i.split(";")[1].includes("Domain=")) { - idRefreshTokenDomain = i.split(";")[1].split("=")[1]; - } - idRefreshTokenHttpOnly = i.split(";").findIndex((j) => j.includes("HttpOnly")) !== -1; } }); + + const refreshTokenFromHeader = res.headers["st-refresh-token"]; + const accessTokenFromHeader = res.headers["st-access-token"]; + + const accessTokenFromAny = accessToken === undefined ? accessTokenFromHeader : accessToken; + const refreshTokenFromAny = refreshToken === undefined ? refreshTokenFromHeader : refreshToken; + return { + status: res.status || res.statusCode, + body: res.body, antiCsrf, accessToken, refreshToken, - idRefreshTokenFromHeader, - idRefreshTokenFromCookie, + accessTokenFromHeader, + refreshTokenFromHeader, + accessTokenFromAny, + refreshTokenFromAny, accessTokenExpiry, refreshTokenExpiry, idRefreshTokenExpiry, @@ -363,6 +360,7 @@ module.exports.signUPRequest = async function (app, email, password) { return new Promise(function (resolve) { request(app) .post("/auth/signup") + .set("st-auth-mode", "cookie") .send({ formFields: [ { @@ -437,11 +435,11 @@ module.exports.signInUPCustomRequest = async function (app, email, id) { }); }; -module.exports.emailVerifyTokenRequest = async function (app, accessToken, idRefreshTokenFromCookie, antiCsrf, userId) { +module.exports.emailVerifyTokenRequest = async function (app, accessToken, antiCsrf, userId) { let result = await new Promise(function (resolve) { request(app) .post("/auth/user/email/verify/token") - .set("Cookie", ["sAccessToken=" + accessToken + ";sIdRefreshToken=" + idRefreshTokenFromCookie]) + .set("Cookie", ["sAccessToken=" + accessToken]) .set("anti-csrf", antiCsrf) .send({ userId, @@ -547,3 +545,17 @@ module.exports.mockResponse = () => { }; return res; }; + +/** + * + * @returns {import("express").Request} + */ +module.exports.mockRequest = () => { + const headers = {}; + const req = { + headers, + get: (key) => headers[key], + header: (key) => headers[key], + }; + return req; +}; diff --git a/test/with-typescript/index.ts b/test/with-typescript/index.ts index 4e38e7baf..3235a335d 100644 --- a/test/with-typescript/index.ts +++ b/test/with-typescript/index.ts @@ -26,6 +26,7 @@ import UserMetadata from "../../recipe/usermetadata"; import { BooleanClaim, PrimitiveClaim, SessionClaim } from "../../recipe/session/claims"; import UserRoles from "../../recipe/userroles"; import Dashboard from "../../recipe/dashboard"; +import JWT from "../../recipe/jwt"; UserRoles.init({ override: { @@ -1015,10 +1016,7 @@ Supertokens.init({ websiteDomain: "", }, recipeList: [ - Session.init({ - antiCsrf: "NONE", - cookieDomain: "", - }), + Session.init({ getTokenTransferMethod: () => "cookie", antiCsrf: "NONE", cookieDomain: "" }), EmailPassword.init({ override: {}, }), @@ -1202,7 +1200,7 @@ EmailPassword.init({ if (isAllowed) { // import Session from "supertokens-node/recipe/session" - let session = await Session.createNewSession(options.res, user.id); + let session = await Session.createNewSession(options.req, options.res, user.id); return { status: "OK", session, @@ -1362,3 +1360,68 @@ Supertokens.init({ Dashboard.init({ apiKey: "", }); + +Session.init({ + getTokenTransferMethod: () => "cookie", +}); + +Session.init({ + getTokenTransferMethod: () => "header", +}); + +Supertokens.init({ + appInfo: { + apiDomain: "..", + appName: "..", + websiteDomain: "..", + }, + recipeList: [JWT.init()], +}); + +app.post("/create-anonymous-session", async (req, res) => { + let token = await JWT.createJWT( + { + sub: "", + isAnonymous: true, + // other info... + }, + 3153600000 + ); // 100 years validity. + if (token.status !== "OK") { + throw new Error("Should never come here"); + } + res.json({ + token: token.jwt, + }); +}); + +Passwordless.init({ + contactMethod: "EMAIL", + flowType: "MAGIC_LINK", + override: { + functions: (original) => { + return { + ...original, + consumeCode: async function (input) { + let device = await Passwordless.listCodesByPreAuthSessionId({ + preAuthSessionId: input.preAuthSessionId, + }); + if (device !== undefined && input.userContext.calledManually === undefined) { + if (device.phoneNumber === "TEST_PHONE_NUMBER") { + let user = await Passwordless.signInUp({ + phoneNumber: "TEST_PHONE_NUMBER", + userContext: { calledManually: true }, + }); + return { + status: "OK", + createdNewUser: user.createdNewUser, + user: user.user, + }; + } + } + return original.consumeCode(input); + }, + }; + }, + }, +}); From 8f224d95c4d56559c7c34c529fec0ec716b89cc0 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Sun, 12 Feb 2023 04:25:31 +0530 Subject: [PATCH 30/82] merge with account-linking implementation --- lib/ts/recipe/emailpassword/api/implementation.ts | 6 +++--- lib/ts/recipe/emailpassword/index.ts | 4 ++-- lib/ts/recipe/emailpassword/recipeImplementation.ts | 6 +++--- lib/ts/recipe/emailpassword/types.ts | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 892f513f9..9a4366652 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -68,7 +68,7 @@ export default function getAPIImplementation(): APIInterface { let response = await options.recipeImplementation.signUp({ email, password, - doAutomaticAccountLinking: false, + doAccountLinking: false, userContext, }); if (response.status !== "OK") { @@ -465,7 +465,7 @@ export default function getAPIImplementation(): APIInterface { email, password: newPassword, userContext, - doAutomaticAccountLinking: false, + doAccountLinking: false, }); if (response.status !== "OK") { throw Error("this error should not be thrown. EP user already for email: " + email); @@ -580,7 +580,7 @@ export default function getAPIImplementation(): APIInterface { let response = await options.recipeImplementation.signUp({ email, password, - doAutomaticAccountLinking: true, + doAccountLinking: true, userContext, }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { diff --git a/lib/ts/recipe/emailpassword/index.ts b/lib/ts/recipe/emailpassword/index.ts index 8d59dac76..0673886c5 100644 --- a/lib/ts/recipe/emailpassword/index.ts +++ b/lib/ts/recipe/emailpassword/index.ts @@ -22,11 +22,11 @@ export default class Wrapper { static Error = SuperTokensError; - static signUp(email: string, password: string, doAutomaticAccountLinking = false, userContext?: any) { + static signUp(email: string, password: string, doAccountLinking = false, userContext?: any) { return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.signUp({ email, password, - doAutomaticAccountLinking, + doAccountLinking, userContext: userContext === undefined ? {} : userContext, }); } diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index 90df09cda..e5ad89889 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -10,12 +10,12 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { signUp: async function ({ email, password, - doAutomaticAccountLinking, + doAccountLinking, userContext, }: { email: string; password: string; - doAutomaticAccountLinking: boolean; + doAccountLinking: boolean; userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { @@ -23,7 +23,7 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { password, }); if (response.status === "OK") { - if (doAutomaticAccountLinking) { + if (doAccountLinking) { let primaryUserId = await AccountLinking.doPostSignUpAccountLinkingOperations( { email, diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index e2c636e4b..62116cd5a 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -94,7 +94,7 @@ export type RecipeInterface = { signUp(input: { email: string; password: string; - doAutomaticAccountLinking: boolean; + doAccountLinking: boolean; userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; From e3711125ce855bedeb69a70894b0e8be842969fe Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 13 Feb 2023 03:18:16 +0530 Subject: [PATCH 31/82] recipe implementation update --- lib/build/recipe/accountlinking/recipe.d.ts | 9 +++ lib/build/recipe/accountlinking/recipe.js | 54 +++++++++++++++++- .../accountlinking/recipeImplementation.js | 4 +- lib/build/recipe/emailpassword/index.d.ts | 2 +- lib/build/recipe/passwordless/index.d.ts | 2 +- .../recipe/thirdpartyemailpassword/index.d.ts | 2 +- .../recipe/thirdpartypasswordless/index.d.ts | 2 +- lib/ts/recipe/accountlinking/recipe.ts | 56 ++++++++++++++++++- .../accountlinking/recipeImplementation.ts | 13 +++-- 9 files changed, 131 insertions(+), 13 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 0ef5c4144..286527fce 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -52,6 +52,15 @@ export default class Recipe extends RecipeModule { info: AccountInfoAndEmailWithRecipeId; userContext: any; }) => Promise; + markEmailAsVerified: ({ + email, + recipeUserId, + userContext, + }: { + email: string; + recipeUserId: string; + userContext: any; + }) => Promise; doPostSignUpAccountLinkingOperations: ({ info, infoVerified, diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 476c95982..df0bf6667 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -57,6 +57,7 @@ const supertokens_js_override_1 = __importDefault(require("supertokens-js-overri const recipeImplementation_1 = __importDefault(require("./recipeImplementation")); const querier_1 = require("../../querier"); const error_1 = __importDefault(require("../../error")); +const recipe_1 = __importDefault(require("../emailverification/recipe")); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, config, _recipes, _ingredients) { super(recipeId, appInfo); @@ -145,6 +146,25 @@ class Recipe extends recipeModule_1.default { } throw Error("it should never reach here"); }); + this.markEmailAsVerified = ({ email, recipeUserId, userContext }) => + __awaiter(this, void 0, void 0, function* () { + const emailVerificationInstance = recipe_1.default.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: recipeUserId, + email: email, + userContext, + } + ); + if (tokenResponse.status === "OK") { + yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext, + }); + } + } + }); this.doPostSignUpAccountLinkingOperations = ({ info, infoVerified, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( @@ -463,22 +483,54 @@ class Recipe extends recipeModule_1.default { } let identitiesForPrimaryUser = this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; + let emailIdentityVerifiedForPrimaryUser = false; + let phoneNumberIdentityVerifiedForPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email) || identitiesForPrimaryUser.unverified.emails.includes(info.email); + emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email); } if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + phoneNumberIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.phoneNumbers.includes( + info.phoneNumber + ); } if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { /** - * TODO: let's Ly belongs to P1 such that Ly equal to Lx. + * let's Ly belongs to P1 such that Ly equal to Lx. * if LY verified, mark Lx as verified. If Lx is verfied, * then mark all Ly as verified */ + if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { + let recipeUserIdsForEmailVerificationUpdate = user.loginMethods + .filter((u) => u.email === info.email && !u.verified) + .map((l) => l.email); + if (!infoVerified) { + recipeUserIdsForEmailVerificationUpdate.push(recipeUser.id); + } + recipeUserIdsForEmailVerificationUpdate = Array.from( + new Set(recipeUserIdsForEmailVerificationUpdate) + ); + for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { + let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; + if (rUserId !== undefined) { + yield this.markEmailAsVerified({ + email: info.email, + recipeUserId: rUserId, + userContext, + }); + } + } + } else if ( + info.phoneNumber !== undefined && + (phoneNumberIdentityVerifiedForPrimaryUser || infoVerified) + ) { + // DISCUSS: should we consider this scenario. phoneNumber will always be verified + } } else { if (shouldDoAccountLinking.shouldRequireVerification) { if (!infoVerified) { diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 54ad7132d..7ded853d5 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -466,7 +466,7 @@ function getRecipeImplementation(querier, config) { fetchFromAccountToLinkTable: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), + new normalisedURLPath_1.default("/recipe/accountlinking/user/link/table"), { recipeUserId, } @@ -477,7 +477,7 @@ function getRecipeImplementation(querier, config) { storeIntoAccountToLinkTable: function ({ recipeUserId, primaryUserId }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), + new normalisedURLPath_1.default("/recipe/accountlinking/user/link/table"), { recipeUserId, primaryUserId, diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index b56deadee..51b059774 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -77,7 +77,7 @@ export default class Wrapper { password?: string; userContext?: any; }): Promise<{ - status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; }>; static sendEmail( input: TypeEmailPasswordEmailDeliveryInput & { diff --git a/lib/build/recipe/passwordless/index.d.ts b/lib/build/recipe/passwordless/index.d.ts index f8966f784..080d1a770 100644 --- a/lib/build/recipe/passwordless/index.d.ts +++ b/lib/build/recipe/passwordless/index.d.ts @@ -90,7 +90,7 @@ export default class Wrapper { phoneNumber?: string | null; userContext?: any; }): Promise<{ - status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; static revokeAllCodes( input: diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index 020257c41..d70cfdbe3 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -83,7 +83,7 @@ export default class Wrapper { password?: string; userContext?: any; }): Promise<{ - status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; }>; static Google: typeof import("../thirdparty/providers/google").default; static Github: typeof import("../thirdparty/providers/github").default; diff --git a/lib/build/recipe/thirdpartypasswordless/index.d.ts b/lib/build/recipe/thirdpartypasswordless/index.d.ts index e18b2425c..be4703e99 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/index.d.ts @@ -107,7 +107,7 @@ export default class Wrapper { phoneNumber?: string | null; userContext?: any; }): Promise<{ - status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; static revokeAllCodes( input: diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 1def947e2..33d22b70e 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -32,6 +32,7 @@ import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; import SuperTokensError from "../../error"; +import EmailVerification from "../emailverification/recipe"; export default class Recipe extends RecipeModule { private static instance: Recipe | undefined = undefined; @@ -242,6 +243,32 @@ export default class Recipe extends RecipeModule { throw Error("it should never reach here"); }; + markEmailAsVerified = async ({ + email, + recipeUserId, + userContext, + }: { + email: string; + recipeUserId: string; + userContext: any; + }): Promise => { + const emailVerificationInstance = EmailVerification.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ + userId: recipeUserId, + email: email, + userContext, + }); + + if (tokenResponse.status === "OK") { + await emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext, + }); + } + } + }; + doPostSignUpAccountLinkingOperations = async ({ info, infoVerified, @@ -614,22 +641,49 @@ export default class Recipe extends RecipeModule { let identitiesForPrimaryUser = this.getIdentitiesForUser(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; + let emailIdentityVerifiedForPrimaryUser = false; + let phoneNumberIdentityVerifiedForPrimaryUser = false; if (info.email !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email) || identitiesForPrimaryUser.unverified.emails.includes(info.email); + emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email); } if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + phoneNumberIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.phoneNumbers.includes( + info.phoneNumber + ); } if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { /** - * TODO: let's Ly belongs to P1 such that Ly equal to Lx. + * let's Ly belongs to P1 such that Ly equal to Lx. * if LY verified, mark Lx as verified. If Lx is verfied, * then mark all Ly as verified */ + if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { + let recipeUserIdsForEmailVerificationUpdate = user.loginMethods + .filter((u) => u.email === info.email && !u.verified) + .map((l) => l.email); + if (!infoVerified) { + recipeUserIdsForEmailVerificationUpdate.push(recipeUser.id); + } + recipeUserIdsForEmailVerificationUpdate = Array.from(new Set(recipeUserIdsForEmailVerificationUpdate)); + for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { + let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; + if (rUserId !== undefined) { + await this.markEmailAsVerified({ + email: info.email, + recipeUserId: rUserId, + userContext, + }); + } + } + } else if (info.phoneNumber !== undefined && (phoneNumberIdentityVerifiedForPrimaryUser || infoVerified)) { + // DISCUSS: should we consider this scenario. phoneNumber will always be verified + } } else { if (shouldDoAccountLinking.shouldRequireVerification) { if (!infoVerified) { diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index ed156d1f1..7ea0cec01 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -627,7 +627,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }: { recipeUserId: string; }): Promise { - let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user/link"), { + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user/link/table"), { recipeUserId, }); return result.user; @@ -639,10 +639,13 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo recipeUserId: string; primaryUserId: string; }): Promise<{ status: "OK" }> { - let result = await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/link"), { - recipeUserId, - primaryUserId, - }); + let result = await querier.sendPostRequest( + new NormalisedURLPath("/recipe/accountlinking/user/link/table"), + { + recipeUserId, + primaryUserId, + } + ); return result; }, }; From 30816fe019eae5e6c9acd08e2d8c96a0d04999c6 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Mon, 13 Feb 2023 07:46:11 +0530 Subject: [PATCH 32/82] account linking claim --- .../accountlinking/accountLinkingClaim.d.ts | 9 +++++ .../accountlinking/accountLinkingClaim.js | 19 ++++++++++ lib/build/recipe/accountlinking/index.d.ts | 11 +++++- lib/build/recipe/accountlinking/recipe.d.ts | 11 +++++- lib/build/recipe/accountlinking/recipe.js | 29 ++++++++++++++- .../accountlinking/accountLinkingClaim.ts | 17 +++++++++ lib/ts/recipe/accountlinking/recipe.ts | 37 +++++++++++++++++-- 7 files changed, 126 insertions(+), 7 deletions(-) create mode 100644 lib/build/recipe/accountlinking/accountLinkingClaim.d.ts create mode 100644 lib/build/recipe/accountlinking/accountLinkingClaim.js create mode 100644 lib/ts/recipe/accountlinking/accountLinkingClaim.ts diff --git a/lib/build/recipe/accountlinking/accountLinkingClaim.d.ts b/lib/build/recipe/accountlinking/accountLinkingClaim.d.ts new file mode 100644 index 000000000..f7141ffb6 --- /dev/null +++ b/lib/build/recipe/accountlinking/accountLinkingClaim.d.ts @@ -0,0 +1,9 @@ +// @ts-nocheck +import { PrimitiveClaim } from "../session/claims"; +/** + * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. + * */ +export declare class AccountLinkingClaimClass extends PrimitiveClaim { + constructor(); +} +export declare const AccountLinkingClaim: AccountLinkingClaimClass; diff --git a/lib/build/recipe/accountlinking/accountLinkingClaim.js b/lib/build/recipe/accountlinking/accountLinkingClaim.js new file mode 100644 index 000000000..c260f8de5 --- /dev/null +++ b/lib/build/recipe/accountlinking/accountLinkingClaim.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AccountLinkingClaim = exports.AccountLinkingClaimClass = void 0; +const claims_1 = require("../session/claims"); +/** + * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. + * */ +class AccountLinkingClaimClass extends claims_1.PrimitiveClaim { + constructor() { + super({ + key: "st-acl", + fetchValue(_, __, ___) { + return undefined; + }, + }); + } +} +exports.AccountLinkingClaimClass = AccountLinkingClaimClass; +exports.AccountLinkingClaim = new AccountLinkingClaimClass(); diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 3b8594e50..437bc5a6e 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -163,7 +163,16 @@ export default class Wrapper { recipeUserId: string, session: SessionContainer | undefined, userContext?: any - ): Promise; + ): Promise< + | { + createNewSession: false; + } + | { + createNewSession: true; + primaryUserId: string; + recipeUserId: string; + } + >; static onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any): Promise; static shouldDoAutomaticAccountLinking( newAccountInfo: AccountInfoAndEmailWithRecipeId, diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 286527fce..d8d5f9f1e 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -125,5 +125,14 @@ export default class Recipe extends RecipeModule { recipeUserId: string; session: SessionContainer | undefined; userContext: any; - }) => Promise; + }) => Promise< + | { + createNewSession: false; + } + | { + createNewSession: true; + primaryUserId: string; + recipeUserId: string; + } + >; } diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index df0bf6667..734028eca 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -58,6 +58,7 @@ const recipeImplementation_1 = __importDefault(require("./recipeImplementation") const querier_1 = require("../../querier"); const error_1 = __importDefault(require("../../error")); const recipe_1 = __importDefault(require("../emailverification/recipe")); +const accountLinkingClaim_1 = require("./accountLinkingClaim"); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, config, _recipes, _ingredients) { super(recipeId, appInfo); @@ -610,7 +611,10 @@ class Recipe extends recipeModule_1.default { recipeUserId: recipeUserId, userContext, }); - // TODO: remove session claim + // remove session claim + if (session !== undefined) { + yield session.removeClaim(accountLinkingClaim_1.AccountLinkingClaim, userContext); + } } } else { /** @@ -635,12 +639,33 @@ class Recipe extends recipeModule_1.default { userContext, }); if (linkAccountsResult.status === "OK") { - // TODO: remove session claim if session claim exists + // remove session claim if session claim exists // else create a new session + if (session !== undefined) { + let existingSessionClaimValue = yield session.getClaimValue( + accountLinkingClaim_1.AccountLinkingClaim, + userContext + ); + if (existingSessionClaimValue !== undefined) { + yield session.removeClaim( + accountLinkingClaim_1.AccountLinkingClaim, + userContext + ); + } else { + return { + createNewSession: true, + primaryUserId: primaryUser.id, + recipeUserId, + }; + } + } } } } } + return { + createNewSession: false, + }; }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); { diff --git a/lib/ts/recipe/accountlinking/accountLinkingClaim.ts b/lib/ts/recipe/accountlinking/accountLinkingClaim.ts new file mode 100644 index 000000000..b38087090 --- /dev/null +++ b/lib/ts/recipe/accountlinking/accountLinkingClaim.ts @@ -0,0 +1,17 @@ +import { PrimitiveClaim } from "../session/claims"; + +/** + * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. + * */ +export class AccountLinkingClaimClass extends PrimitiveClaim { + constructor() { + super({ + key: "st-acl", + fetchValue(_, __, ___) { + return undefined; + }, + }); + } +} + +export const AccountLinkingClaim = new AccountLinkingClaimClass(); diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 33d22b70e..2a28f0f16 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -33,6 +33,7 @@ import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; import SuperTokensError from "../../error"; import EmailVerification from "../emailverification/recipe"; +import { AccountLinkingClaim } from "./accountLinkingClaim"; export default class Recipe extends RecipeModule { private static instance: Recipe | undefined = undefined; @@ -762,7 +763,16 @@ export default class Recipe extends RecipeModule { recipeUserId: string; session: SessionContainer | undefined; userContext: any; - }) => { + }): Promise< + | { + createNewSession: false; + } + | { + createNewSession: true; + primaryUserId: string; + recipeUserId: string; + } + > => { let primaryUser = await this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ recipeUserId, userContext, @@ -785,7 +795,10 @@ export default class Recipe extends RecipeModule { recipeUserId: recipeUserId, userContext, }); - // TODO: remove session claim + // remove session claim + if (session !== undefined) { + await session.removeClaim(AccountLinkingClaim, userContext); + } } } else { /** @@ -812,11 +825,29 @@ export default class Recipe extends RecipeModule { userContext, }); if (linkAccountsResult.status === "OK") { - // TODO: remove session claim if session claim exists + // remove session claim if session claim exists // else create a new session + if (session !== undefined) { + let existingSessionClaimValue = await session.getClaimValue( + AccountLinkingClaim, + userContext + ); + if (existingSessionClaimValue !== undefined) { + await session.removeClaim(AccountLinkingClaim, userContext); + } else { + return { + createNewSession: true, + primaryUserId: primaryUser.id, + recipeUserId, + }; + } + } } } } } + return { + createNewSession: false, + }; }; } From 4b0ad7de59d441a9301ba3bd08075fd979b4b171 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 22 Feb 2023 11:59:33 +0530 Subject: [PATCH 33/82] changes to dashboard recipe types --- lib/build/recipe/dashboard/types.d.ts | 23 ++++++---------- lib/build/recipe/dashboard/utils.d.ts | 11 ++------ .../dashboard/api/userdetails/userGet.ts | 27 +++---------------- lib/ts/recipe/dashboard/types.ts | 27 +++++++------------ lib/ts/recipe/dashboard/utils.ts | 8 +++--- 5 files changed, 26 insertions(+), 70 deletions(-) diff --git a/lib/build/recipe/dashboard/types.d.ts b/lib/build/recipe/dashboard/types.d.ts index 0ef772c19..af1b0c65c 100644 --- a/lib/build/recipe/dashboard/types.d.ts +++ b/lib/build/recipe/dashboard/types.d.ts @@ -40,24 +40,17 @@ export declare type APIInterface = { }; export declare type APIFunction = (apiImplementation: APIInterface, options: APIOptions) => Promise; export declare type RecipeIdForUser = "emailpassword" | "thirdparty" | "passwordless"; -declare type CommonUserInformation = { +export declare type RecipeLevelUser = { + recipeId: "emailpassword" | "thirdparty" | "passwordless"; id: string; timeJoined: number; - firstName: string; - lastName: string; -}; -export declare type EmailPasswordUser = CommonUserInformation & { - email: string; -}; -export declare type ThirdPartyUser = CommonUserInformation & { - email: string; - thirdParty: { + recipeUserId: string; + email?: string; + phoneNumber?: string; + thirdParty?: { id: string; userId: string; }; + firstName: string; + lastName: string; }; -export declare type PasswordlessUser = CommonUserInformation & { - email?: string; - phone?: string; -}; -export {}; diff --git a/lib/build/recipe/dashboard/utils.d.ts b/lib/build/recipe/dashboard/utils.d.ts index 445c41359..dc6d04a43 100644 --- a/lib/build/recipe/dashboard/utils.d.ts +++ b/lib/build/recipe/dashboard/utils.d.ts @@ -2,14 +2,7 @@ import { BaseResponse } from "../../framework"; import NormalisedURLPath from "../../normalisedURLPath"; import { HTTPMethod, NormalisedAppinfo } from "../../types"; -import { - EmailPasswordUser, - PasswordlessUser, - RecipeIdForUser, - ThirdPartyUser, - TypeInput, - TypeNormalisedInput, -} from "./types"; +import { RecipeIdForUser, TypeInput, TypeNormalisedInput, RecipeLevelUser } from "./types"; export declare function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput; export declare function isApiPath(path: NormalisedURLPath, appInfo: NormalisedAppinfo): boolean; export declare function getApiIdIfMatched(path: NormalisedURLPath, method: HTTPMethod): string | undefined; @@ -19,7 +12,7 @@ export declare function getUserForRecipeId( userId: string, recipeId: string ): Promise<{ - user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined; + user: RecipeLevelUser | undefined; recipe: | "emailpassword" | "thirdparty" diff --git a/lib/ts/recipe/dashboard/api/userdetails/userGet.ts b/lib/ts/recipe/dashboard/api/userdetails/userGet.ts index d11baa056..ec17cb14e 100644 --- a/lib/ts/recipe/dashboard/api/userdetails/userGet.ts +++ b/lib/ts/recipe/dashboard/api/userdetails/userGet.ts @@ -1,11 +1,4 @@ -import { - APIFunction, - APIInterface, - APIOptions, - EmailPasswordUser, - PasswordlessUser, - ThirdPartyUser, -} from "../../types"; +import { APIFunction, APIInterface, APIOptions, RecipeLevelUser } from "../../types"; import STError from "../../../../error"; import { getUserForRecipeId, isRecipeInitialised, isValidRecipeId } from "../../utils"; import UserMetaDataRecipe from "../../../usermetadata/recipe"; @@ -20,18 +13,8 @@ type Response = } | { status: "OK"; - recipeId: "emailpassword"; - user: EmailPasswordUser; - } - | { - status: "OK"; - recipeId: "thirdparty"; - user: ThirdPartyUser; - } - | { - status: "OK"; - recipeId: "passwordless"; - user: PasswordlessUser; + recipeId: "emailpassword" | "thirdparty" | "passwordless"; + user: RecipeLevelUser; }; export const userGet: APIFunction = async (_: APIInterface, options: APIOptions): Promise => { @@ -65,9 +48,7 @@ export const userGet: APIFunction = async (_: APIInterface, options: APIOptions) }; } - let user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined = ( - await getUserForRecipeId(userId, recipeId) - ).user; + let user: RecipeLevelUser | undefined = (await getUserForRecipeId(userId, recipeId)).user; if (user === undefined) { return { diff --git a/lib/ts/recipe/dashboard/types.ts b/lib/ts/recipe/dashboard/types.ts index 155677420..a78c3e7d1 100644 --- a/lib/ts/recipe/dashboard/types.ts +++ b/lib/ts/recipe/dashboard/types.ts @@ -62,26 +62,17 @@ export type APIFunction = (apiImplementation: APIInterface, options: APIOptions) export type RecipeIdForUser = "emailpassword" | "thirdparty" | "passwordless"; -type CommonUserInformation = { - id: string; +export type RecipeLevelUser = { + recipeId: "emailpassword" | "thirdparty" | "passwordless"; + id: string; // can be recipeUserId or primaryUserId timeJoined: number; - firstName: string; - lastName: string; -}; - -export type EmailPasswordUser = CommonUserInformation & { - email: string; -}; - -export type ThirdPartyUser = CommonUserInformation & { - email: string; - thirdParty: { + recipeUserId: string; + email?: string; + phoneNumber?: string; + thirdParty?: { id: string; userId: string; }; -}; - -export type PasswordlessUser = CommonUserInformation & { - email?: string; - phone?: string; + firstName: string; + lastName: string; }; diff --git a/lib/ts/recipe/dashboard/utils.ts b/lib/ts/recipe/dashboard/utils.ts index 784de18b9..1eff4b257 100644 --- a/lib/ts/recipe/dashboard/utils.ts +++ b/lib/ts/recipe/dashboard/utils.ts @@ -31,13 +31,11 @@ import { } from "./constants"; import { APIInterface, - EmailPasswordUser, - PasswordlessUser, RecipeIdForUser, RecipeInterface, - ThirdPartyUser, TypeInput, TypeNormalisedInput, + RecipeLevelUser, } from "./types"; import Supertokens from "../.."; import EmailPasswordRecipe from "../emailpassword/recipe"; @@ -146,7 +144,7 @@ export async function getUserForRecipeId( userId: string, recipeId: string ): Promise<{ - user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined; + user: RecipeLevelUser | undefined; recipe: | "emailpassword" | "thirdparty" @@ -156,7 +154,7 @@ export async function getUserForRecipeId( | undefined; }> { let userResponse = await Supertokens.getUserForRecipeId(userId, recipeId); - let user: EmailPasswordUser | ThirdPartyUser | PasswordlessUser | undefined = undefined; + let user: RecipeLevelUser | undefined = undefined; if (userResponse.user !== undefined) { user = { ...userResponse.user, From ed5865ccbac92e35a198a99c03f38d35c634cacc Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 22 Feb 2023 12:35:32 +0530 Subject: [PATCH 34/82] removes unnecessary functions exposed from account linking recipe --- lib/build/recipe/accountlinking/index.d.ts | 99 +--------------------- lib/build/recipe/accountlinking/index.js | 74 +--------------- lib/ts/recipe/accountlinking/index.ts | 91 +------------------- 3 files changed, 6 insertions(+), 258 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 3b8594e50..16e13235f 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,8 +1,6 @@ // @ts-nocheck -import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { AccountInfoAndEmailWithRecipeId, RecipeInterface, RecipeLevelUser } from "./types"; -import type { User } from "../../types"; +import type { RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static getRecipeUserIdsForPrimaryUserIds( @@ -47,7 +45,7 @@ export default class Wrapper { ): Promise< | { status: "OK"; - user: User; + user: import("../../types").User; } | { status: @@ -115,91 +113,10 @@ export default class Wrapper { status: "NO_PRIMARY_USER_FOUND"; } >; - static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId( + static fetchFromAccountToLinkTable( recipeUserId: string, userContext?: any - ): Promise; - static isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any): Promise; - static doPostSignUpAccountLinkingOperations( - info: AccountInfoAndEmailWithRecipeId, - infoVerified: boolean, - recipeUserId: string, - userContext: any - ): Promise; - static accountLinkPostSignInViaSession( - session: SessionContainer, - info: AccountInfoAndEmailWithRecipeId, - infoVerified: boolean, - userContext: any - ): Promise< - | { - createRecipeUser: true; - updateVerificationClaim: boolean; - } - | ({ - createRecipeUser: false; - } & ( - | { - accountsLinked: true; - updateVerificationClaim: boolean; - } - | { - accountsLinked: false; - reason: - | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" - | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" - | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; - } - | { - accountsLinked: false; - reason: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - } - )) - >; - static createPrimaryUserIdOrLinkAccounts( - recipeUserId: string, - session: SessionContainer | undefined, - userContext?: any - ): Promise; - static onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any): Promise; - static shouldDoAutomaticAccountLinking( - newAccountInfo: AccountInfoAndEmailWithRecipeId, - user: User | undefined, - session: SessionContainer | undefined, - userContext?: any - ): Promise< - | { - shouldAutomaticallyLink: false; - } - | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - } - >; - static getIdentitiesForUser( - user: User - ): { - verified: { - emails: string[]; - phoneNumbers: string[]; - thirdpartyInfo: { - id: string; - userId: string; - }[]; - }; - unverified: { - emails: string[]; - phoneNumbers: string[]; - thirdpartyInfo: { - id: string; - userId: string; - }[]; - }; - }; - static fetchFromAccountToLinkTable(recipeUserId: string, userContext?: any): Promise; + ): Promise; static storeIntoAccountToLinkTable( recipeUserId: string, primaryUserId: string, @@ -217,14 +134,6 @@ export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; export declare const canLinkAccounts: typeof Wrapper.canLinkAccounts; export declare const linkAccounts: typeof Wrapper.linkAccounts; export declare const unlinkAccounts: typeof Wrapper.unlinkAccounts; -export declare const getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId: typeof Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; -export declare const isSignUpAllowed: typeof Wrapper.isSignUpAllowed; -export declare const doPostSignUpAccountLinkingOperations: typeof Wrapper.doPostSignUpAccountLinkingOperations; -export declare const accountLinkPostSignInViaSession: typeof Wrapper.accountLinkPostSignInViaSession; -export declare const createPrimaryUserIdOrLinkAccounts: typeof Wrapper.createPrimaryUserIdOrLinkAccounts; -export declare const onAccountLinked: typeof Wrapper.onAccountLinked; -export declare const shouldDoAutomaticAccountLinking: typeof Wrapper.shouldDoAutomaticAccountLinking; -export declare const getIdentitiesForUser: typeof Wrapper.getIdentitiesForUser; export declare const fetchFromAccountToLinkTable: typeof Wrapper.fetchFromAccountToLinkTable; export declare const storeIntoAccountToLinkTable: typeof Wrapper.storeIntoAccountToLinkTable; export type { RecipeInterface }; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index ce4cbd24c..4002928ef 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -50,7 +50,7 @@ var __importDefault = return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.storeIntoAccountToLinkTable = exports.fetchFromAccountToLinkTable = exports.getIdentitiesForUser = exports.shouldDoAutomaticAccountLinking = exports.onAccountLinked = exports.createPrimaryUserIdOrLinkAccounts = exports.accountLinkPostSignInViaSession = exports.doPostSignUpAccountLinkingOperations = exports.isSignUpAllowed = exports.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = exports.unlinkAccounts = exports.linkAccounts = exports.canLinkAccounts = exports.createPrimaryUser = exports.canCreatePrimaryUserId = exports.addNewRecipeUserIdWithoutPrimaryUserId = exports.getPrimaryUserIdsforRecipeUserIds = exports.getRecipeUserIdsForPrimaryUserIds = exports.init = void 0; +exports.storeIntoAccountToLinkTable = exports.fetchFromAccountToLinkTable = exports.unlinkAccounts = exports.linkAccounts = exports.canLinkAccounts = exports.createPrimaryUser = exports.canCreatePrimaryUserId = exports.addNewRecipeUserIdWithoutPrimaryUserId = exports.getPrimaryUserIdsforRecipeUserIds = exports.getRecipeUserIdsForPrimaryUserIds = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); class Wrapper { static getRecipeUserIdsForPrimaryUserIds(primaryUserIds, userContext) { @@ -127,70 +127,6 @@ class Wrapper { }); }); } - static getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId(recipeUserId, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ - recipeUserId, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } - static isSignUpAllowed(info, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().isSignUpAllowed({ - info, - userContext, - }); - }); - } - static doPostSignUpAccountLinkingOperations(info, infoVerified, recipeUserId, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations({ - info, - infoVerified, - recipeUserId, - userContext, - }); - }); - } - static accountLinkPostSignInViaSession(session, info, infoVerified, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ - session, - info, - infoVerified, - userContext, - }); - }); - } - static createPrimaryUserIdOrLinkAccounts(recipeUserId, session, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ - recipeUserId, - session, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } - static onAccountLinked(user, newAccountInfo, userContext) { - return __awaiter(this, void 0, void 0, function* () { - userContext = userContext === undefined ? {} : userContext; - return yield recipe_1.default - .getInstanceOrThrowError() - .config.onAccountLinked(user, newAccountInfo, userContext); - }); - } - static shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext) { - return __awaiter(this, void 0, void 0, function* () { - userContext = userContext === undefined ? {} : userContext; - return yield recipe_1.default - .getInstanceOrThrowError() - .config.shouldDoAutomaticAccountLinking(newAccountInfo, user, session, userContext); - }); - } - static getIdentitiesForUser(user) { - return recipe_1.default.getInstanceOrThrowError().getIdentitiesForUser(user); - } static fetchFromAccountToLinkTable(recipeUserId, userContext) { return __awaiter(this, void 0, void 0, function* () { userContext = userContext === undefined ? {} : userContext; @@ -222,13 +158,5 @@ exports.createPrimaryUser = Wrapper.createPrimaryUser; exports.canLinkAccounts = Wrapper.canLinkAccounts; exports.linkAccounts = Wrapper.linkAccounts; exports.unlinkAccounts = Wrapper.unlinkAccounts; -exports.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; -exports.isSignUpAllowed = Wrapper.isSignUpAllowed; -exports.doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; -exports.accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; -exports.createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; -exports.onAccountLinked = Wrapper.onAccountLinked; -exports.shouldDoAutomaticAccountLinking = Wrapper.shouldDoAutomaticAccountLinking; -exports.getIdentitiesForUser = Wrapper.getIdentitiesForUser; exports.fetchFromAccountToLinkTable = Wrapper.fetchFromAccountToLinkTable; exports.storeIntoAccountToLinkTable = Wrapper.storeIntoAccountToLinkTable; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index 0e6d4c993..92b91e83c 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -13,10 +13,8 @@ * under the License. */ -import { SessionContainer } from "../session"; import Recipe from "./recipe"; -import type { AccountInfoAndEmailWithRecipeId, RecipeInterface, RecipeLevelUser } from "./types"; -import type { User } from "../../types"; +import type { RecipeInterface } from "./types"; export default class Wrapper { static init = Recipe.init; @@ -85,84 +83,6 @@ export default class Wrapper { }); } - static async getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId(recipeUserId: string, userContext?: any) { - return await Recipe.getInstanceOrThrowError().getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ - recipeUserId, - userContext: userContext === undefined ? {} : userContext, - }); - } - - static async isSignUpAllowed(info: AccountInfoAndEmailWithRecipeId, userContext: any) { - return await Recipe.getInstanceOrThrowError().isSignUpAllowed({ - info, - userContext, - }); - } - - static async doPostSignUpAccountLinkingOperations( - info: AccountInfoAndEmailWithRecipeId, - infoVerified: boolean, - recipeUserId: string, - userContext: any - ) { - return await Recipe.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations({ - info, - infoVerified, - recipeUserId, - userContext, - }); - } - - static async accountLinkPostSignInViaSession( - session: SessionContainer, - info: AccountInfoAndEmailWithRecipeId, - infoVerified: boolean, - userContext: any - ) { - return await Recipe.getInstanceOrThrowError().accountLinkPostSignInViaSession({ - session, - info, - infoVerified, - userContext, - }); - } - - static async createPrimaryUserIdOrLinkAccounts( - recipeUserId: string, - session: SessionContainer | undefined, - userContext?: any - ) { - return await Recipe.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ - recipeUserId, - session, - userContext: userContext === undefined ? {} : userContext, - }); - } - - static async onAccountLinked(user: User, newAccountInfo: RecipeLevelUser, userContext?: any) { - userContext = userContext === undefined ? {} : userContext; - return await Recipe.getInstanceOrThrowError().config.onAccountLinked(user, newAccountInfo, userContext); - } - - static async shouldDoAutomaticAccountLinking( - newAccountInfo: AccountInfoAndEmailWithRecipeId, - user: User | undefined, - session: SessionContainer | undefined, - userContext?: any - ) { - userContext = userContext === undefined ? {} : userContext; - return await Recipe.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( - newAccountInfo, - user, - session, - userContext - ); - } - - static getIdentitiesForUser(user: User) { - return Recipe.getInstanceOrThrowError().getIdentitiesForUser(user); - } - static async fetchFromAccountToLinkTable(recipeUserId: string, userContext?: any) { userContext = userContext === undefined ? {} : userContext; return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.fetchFromAccountToLinkTable({ @@ -190,15 +110,6 @@ export const createPrimaryUser = Wrapper.createPrimaryUser; export const canLinkAccounts = Wrapper.canLinkAccounts; export const linkAccounts = Wrapper.linkAccounts; export const unlinkAccounts = Wrapper.unlinkAccounts; -export const getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId = - Wrapper.getPrimaryUserIdLinkedOrCanBeLinkedToRecipeUserId; -export const isSignUpAllowed = Wrapper.isSignUpAllowed; -export const doPostSignUpAccountLinkingOperations = Wrapper.doPostSignUpAccountLinkingOperations; -export const accountLinkPostSignInViaSession = Wrapper.accountLinkPostSignInViaSession; -export const createPrimaryUserIdOrLinkAccounts = Wrapper.createPrimaryUserIdOrLinkAccounts; -export const onAccountLinked = Wrapper.onAccountLinked; -export const shouldDoAutomaticAccountLinking = Wrapper.shouldDoAutomaticAccountLinking; -export const getIdentitiesForUser = Wrapper.getIdentitiesForUser; export const fetchFromAccountToLinkTable = Wrapper.fetchFromAccountToLinkTable; export const storeIntoAccountToLinkTable = Wrapper.storeIntoAccountToLinkTable; From de434e99027d5a70521e61befa8192a9334e2a21 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Thu, 23 Feb 2023 15:47:59 +0530 Subject: [PATCH 35/82] adds a precautionary check --- lib/build/recipe/accountlinking/recipe.js | 3 +++ lib/ts/recipe/accountlinking/recipe.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index df0bf6667..fe2f2d9ff 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -173,6 +173,9 @@ class Recipe extends recipeModule_1.default { undefined, userContext ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } if ( shouldDoAccountLinking.shouldAutomaticallyLink && shouldDoAccountLinking.shouldRequireVerification diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 33d22b70e..7d9985ca9 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -286,6 +286,9 @@ export default class Recipe extends RecipeModule { undefined, userContext ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } if (shouldDoAccountLinking.shouldAutomaticallyLink && shouldDoAccountLinking.shouldRequireVerification) { if (!infoVerified) { return recipeUserId; From 6603119e0b76fde6576efe9e00eda5f57fae7221 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Thu, 23 Feb 2023 16:17:51 +0530 Subject: [PATCH 36/82] small change --- lib/build/recipe/accountlinking/recipe.js | 5 +---- lib/ts/recipe/accountlinking/recipe.ts | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index fe2f2d9ff..e6c74a926 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -176,10 +176,7 @@ class Recipe extends recipeModule_1.default { if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return recipeUserId; } - if ( - shouldDoAccountLinking.shouldAutomaticallyLink && - shouldDoAccountLinking.shouldRequireVerification - ) { + if (shouldDoAccountLinking.shouldRequireVerification) { if (!infoVerified) { return recipeUserId; } diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 7d9985ca9..c31c23509 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -289,7 +289,7 @@ export default class Recipe extends RecipeModule { if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return recipeUserId; } - if (shouldDoAccountLinking.shouldAutomaticallyLink && shouldDoAccountLinking.shouldRequireVerification) { + if (shouldDoAccountLinking.shouldRequireVerification) { if (!infoVerified) { return recipeUserId; } From 8bd66896132ff06259f3067033bdf0636e41c9b1 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:56:51 +0530 Subject: [PATCH 37/82] Update lib/ts/types.ts Co-authored-by: Rishabh Poddar --- lib/ts/types.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/ts/types.ts b/lib/ts/types.ts index b9749a59e..21b70388f 100644 --- a/lib/ts/types.ts +++ b/lib/ts/types.ts @@ -81,9 +81,9 @@ export type User = { isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + thirdParty: { + id: string; + userId: string; }[]; loginMethods: (RecipeLevelUser & { verified: boolean; From 35f00161a48509e47d9495b05a3a005dbe38c500 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:57:47 +0530 Subject: [PATCH 38/82] Update lib/ts/index.ts Co-authored-by: Rishabh Poddar --- lib/ts/index.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/ts/index.ts b/lib/ts/index.ts index 098f8b330..4147428ad 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -72,9 +72,6 @@ export default class SuperTokensWrapper { return SuperTokens.getInstanceOrThrowError().createUserIdMapping(input); } - static getUserForRecipeId(userId: string, recipeId: string) { - return SuperTokens.getInstanceOrThrowError().getUserForRecipeId(userId, recipeId); - } static getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }) { return SuperTokens.getInstanceOrThrowError().getUserIdMapping(input); From 30802c011705d4b458c8ca703e6f79e6562a03a5 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:57:58 +0530 Subject: [PATCH 39/82] Update lib/ts/supertokens.ts Co-authored-by: Rishabh Poddar --- lib/ts/supertokens.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index f470b115d..3e6243fab 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -406,7 +406,8 @@ export default class SuperTokens { throw err; }; - getUserForRecipeId = async ( + // this is an internal use function, therefore it is prefixed with an `_` + _getUserForRecipeId = async ( userId: string, recipeId: string ): Promise<{ From 943dde499569f14ec79d486b519882ad5f37295b Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:58:10 +0530 Subject: [PATCH 40/82] Update lib/ts/recipe/dashboard/api/usersGet.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/dashboard/api/usersGet.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/ts/recipe/dashboard/api/usersGet.ts b/lib/ts/recipe/dashboard/api/usersGet.ts index 8c36dab68..78539b382 100644 --- a/lib/ts/recipe/dashboard/api/usersGet.ts +++ b/lib/ts/recipe/dashboard/api/usersGet.ts @@ -25,9 +25,9 @@ type User = { isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + thirdParty: { + id: string; + userId: string; }[]; firstName?: string; lastName?: string; From 84d56d733ba16659a08beaca8ab4ca95b49e031a Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:58:21 +0530 Subject: [PATCH 41/82] Update lib/ts/index.ts Co-authored-by: Rishabh Poddar --- lib/ts/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/ts/index.ts b/lib/ts/index.ts index 4147428ad..e80821ab5 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -146,6 +146,5 @@ export let listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; export let getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; -export let getUserForRecipeId = SuperTokensWrapper.getUserForRecipeId; export let Error = SuperTokensWrapper.Error; From 5b68aa24415f3ca23cdb26faf6507b4620344171 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:58:34 +0530 Subject: [PATCH 42/82] Update lib/ts/index.ts Co-authored-by: Rishabh Poddar --- lib/ts/index.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/lib/ts/index.ts b/lib/ts/index.ts index e80821ab5..64062c0f8 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -105,12 +105,6 @@ export default class SuperTokensWrapper { userContext: userContext === undefined ? {} : userContext, }); } - static async getUserByAccountInfo(info: AccountInfoWithRecipeId, userContext?: any) { - return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ - info, - userContext: userContext === undefined ? {} : userContext, - }); - } static async deleteUser(userId: string, removeAllLinkedAccounts: boolean = true, userContext?: any) { return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ userId, From e36e9ffb0b6fbc9843b8f87c5821c7f487745ae2 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:58:47 +0530 Subject: [PATCH 43/82] Update lib/ts/index.ts Co-authored-by: Rishabh Poddar --- lib/ts/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/ts/index.ts b/lib/ts/index.ts index 64062c0f8..fa11dedf4 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -138,7 +138,6 @@ export let getUser = SuperTokensWrapper.getUser; export let listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; -export let getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; export let Error = SuperTokensWrapper.Error; From 1db095fcf9978cf3ccf7ea68aa3698256aaaf267 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:58:57 +0530 Subject: [PATCH 44/82] Update lib/ts/recipe/accountlinking/types.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/types.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 7def9756b..e9186280e 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -188,7 +188,6 @@ export type RecipeInterface = { >; getUser: (input: { userId: string; userContext: any }) => Promise; listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; - getUserByAccountInfo: (input: { info: AccountInfoWithRecipeId; userContext: any }) => Promise; deleteUser: (input: { userId: string; removeAllLinkedAccounts: boolean; From 2454f46387223d149aa82bdc279ca3379b277255 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:59:14 +0530 Subject: [PATCH 45/82] Update lib/ts/recipe/accountlinking/recipe.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipe.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index c31c23509..2273617ee 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -113,7 +113,7 @@ export default class Recipe extends RecipeModule { verified: { emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { + thirdParty: { id: string; userId: string; }[]; From 8b021e66d68d930326c9b3906e8a0ece938c4f6f Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 11:59:25 +0530 Subject: [PATCH 46/82] Update lib/ts/recipe/accountlinking/recipe.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipe.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 2273617ee..215e92906 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -121,7 +121,7 @@ export default class Recipe extends RecipeModule { unverified: { emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { + thirdParty: { id: string; userId: string; }[]; From 6a0134be93b22a4e82bfedf1b928ecdfe934f50e Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 12:17:07 +0530 Subject: [PATCH 47/82] Update lib/ts/recipe/accountlinking/recipe.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipe.ts | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 215e92906..b33581e44 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -337,15 +337,7 @@ export default class Recipe extends RecipeModule { if (primaryUser === undefined) { throw Error("this error should never be thrown"); } - shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( - info, - primaryUser, - undefined, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return recipeUserId; - } + let result = await this.recipeInterfaceImpl.linkAccounts({ recipeUserId, primaryUserId: primaryUser.id, From 10f3d9f60c8637dcf505d717dc27396b09afbb3b Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 12:17:44 +0530 Subject: [PATCH 48/82] Update lib/ts/recipe/accountlinking/types.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index e9186280e..a97549580 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -187,7 +187,7 @@ export type RecipeInterface = { } >; getUser: (input: { userId: string; userContext: any }) => Promise; - listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; + listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; deleteUser: (input: { userId: string; removeAllLinkedAccounts: boolean; From ec3eca340c073cd546befcf253fa878e9863429e Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Fri, 24 Feb 2023 12:18:00 +0530 Subject: [PATCH 49/82] Update lib/ts/recipe/accountlinking/recipe.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipe.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index b33581e44..738900f17 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -212,7 +212,7 @@ export default class Recipe extends RecipeModule { info: identifier, userContext, }); - if (users === undefined || users.length === 0) { + if (users.length === 0) { return true; } let primaryUser = users.find((u) => u.isPrimaryUser); From 30e0f300df90c784f50c8e8009fecd0f42c13d1b Mon Sep 17 00:00:00 2001 From: Bhumil Date: Fri, 24 Feb 2023 14:03:20 +0530 Subject: [PATCH 50/82] code review changes --- lib/build/index.d.ts | 20 +- lib/build/index.js | 15 +- lib/build/recipe/accountlinking/recipe.d.ts | 4 +- lib/build/recipe/accountlinking/recipe.js | 163 +++++++++------- .../accountlinking/recipeImplementation.js | 32 +--- lib/build/recipe/accountlinking/types.d.ts | 8 +- lib/build/recipe/dashboard/api/usersGet.d.ts | 6 +- lib/build/recipe/dashboard/utils.js | 4 +- lib/build/supertokens.d.ts | 2 +- lib/build/supertokens.js | 3 +- lib/build/types.d.ts | 6 +- lib/ts/index.ts | 5 +- lib/ts/recipe/accountlinking/recipe.ts | 180 ++++++++++-------- .../accountlinking/recipeImplementation.ts | 34 +--- lib/ts/recipe/accountlinking/types.ts | 5 +- lib/ts/recipe/dashboard/utils.ts | 4 +- 16 files changed, 229 insertions(+), 262 deletions(-) diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index 2868b27a1..0dd941bda 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -2,7 +2,7 @@ import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; import { User } from "./types"; -import { AccountInfo, AccountInfoWithRecipeId } from "./recipe/accountlinking/types"; +import { AccountInfo } from "./recipe/accountlinking/types"; export default class SuperTokensWrapper { static init: typeof SuperTokens.init; static Error: typeof SuperTokensError; @@ -39,19 +39,6 @@ export default class SuperTokensWrapper { doesExternalUserIdExist: boolean; } >; - static getUserForRecipeId( - userId: string, - recipeId: string - ): Promise<{ - user: import("./recipe/accountlinking/types").RecipeLevelUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; - }>; static getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; @@ -82,8 +69,7 @@ export default class SuperTokensWrapper { status: "OK" | "UNKNOWN_MAPPING_ERROR"; }>; static getUser(userId: string, userContext?: any): Promise; - static listUsersByAccountInfo(info: AccountInfo, userContext?: any): Promise; - static getUserByAccountInfo(info: AccountInfoWithRecipeId, userContext?: any): Promise; + static listUsersByAccountInfo(info: AccountInfo, userContext?: any): Promise; static deleteUser( userId: string, removeAllLinkedAccounts?: boolean, @@ -104,6 +90,4 @@ export declare let deleteUserIdMapping: typeof SuperTokensWrapper.deleteUserIdMa export declare let updateOrDeleteUserIdMappingInfo: typeof SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; export declare let getUser: typeof SuperTokensWrapper.getUser; export declare let listUsersByAccountInfo: typeof SuperTokensWrapper.listUsersByAccountInfo; -export declare let getUserByAccountInfo: typeof SuperTokensWrapper.getUserByAccountInfo; -export declare let getUserForRecipeId: typeof SuperTokensWrapper.getUserForRecipeId; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/index.js b/lib/build/index.js index 76d4ace10..263d43464 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -50,7 +50,7 @@ var __importDefault = return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.Error = exports.getUserForRecipeId = exports.getUserByAccountInfo = exports.listUsersByAccountInfo = exports.getUser = exports.updateOrDeleteUserIdMappingInfo = exports.deleteUserIdMapping = exports.getUserIdMapping = exports.createUserIdMapping = exports.deleteUser = exports.getUsersNewestFirst = exports.getUsersOldestFirst = exports.getUserCount = exports.getAllCORSHeaders = exports.init = void 0; +exports.Error = exports.listUsersByAccountInfo = exports.getUser = exports.updateOrDeleteUserIdMappingInfo = exports.deleteUserIdMapping = exports.getUserIdMapping = exports.createUserIdMapping = exports.deleteUser = exports.getUsersNewestFirst = exports.getUsersOldestFirst = exports.getUserCount = exports.getAllCORSHeaders = exports.init = void 0; const supertokens_1 = __importDefault(require("./supertokens")); const error_1 = __importDefault(require("./error")); const recipe_1 = __importDefault(require("./recipe/accountlinking/recipe")); @@ -79,9 +79,6 @@ class SuperTokensWrapper { static createUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().createUserIdMapping(input); } - static getUserForRecipeId(userId, recipeId) { - return supertokens_1.default.getInstanceOrThrowError().getUserForRecipeId(userId, recipeId); - } static getUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().getUserIdMapping(input); } @@ -107,14 +104,6 @@ class SuperTokensWrapper { }); }); } - static getUserByAccountInfo(info, userContext) { - return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByAccountInfo({ - info, - userContext: userContext === undefined ? {} : userContext, - }); - }); - } static deleteUser(userId, removeAllLinkedAccounts = true, userContext) { return __awaiter(this, void 0, void 0, function* () { return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.deleteUser({ @@ -140,6 +129,4 @@ exports.deleteUserIdMapping = SuperTokensWrapper.deleteUserIdMapping; exports.updateOrDeleteUserIdMappingInfo = SuperTokensWrapper.updateOrDeleteUserIdMappingInfo; exports.getUser = SuperTokensWrapper.getUser; exports.listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; -exports.getUserByAccountInfo = SuperTokensWrapper.getUserByAccountInfo; -exports.getUserForRecipeId = SuperTokensWrapper.getUserForRecipeId; exports.Error = SuperTokensWrapper.Error; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 286527fce..581e8295f 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -31,7 +31,7 @@ export default class Recipe extends RecipeModule { verified: { emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { + thirdParty: { id: string; userId: string; }[]; @@ -39,7 +39,7 @@ export default class Recipe extends RecipeModule { unverified: { emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { + thirdParty: { id: string; userId: string; }[]; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index e6c74a926..428914fa8 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -53,6 +53,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const utils_1 = require("./utils"); const __1 = require("../.."); +const supertokens_1 = __importDefault(require("../../supertokens")); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const recipeImplementation_1 = __importDefault(require("./recipeImplementation")); const querier_1 = require("../../querier"); @@ -66,12 +67,12 @@ class Recipe extends recipeModule_1.default { verified: { emails: [], phoneNumbers: [], - thirdpartyInfo: [], + thirdParty: [], }, unverified: { emails: [], phoneNumbers: [], - thirdpartyInfo: [], + thirdParty: [], }, }; for (let i = 0; i < user.loginMethods.length; i++) { @@ -92,12 +93,16 @@ class Recipe extends recipeModule_1.default { } if (loginMethod.thirdParty !== undefined) { if (loginMethod.verified) { - identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); + identities.verified.thirdParty.push(loginMethod.thirdParty); } else { - identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); + identities.unverified.thirdParty.push(loginMethod.thirdParty); } } } + identities.verified.emails = Array.from(new Set(identities.verified.emails)); + identities.unverified.emails = Array.from(new Set(identities.unverified.emails)); + identities.verified.phoneNumbers = Array.from(new Set(identities.verified.phoneNumbers)); + identities.unverified.phoneNumbers = Array.from(new Set(identities.unverified.phoneNumbers)); return identities; }; this.isSignUpAllowed = ({ info, userContext }) => @@ -118,9 +123,13 @@ class Recipe extends recipeModule_1.default { info: identifier, userContext, }); - if (users === undefined || users.length === 0) { + if (users.length === 0) { return true; } + /** + * For a given email/phoneNumber, there can only exists + * one primary user at max + */ let primaryUser = users.find((u) => u.isPrimaryUser); if (primaryUser === undefined) { return true; @@ -131,10 +140,10 @@ class Recipe extends recipeModule_1.default { undefined, userContext ); - let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink - ? shouldDoAccountLinking.shouldRequireVerification - : false; - if (!shouldRequireVerification) { + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return true; + } + if (!shouldDoAccountLinking.shouldRequireVerification) { return true; } let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); @@ -167,34 +176,6 @@ class Recipe extends recipeModule_1.default { }); this.doPostSignUpAccountLinkingOperations = ({ info, infoVerified, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, - undefined, - undefined, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return recipeUserId; - } - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - return recipeUserId; - } - } - let canCreatePrimaryUserId = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId, - userContext, - }); - if (canCreatePrimaryUserId) { - let user = yield this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId, - userContext, - }); - if (user.status !== "OK") { - throw Error("should never come here. Error from createPrimaryUser: " + user.status); - } - return user.user.id; - } let identifier; if (info.email !== undefined) { identifier = { @@ -215,10 +196,7 @@ class Recipe extends recipeModule_1.default { throw Error("this error should never be thrown"); } let primaryUser = users.find((u) => u.isPrimaryUser); - if (primaryUser === undefined) { - throw Error("this error should never be thrown"); - } - shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( info, primaryUser, undefined, @@ -227,15 +205,52 @@ class Recipe extends recipeModule_1.default { if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return recipeUserId; } + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + return recipeUserId; + } + } + let canCreatePrimaryUserId = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId, + userContext, + }); + if (canCreatePrimaryUserId.status === "OK") { + let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId, + userContext, + }); + if (createPrimaryUserResult.status !== "OK") { + throw Error( + "should never come here. Error from createPrimaryUser: " + createPrimaryUserResult.status + ); + } + return createPrimaryUserResult.user.id; + } + /** + * if it reaches this point, it means there should exists a + * primary user to which the recipe userId can be linked to + */ + if (primaryUser === undefined) { + throw Error("this error should never be thrown"); + } let result = yield this.recipeInterfaceImpl.linkAccounts({ recipeUserId, primaryUserId: primaryUser.id, userContext, }); - if (result.status !== "OK") { - throw Error("this error status shouldn't not be thrown. Error" + result.status); + if (result.status === "OK") { + return primaryUser.id; + } + if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + return result.primaryUserId; } - return primaryUser.id; + if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + return result.primaryUserId; + } + if (result.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { + return primaryUser.id; + } + throw Error("this error status shouldn't not be thrown"); }); this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => __awaiter(this, void 0, void 0, function* () { @@ -266,7 +281,9 @@ class Recipe extends recipeModule_1.default { }; } let recipeId = user.loginMethods[0].recipeId; - let recipeUser = yield __1.getUserForRecipeId(user.id, recipeId); + let recipeUser = yield supertokens_1.default + .getInstanceOrThrowError() + ._getUserForRecipeId(user.id, recipeId); if (recipeUser.user === undefined) { throw Error( "This error should never be thrown. Check for bug in `getUserForRecipeId` function" @@ -347,35 +364,43 @@ class Recipe extends recipeModule_1.default { * checking if a recipe user already exists for the given * login info */ - let recipeInfo; - if (info.recipeId === "emailpassword" && info.email !== undefined) { - recipeInfo = { - recipeId: "emailpassword", - email: info.email, - }; - } else if (info.recipeId === "thirdparty" && info.thirdParty !== undefined) { - recipeInfo = { - recipeId: "thirdparty", - thirdpartyId: info.thirdParty.id, - thirdpartyUserId: info.thirdParty.userId, - }; - } else if (info.recipeId === "passwordless" && info.email !== undefined) { - recipeInfo = { - recipeId: "passwordless", + let identifier; + if (info.email !== undefined) { + identifier = { email: info.email, }; - } else if (info.recipeId === "passwordless" && info.phoneNumber !== undefined) { - recipeInfo = { - recipeId: "passwordless", + } + if (info.phoneNumber !== undefined) { + identifier = { phoneNumber: info.phoneNumber, }; } else { throw Error("this error should never be thrown"); } - let recipeUser = yield this.recipeInterfaceImpl.getUserByAccountInfo({ - info: recipeInfo, + let existingRecipeUsersForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: identifier, userContext, }); + let recipeUser = existingRecipeUsersForInputInfo.find((u) => + u.loginMethods.find((lU) => { + if (lU.recipeId === info.recipeId) { + return false; + } + if (info.recipeId === "thirdparty") { + if (info.thirdParty !== undefined) { + if (lU.thirdParty === undefined) { + return false; + } + return ( + lU.thirdParty.id === info.thirdParty.id && + lU.thirdParty.userId === info.thirdParty.userId + ); + } + return false; + } + return lU.email === info.email || info.phoneNumber === info.phoneNumber; + }) + ); if (recipeUser === undefined) { /** * if recipe user doesn't exists, we check if @@ -415,12 +440,8 @@ class Recipe extends recipeModule_1.default { * user which is associated with the identifying info * for the given input */ - let existingRecipeUserForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: recipeInfo, - userContext, - }); - if (existingRecipeUserForInputInfo !== undefined) { - let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); + if (existingRecipeUsersForInputInfo !== undefined) { + let primaryUserIfExists = existingRecipeUsersForInputInfo.find((u) => u.isPrimaryUser); if (primaryUserIfExists !== undefined) { return { createRecipeUser: false, diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 7ded853d5..39560cb61 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -52,7 +52,7 @@ var __importDefault = Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); const session_1 = __importDefault(require("../session")); -const __1 = require("../.."); +const supertokens_1 = __importDefault(require("../../supertokens")); function getRecipeImplementation(querier, config) { return { getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { @@ -163,12 +163,6 @@ function getRecipeImplementation(querier, config) { phoneNumber: loginMethod.phoneNumber, }); } - if (loginMethod.thirdParty !== undefined) { - infos.push({ - thirdpartyId: loginMethod.thirdParty.id, - thirdpartyUserId: loginMethod.thirdParty.userId, - }); - } for (let j = 0; j < infos.length; j++) { let info = infos[j]; let usersList = yield this.listUsersByAccountInfo({ @@ -324,10 +318,9 @@ function getRecipeImplementation(querier, config) { if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = yield __1.getUserForRecipeId( - loginMethodInfo.recipeUserId, - loginMethodInfo.recipeId - ); + let recipeUser = yield supertokens_1.default + .getInstanceOrThrowError() + ._getUserForRecipeId(loginMethodInfo.recipeUserId, loginMethodInfo.recipeId); if (recipeUser.user === undefined) { throw Error("this error should never be thrown"); } @@ -412,22 +405,7 @@ function getRecipeImplementation(querier, config) { new normalisedURLPath_1.default("/users/accountinfo"), Object.assign({}, info) ); - if (result.status === "OK") { - return result.users; - } - return undefined; - }); - }, - getUserByAccountInfo: function ({ info }) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( - new normalisedURLPath_1.default("/users/accountinfo"), - Object.assign({}, info) - ); - if (result.status === "OK") { - return result.users[0]; - } - return undefined; + return result.users; }); }, deleteUser: function ({ userId, removeAllLinkedAccounts, userContext }) { diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 1553c6a05..50b96528f 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -170,8 +170,7 @@ export declare type RecipeInterface = { } >; getUser: (input: { userId: string; userContext: any }) => Promise; - listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; - getUserByAccountInfo: (input: { info: AccountInfoWithRecipeId; userContext: any }) => Promise; + listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; deleteUser: (input: { userId: string; removeAllLinkedAccounts: boolean; @@ -213,10 +212,6 @@ export declare type AccountInfo = | { email: string; } - | { - thirdpartyId: string; - thirdpartyUserId: string; - } | { phoneNumber: string; }; @@ -229,6 +224,7 @@ export declare type AccountInfoWithRecipeId = recipeId: "thirdparty"; thirdpartyId: string; thirdpartyUserId: string; + email: string; } | { recipeId: "passwordless"; diff --git a/lib/build/recipe/dashboard/api/usersGet.d.ts b/lib/build/recipe/dashboard/api/usersGet.d.ts index ec90a7275..788cec3eb 100644 --- a/lib/build/recipe/dashboard/api/usersGet.d.ts +++ b/lib/build/recipe/dashboard/api/usersGet.d.ts @@ -7,9 +7,9 @@ declare type User = { isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + thirdParty: { + id: string; + userId: string; }[]; firstName?: string; lastName?: string; diff --git a/lib/build/recipe/dashboard/utils.js b/lib/build/recipe/dashboard/utils.js index 622b8619b..002811dff 100644 --- a/lib/build/recipe/dashboard/utils.js +++ b/lib/build/recipe/dashboard/utils.js @@ -54,7 +54,7 @@ exports.isRecipeInitialised = exports.getUserForRecipeId = exports.isValidRecipe const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); const utils_1 = require("../../utils"); const constants_1 = require("./constants"); -const __1 = __importDefault(require("../..")); +const supertokens_1 = __importDefault(require("../../supertokens")); const recipe_1 = __importDefault(require("../emailpassword/recipe")); const recipe_2 = __importDefault(require("../thirdparty/recipe")); const recipe_3 = __importDefault(require("../passwordless/recipe")); @@ -146,7 +146,7 @@ function isValidRecipeId(recipeId) { exports.isValidRecipeId = isValidRecipeId; function getUserForRecipeId(userId, recipeId) { return __awaiter(this, void 0, void 0, function* () { - let userResponse = yield __1.default.getUserForRecipeId(userId, recipeId); + let userResponse = yield supertokens_1.default.getInstanceOrThrowError()._getUserForRecipeId(userId, recipeId); let user = undefined; if (userResponse.user !== undefined) { user = Object.assign(Object.assign({}, userResponse.user), { firstName: "", lastName: "" }); diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 8b95e9db7..6035bda5a 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -73,7 +73,7 @@ export default class SuperTokens { }>; middleware: (request: BaseRequest, response: BaseResponse) => Promise; errorHandler: (err: any, request: BaseRequest, response: BaseResponse) => Promise; - getUserForRecipeId: ( + _getUserForRecipeId: ( userId: string, recipeId: string ) => Promise<{ diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index 8ee85185d..6e0f0fa31 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -308,7 +308,8 @@ class SuperTokens { } throw err; }); - this.getUserForRecipeId = (userId, recipeId) => + // this is an internal use function, therefore it is prefixed with an `_` + this._getUserForRecipeId = (userId, recipeId) => __awaiter(this, void 0, void 0, function* () { let user; let recipe; diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index cb43451ef..4de639a1c 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -58,9 +58,9 @@ export declare type User = { isPrimaryUser: boolean; emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { - thirdpartyId: string; - thirdpartyUserId: string; + thirdParty: { + id: string; + userId: string; }[]; loginMethods: (RecipeLevelUser & { verified: boolean; diff --git a/lib/ts/index.ts b/lib/ts/index.ts index fa11dedf4..bc6652ebd 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -17,7 +17,7 @@ import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; import { User } from "./types"; import AccountLinking from "./recipe/accountlinking/recipe"; -import { AccountInfo, AccountInfoWithRecipeId } from "./recipe/accountlinking/types"; +import { AccountInfo } from "./recipe/accountlinking/types"; // For Express export default class SuperTokensWrapper { @@ -72,7 +72,6 @@ export default class SuperTokensWrapper { return SuperTokens.getInstanceOrThrowError().createUserIdMapping(input); } - static getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY" }) { return SuperTokens.getInstanceOrThrowError().getUserIdMapping(input); } @@ -138,6 +137,4 @@ export let getUser = SuperTokensWrapper.getUser; export let listUsersByAccountInfo = SuperTokensWrapper.listUsersByAccountInfo; - - export let Error = SuperTokensWrapper.Error; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 738900f17..3f4a26c95 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -19,15 +19,10 @@ import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction, User } from "../../types"; import { SessionContainer } from "../session"; -import type { - TypeNormalisedInput, - RecipeInterface, - TypeInput, - AccountInfoAndEmailWithRecipeId, - AccountInfoWithRecipeId, -} from "./types"; +import type { TypeNormalisedInput, RecipeInterface, TypeInput, AccountInfoAndEmailWithRecipeId } from "./types"; import { validateAndNormaliseUserInput } from "./utils"; -import { getUser, getUserForRecipeId } from "../.."; +import { getUser } from "../.."; +import SuperTokens from "../../supertokens"; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; @@ -131,7 +126,7 @@ export default class Recipe extends RecipeModule { verified: { emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { + thirdParty: { id: string; userId: string; }[]; @@ -139,7 +134,7 @@ export default class Recipe extends RecipeModule { unverified: { emails: string[]; phoneNumbers: string[]; - thirdpartyInfo: { + thirdParty: { id: string; userId: string; }[]; @@ -148,12 +143,12 @@ export default class Recipe extends RecipeModule { verified: { emails: [], phoneNumbers: [], - thirdpartyInfo: [], + thirdParty: [], }, unverified: { emails: [], phoneNumbers: [], - thirdpartyInfo: [], + thirdParty: [], }, }; for (let i = 0; i < user.loginMethods.length; i++) { @@ -174,12 +169,16 @@ export default class Recipe extends RecipeModule { } if (loginMethod.thirdParty !== undefined) { if (loginMethod.verified) { - identities.verified.thirdpartyInfo.push(loginMethod.thirdParty); + identities.verified.thirdParty.push(loginMethod.thirdParty); } else { - identities.unverified.thirdpartyInfo.push(loginMethod.thirdParty); + identities.unverified.thirdParty.push(loginMethod.thirdParty); } } } + identities.verified.emails = Array.from(new Set(identities.verified.emails)); + identities.unverified.emails = Array.from(new Set(identities.unverified.emails)); + identities.verified.phoneNumbers = Array.from(new Set(identities.verified.phoneNumbers)); + identities.unverified.phoneNumbers = Array.from(new Set(identities.unverified.phoneNumbers)); return identities; }; @@ -215,6 +214,10 @@ export default class Recipe extends RecipeModule { if (users.length === 0) { return true; } + /** + * For a given email/phoneNumber, there can only exists + * one primary user at max + */ let primaryUser = users.find((u) => u.isPrimaryUser); if (primaryUser === undefined) { return true; @@ -225,10 +228,10 @@ export default class Recipe extends RecipeModule { undefined, userContext ); - let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink - ? shouldDoAccountLinking.shouldRequireVerification - : false; - if (!shouldRequireVerification) { + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return true; + } + if (!shouldDoAccountLinking.shouldRequireVerification) { return true; } @@ -280,34 +283,6 @@ export default class Recipe extends RecipeModule { recipeUserId: string; userContext: any; }): Promise => { - let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( - info, - undefined, - undefined, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return recipeUserId; - } - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - return recipeUserId; - } - } - let canCreatePrimaryUserId = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId, - userContext, - }); - if (canCreatePrimaryUserId) { - let user = await this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId, - userContext, - }); - if (user.status !== "OK") { - throw Error("should never come here. Error from createPrimaryUser: " + user.status); - } - return user.user.id; - } let identifier: | { email: string; @@ -334,19 +309,60 @@ export default class Recipe extends RecipeModule { throw Error("this error should never be thrown"); } let primaryUser = users.find((u) => u.isPrimaryUser); + let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + info, + primaryUser, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } + if (shouldDoAccountLinking.shouldRequireVerification) { + if (!infoVerified) { + return recipeUserId; + } + } + let canCreatePrimaryUserId = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId, + userContext, + }); + if (canCreatePrimaryUserId.status === "OK") { + let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId, + userContext, + }); + if (createPrimaryUserResult.status !== "OK") { + throw Error("should never come here. Error from createPrimaryUser: " + createPrimaryUserResult.status); + } + return createPrimaryUserResult.user.id; + } + /** + * if it reaches this point, it means there should exists a + * primary user to which the recipe userId can be linked to + */ if (primaryUser === undefined) { throw Error("this error should never be thrown"); } - + let result = await this.recipeInterfaceImpl.linkAccounts({ recipeUserId, primaryUserId: primaryUser.id, userContext, }); - if (result.status !== "OK") { - throw Error("this error status shouldn't not be thrown. Error" + result.status); + if (result.status === "OK") { + return primaryUser.id; + } + if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + return result.primaryUserId; } - return primaryUser.id; + if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + return result.primaryUserId; + } + if (result.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { + return primaryUser.id; + } + throw Error("this error status shouldn't not be thrown"); }; accountLinkPostSignInViaSession = async ({ @@ -415,7 +431,7 @@ export default class Recipe extends RecipeModule { } let recipeId = user.loginMethods[0].recipeId; - let recipeUser = await getUserForRecipeId(user.id, recipeId); + let recipeUser = await SuperTokens.getInstanceOrThrowError()._getUserForRecipeId(user.id, recipeId); if (recipeUser.user === undefined) { throw Error("This error should never be thrown. Check for bug in `getUserForRecipeId` function"); @@ -498,35 +514,48 @@ export default class Recipe extends RecipeModule { * checking if a recipe user already exists for the given * login info */ - let recipeInfo: AccountInfoWithRecipeId; - if (info.recipeId === "emailpassword" && info.email !== undefined) { - recipeInfo = { - recipeId: "emailpassword", - email: info.email, - }; - } else if (info.recipeId === "thirdparty" && info.thirdParty !== undefined) { - recipeInfo = { - recipeId: "thirdparty", - thirdpartyId: info.thirdParty.id, - thirdpartyUserId: info.thirdParty.userId, - }; - } else if (info.recipeId === "passwordless" && info.email !== undefined) { - recipeInfo = { - recipeId: "passwordless", + let identifier: + | { + email: string; + } + | { + phoneNumber: string; + }; + if (info.email !== undefined) { + identifier = { email: info.email, }; - } else if (info.recipeId === "passwordless" && info.phoneNumber !== undefined) { - recipeInfo = { - recipeId: "passwordless", + } + if (info.phoneNumber !== undefined) { + identifier = { phoneNumber: info.phoneNumber, }; } else { throw Error("this error should never be thrown"); } - let recipeUser = await this.recipeInterfaceImpl.getUserByAccountInfo({ - info: recipeInfo, + let existingRecipeUsersForInputInfo = await this.recipeInterfaceImpl.listUsersByAccountInfo({ + info: identifier, userContext, }); + let recipeUser = existingRecipeUsersForInputInfo.find((u) => + u.loginMethods.find((lU) => { + if (lU.recipeId === info.recipeId) { + return false; + } + if (info.recipeId === "thirdparty") { + if (info.thirdParty !== undefined) { + if (lU.thirdParty === undefined) { + return false; + } + return ( + lU.thirdParty.id === info.thirdParty.id && lU.thirdParty.userId === info.thirdParty.userId + ); + } + return false; + } + return lU.email === info.email || info.phoneNumber === info.phoneNumber; + }) + ); if (recipeUser === undefined) { /** * if recipe user doesn't exists, we check if @@ -561,18 +590,13 @@ export default class Recipe extends RecipeModule { }; } } - /** * checking if there already exists any other primary * user which is associated with the identifying info * for the given input */ - let existingRecipeUserForInputInfo = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: recipeInfo, - userContext, - }); - if (existingRecipeUserForInputInfo !== undefined) { - let primaryUserIfExists = existingRecipeUserForInputInfo.find((u) => u.isPrimaryUser); + if (existingRecipeUsersForInputInfo !== undefined) { + let primaryUserIfExists = existingRecipeUsersForInputInfo.find((u) => u.isPrimaryUser); if (primaryUserIfExists !== undefined) { return { createRecipeUser: false, diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 7ea0cec01..ae5474ccf 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -13,12 +13,12 @@ * under the License. */ -import { AccountInfo, AccountInfoWithRecipeId, RecipeInterface, TypeNormalisedInput } from "./types"; +import { AccountInfo, RecipeInterface, TypeNormalisedInput } from "./types"; import { Querier } from "../../querier"; import type { User } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; import Session from "../session"; -import { getUserForRecipeId } from "../.."; +import SuperTokens from "../../supertokens"; export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface { return { @@ -188,12 +188,6 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo phoneNumber: loginMethod.phoneNumber, }); } - if (loginMethod.thirdParty !== undefined) { - infos.push({ - thirdpartyId: loginMethod.thirdParty.id, - thirdpartyUserId: loginMethod.thirdParty.userId, - }); - } for (let j = 0; j < infos.length; j++) { let info = infos[j]; let usersList = await this.listUsersByAccountInfo({ @@ -461,7 +455,10 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = await getUserForRecipeId(loginMethodInfo.recipeUserId, loginMethodInfo.recipeId); + let recipeUser = await SuperTokens.getInstanceOrThrowError()._getUserForRecipeId( + loginMethodInfo.recipeUserId, + loginMethodInfo.recipeId + ); if (recipeUser.user === undefined) { throw Error("this error should never be thrown"); } @@ -550,26 +547,11 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo listUsersByAccountInfo: async function ( this: RecipeInterface, { info }: { info: AccountInfo } - ): Promise { - let result = await querier.sendGetRequest(new NormalisedURLPath("/users/accountinfo"), { - ...info, - }); - if (result.status === "OK") { - return result.users; - } - return undefined; - }, - getUserByAccountInfo: async function ( - this: RecipeInterface, - { info }: { info: AccountInfoWithRecipeId } - ): Promise { + ): Promise { let result = await querier.sendGetRequest(new NormalisedURLPath("/users/accountinfo"), { ...info, }); - if (result.status === "OK") { - return result.users[0]; - } - return undefined; + return result.users; }, deleteUser: async function ( this: RecipeInterface, diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index a97549580..6edfdc2c9 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -228,10 +228,6 @@ export type AccountInfo = | { email: string; } - | { - thirdpartyId: string; - thirdpartyUserId: string; - } | { phoneNumber: string; }; @@ -245,6 +241,7 @@ export type AccountInfoWithRecipeId = recipeId: "thirdparty"; thirdpartyId: string; thirdpartyUserId: string; + email: string; } | { recipeId: "passwordless"; diff --git a/lib/ts/recipe/dashboard/utils.ts b/lib/ts/recipe/dashboard/utils.ts index 1eff4b257..aed08ba25 100644 --- a/lib/ts/recipe/dashboard/utils.ts +++ b/lib/ts/recipe/dashboard/utils.ts @@ -37,7 +37,7 @@ import { TypeNormalisedInput, RecipeLevelUser, } from "./types"; -import Supertokens from "../.."; +import Supertokens from "../../supertokens"; import EmailPasswordRecipe from "../emailpassword/recipe"; import ThirdPartyRecipe from "../thirdparty/recipe"; import PasswordlessRecipe from "../passwordless/recipe"; @@ -153,7 +153,7 @@ export async function getUserForRecipeId( | "thirdpartypasswordless" | undefined; }> { - let userResponse = await Supertokens.getUserForRecipeId(userId, recipeId); + let userResponse = await Supertokens.getInstanceOrThrowError()._getUserForRecipeId(userId, recipeId); let user: RecipeLevelUser | undefined = undefined; if (userResponse.user !== undefined) { user = { From 55525dc8da69368a76cf17c9575f5ff7bd195598 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Fri, 24 Feb 2023 14:42:20 +0530 Subject: [PATCH 51/82] mark email as verify if it is already verified in either primary user or the current recipe user --- lib/build/recipe/accountlinking/recipe.js | 33 +++++++++++++++++++++++ lib/ts/recipe/accountlinking/recipe.ts | 29 ++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 428914fa8..376226588 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -239,6 +239,39 @@ class Recipe extends recipeModule_1.default { userContext, }); if (result.status === "OK") { + /** + * let's Ly belongs to P1 such that Ly equal to Lx. + * if LY verified, mark Lx as verified. If Lx is verfied, + * then mark all Ly as verified + */ + let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); + let emailIdentityVerifiedForPrimaryUser = false; + if (info.email !== undefined) { + emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes( + info.email + ); + } + if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { + let recipeUserIdsForEmailVerificationUpdate = primaryUser.loginMethods + .filter((u) => u.email === info.email && !u.verified) + .map((l) => l.email); + if (!infoVerified) { + recipeUserIdsForEmailVerificationUpdate.push(recipeUserId); + } + recipeUserIdsForEmailVerificationUpdate = Array.from( + new Set(recipeUserIdsForEmailVerificationUpdate) + ); + for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { + let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; + if (rUserId !== undefined) { + yield this.markEmailAsVerified({ + email: info.email, + recipeUserId: rUserId, + userContext, + }); + } + } + } return primaryUser.id; } if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 3f4a26c95..e1387577a 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -351,6 +351,35 @@ export default class Recipe extends RecipeModule { userContext, }); if (result.status === "OK") { + /** + * let's Ly belongs to P1 such that Ly equal to Lx. + * if LY verified, mark Lx as verified. If Lx is verfied, + * then mark all Ly as verified + */ + let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); + let emailIdentityVerifiedForPrimaryUser = false; + if (info.email !== undefined) { + emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email); + } + if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { + let recipeUserIdsForEmailVerificationUpdate = primaryUser.loginMethods + .filter((u) => u.email === info.email && !u.verified) + .map((l) => l.email); + if (!infoVerified) { + recipeUserIdsForEmailVerificationUpdate.push(recipeUserId); + } + recipeUserIdsForEmailVerificationUpdate = Array.from(new Set(recipeUserIdsForEmailVerificationUpdate)); + for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { + let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; + if (rUserId !== undefined) { + await this.markEmailAsVerified({ + email: info.email, + recipeUserId: rUserId, + userContext, + }); + } + } + } return primaryUser.id; } if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { From 4bc7809145d4a5f27442db621b1f1907572bf263 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Mon, 27 Feb 2023 11:30:54 +0530 Subject: [PATCH 52/82] fixes and refactors --- lib/build/index.d.ts | 2 +- lib/build/index.js | 4 +- lib/build/recipe/accountlinking/recipe.d.ts | 14 +- lib/build/recipe/accountlinking/recipe.js | 155 +++++++------ .../accountlinking/recipeImplementation.js | 6 +- lib/build/recipe/accountlinking/types.d.ts | 17 +- lib/ts/index.ts | 4 +- lib/ts/recipe/accountlinking/recipe.ts | 203 ++++++++---------- .../accountlinking/recipeImplementation.ts | 6 +- lib/ts/recipe/accountlinking/types.ts | 18 +- 10 files changed, 192 insertions(+), 237 deletions(-) diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index 0dd941bda..a20f04e90 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -69,7 +69,7 @@ export default class SuperTokensWrapper { status: "OK" | "UNKNOWN_MAPPING_ERROR"; }>; static getUser(userId: string, userContext?: any): Promise; - static listUsersByAccountInfo(info: AccountInfo, userContext?: any): Promise; + static listUsersByAccountInfo(accountInfo: AccountInfo, userContext?: any): Promise; static deleteUser( userId: string, removeAllLinkedAccounts?: boolean, diff --git a/lib/build/index.js b/lib/build/index.js index 263d43464..9dd74d7f2 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -96,10 +96,10 @@ class SuperTokensWrapper { }); }); } - static listUsersByAccountInfo(info, userContext) { + static listUsersByAccountInfo(accountInfo, userContext) { return __awaiter(this, void 0, void 0, function* () { return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ - info, + accountInfo, userContext: userContext === undefined ? {} : userContext, }); }); diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 581e8295f..d266a4e4c 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -25,7 +25,7 @@ export default class Recipe extends RecipeModule { handleError(error: error, _request: BaseRequest, _response: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; - getIdentitiesForUser: ( + transformUserInfoIntoVerifiedAndUnverifiedBucket: ( user: User ) => { verified: { @@ -46,10 +46,10 @@ export default class Recipe extends RecipeModule { }; }; isSignUpAllowed: ({ - info, + newUser, userContext, }: { - info: AccountInfoAndEmailWithRecipeId; + newUser: AccountInfoAndEmailWithRecipeId; userContext: any; }) => Promise; markEmailAsVerified: ({ @@ -62,13 +62,13 @@ export default class Recipe extends RecipeModule { userContext: any; }) => Promise; doPostSignUpAccountLinkingOperations: ({ - info, - infoVerified, + newUser, + newUserVerified, recipeUserId, userContext, }: { - info: AccountInfoAndEmailWithRecipeId; - infoVerified: boolean; + newUser: AccountInfoAndEmailWithRecipeId; + newUserVerified: boolean; recipeUserId: string; userContext: any; }) => Promise; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 376226588..0104a8e38 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -62,7 +62,7 @@ const recipe_1 = __importDefault(require("../emailverification/recipe")); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, config, _recipes, _ingredients) { super(recipeId, appInfo); - this.getIdentitiesForUser = (user) => { + this.transformUserInfoIntoVerifiedAndUnverifiedBucket = (user) => { let identities = { verified: { emails: [], @@ -99,28 +99,37 @@ class Recipe extends recipeModule_1.default { } } } + // we remove duplicate emails / phone numbers from the above arrays. identities.verified.emails = Array.from(new Set(identities.verified.emails)); identities.unverified.emails = Array.from(new Set(identities.unverified.emails)); identities.verified.phoneNumbers = Array.from(new Set(identities.verified.phoneNumbers)); identities.unverified.phoneNumbers = Array.from(new Set(identities.unverified.phoneNumbers)); + // Note that we do not need to filter out thirdParty info based on uniqueness, cause + // one user can only have one unique thirdPart login. return identities; }; - this.isSignUpAllowed = ({ info, userContext }) => + this.isSignUpAllowed = ({ newUser, userContext }) => __awaiter(this, void 0, void 0, function* () { - let identifier; - if (info.email !== undefined) { - identifier = { - email: info.email, + let accountInfo; + if (newUser.email !== undefined) { + accountInfo = { + email: newUser.email, }; - } else if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, + } else if (newUser.phoneNumber !== undefined) { + accountInfo = { + phoneNumber: newUser.phoneNumber, + }; + } else if (newUser.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: newUser.thirdParty.id, + thirdPartyUserId: newUser.thirdParty.userId, }; } else { - throw Error("this error should never be thrown"); + // It's not possible to come here because all the login methods are covered above. + throw new Error("Should never come here"); } let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo, userContext, }); if (users.length === 0) { @@ -135,7 +144,7 @@ class Recipe extends recipeModule_1.default { return true; } let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, + newUser, primaryUser, undefined, userContext @@ -146,14 +155,14 @@ class Recipe extends recipeModule_1.default { if (!shouldDoAccountLinking.shouldRequireVerification) { return true; } - let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); - if (info.email !== undefined) { - return identitiesForPrimaryUser.verified.emails.includes(info.email); + let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); + if (newUser.email !== undefined) { + return identitiesForPrimaryUser.verified.emails.includes(newUser.email); } - if (info.phoneNumber !== undefined) { - return identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber); + if (newUser.phoneNumber !== undefined) { + return identitiesForPrimaryUser.verified.phoneNumbers.includes(newUser.phoneNumber); } - throw Error("it should never reach here"); + return false; }); this.markEmailAsVerified = ({ email, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { @@ -174,30 +183,36 @@ class Recipe extends recipeModule_1.default { } } }); - this.doPostSignUpAccountLinkingOperations = ({ info, infoVerified, recipeUserId, userContext }) => + // this function returns the user ID for which the session will be created. + this.doPostSignUpAccountLinkingOperations = ({ newUser, newUserVerified, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { - let identifier; - if (info.email !== undefined) { - identifier = { - email: info.email, + let accountInfo; + if (newUser.email !== undefined) { + accountInfo = { + email: newUser.email, }; - } else if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, + } else if (newUser.phoneNumber !== undefined) { + accountInfo = { + phoneNumber: newUser.phoneNumber, + }; + } else if (newUser.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: newUser.thirdParty.id, + thirdPartyUserId: newUser.thirdParty.userId, }; } else { throw Error("this error should never be thrown"); } let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo, userContext, }); - if (users === undefined || users.length === 0) { - throw Error("this error should never be thrown"); + if (users.length === 0) { + return recipeUserId; } let primaryUser = users.find((u) => u.isPrimaryUser); let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, + newUser, primaryUser, undefined, userContext @@ -205,10 +220,8 @@ class Recipe extends recipeModule_1.default { if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return recipeUserId; } - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - return recipeUserId; - } + if (shouldDoAccountLinking.shouldRequireVerification && !newUserVerified) { + return recipeUserId; } let canCreatePrimaryUserId = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ recipeUserId, @@ -219,19 +232,21 @@ class Recipe extends recipeModule_1.default { recipeUserId, userContext, }); - if (createPrimaryUserResult.status !== "OK") { - throw Error( - "should never come here. Error from createPrimaryUser: " + createPrimaryUserResult.status - ); + if (createPrimaryUserResult.status === "OK") { + return createPrimaryUserResult.user.id; } - return createPrimaryUserResult.user.id; + // if it comes here, it means that that there is already a primary user for the + // account info, or that this recipeUserId is already linked. Either way, we proceed + // to the next step, cause that takes care of both these cases. } - /** - * if it reaches this point, it means there should exists a - * primary user to which the recipe userId can be linked to - */ if (primaryUser === undefined) { - throw Error("this error should never be thrown"); + // it can come here if there is a race condition. So we just try again + return yield this.doPostSignUpAccountLinkingOperations({ + newUser: newUser, + newUserVerified: newUserVerified, + recipeUserId, + userContext, + }); } let result = yield this.recipeInterfaceImpl.linkAccounts({ recipeUserId, @@ -240,50 +255,32 @@ class Recipe extends recipeModule_1.default { }); if (result.status === "OK") { /** - * let's Ly belongs to P1 such that Ly equal to Lx. - * if LY verified, mark Lx as verified. If Lx is verfied, - * then mark all Ly as verified + * We now mark the same email of other linked recipes as verified if the new user's email + * is verified. */ - let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); - let emailIdentityVerifiedForPrimaryUser = false; - if (info.email !== undefined) { - emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes( - info.email - ); - } - if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { + if (newUser.email !== undefined && newUserVerified) { let recipeUserIdsForEmailVerificationUpdate = primaryUser.loginMethods - .filter((u) => u.email === info.email && !u.verified) - .map((l) => l.email); - if (!infoVerified) { - recipeUserIdsForEmailVerificationUpdate.push(recipeUserId); - } + .filter((u) => u.email === newUser.email && !u.verified) + .map((l) => l.recipeUserId); recipeUserIdsForEmailVerificationUpdate = Array.from( new Set(recipeUserIdsForEmailVerificationUpdate) ); for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { - let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; - if (rUserId !== undefined) { - yield this.markEmailAsVerified({ - email: info.email, - recipeUserId: rUserId, - userContext, - }); - } + yield this.markEmailAsVerified({ + email: newUser.email, + recipeUserId: recipeUserIdsForEmailVerificationUpdate[i], + userContext, + }); } } return primaryUser.id; - } - if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + } else if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { return result.primaryUserId; - } - if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + } else if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { return result.primaryUserId; - } - if (result.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { + } else { return primaryUser.id; } - throw Error("this error status shouldn't not be thrown"); }); this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => __awaiter(this, void 0, void 0, function* () { @@ -411,7 +408,7 @@ class Recipe extends recipeModule_1.default { throw Error("this error should never be thrown"); } let existingRecipeUsersForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo: identifier, userContext, }); let recipeUser = existingRecipeUsersForInputInfo.find((u) => @@ -445,7 +442,7 @@ class Recipe extends recipeModule_1.default { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -535,7 +532,7 @@ class Recipe extends recipeModule_1.default { primaryUserId: canLinkAccounts.primaryUserId, }; } - let identitiesForPrimaryUser = this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; let emailIdentityVerifiedForPrimaryUser = false; let phoneNumberIdentityVerifiedForPrimaryUser = false; @@ -634,7 +631,7 @@ class Recipe extends recipeModule_1.default { throw Error("this error should never be thrown"); } let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo: identifier, userContext, }); if (users === undefined || users.length === 0) { diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 39560cb61..a2df264ac 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -166,7 +166,7 @@ function getRecipeImplementation(querier, config) { for (let j = 0; j < infos.length; j++) { let info = infos[j]; let usersList = yield this.listUsersByAccountInfo({ - info, + accountInfo: info, userContext, }); if (usersList !== undefined) { @@ -399,11 +399,11 @@ function getRecipeImplementation(querier, config) { return undefined; }); }, - listUsersByAccountInfo: function ({ info }) { + listUsersByAccountInfo: function ({ accountInfo }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendGetRequest( new normalisedURLPath_1.default("/users/accountinfo"), - Object.assign({}, info) + Object.assign({}, accountInfo) ); return result.users; }); diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 50b96528f..0a36d20d4 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -170,7 +170,7 @@ export declare type RecipeInterface = { } >; getUser: (input: { userId: string; userContext: any }) => Promise; - listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; + listUsersByAccountInfo: (input: { accountInfo: AccountInfo; userContext: any }) => Promise; deleteUser: (input: { userId: string; removeAllLinkedAccounts: boolean; @@ -214,19 +214,8 @@ export declare type AccountInfo = } | { phoneNumber: string; - }; -export declare type AccountInfoWithRecipeId = - | { - recipeId: "emailpassword" | "passwordless"; - email: string; } | { - recipeId: "thirdparty"; - thirdpartyId: string; - thirdpartyUserId: string; - email: string; - } - | { - recipeId: "passwordless"; - phoneNumber: string; + thirdPartyId: string; + thirdPartyUserId: string; }; diff --git a/lib/ts/index.ts b/lib/ts/index.ts index bc6652ebd..bb9f6bac4 100644 --- a/lib/ts/index.ts +++ b/lib/ts/index.ts @@ -98,9 +98,9 @@ export default class SuperTokensWrapper { userContext: userContext === undefined ? {} : userContext, }); } - static async listUsersByAccountInfo(info: AccountInfo, userContext?: any) { + static async listUsersByAccountInfo(accountInfo: AccountInfo, userContext?: any) { return await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.listUsersByAccountInfo({ - info, + accountInfo, userContext: userContext === undefined ? {} : userContext, }); } diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index e1387577a..f202eab79 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -19,7 +19,13 @@ import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction, User } from "../../types"; import { SessionContainer } from "../session"; -import type { TypeNormalisedInput, RecipeInterface, TypeInput, AccountInfoAndEmailWithRecipeId } from "./types"; +import type { + TypeNormalisedInput, + RecipeInterface, + TypeInput, + AccountInfoAndEmailWithRecipeId, + AccountInfo, +} from "./types"; import { validateAndNormaliseUserInput } from "./utils"; import { getUser } from "../.."; import SuperTokens from "../../supertokens"; @@ -102,26 +108,7 @@ export default class Recipe extends RecipeModule { return SuperTokensError.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; } - getIdentitiesForUser = ( - user: User - ): { - verified: { - emails: string[]; - phoneNumbers: string[]; - thirdParty: { - id: string; - userId: string; - }[]; - }; - unverified: { - emails: string[]; - phoneNumbers: string[]; - thirdParty: { - id: string; - userId: string; - }[]; - }; - } => { + transformUserInfoIntoVerifiedAndUnverifiedBucket = (user: User) => { let identities: { verified: { emails: string[]; @@ -175,40 +162,45 @@ export default class Recipe extends RecipeModule { } } } + + // we remove duplicate emails / phone numbers from the above arrays. identities.verified.emails = Array.from(new Set(identities.verified.emails)); identities.unverified.emails = Array.from(new Set(identities.unverified.emails)); identities.verified.phoneNumbers = Array.from(new Set(identities.verified.phoneNumbers)); identities.unverified.phoneNumbers = Array.from(new Set(identities.unverified.phoneNumbers)); + // Note that we do not need to filter out thirdParty info based on uniqueness, cause + // one user can only have one unique thirdPart login. return identities; }; isSignUpAllowed = async ({ - info, + newUser, userContext, }: { - info: AccountInfoAndEmailWithRecipeId; + newUser: AccountInfoAndEmailWithRecipeId; userContext: any; }): Promise => { - let identifier: - | { - email: string; - } - | { - phoneNumber: string; - }; - if (info.email !== undefined) { - identifier = { - email: info.email, + let accountInfo: AccountInfo; + if (newUser.email !== undefined) { + accountInfo = { + email: newUser.email, }; - } else if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, + } else if (newUser.phoneNumber !== undefined) { + accountInfo = { + phoneNumber: newUser.phoneNumber, + }; + } else if (newUser.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: newUser.thirdParty.id, + thirdPartyUserId: newUser.thirdParty.userId, }; } else { - throw Error("this error should never be thrown"); + // It's not possible to come here because all the login methods are covered above. + throw new Error("Should never come here"); } + let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo, userContext, }); if (users.length === 0) { @@ -223,7 +215,7 @@ export default class Recipe extends RecipeModule { return true; } let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( - info, + newUser, primaryUser, undefined, userContext @@ -235,15 +227,15 @@ export default class Recipe extends RecipeModule { return true; } - let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); + let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); - if (info.email !== undefined) { - return identitiesForPrimaryUser.verified.emails.includes(info.email); + if (newUser.email !== undefined) { + return identitiesForPrimaryUser.verified.emails.includes(newUser.email); } - if (info.phoneNumber !== undefined) { - return identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber); + if (newUser.phoneNumber !== undefined) { + return identitiesForPrimaryUser.verified.phoneNumbers.includes(newUser.phoneNumber); } - throw Error("it should never reach here"); + return false; }; markEmailAsVerified = async ({ @@ -272,45 +264,45 @@ export default class Recipe extends RecipeModule { } }; + // this function returns the user ID for which the session will be created. doPostSignUpAccountLinkingOperations = async ({ - info, - infoVerified, + newUser, + newUserVerified, recipeUserId, userContext, }: { - info: AccountInfoAndEmailWithRecipeId; - infoVerified: boolean; + newUser: AccountInfoAndEmailWithRecipeId; + newUserVerified: boolean; recipeUserId: string; userContext: any; }): Promise => { - let identifier: - | { - email: string; - } - | { - phoneNumber: string; - }; - if (info.email !== undefined) { - identifier = { - email: info.email, + let accountInfo: AccountInfo; + if (newUser.email !== undefined) { + accountInfo = { + email: newUser.email, }; - } else if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, + } else if (newUser.phoneNumber !== undefined) { + accountInfo = { + phoneNumber: newUser.phoneNumber, + }; + } else if (newUser.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: newUser.thirdParty.id, + thirdPartyUserId: newUser.thirdParty.userId, }; } else { throw Error("this error should never be thrown"); } let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo, userContext, }); - if (users === undefined || users.length === 0) { - throw Error("this error should never be thrown"); + if (users.length === 0) { + return recipeUserId; } let primaryUser = users.find((u) => u.isPrimaryUser); let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( - info, + newUser, primaryUser, undefined, userContext @@ -318,10 +310,8 @@ export default class Recipe extends RecipeModule { if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return recipeUserId; } - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - return recipeUserId; - } + if (shouldDoAccountLinking.shouldRequireVerification && !newUserVerified) { + return recipeUserId; } let canCreatePrimaryUserId = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ recipeUserId, @@ -332,17 +322,22 @@ export default class Recipe extends RecipeModule { recipeUserId, userContext, }); - if (createPrimaryUserResult.status !== "OK") { - throw Error("should never come here. Error from createPrimaryUser: " + createPrimaryUserResult.status); + if (createPrimaryUserResult.status === "OK") { + return createPrimaryUserResult.user.id; } - return createPrimaryUserResult.user.id; + // if it comes here, it means that that there is already a primary user for the + // account info, or that this recipeUserId is already linked. Either way, we proceed + // to the next step, cause that takes care of both these cases. } - /** - * if it reaches this point, it means there should exists a - * primary user to which the recipe userId can be linked to - */ + if (primaryUser === undefined) { - throw Error("this error should never be thrown"); + // it can come here if there is a race condition. So we just try again + return await this.doPostSignUpAccountLinkingOperations({ + newUser: newUser, + newUserVerified: newUserVerified, + recipeUserId, + userContext, + }); } let result = await this.recipeInterfaceImpl.linkAccounts({ @@ -352,46 +347,32 @@ export default class Recipe extends RecipeModule { }); if (result.status === "OK") { /** - * let's Ly belongs to P1 such that Ly equal to Lx. - * if LY verified, mark Lx as verified. If Lx is verfied, - * then mark all Ly as verified + * We now mark the same email of other linked recipes as verified if the new user's email + * is verified. */ - let identitiesForPrimaryUser = this.getIdentitiesForUser(primaryUser); - let emailIdentityVerifiedForPrimaryUser = false; - if (info.email !== undefined) { - emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email); - } - if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { + + if (newUser.email !== undefined && newUserVerified) { let recipeUserIdsForEmailVerificationUpdate = primaryUser.loginMethods - .filter((u) => u.email === info.email && !u.verified) - .map((l) => l.email); - if (!infoVerified) { - recipeUserIdsForEmailVerificationUpdate.push(recipeUserId); - } + .filter((u) => u.email === newUser.email && !u.verified) + .map((l) => l.recipeUserId); recipeUserIdsForEmailVerificationUpdate = Array.from(new Set(recipeUserIdsForEmailVerificationUpdate)); + for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { - let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; - if (rUserId !== undefined) { - await this.markEmailAsVerified({ - email: info.email, - recipeUserId: rUserId, - userContext, - }); - } + await this.markEmailAsVerified({ + email: newUser.email, + recipeUserId: recipeUserIdsForEmailVerificationUpdate[i], + userContext, + }); } } return primaryUser.id; - } - if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + } else if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { return result.primaryUserId; - } - if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + } else if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { return result.primaryUserId; - } - if (result.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { + } else { return primaryUser.id; } - throw Error("this error status shouldn't not be thrown"); }; accountLinkPostSignInViaSession = async ({ @@ -563,7 +544,7 @@ export default class Recipe extends RecipeModule { throw Error("this error should never be thrown"); } let existingRecipeUsersForInputInfo = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo: identifier, userContext, }); let recipeUser = existingRecipeUsersForInputInfo.find((u) => @@ -596,7 +577,7 @@ export default class Recipe extends RecipeModule { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); if (info.email !== undefined) { let result = identitiesForPrimaryUser.verified.emails.includes(info.email) || @@ -687,7 +668,7 @@ export default class Recipe extends RecipeModule { }; } - let identitiesForPrimaryUser = this.getIdentitiesForUser(user); + let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; let emailIdentityVerifiedForPrimaryUser = false; let phoneNumberIdentityVerifiedForPrimaryUser = false; @@ -793,7 +774,7 @@ export default class Recipe extends RecipeModule { throw Error("this error should never be thrown"); } let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - info: identifier, + accountInfo: identifier, userContext, }); if (users === undefined || users.length === 0) { diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index ae5474ccf..bfa7f1331 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -191,7 +191,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo for (let j = 0; j < infos.length; j++) { let info = infos[j]; let usersList = await this.listUsersByAccountInfo({ - info, + accountInfo: info, userContext, }); if (usersList !== undefined) { @@ -546,10 +546,10 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }, listUsersByAccountInfo: async function ( this: RecipeInterface, - { info }: { info: AccountInfo } + { accountInfo }: { accountInfo: AccountInfo } ): Promise { let result = await querier.sendGetRequest(new NormalisedURLPath("/users/accountinfo"), { - ...info, + ...accountInfo, }); return result.users; }, diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 6edfdc2c9..169d35094 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -187,7 +187,7 @@ export type RecipeInterface = { } >; getUser: (input: { userId: string; userContext: any }) => Promise; - listUsersByAccountInfo: (input: { info: AccountInfo; userContext: any }) => Promise; + listUsersByAccountInfo: (input: { accountInfo: AccountInfo; userContext: any }) => Promise; deleteUser: (input: { userId: string; removeAllLinkedAccounts: boolean; @@ -230,20 +230,8 @@ export type AccountInfo = } | { phoneNumber: string; - }; - -export type AccountInfoWithRecipeId = - | { - recipeId: "emailpassword" | "passwordless"; - email: string; } | { - recipeId: "thirdparty"; - thirdpartyId: string; - thirdpartyUserId: string; - email: string; - } - | { - recipeId: "passwordless"; - phoneNumber: string; + thirdPartyId: string; + thirdPartyUserId: string; }; From 9fb35867d726af68f0b341b0cc9b172ea695e87f Mon Sep 17 00:00:00 2001 From: Rishabh Poddar Date: Wed, 1 Mar 2023 13:43:06 +0530 Subject: [PATCH 53/82] account linking: fixes bugs and refactors (#498) * fixes bugs and refactors * small refactors and fixes * small refactor * small type changes * review changes --- lib/build/recipe/accountlinking/index.d.ts | 4 +- lib/build/recipe/accountlinking/index.js | 8 +- lib/build/recipe/accountlinking/recipe.d.ts | 18 +- lib/build/recipe/accountlinking/recipe.js | 463 ++++++++++------- .../accountlinking/recipeImplementation.js | 45 +- lib/build/recipe/accountlinking/types.d.ts | 3 +- lib/build/recipe/dashboard/types.d.ts | 1 - lib/ts/recipe/accountlinking/index.ts | 6 +- lib/ts/recipe/accountlinking/recipe.ts | 481 +++++++++++------- .../accountlinking/recipeImplementation.ts | 53 +- lib/ts/recipe/accountlinking/types.ts | 3 +- lib/ts/recipe/dashboard/types.ts | 1 - 12 files changed, 673 insertions(+), 413 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 16e13235f..e0370758c 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -9,7 +9,7 @@ export default class Wrapper { ): Promise<{ [primaryUserId: string]: string[]; }>; - static getPrimaryUserIdsforRecipeUserIds( + static getPrimaryUserIdsForRecipeUserIds( recipeUserIds: string[], userContext?: any ): Promise<{ @@ -127,7 +127,7 @@ export default class Wrapper { } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; -export declare const getPrimaryUserIdsforRecipeUserIds: typeof Wrapper.getPrimaryUserIdsforRecipeUserIds; +export declare const getPrimaryUserIdsForRecipeUserIds: typeof Wrapper.getPrimaryUserIdsForRecipeUserIds; export declare const addNewRecipeUserIdWithoutPrimaryUserId: typeof Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; export declare const canCreatePrimaryUserId: typeof Wrapper.canCreatePrimaryUserId; export declare const createPrimaryUser: typeof Wrapper.createPrimaryUser; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 4002928ef..0cc4e1b7d 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -50,7 +50,7 @@ var __importDefault = return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.storeIntoAccountToLinkTable = exports.fetchFromAccountToLinkTable = exports.unlinkAccounts = exports.linkAccounts = exports.canLinkAccounts = exports.createPrimaryUser = exports.canCreatePrimaryUserId = exports.addNewRecipeUserIdWithoutPrimaryUserId = exports.getPrimaryUserIdsforRecipeUserIds = exports.getRecipeUserIdsForPrimaryUserIds = exports.init = void 0; +exports.storeIntoAccountToLinkTable = exports.fetchFromAccountToLinkTable = exports.unlinkAccounts = exports.linkAccounts = exports.canLinkAccounts = exports.createPrimaryUser = exports.canCreatePrimaryUserId = exports.addNewRecipeUserIdWithoutPrimaryUserId = exports.getPrimaryUserIdsForRecipeUserIds = exports.getRecipeUserIdsForPrimaryUserIds = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); class Wrapper { static getRecipeUserIdsForPrimaryUserIds(primaryUserIds, userContext) { @@ -63,11 +63,11 @@ class Wrapper { }); }); } - static getPrimaryUserIdsforRecipeUserIds(recipeUserIds, userContext) { + static getPrimaryUserIdsForRecipeUserIds(recipeUserIds, userContext) { return __awaiter(this, void 0, void 0, function* () { return yield recipe_1.default .getInstanceOrThrowError() - .recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ + .recipeInterfaceImpl.getPrimaryUserIdsForRecipeUserIds({ recipeUserIds, userContext: userContext === undefined ? {} : userContext, }); @@ -151,7 +151,7 @@ exports.default = Wrapper; Wrapper.init = recipe_1.default.init; exports.init = Wrapper.init; exports.getRecipeUserIdsForPrimaryUserIds = Wrapper.getRecipeUserIdsForPrimaryUserIds; -exports.getPrimaryUserIdsforRecipeUserIds = Wrapper.getPrimaryUserIdsforRecipeUserIds; +exports.getPrimaryUserIdsForRecipeUserIds = Wrapper.getPrimaryUserIdsForRecipeUserIds; exports.addNewRecipeUserIdWithoutPrimaryUserId = Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; exports.canCreatePrimaryUserId = Wrapper.canCreatePrimaryUserId; exports.createPrimaryUser = Wrapper.createPrimaryUser; diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index d266a4e4c..4e09c8b71 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -74,25 +74,29 @@ export default class Recipe extends RecipeModule { }) => Promise; accountLinkPostSignInViaSession: ({ session, - info, - infoVerified, + newUser, + newUserVerified, userContext, }: { session: SessionContainer; - info: AccountInfoAndEmailWithRecipeId; - infoVerified: boolean; + newUser: AccountInfoAndEmailWithRecipeId; + newUserVerified: boolean; userContext: any; }) => Promise< | { createRecipeUser: true; - updateVerificationClaim: boolean; + updateAccountLinkingClaim: "ADD_CLAIM" | "NO_CHANGE"; } | ({ createRecipeUser: false; } & ( | { accountsLinked: true; - updateVerificationClaim: boolean; + updateAccountLinkingClaim: "REMOVE_CLAIM"; + } + | { + accountsLinked: false; + updateAccountLinkingClaim: "ADD_CLAIM"; } | { accountsLinked: false; @@ -117,7 +121,7 @@ export default class Recipe extends RecipeModule { recipeUserId: string; userContext: any; }) => Promise; - createPrimaryUserIdOrLinkAccounts: ({ + createPrimaryUserIdOrLinkAccountsAfterEmailVerification: ({ recipeUserId, session, userContext, diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 0104a8e38..e9d637996 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -53,7 +53,6 @@ Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const utils_1 = require("./utils"); const __1 = require("../.."); -const supertokens_1 = __importDefault(require("../../supertokens")); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const recipeImplementation_1 = __importDefault(require("./recipeImplementation")); const querier_1 = require("../../querier"); @@ -167,11 +166,11 @@ class Recipe extends recipeModule_1.default { this.markEmailAsVerified = ({ email, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { const emailVerificationInstance = recipe_1.default.getInstance(); - if (emailVerificationInstance) { + if (emailVerificationInstance !== undefined) { const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( { userId: recipeUserId, - email: email, + email, userContext, } ); @@ -282,104 +281,142 @@ class Recipe extends recipeModule_1.default { return primaryUser.id; } }); - this.accountLinkPostSignInViaSession = ({ session, info, infoVerified, userContext }) => + this.accountLinkPostSignInViaSession = ({ session, newUser, newUserVerified, userContext }) => __awaiter(this, void 0, void 0, function* () { let userId = session.getUserId(); - let user = yield this.recipeInterfaceImpl.getUser({ + let existingUser = yield this.recipeInterfaceImpl.getUser({ userId, userContext, }); - if (user === undefined) { - throw Error("this should not be thrown"); + if (existingUser === undefined) { + // this can come here if the user ID in the session belongs to a user + // that is not recognized by SuperTokens. In this case, we + // disallow this kind of operation. + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + }; } /** * checking if the user with existing session * is a primary user or not */ - if (!user.isPrimaryUser) { - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, + if (!existingUser.isPrimaryUser) { + // first we check if the newUser should be a candidate for account linking + const shouldDoAccountLinkingOfNewUser = yield this.config.shouldDoAutomaticAccountLinking( + newUser, undefined, session, userContext ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + if (!shouldDoAccountLinkingOfNewUser.shouldAutomaticallyLink) { return { createRecipeUser: false, accountsLinked: false, reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } - let recipeId = user.loginMethods[0].recipeId; - let recipeUser = yield supertokens_1.default - .getInstanceOrThrowError() - ._getUserForRecipeId(user.id, recipeId); - if (recipeUser.user === undefined) { - throw Error( - "This error should never be thrown. Check for bug in `getUserForRecipeId` function" - ); - } - shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - recipeUser.user, + // Now we ask the user if the existing login method can be linked to anything + // (since it's not a primary user) + // here we can use the index of 0 cause the existingUser is not a primary user, + // therefore it will only have one login method in the loginMethods' array. + let existingUserAccountInfoAndEmailWithRecipeId = { + recipeId: existingUser.loginMethods[0].recipeId, + email: existingUser.loginMethods[0].email, + phoneNumber: existingUser.loginMethods[0].phoneNumber, + thirdParty: existingUser.loginMethods[0].thirdParty, + }; + const shouldDoAccountLinkingOfExistingUser = yield this.config.shouldDoAutomaticAccountLinking( + existingUserAccountInfoAndEmailWithRecipeId, undefined, session, userContext ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + if (!shouldDoAccountLinkingOfExistingUser.shouldAutomaticallyLink) { return { createRecipeUser: false, accountsLinked: false, reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!user.loginMethods[0].verified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } + if ( + shouldDoAccountLinkingOfExistingUser.shouldRequireVerification && + !existingUser.loginMethods[0].verified + ) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; } /** * checking if primary user can be created for the existing recipe user */ - let canCreatePrimaryUser = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId: user.id, + let canCreatePrimaryUserResult = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, }); - if (canCreatePrimaryUser.status !== "OK") { + if (canCreatePrimaryUserResult.status !== "OK") { + // TODO: we need to think about the implications of the different + // reasons here - which is possible? and which is not? return { createRecipeUser: false, accountsLinked: false, - reason: canCreatePrimaryUser.status, - primaryUserId: canCreatePrimaryUser.primaryUserId, + reason: canCreatePrimaryUserResult.status, + primaryUserId: canCreatePrimaryUserResult.primaryUserId, }; } /** * creating primary user for the recipe user */ let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId: user.id, + recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, }); - if (createPrimaryUserResult.status !== "OK") { + if ( + createPrimaryUserResult.status === + "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + // this can happen if there is a race condition in which the + // existing user becomes a primary user ID by the time the code + // execution comes into this block. So we call the function once again. + return yield this.accountLinkPostSignInViaSession({ + session, + newUser, + newUserVerified, + userContext, + }); + } else if ( + createPrimaryUserResult.status === + "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + /* this can come here if in the following example: + - User creates a primary account (P1) using email R + - User2 created another account (A2) with email R (but this is not yet linked to P1 cause maybe A2 is not a candidate for account linking) + - Now User2 is logged in with A2 account, and they are trying to link with another account. + - In this case, existingUser (A2 account), cannot become a primary user + - So we are in a stuck state, and must ask the end user to contact support*/ return { createRecipeUser: false, accountsLinked: false, reason: createPrimaryUserResult.status, primaryUserId: createPrimaryUserResult.primaryUserId, }; + } else if (createPrimaryUserResult.status === "OK") { + // this if condition is not needed, but for some reason TS complains if it's not there. + existingUser = createPrimaryUserResult.user; } - user = createPrimaryUserResult.user; + // at this point, the existingUser is a primary user. So we can + // go ahead and attempt account linking for the new user and existingUser. } /** * checking if account linking is allowed for given primary user * and new login info */ - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - info, - user, + const shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + newUser, + existingUser, session, userContext ); @@ -394,44 +431,56 @@ class Recipe extends recipeModule_1.default { * checking if a recipe user already exists for the given * login info */ - let identifier; - if (info.email !== undefined) { - identifier = { - email: info.email, + let accountInfo; + if (newUser.email !== undefined) { + accountInfo = { + email: newUser.email, }; - } - if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, + } else if (newUser.phoneNumber !== undefined) { + accountInfo = { + phoneNumber: newUser.phoneNumber, + }; + } else if (newUser.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: newUser.thirdParty.id, + thirdPartyUserId: newUser.thirdParty.userId, }; } else { throw Error("this error should never be thrown"); } - let existingRecipeUsersForInputInfo = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo: identifier, + /** + * We try and find if there is an existing recipe user for the same login method + * and same identifying info as the newUser object. + */ + let usersArrayThatHaveSameAccountInfoAsNewUser = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + accountInfo, userContext, }); - let recipeUser = existingRecipeUsersForInputInfo.find((u) => - u.loginMethods.find((lU) => { - if (lU.recipeId === info.recipeId) { - return false; - } - if (info.recipeId === "thirdparty") { - if (info.thirdParty !== undefined) { + const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find( + (u) => + u.loginMethods.find((lU) => { + if (lU.recipeId !== newUser.recipeId) { + return false; + } + if (newUser.recipeId === "thirdparty") { if (lU.thirdParty === undefined) { return false; } return ( - lU.thirdParty.id === info.thirdParty.id && - lU.thirdParty.userId === info.thirdParty.userId + lU.thirdParty.id === newUser.thirdParty.id && + lU.thirdParty.userId === newUser.thirdParty.userId ); } - return false; - } - return lU.email === info.email || info.phoneNumber === info.phoneNumber; - }) + return lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; + }) ); - if (recipeUser === undefined) { + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser === undefined) { + /* + Before proceeding to linking accounts, we need to create the recipe user ID associated + with newUser. In order to do that in a secure way, we need to check if the accountInfo + of the newUser is the same as of the existingUser - if it is, then we can go ahead, else + we will have to check about the verification status of the newUser's accountInfo + */ /** * if recipe user doesn't exists, we check if * any of the identifying info associated with @@ -442,44 +491,43 @@ class Recipe extends recipeModule_1.default { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); - if (info.email !== undefined) { + let identitiesForExistingUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(existingUser); + if (newUser.email !== undefined) { let result = - identitiesForPrimaryUser.verified.emails.includes(info.email) || - identitiesForPrimaryUser.unverified.emails.includes(info.email); + identitiesForExistingUser.verified.emails.includes(newUser.email) || + identitiesForExistingUser.unverified.emails.includes(newUser.email); if (result) { return { createRecipeUser: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "NO_CHANGE", }; } } - if (info.phoneNumber !== undefined) { + if (newUser.phoneNumber !== undefined) { let result = - identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || - identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + identitiesForExistingUser.verified.phoneNumbers.includes(newUser.phoneNumber) || + identitiesForExistingUser.unverified.phoneNumbers.includes(newUser.phoneNumber); if (result) { return { createRecipeUser: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "NO_CHANGE", }; } } /** * checking if there already exists any other primary - * user which is associated with the identifying info - * for the given input + * user which is associated with the account info + * for the newUser */ - if (existingRecipeUsersForInputInfo !== undefined) { - let primaryUserIfExists = existingRecipeUsersForInputInfo.find((u) => u.isPrimaryUser); - if (primaryUserIfExists !== undefined) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: primaryUserIfExists.id, - }; - } + const primaryUserIfExists = usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.isPrimaryUser); + if (primaryUserIfExists !== undefined) { + // TODO: as per the lucid chart diagram, there should be an assert here? + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUserIfExists.id, + }; } /** * if the existing info is not verified, we do want @@ -487,44 +535,59 @@ class Recipe extends recipeModule_1.default { * to again callback this function for any further * linking part. Instead, we want the recipe to * update the session claim so it can be known that - * the new account needs to be verified. so, return + * the new account needs to be verified. So, return * createRecipeUser as true to let the recipe know * that a recipe user needs to be created and set * updateVerificationClaim to true so the recipe will * not call back this function and update the session * claim instead */ - if (!infoVerified) { - if (shouldDoAccountLinking.shouldRequireVerification) { - return { - createRecipeUser: true, - updateVerificationClaim: true, - }; - } + if (!newUserVerified && shouldDoAccountLinking.shouldRequireVerification) { + return { + createRecipeUser: true, + updateAccountLinkingClaim: "ADD_CLAIM", + }; } return { createRecipeUser: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "NO_CHANGE", }; } /** - * checking if th primary user (associated with session) + * checking if the primary user (associated with session) * and recipe user (associated with login info) can be * linked */ let canLinkAccounts = yield this.recipeInterfaceImpl.canLinkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, + recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, + primaryUserId: existingUser.id, userContext, }); if (canLinkAccounts.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { return { createRecipeUser: false, accountsLinked: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "REMOVE_CLAIM", }; } - if (canLinkAccounts.status !== "OK") { + if ( + canLinkAccounts.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + canLinkAccounts.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + /* ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR can be possible if + - existingUser has email E1 + - you try and link an account with email E2 + - there already exists another primary account with email E2 + - so linking of existingUser and new account would fail + - this is a stuck state cause the user will have to contact support or login to their other account.*/ + /** + * RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR can be possible if: + - existingUser has email E1 + - you try and link an account with email E2 + - there already exists another primary account with email E2 that is linked to new account (input to this function) + - so linking of existingUser and new account would fail + - this is a stuck state cause the user will have to contact support or login to their other account. + */ return { createRecipeUser: false, accountsLinked: false, @@ -532,77 +595,82 @@ class Recipe extends recipeModule_1.default { primaryUserId: canLinkAccounts.primaryUserId, }; } - let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); - let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; - let emailIdentityVerifiedForPrimaryUser = false; - let phoneNumberIdentityVerifiedForPrimaryUser = false; - if (info.email !== undefined) { - recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = - identitiesForPrimaryUser.verified.emails.includes(info.email) || - identitiesForPrimaryUser.unverified.emails.includes(info.email); - emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email); - } - if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { - recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = - identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || - identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); - phoneNumberIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.phoneNumbers.includes( - info.phoneNumber + let accountInfoForExistingUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(existingUser); + let newUserAccountInfoIsAssociatedWithExistingUser = false; + let newUsersEmailAlreadyVerifiedInExistingUser = false; + if (newUser.email !== undefined) { + newUserAccountInfoIsAssociatedWithExistingUser = + accountInfoForExistingUser.verified.emails.includes(newUser.email) || + accountInfoForExistingUser.unverified.emails.includes(newUser.email); + newUsersEmailAlreadyVerifiedInExistingUser = accountInfoForExistingUser.verified.emails.includes( + newUser.email ); + } else if (newUser.phoneNumber !== undefined) { + newUserAccountInfoIsAssociatedWithExistingUser = + accountInfoForExistingUser.verified.phoneNumbers.includes(newUser.phoneNumber) || + accountInfoForExistingUser.unverified.phoneNumbers.includes(newUser.phoneNumber); } - if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { + if (newUserAccountInfoIsAssociatedWithExistingUser) { /** - * let's Ly belongs to P1 such that Ly equal to Lx. - * if LY verified, mark Lx as verified. If Lx is verfied, - * then mark all Ly as verified + * let Ly belong to P1 such that Ly equal to Lx. + * if LY verified or if Lx is verfied, + * then mark all Ly and Lx as verified */ - if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { - let recipeUserIdsForEmailVerificationUpdate = user.loginMethods - .filter((u) => u.email === info.email && !u.verified) - .map((l) => l.email); - if (!infoVerified) { - recipeUserIdsForEmailVerificationUpdate.push(recipeUser.id); + if ( + newUser.email !== undefined && + (newUsersEmailAlreadyVerifiedInExistingUser || newUserVerified) + ) { + let recipeUserIdsForEmailVerificationUpdate = existingUser.loginMethods + .filter((u) => u.email === newUser.email && !u.verified) + .map((l) => l.recipeUserId); + if (!newUserVerified) { + recipeUserIdsForEmailVerificationUpdate.push( + userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id + ); } recipeUserIdsForEmailVerificationUpdate = Array.from( new Set(recipeUserIdsForEmailVerificationUpdate) ); for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { - let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; - if (rUserId !== undefined) { - yield this.markEmailAsVerified({ - email: info.email, - recipeUserId: rUserId, - userContext, - }); - } + const recipeUserId = recipeUserIdsForEmailVerificationUpdate[i]; + yield this.markEmailAsVerified({ + email: newUser.email, + recipeUserId, + userContext, + }); } - } else if ( - info.phoneNumber !== undefined && - (phoneNumberIdentityVerifiedForPrimaryUser || infoVerified) - ) { - // DISCUSS: should we consider this scenario. phoneNumber will always be verified } } else { - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } + if (shouldDoAccountLinking.shouldRequireVerification && !newUserVerified) { + return { + createRecipeUser: false, + accountsLinked: false, + updateAccountLinkingClaim: "ADD_CLAIM", + }; } } - yield this.recipeInterfaceImpl.linkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, + const linkAccountResponse = yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, + primaryUserId: existingUser.id, userContext, }); - return { - createRecipeUser: false, - accountsLinked: true, - updateVerificationClaim: true, - }; + if ( + linkAccountResponse.status === "OK" || + linkAccountResponse.status === "ACCOUNTS_ALREADY_LINKED_ERROR" + ) { + return { + createRecipeUser: false, + accountsLinked: true, + updateAccountLinkingClaim: "REMOVE_CLAIM", + }; + } else { + return { + createRecipeUser: false, + accountsLinked: false, + primaryUserId: linkAccountResponse.primaryUserId, + reason: linkAccountResponse.status, + }; + } }); this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId = ({ recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { @@ -617,29 +685,31 @@ class Recipe extends recipeModule_1.default { if (pUser !== undefined && pUser.isPrimaryUser) { return pUser; } - let identifier; + let accountInfo; let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array if (loginMethodInfo.email !== undefined) { - identifier = { + accountInfo = { email: loginMethodInfo.email, }; } else if (loginMethodInfo.phoneNumber !== undefined) { - identifier = { + accountInfo = { phoneNumber: loginMethodInfo.phoneNumber, }; + } else if (loginMethodInfo.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: loginMethodInfo.thirdParty.id, + thirdPartyUserId: loginMethodInfo.thirdParty.userId, + }; } else { throw Error("this error should never be thrown"); } let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo: identifier, + accountInfo, userContext, }); - if (users === undefined || users.length === 0) { - return undefined; - } return users.find((u) => u.isPrimaryUser); }); - this.createPrimaryUserIdOrLinkAccounts = ({ recipeUserId, session, userContext }) => + this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification = ({ recipeUserId, session, userContext }) => __awaiter(this, void 0, void 0, function* () { let primaryUser = yield this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ recipeUserId, @@ -647,34 +717,71 @@ class Recipe extends recipeModule_1.default { }); if (primaryUser === undefined) { let user = yield __1.getUser(recipeUserId, userContext); - if (user === undefined || user.isPrimaryUser) { + if (user === undefined) { throw Error("this error should never be thrown"); } + if (user.isPrimaryUser) { + // this can come here cause of a race condition. + yield this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + return; + } let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - Object.assign({}, user.loginMethods[0]), + { + recipeId: user.loginMethods[0].recipeId, + email: user.loginMethods[0].email, + phoneNumber: user.loginMethods[0].phoneNumber, + thirdParty: user.loginMethods[0].thirdParty, + }, undefined, session, userContext ); if (shouldDoAccountLinking.shouldAutomaticallyLink) { - yield this.recipeInterfaceImpl.createPrimaryUser({ + let response = yield this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: recipeUserId, userContext, }); - // TODO: remove session claim + if (response.status === "OK") { + // TODO: remove session claim + } else { + // it can come here cause of a race condition.. + yield this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + } } } else { /** * recipeUser already linked with primaryUser */ - let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); + let recipeUser = primaryUser.loginMethods.find((u) => u.recipeUserId === recipeUserId); if (recipeUser === undefined) { let user = yield __1.getUser(recipeUserId, userContext); - if (user === undefined || user.isPrimaryUser) { + if (user === undefined) { throw Error("this error should never be thrown"); } + if (user.isPrimaryUser) { + // this can come here cause of a race condition. + yield this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + return; + } let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( - Object.assign({}, user.loginMethods[0]), + { + recipeId: user.loginMethods[0].recipeId, + email: user.loginMethods[0].email, + phoneNumber: user.loginMethods[0].phoneNumber, + thirdParty: user.loginMethods[0].thirdParty, + }, primaryUser, session, userContext @@ -685,10 +792,18 @@ class Recipe extends recipeModule_1.default { primaryUserId: primaryUser.id, userContext, }); - if (linkAccountsResult.status === "OK") { - // TODO: remove session claim if session claim exists - // else create a new session + let primaryUserId = primaryUser.id; + if ( + linkAccountsResult.status === + "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + linkAccountsResult.status === + "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + primaryUserId = linkAccountsResult.primaryUserId; } + console.log(primaryUserId); // TODO: remove this + // TODO: remove session claim if session claim exists + // else create a new session } } } diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index a2df264ac..ca280eb50 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -52,7 +52,6 @@ var __importDefault = Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); const session_1 = __importDefault(require("../session")); -const supertokens_1 = __importDefault(require("../../supertokens")); function getRecipeImplementation(querier, config) { return { getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { @@ -66,7 +65,7 @@ function getRecipeImplementation(querier, config) { return result.userIdMapping; }); }, - getPrimaryUserIdsforRecipeUserIds: function ({ recipeUserIds }) { + getPrimaryUserIdsForRecipeUserIds: function ({ recipeUserIds }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendGetRequest( new normalisedURLPath_1.default("/recipe/accountlinking/users"), @@ -111,7 +110,7 @@ function getRecipeImplementation(querier, config) { * This is to know if the existing recipeUserId * is already associated with a primaryUserId */ - let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsforRecipeUserIds({ + let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsForRecipeUserIds({ recipeUserIds: [recipeUserId], userContext, }); @@ -119,7 +118,11 @@ function getRecipeImplementation(querier, config) { * checking if primaryUserId exists for the recipeUserId */ let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId !== undefined && primaryUserId !== null) { + if (primaryUserId === undefined) { + // this means that the recipeUserId doesn't exist + throw new Error("The input recipeUserId does not exist"); + } + if (primaryUserId !== null) { return { status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", primaryUserId, @@ -141,7 +144,7 @@ function getRecipeImplementation(querier, config) { * precautionary check */ if (user === undefined) { - throw Error("this error should not be thrown"); + throw new Error("The input recipeUserId does not exist"); } /** * for all the identifying info associated with the recipeUser, @@ -163,6 +166,12 @@ function getRecipeImplementation(querier, config) { phoneNumber: loginMethod.phoneNumber, }); } + if (loginMethod.thirdParty !== undefined) { + infos.push({ + thirdPartyId: loginMethod.thirdParty.id, + thirdPartyUserId: loginMethod.thirdParty.userId, + }); + } for (let j = 0; j < infos.length; j++) { let info = infos[j]; let usersList = yield this.listUsersByAccountInfo({ @@ -318,13 +327,18 @@ function getRecipeImplementation(querier, config) { if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = yield supertokens_1.default - .getInstanceOrThrowError() - ._getUserForRecipeId(loginMethodInfo.recipeUserId, loginMethodInfo.recipeId); - if (recipeUser.user === undefined) { - throw Error("this error should never be thrown"); - } - yield config.onAccountLinked(user, recipeUser.user, userContext); + yield config.onAccountLinked( + user, + { + recipeId: loginMethodInfo.recipeId, + recipeUserId: loginMethodInfo.recipeUserId, + timeJoined: loginMethodInfo.timeJoined, + email: loginMethodInfo.email, + phoneNumber: loginMethodInfo.phoneNumber, + thirdParty: loginMethodInfo.thirdParty, + }, + userContext + ); } else { throw Error(`error thrown from core while linking accounts: ${accountsLinkingResult.status}`); } @@ -333,12 +347,15 @@ function getRecipeImplementation(querier, config) { }, unlinkAccounts: function ({ recipeUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsforRecipeUserIds({ + let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsForRecipeUserIds({ recipeUserIds: [recipeUserId], userContext, }); let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId === undefined || primaryUserId === null) { + if (primaryUserId === undefined) { + throw new Error("input recipeUserId does not exist"); + } + if (primaryUserId === null) { throw Error("recipeUserId is not associated with any primaryUserId"); } /** diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 0a36d20d4..441535b32 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -55,7 +55,7 @@ export declare type RecipeInterface = { }) => Promise<{ [primaryUserId: string]: string[]; }>; - getPrimaryUserIdsforRecipeUserIds: (input: { + getPrimaryUserIdsForRecipeUserIds: (input: { recipeUserIds: string[]; userContext: any; }) => Promise<{ @@ -189,7 +189,6 @@ export declare type RecipeInterface = { }; export declare type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; - id: string; timeJoined: number; recipeUserId: string; email?: string; diff --git a/lib/build/recipe/dashboard/types.d.ts b/lib/build/recipe/dashboard/types.d.ts index af1b0c65c..b35894316 100644 --- a/lib/build/recipe/dashboard/types.d.ts +++ b/lib/build/recipe/dashboard/types.d.ts @@ -42,7 +42,6 @@ export declare type APIFunction = (apiImplementation: APIInterface, options: API export declare type RecipeIdForUser = "emailpassword" | "thirdparty" | "passwordless"; export declare type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; - id: string; timeJoined: number; recipeUserId: string; email?: string; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index 92b91e83c..984f2e970 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -25,8 +25,8 @@ export default class Wrapper { }); } - static async getPrimaryUserIdsforRecipeUserIds(recipeUserIds: string[], userContext?: any) { - return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdsforRecipeUserIds({ + static async getPrimaryUserIdsForRecipeUserIds(recipeUserIds: string[], userContext?: any) { + return await Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdsForRecipeUserIds({ recipeUserIds, userContext: userContext === undefined ? {} : userContext, }); @@ -103,7 +103,7 @@ export default class Wrapper { export const init = Wrapper.init; export const getRecipeUserIdsForPrimaryUserIds = Wrapper.getRecipeUserIdsForPrimaryUserIds; -export const getPrimaryUserIdsforRecipeUserIds = Wrapper.getPrimaryUserIdsforRecipeUserIds; +export const getPrimaryUserIdsForRecipeUserIds = Wrapper.getPrimaryUserIdsForRecipeUserIds; export const addNewRecipeUserIdWithoutPrimaryUserId = Wrapper.addNewRecipeUserIdWithoutPrimaryUserId; export const canCreatePrimaryUserId = Wrapper.canCreatePrimaryUserId; export const createPrimaryUser = Wrapper.createPrimaryUser; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index f202eab79..424ee5be7 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -28,7 +28,6 @@ import type { } from "./types"; import { validateAndNormaliseUserInput } from "./utils"; import { getUser } from "../.."; -import SuperTokens from "../../supertokens"; import OverrideableBuilder from "supertokens-js-override"; import RecipeImplementation from "./recipeImplementation"; import { Querier } from "../../querier"; @@ -248,10 +247,10 @@ export default class Recipe extends RecipeModule { userContext: any; }): Promise => { const emailVerificationInstance = EmailVerification.getInstance(); - if (emailVerificationInstance) { + if (emailVerificationInstance !== undefined) { const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ userId: recipeUserId, - email: email, + email, userContext, }); @@ -377,25 +376,32 @@ export default class Recipe extends RecipeModule { accountLinkPostSignInViaSession = async ({ session, - info, - infoVerified, + newUser, + newUserVerified, userContext, }: { session: SessionContainer; - info: AccountInfoAndEmailWithRecipeId; - infoVerified: boolean; + newUser: AccountInfoAndEmailWithRecipeId; + newUserVerified: boolean; userContext: any; }): Promise< | { createRecipeUser: true; - updateVerificationClaim: boolean; + + // if the value of updateAccountLinkingClaim is NO_CHANGE, it also means that the + // consumer of this function should call this function again. + updateAccountLinkingClaim: "ADD_CLAIM" | "NO_CHANGE"; } | ({ createRecipeUser: false; } & ( | { accountsLinked: true; - updateVerificationClaim: boolean; + updateAccountLinkingClaim: "REMOVE_CLAIM"; + } + | { + accountsLinked: false; + updateAccountLinkingClaim: "ADD_CLAIM"; } | { accountsLinked: false; @@ -414,25 +420,33 @@ export default class Recipe extends RecipeModule { )) > => { let userId = session.getUserId(); - let user = await this.recipeInterfaceImpl.getUser({ + let existingUser = await this.recipeInterfaceImpl.getUser({ userId, userContext, }); - if (user === undefined) { - throw Error("this should not be thrown"); + if (existingUser === undefined) { + // this can come here if the user ID in the session belongs to a user + // that is not recognized by SuperTokens. In this case, we + // disallow this kind of operation. + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + }; } /** * checking if the user with existing session * is a primary user or not */ - if (!user.isPrimaryUser) { - let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( - info, + if (!existingUser.isPrimaryUser) { + // first we check if the newUser should be a candidate for account linking + const shouldDoAccountLinkingOfNewUser = await this.config.shouldDoAutomaticAccountLinking( + newUser, undefined, session, userContext ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + if (!shouldDoAccountLinkingOfNewUser.shouldAutomaticallyLink) { return { createRecipeUser: false, accountsLinked: false, @@ -440,75 +454,108 @@ export default class Recipe extends RecipeModule { }; } - let recipeId = user.loginMethods[0].recipeId; - let recipeUser = await SuperTokens.getInstanceOrThrowError()._getUserForRecipeId(user.id, recipeId); + // Now we ask the user if the existing login method can be linked to anything + // (since it's not a primary user) - if (recipeUser.user === undefined) { - throw Error("This error should never be thrown. Check for bug in `getUserForRecipeId` function"); - } + // here we can use the index of 0 cause the existingUser is not a primary user, + // therefore it will only have one login method in the loginMethods' array. + let existingUserAccountInfoAndEmailWithRecipeId: AccountInfoAndEmailWithRecipeId = { + recipeId: existingUser.loginMethods[0].recipeId, + email: existingUser.loginMethods[0].email, + phoneNumber: existingUser.loginMethods[0].phoneNumber, + thirdParty: existingUser.loginMethods[0].thirdParty, + }; - shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( - recipeUser.user, + const shouldDoAccountLinkingOfExistingUser = await this.config.shouldDoAutomaticAccountLinking( + existingUserAccountInfoAndEmailWithRecipeId, undefined, session, userContext ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + if (!shouldDoAccountLinkingOfExistingUser.shouldAutomaticallyLink) { return { createRecipeUser: false, accountsLinked: false, reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!user.loginMethods[0].verified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } + if ( + shouldDoAccountLinkingOfExistingUser.shouldRequireVerification && + !existingUser.loginMethods[0].verified + ) { + return { + createRecipeUser: false, + accountsLinked: false, + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; } /** * checking if primary user can be created for the existing recipe user */ - let canCreatePrimaryUser = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId: user.id, + let canCreatePrimaryUserResult = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ + recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, }); - if (canCreatePrimaryUser.status !== "OK") { + if (canCreatePrimaryUserResult.status !== "OK") { + // TODO: we need to think about the implications of the different + // reasons here - which is possible? and which is not? return { createRecipeUser: false, accountsLinked: false, - reason: canCreatePrimaryUser.status, - primaryUserId: canCreatePrimaryUser.primaryUserId, + reason: canCreatePrimaryUserResult.status, + primaryUserId: canCreatePrimaryUserResult.primaryUserId, }; } /** * creating primary user for the recipe user */ let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId: user.id, + recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, }); - if (createPrimaryUserResult.status !== "OK") { + + if (createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + // this can happen if there is a race condition in which the + // existing user becomes a primary user ID by the time the code + // execution comes into this block. So we call the function once again. + return await this.accountLinkPostSignInViaSession({ + session, + newUser, + newUserVerified, + userContext, + }); + } else if ( + createPrimaryUserResult.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + /* this can come here if in the following example: + - User creates a primary account (P1) using email R + - User2 created another account (A2) with email R (but this is not yet linked to P1 cause maybe A2 is not a candidate for account linking) + - Now User2 is logged in with A2 account, and they are trying to link with another account. + - In this case, existingUser (A2 account), cannot become a primary user + - So we are in a stuck state, and must ask the end user to contact support*/ return { createRecipeUser: false, accountsLinked: false, reason: createPrimaryUserResult.status, primaryUserId: createPrimaryUserResult.primaryUserId, }; + } else if (createPrimaryUserResult.status === "OK") { + // this if condition is not needed, but for some reason TS complains if it's not there. + existingUser = createPrimaryUserResult.user; } - user = createPrimaryUserResult.user; + + // at this point, the existingUser is a primary user. So we can + // go ahead and attempt account linking for the new user and existingUser. } + /** * checking if account linking is allowed for given primary user * and new login info */ - let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( - info, - user, + const shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( + newUser, + existingUser, session, userContext ); @@ -524,49 +571,59 @@ export default class Recipe extends RecipeModule { * checking if a recipe user already exists for the given * login info */ - let identifier: - | { - email: string; - } - | { - phoneNumber: string; - }; - if (info.email !== undefined) { - identifier = { - email: info.email, + let accountInfo: AccountInfo; + if (newUser.email !== undefined) { + accountInfo = { + email: newUser.email, }; - } - if (info.phoneNumber !== undefined) { - identifier = { - phoneNumber: info.phoneNumber, + } else if (newUser.phoneNumber !== undefined) { + accountInfo = { + phoneNumber: newUser.phoneNumber, + }; + } else if (newUser.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: newUser.thirdParty.id, + thirdPartyUserId: newUser.thirdParty.userId, }; } else { throw Error("this error should never be thrown"); } - let existingRecipeUsersForInputInfo = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo: identifier, + + /** + * We try and find if there is an existing recipe user for the same login method + * and same identifying info as the newUser object. + */ + let usersArrayThatHaveSameAccountInfoAsNewUser = await this.recipeInterfaceImpl.listUsersByAccountInfo({ + accountInfo, userContext, }); - let recipeUser = existingRecipeUsersForInputInfo.find((u) => + + const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.loginMethods.find((lU) => { - if (lU.recipeId === info.recipeId) { + if (lU.recipeId !== newUser.recipeId) { return false; } - if (info.recipeId === "thirdparty") { - if (info.thirdParty !== undefined) { - if (lU.thirdParty === undefined) { - return false; - } - return ( - lU.thirdParty.id === info.thirdParty.id && lU.thirdParty.userId === info.thirdParty.userId - ); + if (newUser.recipeId === "thirdparty") { + if (lU.thirdParty === undefined) { + return false; } - return false; + return ( + lU.thirdParty.id === newUser.thirdParty!.id && + lU.thirdParty.userId === newUser.thirdParty!.userId + ); } - return lU.email === info.email || info.phoneNumber === info.phoneNumber; + return lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; }) ); - if (recipeUser === undefined) { + + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser === undefined) { + /* + Before proceeding to linking accounts, we need to create the recipe user ID associated + with newUser. In order to do that in a secure way, we need to check if the accountInfo + of the newUser is the same as of the existingUser - if it is, then we can go ahead, else + we will have to check about the verification status of the newUser's accountInfo + */ + /** * if recipe user doesn't exists, we check if * any of the identifying info associated with @@ -577,44 +634,43 @@ export default class Recipe extends RecipeModule { * so the recipe will call back this function when the * recipe user is created */ - let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); - if (info.email !== undefined) { + let identitiesForExistingUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(existingUser); + if (newUser.email !== undefined) { let result = - identitiesForPrimaryUser.verified.emails.includes(info.email) || - identitiesForPrimaryUser.unverified.emails.includes(info.email); + identitiesForExistingUser.verified.emails.includes(newUser.email) || + identitiesForExistingUser.unverified.emails.includes(newUser.email); if (result) { return { createRecipeUser: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "NO_CHANGE", }; } } - if (info.phoneNumber !== undefined) { + if (newUser.phoneNumber !== undefined) { let result = - identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || - identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); + identitiesForExistingUser.verified.phoneNumbers.includes(newUser.phoneNumber) || + identitiesForExistingUser.unverified.phoneNumbers.includes(newUser.phoneNumber); if (result) { return { createRecipeUser: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "NO_CHANGE", }; } } /** * checking if there already exists any other primary - * user which is associated with the identifying info - * for the given input + * user which is associated with the account info + * for the newUser */ - if (existingRecipeUsersForInputInfo !== undefined) { - let primaryUserIfExists = existingRecipeUsersForInputInfo.find((u) => u.isPrimaryUser); - if (primaryUserIfExists !== undefined) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: primaryUserIfExists.id, - }; - } + const primaryUserIfExists = usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.isPrimaryUser); + if (primaryUserIfExists !== undefined) { + // TODO: as per the lucid chart diagram, there should be an assert here? + return { + createRecipeUser: false, + accountsLinked: false, + reason: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: primaryUserIfExists.id, + }; } /** * if the existing info is not verified, we do want @@ -622,44 +678,61 @@ export default class Recipe extends RecipeModule { * to again callback this function for any further * linking part. Instead, we want the recipe to * update the session claim so it can be known that - * the new account needs to be verified. so, return + * the new account needs to be verified. So, return * createRecipeUser as true to let the recipe know * that a recipe user needs to be created and set * updateVerificationClaim to true so the recipe will * not call back this function and update the session * claim instead */ - if (!infoVerified) { - if (shouldDoAccountLinking.shouldRequireVerification) { - return { - createRecipeUser: true, - updateVerificationClaim: true, - }; - } + if (!newUserVerified && shouldDoAccountLinking.shouldRequireVerification) { + return { + createRecipeUser: true, + updateAccountLinkingClaim: "ADD_CLAIM", + }; } return { createRecipeUser: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "NO_CHANGE", }; } + /** - * checking if th primary user (associated with session) + * checking if the primary user (associated with session) * and recipe user (associated with login info) can be * linked */ let canLinkAccounts = await this.recipeInterfaceImpl.canLinkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, + recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, + primaryUserId: existingUser.id, userContext, }); if (canLinkAccounts.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { return { createRecipeUser: false, accountsLinked: true, - updateVerificationClaim: false, + updateAccountLinkingClaim: "REMOVE_CLAIM", }; } - if (canLinkAccounts.status !== "OK") { + if ( + canLinkAccounts.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + canLinkAccounts.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + /* ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR can be possible if + - existingUser has email E1 + - you try and link an account with email E2 + - there already exists another primary account with email E2 + - so linking of existingUser and new account would fail + - this is a stuck state cause the user will have to contact support or login to their other account.*/ + + /** + * RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR can be possible if: + - existingUser has email E1 + - you try and link an account with email E2 + - there already exists another primary account with email E2 that is linked to new account (input to this function) + - so linking of existingUser and new account would fail + - this is a stuck state cause the user will have to contact support or login to their other account. + */ return { createRecipeUser: false, accountsLinked: false, @@ -668,72 +741,74 @@ export default class Recipe extends RecipeModule { }; } - let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(user); - let recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = false; - let emailIdentityVerifiedForPrimaryUser = false; - let phoneNumberIdentityVerifiedForPrimaryUser = false; - if (info.email !== undefined) { - recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = - identitiesForPrimaryUser.verified.emails.includes(info.email) || - identitiesForPrimaryUser.unverified.emails.includes(info.email); - emailIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.emails.includes(info.email); - } - if (!recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser && info.phoneNumber !== undefined) { - recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser = - identitiesForPrimaryUser.verified.phoneNumbers.includes(info.phoneNumber) || - identitiesForPrimaryUser.unverified.phoneNumbers.includes(info.phoneNumber); - phoneNumberIdentityVerifiedForPrimaryUser = identitiesForPrimaryUser.verified.phoneNumbers.includes( - info.phoneNumber + let accountInfoForExistingUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(existingUser); + + let newUserAccountInfoIsAssociatedWithExistingUser = false; + let newUsersEmailAlreadyVerifiedInExistingUser = false; + if (newUser.email !== undefined) { + newUserAccountInfoIsAssociatedWithExistingUser = + accountInfoForExistingUser.verified.emails.includes(newUser.email) || + accountInfoForExistingUser.unverified.emails.includes(newUser.email); + newUsersEmailAlreadyVerifiedInExistingUser = accountInfoForExistingUser.verified.emails.includes( + newUser.email ); + } else if (newUser.phoneNumber !== undefined) { + newUserAccountInfoIsAssociatedWithExistingUser = + accountInfoForExistingUser.verified.phoneNumbers.includes(newUser.phoneNumber) || + accountInfoForExistingUser.unverified.phoneNumbers.includes(newUser.phoneNumber); } - if (recipeUserIdentifyingInfoIsAssociatedWithPrimaryUser) { + if (newUserAccountInfoIsAssociatedWithExistingUser) { /** - * let's Ly belongs to P1 such that Ly equal to Lx. - * if LY verified, mark Lx as verified. If Lx is verfied, - * then mark all Ly as verified + * let Ly belong to P1 such that Ly equal to Lx. + * if LY verified or if Lx is verfied, + * then mark all Ly and Lx as verified */ - if (info.email !== undefined && (emailIdentityVerifiedForPrimaryUser || infoVerified)) { - let recipeUserIdsForEmailVerificationUpdate = user.loginMethods - .filter((u) => u.email === info.email && !u.verified) - .map((l) => l.email); - if (!infoVerified) { - recipeUserIdsForEmailVerificationUpdate.push(recipeUser.id); + if (newUser.email !== undefined && (newUsersEmailAlreadyVerifiedInExistingUser || newUserVerified)) { + let recipeUserIdsForEmailVerificationUpdate = existingUser.loginMethods + .filter((u) => u.email === newUser.email && !u.verified) + .map((l) => l.recipeUserId); + if (!newUserVerified) { + recipeUserIdsForEmailVerificationUpdate.push(userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id); } recipeUserIdsForEmailVerificationUpdate = Array.from(new Set(recipeUserIdsForEmailVerificationUpdate)); for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { - let rUserId = recipeUserIdsForEmailVerificationUpdate[i]; - if (rUserId !== undefined) { - await this.markEmailAsVerified({ - email: info.email, - recipeUserId: rUserId, - userContext, - }); - } + const recipeUserId = recipeUserIdsForEmailVerificationUpdate[i]; + await this.markEmailAsVerified({ + email: newUser.email, + recipeUserId, + userContext, + }); } - } else if (info.phoneNumber !== undefined && (phoneNumberIdentityVerifiedForPrimaryUser || infoVerified)) { - // DISCUSS: should we consider this scenario. phoneNumber will always be verified } } else { - if (shouldDoAccountLinking.shouldRequireVerification) { - if (!infoVerified) { - return { - createRecipeUser: false, - accountsLinked: false, - reason: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", - }; - } + if (shouldDoAccountLinking.shouldRequireVerification && !newUserVerified) { + return { + createRecipeUser: false, + accountsLinked: false, + updateAccountLinkingClaim: "ADD_CLAIM", + }; } } - await this.recipeInterfaceImpl.linkAccounts({ - recipeUserId: recipeUser.id, - primaryUserId: user.id, + + const linkAccountResponse = await this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, + primaryUserId: existingUser.id, userContext, }); - return { - createRecipeUser: false, - accountsLinked: true, - updateVerificationClaim: true, - }; + if (linkAccountResponse.status === "OK" || linkAccountResponse.status === "ACCOUNTS_ALREADY_LINKED_ERROR") { + return { + createRecipeUser: false, + accountsLinked: true, + updateAccountLinkingClaim: "REMOVE_CLAIM", + }; + } else { + return { + createRecipeUser: false, + accountsLinked: false, + primaryUserId: linkAccountResponse.primaryUserId, + reason: linkAccountResponse.status, + }; + } }; getPrimaryUserIdThatCanBeLinkedToRecipeUserId = async ({ @@ -754,36 +829,33 @@ export default class Recipe extends RecipeModule { if (pUser !== undefined && pUser.isPrimaryUser) { return pUser; } - let identifier: - | { - email: string; - } - | { - phoneNumber: string; - }; + + let accountInfo: AccountInfo; let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array if (loginMethodInfo.email !== undefined) { - identifier = { + accountInfo = { email: loginMethodInfo.email, }; } else if (loginMethodInfo.phoneNumber !== undefined) { - identifier = { + accountInfo = { phoneNumber: loginMethodInfo.phoneNumber, }; + } else if (loginMethodInfo.thirdParty !== undefined) { + accountInfo = { + thirdPartyId: loginMethodInfo.thirdParty.id, + thirdPartyUserId: loginMethodInfo.thirdParty.userId, + }; } else { throw Error("this error should never be thrown"); } let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo: identifier, + accountInfo, userContext, }); - if (users === undefined || users.length === 0) { - return undefined; - } return users.find((u) => u.isPrimaryUser); }; - createPrimaryUserIdOrLinkAccounts = async ({ + createPrimaryUserIdOrLinkAccountsAfterEmailVerification = async ({ recipeUserId, session, userContext, @@ -798,52 +870,95 @@ export default class Recipe extends RecipeModule { }); if (primaryUser === undefined) { let user = await getUser(recipeUserId, userContext); - if (user === undefined || user.isPrimaryUser) { + if (user === undefined) { throw Error("this error should never be thrown"); } + if (user.isPrimaryUser) { + // this can come here cause of a race condition. + await this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + return; + } let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( { - ...user.loginMethods[0], + recipeId: user.loginMethods[0].recipeId, + email: user.loginMethods[0].email, + phoneNumber: user.loginMethods[0].phoneNumber, + thirdParty: user.loginMethods[0].thirdParty, }, undefined, session, userContext ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { - await this.recipeInterfaceImpl.createPrimaryUser({ + let response = await this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: recipeUserId, userContext, }); - // TODO: remove session claim + if (response.status === "OK") { + // TODO: remove session claim + } else { + // it can come here cause of a race condition.. + await this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + } } } else { /** * recipeUser already linked with primaryUser */ - let recipeUser = primaryUser.loginMethods.find((u) => u.id === recipeUserId); + let recipeUser = primaryUser.loginMethods.find((u) => u.recipeUserId === recipeUserId); if (recipeUser === undefined) { let user = await getUser(recipeUserId, userContext); - if (user === undefined || user.isPrimaryUser) { + if (user === undefined) { throw Error("this error should never be thrown"); } + if (user.isPrimaryUser) { + // this can come here cause of a race condition. + await this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + return; + } let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( { - ...user.loginMethods[0], + recipeId: user.loginMethods[0].recipeId, + email: user.loginMethods[0].email, + phoneNumber: user.loginMethods[0].phoneNumber, + thirdParty: user.loginMethods[0].thirdParty, }, primaryUser, session, userContext ); + if (shouldDoAccountLinking.shouldAutomaticallyLink) { let linkAccountsResult = await this.recipeInterfaceImpl.linkAccounts({ recipeUserId: recipeUserId, primaryUserId: primaryUser.id, userContext, }); - if (linkAccountsResult.status === "OK") { - // TODO: remove session claim if session claim exists - // else create a new session + let primaryUserId = primaryUser.id; + if ( + linkAccountsResult.status === + "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + linkAccountsResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + primaryUserId = linkAccountsResult.primaryUserId; } + console.log(primaryUserId); // TODO: remove this + + // TODO: remove session claim if session claim exists + // else create a new session } } } diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index bfa7f1331..4e37de0f8 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -13,12 +13,11 @@ * under the License. */ -import { AccountInfo, RecipeInterface, TypeNormalisedInput } from "./types"; +import { AccountInfo, RecipeInterface, TypeNormalisedInput, RecipeLevelUser } from "./types"; import { Querier } from "../../querier"; import type { User } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; import Session from "../session"; -import SuperTokens from "../../supertokens"; export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface { return { @@ -37,7 +36,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }); return result.userIdMapping; }, - getPrimaryUserIdsforRecipeUserIds: async function ( + getPrimaryUserIdsForRecipeUserIds: async function ( this: RecipeInterface, { recipeUserIds, @@ -131,7 +130,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo * This is to know if the existing recipeUserId * is already associated with a primaryUserId */ - let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsforRecipeUserIds({ + let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsForRecipeUserIds({ recipeUserIds: [recipeUserId], userContext, }); @@ -140,7 +139,11 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo * checking if primaryUserId exists for the recipeUserId */ let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId !== undefined && primaryUserId !== null) { + if (primaryUserId === undefined) { + // this means that the recipeUserId doesn't exist + throw new Error("The input recipeUserId does not exist"); + } + if (primaryUserId !== null) { return { status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", primaryUserId, @@ -164,7 +167,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo * precautionary check */ if (user === undefined) { - throw Error("this error should not be thrown"); + throw new Error("The input recipeUserId does not exist"); } /** @@ -173,7 +176,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo * From those users, we'll try to find if there already exists * a primaryUser which is associated with the identifying info */ - let usersForAccountInfo = []; + let usersForAccountInfo: User[] = []; for (let i = 0; i < user.loginMethods.length; i++) { let loginMethod = user.loginMethods[i]; @@ -188,6 +191,12 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo phoneNumber: loginMethod.phoneNumber, }); } + if (loginMethod.thirdParty !== undefined) { + infos.push({ + thirdPartyId: loginMethod.thirdParty.id, + thirdPartyUserId: loginMethod.thirdParty.userId, + }); + } for (let j = 0; j < infos.length; j++) { let info = infos[j]; let usersList = await this.listUsersByAccountInfo({ @@ -455,14 +464,18 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo if (loginMethodInfo === undefined) { throw Error("this error should never be thrown"); } - let recipeUser = await SuperTokens.getInstanceOrThrowError()._getUserForRecipeId( - loginMethodInfo.recipeUserId, - loginMethodInfo.recipeId + await config.onAccountLinked( + user, + { + recipeId: loginMethodInfo.recipeId, + recipeUserId: loginMethodInfo.recipeUserId, + timeJoined: loginMethodInfo.timeJoined, + email: loginMethodInfo.email, + phoneNumber: loginMethodInfo.phoneNumber, + thirdParty: loginMethodInfo.thirdParty, + }, + userContext ); - if (recipeUser.user === undefined) { - throw Error("this error should never be thrown"); - } - await config.onAccountLinked(user, recipeUser.user, userContext); } else { throw Error(`error thrown from core while linking accounts: ${accountsLinkingResult.status}`); } @@ -481,12 +494,15 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo status: "OK"; wasRecipeUserDeleted: boolean; }> { - let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsforRecipeUserIds({ + let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsForRecipeUserIds({ recipeUserIds: [recipeUserId], userContext, }); let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId === undefined || primaryUserId === null) { + if (primaryUserId === undefined) { + throw new Error("input recipeUserId does not exist"); + } + if (primaryUserId === null) { throw Error("recipeUserId is not associated with any primaryUserId"); } /** @@ -575,10 +591,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }; } - let recipeUsersToRemove: { - recipeId: string; - recipeUserId: string; - }[] = []; + let recipeUsersToRemove: RecipeLevelUser[] = []; /** * if true, the user should be treated as primaryUser diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 169d35094..b4a432a26 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -72,7 +72,7 @@ export type RecipeInterface = { }) => Promise<{ [primaryUserId: string]: string[]; // recipeUserIds. If input primary user ID doesn't exists, those ids will not be part of the output set. }>; - getPrimaryUserIdsforRecipeUserIds: (input: { + getPrimaryUserIdsForRecipeUserIds: (input: { recipeUserIds: string[]; userContext: any; }) => Promise<{ @@ -203,7 +203,6 @@ export type RecipeInterface = { export type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; - id: string; // can be recipeUserId or primaryUserId timeJoined: number; recipeUserId: string; email?: string; diff --git a/lib/ts/recipe/dashboard/types.ts b/lib/ts/recipe/dashboard/types.ts index a78c3e7d1..28dd4980f 100644 --- a/lib/ts/recipe/dashboard/types.ts +++ b/lib/ts/recipe/dashboard/types.ts @@ -64,7 +64,6 @@ export type RecipeIdForUser = "emailpassword" | "thirdparty" | "passwordless"; export type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; - id: string; // can be recipeUserId or primaryUserId timeJoined: number; recipeUserId: string; email?: string; From 2f16711774ebc7e8638db0f8b9d3a18bcb14555b Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 1 Mar 2023 14:09:42 +0530 Subject: [PATCH 54/82] removes redundant check --- lib/build/recipe/accountlinking/recipe.js | 20 -------------------- lib/ts/recipe/accountlinking/recipe.ts | 20 -------------------- 2 files changed, 40 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index e9d637996..334e5b8fe 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -350,26 +350,6 @@ class Recipe extends recipeModule_1.default { reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", }; } - /** - * checking if primary user can be created for the existing recipe user - */ - let canCreatePrimaryUserResult = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId: existingUser.loginMethods[0].recipeUserId, - userContext, - }); - if (canCreatePrimaryUserResult.status !== "OK") { - // TODO: we need to think about the implications of the different - // reasons here - which is possible? and which is not? - return { - createRecipeUser: false, - accountsLinked: false, - reason: canCreatePrimaryUserResult.status, - primaryUserId: canCreatePrimaryUserResult.primaryUserId, - }; - } - /** - * creating primary user for the recipe user - */ let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 424ee5be7..b717f8be5 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -490,26 +490,6 @@ export default class Recipe extends RecipeModule { }; } - /** - * checking if primary user can be created for the existing recipe user - */ - let canCreatePrimaryUserResult = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ - recipeUserId: existingUser.loginMethods[0].recipeUserId, - userContext, - }); - if (canCreatePrimaryUserResult.status !== "OK") { - // TODO: we need to think about the implications of the different - // reasons here - which is possible? and which is not? - return { - createRecipeUser: false, - accountsLinked: false, - reason: canCreatePrimaryUserResult.status, - primaryUserId: canCreatePrimaryUserResult.primaryUserId, - }; - } - /** - * creating primary user for the recipe user - */ let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, From 2c29bf4c818a482b1b519a5cb4dbd02204ede221 Mon Sep 17 00:00:00 2001 From: Rishabh Poddar Date: Wed, 1 Mar 2023 15:46:19 +0530 Subject: [PATCH 55/82] account linking: removes ANOTHER from canCreatePrimaryUserId status return type (#500) * removes ANOTHER from canCreatePrimaryUserId status return type * small change related to status change in primary user id creation --- lib/build/recipe/accountlinking/index.d.ts | 4 +- lib/build/recipe/accountlinking/recipe.js | 29 ++++++------- .../accountlinking/recipeImplementation.js | 27 ++++++------ lib/build/recipe/accountlinking/types.d.ts | 4 +- lib/ts/recipe/accountlinking/recipe.ts | 27 ++++++------ .../accountlinking/recipeImplementation.ts | 42 +++++++------------ lib/ts/recipe/accountlinking/types.ts | 4 +- 7 files changed, 61 insertions(+), 76 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index e0370758c..07fdc4be2 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -33,7 +33,7 @@ export default class Wrapper { } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; @@ -49,7 +49,7 @@ export default class Wrapper { } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 334e5b8fe..0f92eda52 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -222,22 +222,22 @@ class Recipe extends recipeModule_1.default { if (shouldDoAccountLinking.shouldRequireVerification && !newUserVerified) { return recipeUserId; } - let canCreatePrimaryUserId = yield this.recipeInterfaceImpl.canCreatePrimaryUserId({ + let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId, userContext, }); - if (canCreatePrimaryUserId.status === "OK") { - let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId, - userContext, - }); - if (createPrimaryUserResult.status === "OK") { - return createPrimaryUserResult.user.id; - } - // if it comes here, it means that that there is already a primary user for the - // account info, or that this recipeUserId is already linked. Either way, we proceed - // to the next step, cause that takes care of both these cases. + if (createPrimaryUserResult.status === "OK") { + return createPrimaryUserResult.user.id; } + if ( + createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" && + createPrimaryUserResult.primaryUserId === recipeUserId + ) { + return createPrimaryUserResult.primaryUserId; + } + // if it comes here, it means that that there is already a primary user for the + // account info, or that this recipeUserId is already linked. Either way, we proceed + // to the next step, cause that takes care of both these cases. if (primaryUser === undefined) { // it can come here if there is a race condition. So we just try again return yield this.doPostSignUpAccountLinkingOperations({ @@ -354,10 +354,7 @@ class Recipe extends recipeModule_1.default { recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, }); - if ( - createPrimaryUserResult.status === - "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - ) { + if (createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { // this can happen if there is a race condition in which the // existing user becomes a primary user ID by the time the code // execution comes into this block. So we call the function once again. diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index ca280eb50..6f6f6a498 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -124,7 +124,7 @@ function getRecipeImplementation(querier, config) { } if (primaryUserId !== null) { return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR", primaryUserId, description: "Recipe user is already linked with another primary user id", }; @@ -204,15 +204,8 @@ function getRecipeImplementation(querier, config) { }; }); }, - createPrimaryUser: function ({ recipeUserId, userContext }) { + createPrimaryUser: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ - recipeUserId, - userContext, - }); - if (canCreatePrimaryUser.status !== "OK") { - return canCreatePrimaryUser; - } let primaryUser = yield querier.sendPostRequest( new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), { @@ -267,16 +260,18 @@ function getRecipeImplementation(querier, config) { recipeUserId, userContext, }); - if ( - canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - ) { + if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { if (canCreatePrimaryUser.primaryUserId === primaryUserId) { return { status: "ACCOUNTS_ALREADY_LINKED_ERROR", description: "accounts are already linked", }; } - return canCreatePrimaryUser; + return { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: canCreatePrimaryUser.primaryUserId, + description: canCreatePrimaryUser.description, + }; } if (canCreatePrimaryUser.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { /** @@ -289,7 +284,11 @@ function getRecipeImplementation(querier, config) { * to be linked with the input primaryUserId */ if (canCreatePrimaryUser.primaryUserId !== primaryUserId) { - return canCreatePrimaryUser; + return { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + description: canCreatePrimaryUser.description, + primaryUserId: canCreatePrimaryUser.primaryUserId, + }; } } return { diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 441535b32..7f5f5a6ce 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -89,7 +89,7 @@ export declare type RecipeInterface = { } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; @@ -105,7 +105,7 @@ export declare type RecipeInterface = { } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index b717f8be5..e8648a181 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -312,22 +312,23 @@ export default class Recipe extends RecipeModule { if (shouldDoAccountLinking.shouldRequireVerification && !newUserVerified) { return recipeUserId; } - let canCreatePrimaryUserId = await this.recipeInterfaceImpl.canCreatePrimaryUserId({ + + let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ recipeUserId, userContext, }); - if (canCreatePrimaryUserId.status === "OK") { - let createPrimaryUserResult = await this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId, - userContext, - }); - if (createPrimaryUserResult.status === "OK") { - return createPrimaryUserResult.user.id; - } - // if it comes here, it means that that there is already a primary user for the - // account info, or that this recipeUserId is already linked. Either way, we proceed - // to the next step, cause that takes care of both these cases. + if (createPrimaryUserResult.status === "OK") { + return createPrimaryUserResult.user.id; + } + if ( + createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" && + createPrimaryUserResult.primaryUserId === recipeUserId + ) { + return createPrimaryUserResult.primaryUserId; } + // if it comes here, it means that that there is already a primary user for the + // account info, or that this recipeUserId is already linked. Either way, we proceed + // to the next step, cause that takes care of both these cases. if (primaryUser === undefined) { // it can come here if there is a race condition. So we just try again @@ -495,7 +496,7 @@ export default class Recipe extends RecipeModule { userContext, }); - if (createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + if (createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { // this can happen if there is a race condition in which the // existing user becomes a primary user ID by the time the code // execution comes into this block. So we call the function once again. diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 4e37de0f8..bd6c76b97 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -119,7 +119,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; @@ -145,7 +145,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } if (primaryUserId !== null) { return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR", primaryUserId, description: "Recipe user is already linked with another primary user id", }; @@ -234,10 +234,8 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo this: RecipeInterface, { recipeUserId, - userContext, }: { recipeUserId: string; - userContext: any; } ): Promise< | { @@ -246,30 +244,12 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; } > { - let canCreatePrimaryUser: - | { - status: "OK"; - } - | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } = await this.canCreatePrimaryUserId({ - recipeUserId, - userContext, - }); - if (canCreatePrimaryUser.status !== "OK") { - return canCreatePrimaryUser; - } - let primaryUser: { status: "OK"; user: User; @@ -354,7 +334,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; @@ -362,14 +342,18 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo recipeUserId, userContext, }); - if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { if (canCreatePrimaryUser.primaryUserId === primaryUserId) { return { status: "ACCOUNTS_ALREADY_LINKED_ERROR", description: "accounts are already linked", }; } - return canCreatePrimaryUser; + return { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + primaryUserId: canCreatePrimaryUser.primaryUserId, + description: canCreatePrimaryUser.description, + }; } if (canCreatePrimaryUser.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { /** @@ -382,7 +366,11 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo * to be linked with the input primaryUserId */ if (canCreatePrimaryUser.primaryUserId !== primaryUserId) { - return canCreatePrimaryUser; + return { + status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", + description: canCreatePrimaryUser.description, + primaryUserId: canCreatePrimaryUser.primaryUserId, + }; } } return { diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index b4a432a26..69ccaed5d 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -106,7 +106,7 @@ export type RecipeInterface = { } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; @@ -122,7 +122,7 @@ export type RecipeInterface = { } | { status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; primaryUserId: string; description: string; From d5ffa6f43f85598c30e6bf57c77a7c376fe19587 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 1 Mar 2023 15:50:00 +0530 Subject: [PATCH 56/82] change to canLinkAccounts --- .../accountlinking/recipeImplementation.js | 8 ------ .../accountlinking/recipeImplementation.ts | 25 ------------------- 2 files changed, 33 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 6f6f6a498..d6cbcc00d 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -298,14 +298,6 @@ function getRecipeImplementation(querier, config) { }, linkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let canLinkAccountsResult = yield this.canLinkAccounts({ - recipeUserId, - primaryUserId, - userContext, - }); - if (canLinkAccountsResult.status !== "OK") { - return canLinkAccountsResult; - } let accountsLinkingResult = yield querier.sendPostRequest( new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), { diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index bd6c76b97..12679143f 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -407,31 +407,6 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } > { - let canLinkAccountsResult: - | { - status: "OK"; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } - | { - status: "ACCOUNTS_ALREADY_LINKED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } = await this.canLinkAccounts({ - recipeUserId, - primaryUserId, - userContext, - }); - if (canLinkAccountsResult.status !== "OK") { - return canLinkAccountsResult; - } let accountsLinkingResult = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/link"), { From e05b4812803671e3e296407f183f937d2106ad3c Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Thu, 2 Mar 2023 14:36:08 +0530 Subject: [PATCH 57/82] Update lib/ts/recipe/accountlinking/recipeImplementation.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipeImplementation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 12679143f..4172e6d7a 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -59,7 +59,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo timeJoined, }: { recipeUserId: string; - recipeId: string; + recipeId:"emailpassword" | "thirdparty" | "passwordless"; timeJoined: number; } ): Promise<{ From 4034ea15df719e6ce7fd15a1802810890876c0ee Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Thu, 2 Mar 2023 14:36:42 +0530 Subject: [PATCH 58/82] Update lib/ts/recipe/accountlinking/types.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 69ccaed5d..a3721edfc 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -198,7 +198,7 @@ export type RecipeInterface = { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise<{ status: "OK" }>; + }) => Promise<{ status: "OK", didInsertNewRow: boolean } | {status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR", primaryUserId: string }}>; }; export type RecipeLevelUser = { From 6e3d61b3ad88f5c947e9cb44d0f35f06951f1468 Mon Sep 17 00:00:00 2001 From: Bhumil Sarvaiya Date: Thu, 2 Mar 2023 14:37:09 +0530 Subject: [PATCH 59/82] Update lib/ts/recipe/accountlinking/recipeImplementation.ts Co-authored-by: Rishabh Poddar --- lib/ts/recipe/accountlinking/recipeImplementation.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 4172e6d7a..ad6678bfb 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -478,10 +478,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }); if (user === undefined) { - return { - status: "OK", - wasRecipeUserDeleted: false, - }; + throw new Error("Seems like a race condition issue occurred. Please try again"); } if (user.loginMethods.length > 1) { await this.deleteUser({ From 5fd30cfb2be92b55967dad96a934ae7e414ad8ba Mon Sep 17 00:00:00 2001 From: Bhumil Date: Thu, 2 Mar 2023 15:53:43 +0530 Subject: [PATCH 60/82] code review changes --- lib/build/recipe/accountlinking/index.d.ts | 15 +- .../accountlinking/recipeImplementation.js | 236 ++-------------- lib/build/recipe/accountlinking/types.d.ts | 15 +- lib/ts/recipe/accountlinking/index.ts | 2 +- .../accountlinking/recipeImplementation.ts | 265 ++---------------- lib/ts/recipe/accountlinking/types.ts | 7 +- 6 files changed, 80 insertions(+), 460 deletions(-) diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index 07fdc4be2..c9946f603 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -17,7 +17,7 @@ export default class Wrapper { }>; static addNewRecipeUserIdWithoutPrimaryUserId( recipeUserId: string, - recipeId: string, + recipeId: "emailpassword" | "thirdparty" | "passwordless", timeJoined: number, userContext?: any ): Promise<{ @@ -121,9 +121,16 @@ export default class Wrapper { recipeUserId: string, primaryUserId: string, userContext?: any - ): Promise<{ - status: "OK"; - }>; + ): Promise< + | { + status: "OK"; + didInsertNewRow: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + } + >; } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index d6cbcc00d..29ac20df0 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -103,197 +103,38 @@ function getRecipeImplementation(querier, config) { }; }); }, - canCreatePrimaryUserId: function ({ recipeUserId, userContext }) { + canCreatePrimaryUserId: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - /** - * getting map of recipeUserIds to primaryUserIds - * This is to know if the existing recipeUserId - * is already associated with a primaryUserId - */ - let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsForRecipeUserIds({ - recipeUserIds: [recipeUserId], - userContext, - }); - /** - * checking if primaryUserId exists for the recipeUserId - */ - let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId === undefined) { - // this means that the recipeUserId doesn't exist - throw new Error("The input recipeUserId does not exist"); - } - if (primaryUserId !== null) { - return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR", - primaryUserId, - description: "Recipe user is already linked with another primary user id", - }; - } - /** - * if the code reaches this point, it means - * the recipeuserId is definitely not associated - * with any primaryUserId. So the getUser function - * here will return an user object which would - * definitely be a recipeUser only. - */ - let user = yield this.getUser({ - userId: recipeUserId, - userContext, - }); - /** - * precautionary check - */ - if (user === undefined) { - throw new Error("The input recipeUserId does not exist"); - } - /** - * for all the identifying info associated with the recipeUser, - * we get all the accounts with those identifying infos. - * From those users, we'll try to find if there already exists - * a primaryUser which is associated with the identifying info - */ - let usersForAccountInfo = []; - for (let i = 0; i < user.loginMethods.length; i++) { - let loginMethod = user.loginMethods[i]; - let infos = []; - if (loginMethod.email !== undefined) { - infos.push({ - email: loginMethod.email, - }); - } - if (loginMethod.phoneNumber !== undefined) { - infos.push({ - phoneNumber: loginMethod.phoneNumber, - }); - } - if (loginMethod.thirdParty !== undefined) { - infos.push({ - thirdPartyId: loginMethod.thirdParty.id, - thirdPartyUserId: loginMethod.thirdParty.userId, - }); - } - for (let j = 0; j < infos.length; j++) { - let info = infos[j]; - let usersList = yield this.listUsersByAccountInfo({ - accountInfo: info, - userContext, - }); - if (usersList !== undefined) { - usersForAccountInfo.push(...usersList); - } + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/primary/check"), + { + recipeUserId, } - } - let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); - /** - * checking if primaryUserId exists for the account identifying info - */ - if (primaryUser !== undefined) { - return { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: primaryUser.id, - description: - "Account info related to recipe user is already linked with another primary user id", - }; - } - /** - * no primaryUser found for either recipeUserId or - * the identiyfing info asscociated with the recipeUser - */ - return { - status: "OK", - }; + ); + return result; }); }, createPrimaryUser: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - let primaryUser = yield querier.sendPostRequest( + let result = yield querier.sendPostRequest( new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), { recipeUserId, } ); - if (!primaryUser.user.isPrimaryUser) { - throw Error("creating primaryUser for recipeUser failed in core"); - } - return primaryUser; + return result; }); }, - canLinkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { + canLinkAccounts: function ({ recipeUserId, primaryUserId }) { return __awaiter(this, void 0, void 0, function* () { - let primaryUser = yield this.getUser({ - userId: primaryUserId, - userContext, - }); - if (primaryUser === undefined) { - throw Error("primary user not found"); - } - /** - * getUser function returns a primaryUser even if - * recipeUserId is passed, if the recipeUserId has - * an associated primaryUserId. Here, after calling - * getUser for the recipeUser, we will check if there - * is already a primaryUser associated with it. If - * there is, we'll check if there exists if it's the - * input primaryUserId or some different primaryUserId - */ - let recipeUser = yield this.getUser({ - userId: recipeUserId, - userContext, - }); - if (recipeUser === undefined) { - throw Error("recipe user not found"); - } - if (recipeUser.isPrimaryUser) { - if (recipeUser.id === primaryUserId) { - return { - status: "ACCOUNTS_ALREADY_LINKED_ERROR", - description: "accounts are already linked", - }; - } - return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - description: "recipeUserId already associated with another primaryUserId", - primaryUserId: recipeUser.id, // this is actually the primary user ID cause isPrimaryUser is true - }; - } - let canCreatePrimaryUser = yield this.canCreatePrimaryUserId({ - recipeUserId, - userContext, - }); - if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { - if (canCreatePrimaryUser.primaryUserId === primaryUserId) { - return { - status: "ACCOUNTS_ALREADY_LINKED_ERROR", - description: "accounts are already linked", - }; - } - return { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: canCreatePrimaryUser.primaryUserId, - description: canCreatePrimaryUser.description, - }; - } - if (canCreatePrimaryUser.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { - /** - * if canCreatePrimaryUser.status is - * ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR and - * canCreatePrimaryUser.primaryUserId is equal to the input primaryUserId, - * we don't return ACCOUNTS_ALREADY_LINKED_ERROR cause here the accounts - * are not yet linked. It's just that the identifyingInfo associated with the - * recipeUser is linked to the primaryUser. Input recipeUser still needs - * to be linked with the input primaryUserId - */ - if (canCreatePrimaryUser.primaryUserId !== primaryUserId) { - return { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - description: canCreatePrimaryUser.description, - primaryUserId: canCreatePrimaryUser.primaryUserId, - }; + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link/check"), + { + recipeUserId, + primaryUserId, } - } - return { - status: "OK", - }; + ); + return result; }); }, linkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { @@ -330,8 +171,6 @@ function getRecipeImplementation(querier, config) { }, userContext ); - } else { - throw Error(`error thrown from core while linking accounts: ${accountsLinkingResult.status}`); } return accountsLinkingResult; }); @@ -358,10 +197,7 @@ function getRecipeImplementation(querier, config) { userContext, }); if (user === undefined) { - return { - status: "OK", - wasRecipeUserDeleted: false, - }; + throw new Error("Seems like a race condition issue occurred. Please try again"); } if (user.loginMethods.length > 1) { yield this.deleteUser({ @@ -416,37 +252,13 @@ function getRecipeImplementation(querier, config) { return result.users; }); }, - deleteUser: function ({ userId, removeAllLinkedAccounts, userContext }) { + deleteUser: function ({ userId, removeAllLinkedAccounts }) { return __awaiter(this, void 0, void 0, function* () { - let user = yield this.getUser({ userId, userContext }); - if (user === undefined) { - return { - status: "OK", - }; - } - let recipeUsersToRemove = []; - /** - * if true, the user should be treated as primaryUser - */ - if (removeAllLinkedAccounts) { - recipeUsersToRemove = user.loginMethods; - } else { - recipeUsersToRemove = user.loginMethods.filter((u) => u.recipeUserId === userId); - } - for (let i = 0; i < recipeUsersToRemove.length; i++) { - /** - * - the core will also remove any primary userId association, if exists - * - while removing the primary userId association, if there exists no - * other recipe user associated with the primary user, the core will - * also remove all data linked to the primary user in other non-auth tables - */ - yield querier.sendPostRequest(new normalisedURLPath_1.default("/user/remove"), { - userId: recipeUsersToRemove[i].recipeUserId, - }); - } - return { - status: "OK", - }; + let result = yield querier.sendPostRequest(new normalisedURLPath_1.default("/user/remove"), { + userId, + removeAllLinkedAccounts, + }); + return result; }); }, fetchFromAccountToLinkTable: function ({ recipeUserId }) { diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 7f5f5a6ce..f30b37da5 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -63,7 +63,7 @@ export declare type RecipeInterface = { }>; addNewRecipeUserIdWithoutPrimaryUserId: (input: { recipeUserId: string; - recipeId: string; + recipeId: "emailpassword" | "thirdparty" | "passwordless"; timeJoined: number; userContext: any; }) => Promise<{ @@ -183,9 +183,16 @@ export declare type RecipeInterface = { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - }>; + }) => Promise< + | { + status: "OK"; + didInsertNewRow: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + } + >; }; export declare type RecipeLevelUser = { recipeId: "emailpassword" | "thirdparty" | "passwordless"; diff --git a/lib/ts/recipe/accountlinking/index.ts b/lib/ts/recipe/accountlinking/index.ts index 984f2e970..30929c085 100644 --- a/lib/ts/recipe/accountlinking/index.ts +++ b/lib/ts/recipe/accountlinking/index.ts @@ -34,7 +34,7 @@ export default class Wrapper { static async addNewRecipeUserIdWithoutPrimaryUserId( recipeUserId: string, - recipeId: string, + recipeId: "emailpassword" | "thirdparty" | "passwordless", timeJoined: number, userContext?: any ) { diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index ad6678bfb..05fb3b0b7 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -13,7 +13,7 @@ * under the License. */ -import { AccountInfo, RecipeInterface, TypeNormalisedInput, RecipeLevelUser } from "./types"; +import { AccountInfo, RecipeInterface, TypeNormalisedInput } from "./types"; import { Querier } from "../../querier"; import type { User } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -59,7 +59,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo timeJoined, }: { recipeUserId: string; - recipeId:"emailpassword" | "thirdparty" | "passwordless"; + recipeId: "emailpassword" | "thirdparty" | "passwordless"; timeJoined: number; } ): Promise<{ @@ -108,10 +108,8 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo this: RecipeInterface, { recipeUserId, - userContext, }: { recipeUserId: string; - userContext: any; } ): Promise< | { @@ -125,110 +123,13 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } > { - /** - * getting map of recipeUserIds to primaryUserIds - * This is to know if the existing recipeUserId - * is already associated with a primaryUserId - */ - let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsForRecipeUserIds({ - recipeUserIds: [recipeUserId], - userContext, - }); - - /** - * checking if primaryUserId exists for the recipeUserId - */ - let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId === undefined) { - // this means that the recipeUserId doesn't exist - throw new Error("The input recipeUserId does not exist"); - } - if (primaryUserId !== null) { - return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR", - primaryUserId, - description: "Recipe user is already linked with another primary user id", - }; - } - - /** - * if the code reaches this point, it means - * the recipeuserId is definitely not associated - * with any primaryUserId. So the getUser function - * here will return an user object which would - * definitely be a recipeUser only. - */ - let user = await this.getUser({ - userId: recipeUserId, - userContext, - }); - - /** - * precautionary check - */ - if (user === undefined) { - throw new Error("The input recipeUserId does not exist"); - } - - /** - * for all the identifying info associated with the recipeUser, - * we get all the accounts with those identifying infos. - * From those users, we'll try to find if there already exists - * a primaryUser which is associated with the identifying info - */ - let usersForAccountInfo: User[] = []; - - for (let i = 0; i < user.loginMethods.length; i++) { - let loginMethod = user.loginMethods[i]; - let infos: AccountInfo[] = []; - if (loginMethod.email !== undefined) { - infos.push({ - email: loginMethod.email, - }); - } - if (loginMethod.phoneNumber !== undefined) { - infos.push({ - phoneNumber: loginMethod.phoneNumber, - }); - } - if (loginMethod.thirdParty !== undefined) { - infos.push({ - thirdPartyId: loginMethod.thirdParty.id, - thirdPartyUserId: loginMethod.thirdParty.userId, - }); - } - for (let j = 0; j < infos.length; j++) { - let info = infos[j]; - let usersList = await this.listUsersByAccountInfo({ - accountInfo: info, - userContext, - }); - if (usersList !== undefined) { - usersForAccountInfo.push(...usersList); - } + let result = await querier.sendGetRequest( + new NormalisedURLPath("/recipe/accountlinking/user/primary/check"), + { + recipeUserId, } - } - - let primaryUser = usersForAccountInfo.find((u) => u.isPrimaryUser); - - /** - * checking if primaryUserId exists for the account identifying info - */ - if (primaryUser !== undefined) { - return { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: primaryUser.id, - description: "Account info related to recipe user is already linked with another primary user id", - }; - } - - /** - * no primaryUser found for either recipeUserId or - * the identiyfing info asscociated with the recipeUser - */ - return { - status: "OK", - }; + ); + return result; }, createPrimaryUser: async function ( this: RecipeInterface, @@ -250,28 +151,20 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } > { - let primaryUser: { - status: "OK"; - user: User; - } = await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/primary"), { + let result = await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/primary"), { recipeUserId, }); - if (!primaryUser.user.isPrimaryUser) { - throw Error("creating primaryUser for recipeUser failed in core"); - } - return primaryUser; + return result; }, canLinkAccounts: async function ( this: RecipeInterface, { recipeUserId, primaryUserId, - userContext, }: { recipeUserId: string; primaryUserId: string; - userContext: any; } ): Promise< | { @@ -292,90 +185,11 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo description: string; } > { - let primaryUser: User | undefined = await this.getUser({ - userId: primaryUserId, - userContext, - }); - if (primaryUser === undefined) { - throw Error("primary user not found"); - } - /** - * getUser function returns a primaryUser even if - * recipeUserId is passed, if the recipeUserId has - * an associated primaryUserId. Here, after calling - * getUser for the recipeUser, we will check if there - * is already a primaryUser associated with it. If - * there is, we'll check if there exists if it's the - * input primaryUserId or some different primaryUserId - */ - let recipeUser: User | undefined = await this.getUser({ - userId: recipeUserId, - userContext, - }); - if (recipeUser === undefined) { - throw Error("recipe user not found"); - } - if (recipeUser.isPrimaryUser) { - if (recipeUser.id === primaryUserId) { - return { - status: "ACCOUNTS_ALREADY_LINKED_ERROR", - description: "accounts are already linked", - }; - } - return { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - description: "recipeUserId already associated with another primaryUserId", - primaryUserId: recipeUser.id, // this is actually the primary user ID cause isPrimaryUser is true - }; - } - let canCreatePrimaryUser: - | { - status: "OK"; - } - | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } = await this.canCreatePrimaryUserId({ + let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user/link/check"), { recipeUserId, - userContext, + primaryUserId, }); - if (canCreatePrimaryUser.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { - if (canCreatePrimaryUser.primaryUserId === primaryUserId) { - return { - status: "ACCOUNTS_ALREADY_LINKED_ERROR", - description: "accounts are already linked", - }; - } - return { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - primaryUserId: canCreatePrimaryUser.primaryUserId, - description: canCreatePrimaryUser.description, - }; - } - if (canCreatePrimaryUser.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { - /** - * if canCreatePrimaryUser.status is - * ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR and - * canCreatePrimaryUser.primaryUserId is equal to the input primaryUserId, - * we don't return ACCOUNTS_ALREADY_LINKED_ERROR cause here the accounts - * are not yet linked. It's just that the identifyingInfo associated with the - * recipeUser is linked to the primaryUser. Input recipeUser still needs - * to be linked with the input primaryUserId - */ - if (canCreatePrimaryUser.primaryUserId !== primaryUserId) { - return { - status: "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR", - description: canCreatePrimaryUser.description, - primaryUserId: canCreatePrimaryUser.primaryUserId, - }; - } - } - return { - status: "OK", - }; + return result; }, linkAccounts: async function ( this: RecipeInterface, @@ -439,8 +253,6 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }, userContext ); - } else { - throw Error(`error thrown from core while linking accounts: ${accountsLinkingResult.status}`); } return accountsLinkingResult; }, @@ -534,48 +346,18 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo { userId, removeAllLinkedAccounts, - userContext, }: { userId: string; removeAllLinkedAccounts: boolean; - userContext: any; } ): Promise<{ status: "OK"; }> { - let user: User | undefined = await this.getUser({ userId, userContext }); - - if (user === undefined) { - return { - status: "OK", - }; - } - - let recipeUsersToRemove: RecipeLevelUser[] = []; - - /** - * if true, the user should be treated as primaryUser - */ - if (removeAllLinkedAccounts) { - recipeUsersToRemove = user.loginMethods; - } else { - recipeUsersToRemove = user.loginMethods.filter((u) => u.recipeUserId === userId); - } - - for (let i = 0; i < recipeUsersToRemove.length; i++) { - /** - * - the core will also remove any primary userId association, if exists - * - while removing the primary userId association, if there exists no - * other recipe user associated with the primary user, the core will - * also remove all data linked to the primary user in other non-auth tables - */ - await querier.sendPostRequest(new NormalisedURLPath("/user/remove"), { - userId: recipeUsersToRemove[i].recipeUserId, - }); - } - return { - status: "OK", - }; + let result = await querier.sendPostRequest(new NormalisedURLPath("/user/remove"), { + userId, + removeAllLinkedAccounts, + }); + return result; }, fetchFromAccountToLinkTable: async function ({ recipeUserId, @@ -593,7 +375,16 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }: { recipeUserId: string; primaryUserId: string; - }): Promise<{ status: "OK" }> { + }): Promise< + | { + status: "OK"; + didInsertNewRow: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + } + > { let result = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/link/table"), { diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index a3721edfc..b1c9f39f8 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -80,7 +80,7 @@ export type RecipeInterface = { }>; addNewRecipeUserIdWithoutPrimaryUserId: (input: { recipeUserId: string; - recipeId: string; + recipeId: "emailpassword" | "thirdparty" | "passwordless"; timeJoined: number; userContext: any; }) => Promise<{ @@ -198,7 +198,10 @@ export type RecipeInterface = { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise<{ status: "OK", didInsertNewRow: boolean } | {status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR", primaryUserId: string }}>; + }) => Promise< + | { status: "OK"; didInsertNewRow: boolean } + | { status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; primaryUserId: string } + >; }; export type RecipeLevelUser = { From 25613e43c0765212c168e8d0550ba0486ef7489f Mon Sep 17 00:00:00 2001 From: Bhumil Date: Sun, 12 Mar 2023 21:11:23 +0530 Subject: [PATCH 61/82] review changes --- .../accountlinking/accountLinkingClaim.js | 2 +- lib/build/recipe/accountlinking/index.d.ts | 4 +- lib/build/recipe/accountlinking/recipe.d.ts | 10 +-- lib/build/recipe/accountlinking/recipe.js | 1 + .../emailpassword/api/implementation.js | 65 +++++++++++-------- .../services/backwardCompatibility/index.js | 32 +++++---- lib/build/recipe/emailpassword/index.d.ts | 10 ++- lib/build/recipe/emailpassword/recipe.js | 17 +++-- .../emailpassword/recipeImplementation.js | 8 ++- lib/build/recipe/emailpassword/types.d.ts | 28 +++++--- .../recipe/thirdpartyemailpassword/index.d.ts | 15 +++-- .../thirdPartyRecipeImplementation.js | 8 +-- .../recipe/thirdpartyemailpassword/types.d.ts | 23 ++++--- lib/build/supertokens.js | 45 +++++++++++-- .../accountlinking/accountLinkingClaim.ts | 2 +- lib/ts/recipe/accountlinking/recipe.ts | 11 ++-- .../emailpassword/api/implementation.ts | 61 +++++++++-------- .../services/backwardCompatibility/index.ts | 46 ++++++------- lib/ts/recipe/emailpassword/index.ts | 3 +- lib/ts/recipe/emailpassword/recipe.ts | 17 +++-- .../emailpassword/recipeImplementation.ts | 22 +++++-- lib/ts/recipe/emailpassword/types.ts | 30 +++++---- .../emailPasswordRecipeImplementation.ts | 15 +++-- .../recipeImplementation/index.ts | 42 ++++++++---- .../thirdPartyRecipeImplementation.ts | 8 +-- .../recipe/thirdpartyemailpassword/types.ts | 22 ++++--- lib/ts/supertokens.ts | 61 ++++++++++++----- 27 files changed, 392 insertions(+), 216 deletions(-) diff --git a/lib/build/recipe/accountlinking/accountLinkingClaim.js b/lib/build/recipe/accountlinking/accountLinkingClaim.js index c260f8de5..ea25bce78 100644 --- a/lib/build/recipe/accountlinking/accountLinkingClaim.js +++ b/lib/build/recipe/accountlinking/accountLinkingClaim.js @@ -8,7 +8,7 @@ const claims_1 = require("../session/claims"); class AccountLinkingClaimClass extends claims_1.PrimitiveClaim { constructor() { super({ - key: "st-acl", + key: "st-linking", fetchValue(_, __, ___) { return undefined; }, diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index c9946f603..86edd980a 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -45,7 +45,7 @@ export default class Wrapper { ): Promise< | { status: "OK"; - user: import("../../types").User; + user: import("../emailpassword").User; } | { status: @@ -116,7 +116,7 @@ export default class Wrapper { static fetchFromAccountToLinkTable( recipeUserId: string, userContext?: any - ): Promise; + ): Promise; static storeIntoAccountToLinkTable( recipeUserId: string, primaryUserId: string, diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index f37c6dff4..fe790b439 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -100,10 +100,12 @@ export default class Recipe extends RecipeModule { } | { accountsLinked: false; - reason: - | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" - | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" - | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + } + | { + accountsLinked: false; + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + userId: string; } | { accountsLinked: false; diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index f111146aa..1a43205b1 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -349,6 +349,7 @@ class Recipe extends recipeModule_1.default { createRecipeUser: false, accountsLinked: false, reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + userId: existingUser.loginMethods[0].recipeUserId, }; } let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index 32925eaf3..879409a60 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -170,19 +170,42 @@ function getAPIImplementation() { } if (!result.accountsLinked && "reason" in result) { if (result.reason === "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + const emailVerificationInstance = recipe_2.default.getInstance(); + if (emailVerificationInstance !== undefined) { + let emailVerificationResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: result.userId, + email, + userContext, + } + ); + if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { + yield session.fetchAndSetClaim( + emailVerificationClaim_1.EmailVerificationClaim, + userContext + ); + let emailVerifyLink = utils_1.getEmailVerifyLink({ + appInfo: options.appInfo, + token: emailVerificationResponse.token, + recipeId: options.recipeId, + }); + yield emailVerificationInstance.emailDelivery.ingredientInterfaceImpl.sendEmail({ + type: "EMAIL_VERIFICATION", + user: { + id: result.userId, + email, + }, + emailVerifyLink, + userContext, + }); + } + } return { status: "ACCOUNT_NOT_VERIFIED_ERROR", isNotVerifiedAccountFromInputSession: true, description: "", }; } - if (result.reason === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { - return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: false, - description: "", - }; - } if ( result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" @@ -210,23 +233,9 @@ function getAPIImplementation() { "this error should never be thrown. Can't find primary user with userId: " + session.getUserId() ); } - let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); - if (recipeUser === undefined) { - throw Error( - "this error should never be thrown. Can't find emailPassword recipeUser with email: " + - email + - " and primary userId: " + - session.getUserId() - ); - } return { status: "OK", - user: { - id: user.id, - recipeUserId: recipeUser.recipeUserId, - timeJoined: recipeUser.timeJoined, - email, - }, + user, createdNewRecipeUser, wereAccountsAlreadyLinked, session, @@ -246,7 +255,7 @@ function getAPIImplementation() { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let userIdForPasswordReset = undefined; - let recipeUserId = undefined; + let recipeUserId; /** * check if primaryUserId is linked with this email */ @@ -313,6 +322,7 @@ function getAPIImplementation() { } } userIdForPasswordReset = primaryUser.id; + recipeUserId = primaryUser.id; } else { /** * this means emailpassword user associated with the input email exists but it @@ -547,11 +557,12 @@ function getAPIImplementation() { return response; } let user = response.user; + let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); let session = yield session_1.default.createNewSession( options.req, options.res, user.id, - user.recipeUserId, + recipeUser === null || recipeUser === void 0 ? void 0 : recipeUser.recipeUserId, {}, {}, userContext @@ -590,11 +601,12 @@ function getAPIImplementation() { return response; } let user = response.user; + let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); let session = yield session_1.default.createNewSession( options.req, options.res, user.id, - user.recipeUserId, + recipeUser === null || recipeUser === void 0 ? void 0 : recipeUser.recipeUserId, {}, {}, userContext @@ -603,7 +615,8 @@ function getAPIImplementation() { status: "OK", session, user, - createdNewUser: user.id === user.recipeUserId, + createdNewUser: + user.id === (recipeUser === null || recipeUser === void 0 ? void 0 : recipeUser.recipeUserId), createdNewRecipeUser: true, }; }); diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js index a94521b5b..fe27486c1 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -45,33 +45,39 @@ class BackwardCompatibilityService { }) : undefined; if (input.user.recipeUserId === undefined) { - let primaryUser = yield __1.getUser(input.user.id); - if (primaryUser === undefined) { - throw Error("this should never come here"); - } - user = { - id: primaryUser.id, - recipeUserId: undefined, - timeJoined: primaryUser.timeJoined, - email: input.user.email, - }; + user = yield __1.getUser(input.user.id); } if (user === undefined) { throw Error("this should never come here"); } + let recipeLoginMethod = user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.email === input.user.email + ); + if (recipeLoginMethod === undefined) { + throw Error("this should never come here"); + } // we add this here cause the user may have overridden the sendEmail function // to change the input email and if we don't do this, the input email // will get reset by the getUserById call above. - user.email = input.user.email; + let passwordResetEmailUser = { + id: input.user.id, + recipeUserId: recipeLoginMethod.recipeUserId, + email: input.user.email, + timeJoined: recipeLoginMethod.timeJoined, + }; try { if (!this.isInServerlessEnv) { this.resetPasswordUsingTokenFeature - .createAndSendCustomEmail(user, input.passwordResetLink, input.userContext) + .createAndSendCustomEmail( + passwordResetEmailUser, + input.passwordResetLink, + input.userContext + ) .catch((_) => {}); } else { // see https://github.com/supertokens/supertokens-node/pull/135 yield this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( - user, + passwordResetEmailUser, input.passwordResetLink, input.userContext ); diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index 8d3f082b2..d92ffb6c7 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -1,7 +1,8 @@ // @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; -import { RecipeInterface, User, APIOptions, APIInterface, TypeEmailPasswordEmailDeliveryInput } from "./types"; +import { RecipeInterface, APIOptions, APIInterface, TypeEmailPasswordEmailDeliveryInput } from "./types"; +import { User } from "../../types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; @@ -13,6 +14,7 @@ export default class Wrapper { ): Promise< | { status: "OK"; + newUserCreated: boolean; user: User; } | { @@ -78,7 +80,11 @@ export default class Wrapper { password?: string; userContext?: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; static sendEmail( input: TypeEmailPasswordEmailDeliveryInput & { diff --git a/lib/build/recipe/emailpassword/recipe.js b/lib/build/recipe/emailpassword/recipe.js index 691d40846..879c92946 100644 --- a/lib/build/recipe/emailpassword/recipe.js +++ b/lib/build/recipe/emailpassword/recipe.js @@ -165,12 +165,17 @@ class Recipe extends recipeModule_1.default { // extra instance functions below............... this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo !== undefined) { - return { - status: "OK", - email: userInfo.email, - }; + let user = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (user !== undefined) { + let recipeLevelUser = user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (recipeLevelUser !== undefined && recipeLevelUser.email !== undefined) { + return { + status: "OK", + email: recipeLevelUser.email, + }; + } } return { status: "UNKNOWN_USER_ID_ERROR", diff --git a/lib/build/recipe/emailpassword/recipeImplementation.js b/lib/build/recipe/emailpassword/recipeImplementation.js index b7888ebf3..1f10d8f3b 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -49,6 +49,7 @@ function getRecipeInterface(querier) { password, }); if (response.status === "OK") { + let newUserCreated = true; if (doAccountLinking) { let primaryUserId = yield recipe_1.default .getInstanceOrThrowError() @@ -61,9 +62,12 @@ function getRecipeInterface(querier) { recipeUserId: response.user.id, userContext, }); + if (response.user.id !== primaryUserId) { + newUserCreated = false; + } response.user.id = primaryUserId; } - return response; + return Object.assign(Object.assign({}, response), { newUserCreated }); } else { return { status: "EMAIL_ALREADY_EXISTS_ERROR", @@ -158,7 +162,7 @@ function getRecipeInterface(querier) { if (primaryUserFromEmailUsers !== undefined) { if (primaryUserFromEmailUsers.id !== userForUserId.id) { return { - status: "EMAIL_CHANGE_NOT_ALLOWED", + status: "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING", }; } markEmailAsVerified = true; diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index 59c103cd8..28ea41a45 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -7,7 +7,7 @@ import { TypeInputWithService as EmailDeliveryTypeInputWithService, } from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; -import { GeneralErrorResponse, NormalisedAppinfo } from "../../types"; +import { GeneralErrorResponse, NormalisedAppinfo, User } from "../../types"; export declare type TypeNormalisedInput = { signUpFeature: TypeNormalisedInputSignUp; signInFeature: TypeNormalisedInputSignIn; @@ -51,12 +51,6 @@ export declare type TypeNormalisedInputResetPasswordUsingTokenFeature = { formFieldsForGenerateTokenForm: NormalisedFormField[]; formFieldsForPasswordResetForm: NormalisedFormField[]; }; -export declare type User = { - id: string; - recipeUserId: string; - email: string; - timeJoined: number; -}; export declare type TypeInput = { signUpFeature?: TypeInputSignUp; emailDelivery?: EmailDeliveryTypeInput; @@ -72,11 +66,23 @@ export declare type RecipeInterface = { signUp(input: { email: string; password: string; + /** + * we now do account-linking in the recipe implementation of + * this function. If someone wants to call this function + * manually and wants the any other account with the same email + * to be linked automatically, all they need to do is pass this + * boolean. If the user doesn't want to do automatic account linking + * while calling this function, they can pass false. Default value + * of the parameter would be false. So if we are moving the account + * linking part to be part of this function, ideally we should keep + * this boolean parameter + */ doAccountLinking: boolean; userContext: any; }): Promise< | { status: "OK"; + newUserCreated: boolean; user: User; } | { @@ -142,7 +148,11 @@ export declare type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; }; export declare type APIOptions = { @@ -298,7 +308,7 @@ export declare type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; user: { id: string; - recipeUserId?: string; + recipeUserId: string; email: string; }; passwordResetLink: string; diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index ac45626e8..dea9f8d43 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -30,7 +30,8 @@ export default class Wrapper { ): Promise< | { status: "OK"; - user: User; + newUserCreated: boolean; + user: import("../emailpassword").User; } | { status: "EMAIL_ALREADY_EXISTS_ERROR"; @@ -43,14 +44,14 @@ export default class Wrapper { ): Promise< | { status: "OK"; - user: User; + user: import("../emailpassword").User; } | { status: "WRONG_CREDENTIALS_ERROR"; } >; - static getUserById(userId: string, userContext?: any): Promise; - static getUsersByEmail(email: string, userContext?: any): Promise; + static getUserById(userId: string, userContext?: any): Promise; + static getUsersByEmail(email: string, userContext?: any): Promise<(import("../emailpassword").User | User)[]>; static createResetPasswordToken( userId: string, email: string, @@ -84,7 +85,11 @@ export default class Wrapper { password?: string; userContext?: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; static Google: typeof import("../thirdparty/providers/google").default; static Github: typeof import("../thirdparty/providers/github").default; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js index 1b2784d4e..25f155ca3 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js @@ -74,13 +74,7 @@ function getRecipeInterface(recipeInterface) { // either user is undefined or it's an email password user. return undefined; } - return { - email: user.email, - id: user.id, - recipeUserId: user.recipeUserId, - timeJoined: user.timeJoined, - thirdParty: user.thirdParty, - }; + return user; }); }, getUsersByEmail: function (input) { diff --git a/lib/build/recipe/thirdpartyemailpassword/types.d.ts b/lib/build/recipe/thirdpartyemailpassword/types.d.ts index 34cf09665..fa41ded01 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -14,7 +14,7 @@ import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService, } from "../../ingredients/emaildelivery/types"; -import { GeneralErrorResponse } from "../../types"; +import { GeneralErrorResponse, User as GlobalUser } from "../../types"; export declare type User = { id: string; recipeUserId: string; @@ -70,8 +70,8 @@ export declare type TypeNormalisedInput = { }; }; export declare type RecipeInterface = { - getUserById(input: { userId: string; userContext: any }): Promise; - getUsersByEmail(input: { email: string; userContext: any }): Promise; + getUserById(input: { userId: string; userContext: any }): Promise; + getUsersByEmail(input: { email: string; userContext: any }): Promise<(User | GlobalUser)[]>; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -95,7 +95,8 @@ export declare type RecipeInterface = { }): Promise< | { status: "OK"; - user: User; + newUserCreated: boolean; + user: GlobalUser; } | { status: "EMAIL_ALREADY_EXISTS_ERROR"; @@ -108,7 +109,7 @@ export declare type RecipeInterface = { }): Promise< | { status: "OK"; - user: User; + user: GlobalUser; } | { status: "WRONG_CREDENTIALS_ERROR"; @@ -147,7 +148,11 @@ export declare type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; }; export declare type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; @@ -306,7 +311,7 @@ export declare type APIInterface = { }) => Promise< | { status: "OK"; - user: User; + user: GlobalUser; createdNewRecipeUser: boolean; session: SessionContainerInterface; wereAccountsAlreadyLinked: boolean; @@ -344,7 +349,7 @@ export declare type APIInterface = { }) => Promise< | { status: "OK"; - user: User; + user: GlobalUser; session: SessionContainerInterface; } | { @@ -364,7 +369,7 @@ export declare type APIInterface = { }) => Promise< | { status: "OK"; - user: User; + user: GlobalUser; createdNewUser: boolean; session: SessionContainerInterface; } diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index 6e0f0fa31..084450cdb 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -317,8 +317,13 @@ class SuperTokens { try { const userResponse = yield emailpassword_1.default.getUserById(userId); if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); - recipe = "emailpassword"; + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); + recipe = "emailpassword"; + } } } catch (e) { // No - op @@ -327,8 +332,22 @@ class SuperTokens { try { const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "emailpassword" }); - recipe = "thirdpartyemailpassword"; + if ("loginMethods" in userResponse) { + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = Object.assign(Object.assign({}, loginMethod), { + recipeId: "emailpassword", + }); + recipe = "thirdpartyemailpassword"; + } + } else { + user = Object.assign(Object.assign({}, userResponse), { + recipeId: "emailpassword", + }); + recipe = "thirdpartyemailpassword"; + } } } catch (e) { // No - op @@ -348,8 +367,22 @@ class SuperTokens { try { const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdpartyemailpassword"; + if ("loginMethods" in userResponse) { + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "thirdparty" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = Object.assign(Object.assign({}, loginMethod), { + recipeId: "thirdparty", + }); + recipe = "thirdpartyemailpassword"; + } + } else { + user = Object.assign(Object.assign({}, userResponse), { + recipeId: "emailpassword", + }); + recipe = "thirdpartyemailpassword"; + } } } catch (e) { // No - op diff --git a/lib/ts/recipe/accountlinking/accountLinkingClaim.ts b/lib/ts/recipe/accountlinking/accountLinkingClaim.ts index b38087090..005f3b35f 100644 --- a/lib/ts/recipe/accountlinking/accountLinkingClaim.ts +++ b/lib/ts/recipe/accountlinking/accountLinkingClaim.ts @@ -6,7 +6,7 @@ import { PrimitiveClaim } from "../session/claims"; export class AccountLinkingClaimClass extends PrimitiveClaim { constructor() { super({ - key: "st-acl", + key: "st-linking", fetchValue(_, __, ___) { return undefined; }, diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index 1ae4a37ac..ffa48f996 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -407,10 +407,12 @@ export default class Recipe extends RecipeModule { } | { accountsLinked: false; - reason: - | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" - | "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" - | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + } + | { + accountsLinked: false; + reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + userId: string; } | { accountsLinked: false; @@ -489,6 +491,7 @@ export default class Recipe extends RecipeModule { createRecipeUser: false, accountsLinked: false, reason: "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + userId: existingUser.loginMethods[0].recipeUserId, }; } diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 9861f7758..9596d1570 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -134,19 +134,39 @@ export default function getAPIImplementation(): APIInterface { } if (!result.accountsLinked && "reason" in result) { if (result.reason === "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + const emailVerificationInstance = EmailVerification.getInstance(); + if (emailVerificationInstance !== undefined) { + let emailVerificationResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: result.userId, + email, + userContext, + } + ); + if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { + await session.fetchAndSetClaim(EmailVerificationClaim, userContext); + let emailVerifyLink = getEmailVerifyLink({ + appInfo: options.appInfo, + token: emailVerificationResponse.token, + recipeId: options.recipeId, + }); + await emailVerificationInstance.emailDelivery.ingredientInterfaceImpl.sendEmail({ + type: "EMAIL_VERIFICATION", + user: { + id: result.userId, + email, + }, + emailVerifyLink, + userContext, + }); + } + } return { status: "ACCOUNT_NOT_VERIFIED_ERROR", isNotVerifiedAccountFromInputSession: true, description: "", }; } - if (result.reason === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { - return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: false, - description: "", - }; - } if ( result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" @@ -174,23 +194,9 @@ export default function getAPIImplementation(): APIInterface { "this error should never be thrown. Can't find primary user with userId: " + session.getUserId() ); } - let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); - if (recipeUser === undefined) { - throw Error( - "this error should never be thrown. Can't find emailPassword recipeUser with email: " + - email + - " and primary userId: " + - session.getUserId() - ); - } return { status: "OK", - user: { - id: user.id, - recipeUserId: recipeUser.recipeUserId, - timeJoined: recipeUser.timeJoined, - email, - }, + user, createdNewRecipeUser, wereAccountsAlreadyLinked, session, @@ -238,7 +244,7 @@ export default function getAPIImplementation(): APIInterface { > { let email = formFields.filter((f) => f.id === "email")[0].value; let userIdForPasswordReset: string | undefined = undefined; - let recipeUserId: string | undefined = undefined; + let recipeUserId: string; /** * check if primaryUserId is linked with this email @@ -304,6 +310,7 @@ export default function getAPIImplementation(): APIInterface { } } userIdForPasswordReset = primaryUser.id; + recipeUserId = primaryUser.id; } else { /** * this means emailpassword user associated with the input email exists but it @@ -577,11 +584,12 @@ export default function getAPIImplementation(): APIInterface { } let user = response.user; + let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); let session = await Session.createNewSession( options.req, options.res, user.id, - user.recipeUserId, + recipeUser?.recipeUserId, {}, {}, userContext @@ -647,12 +655,13 @@ export default function getAPIImplementation(): APIInterface { return response; } let user = response.user; + let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); let session = await Session.createNewSession( options.req, options.res, user.id, - user.recipeUserId, + recipeUser?.recipeUserId, {}, {}, userContext @@ -661,7 +670,7 @@ export default function getAPIImplementation(): APIInterface { status: "OK", session, user, - createdNewUser: user.id === user.recipeUserId, + createdNewUser: user.id === recipeUser?.recipeUserId, createdNewRecipeUser: true, }; }, diff --git a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts index 870c0e920..a36a24b05 100644 --- a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts +++ b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts @@ -14,7 +14,7 @@ */ import { TypeEmailPasswordEmailDeliveryInput, RecipeInterface } from "../../../types"; import { createAndSendCustomEmail as defaultCreateAndSendCustomEmail } from "../../../passwordResetFunctions"; -import { NormalisedAppinfo } from "../../../../../types"; +import { NormalisedAppinfo, User } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { getUser } from "../../../../.."; @@ -27,7 +27,7 @@ export default class BackwardCompatibilityService createAndSendCustomEmail: ( user: { id: string; - recipeUserId?: string; + recipeUserId: string; email: string; timeJoined: number; }, @@ -48,14 +48,7 @@ export default class BackwardCompatibilityService } sendEmail = async (input: TypeEmailPasswordEmailDeliveryInput & { userContext: any }) => { - let user: - | { - id: string; - recipeUserId?: string; - email: string; - timeJoined: number; - } - | undefined = + let user: User | undefined = input.user.recipeUserId !== undefined ? await this.recipeInterfaceImpl.getUserById({ userId: input.user.recipeUserId, @@ -63,33 +56,40 @@ export default class BackwardCompatibilityService }) : undefined; if (input.user.recipeUserId === undefined) { - let primaryUser = await getUser(input.user.id); - if (primaryUser === undefined) { - throw Error("this should never come here"); - } - user = { - id: primaryUser.id, - recipeUserId: undefined, - timeJoined: primaryUser.timeJoined, - email: input.user.email, - }; + user = await getUser(input.user.id); } if (user === undefined) { throw Error("this should never come here"); } + let recipeLoginMethod = user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.email === input.user.email + ); + if (recipeLoginMethod === undefined) { + throw Error("this should never come here"); + } // we add this here cause the user may have overridden the sendEmail function // to change the input email and if we don't do this, the input email // will get reset by the getUserById call above. - user.email = input.user.email; + let passwordResetEmailUser: { + id: string; + recipeUserId: string; + email: string; + timeJoined: number; + } = { + id: input.user.id, + recipeUserId: recipeLoginMethod.recipeUserId, + email: input.user.email, + timeJoined: recipeLoginMethod.timeJoined, + }; try { if (!this.isInServerlessEnv) { this.resetPasswordUsingTokenFeature - .createAndSendCustomEmail(user, input.passwordResetLink, input.userContext) + .createAndSendCustomEmail(passwordResetEmailUser, input.passwordResetLink, input.userContext) .catch((_) => {}); } else { // see https://github.com/supertokens/supertokens-node/pull/135 await this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( - user, + passwordResetEmailUser, input.passwordResetLink, input.userContext ); diff --git a/lib/ts/recipe/emailpassword/index.ts b/lib/ts/recipe/emailpassword/index.ts index 0673886c5..4c6026eb3 100644 --- a/lib/ts/recipe/emailpassword/index.ts +++ b/lib/ts/recipe/emailpassword/index.ts @@ -15,7 +15,8 @@ import Recipe from "./recipe"; import SuperTokensError from "./error"; -import { RecipeInterface, User, APIOptions, APIInterface, TypeEmailPasswordEmailDeliveryInput } from "./types"; +import { RecipeInterface, APIOptions, APIInterface, TypeEmailPasswordEmailDeliveryInput } from "./types"; +import { User } from "../../types"; export default class Wrapper { static init = Recipe.init; diff --git a/lib/ts/recipe/emailpassword/recipe.ts b/lib/ts/recipe/emailpassword/recipe.ts index 5b8626318..8b6d6b16c 100644 --- a/lib/ts/recipe/emailpassword/recipe.ts +++ b/lib/ts/recipe/emailpassword/recipe.ts @@ -224,12 +224,17 @@ export default class Recipe extends RecipeModule { // extra instance functions below............... getEmailForUserId: GetEmailForUserIdFunc = async (userId, userContext) => { - let userInfo = await this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo !== undefined) { - return { - status: "OK", - email: userInfo.email, - }; + let user = await this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (user !== undefined) { + let recipeLevelUser = user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (recipeLevelUser !== undefined && recipeLevelUser.email !== undefined) { + return { + status: "OK", + email: recipeLevelUser.email, + }; + } } return { status: "UNKNOWN_USER_ID_ERROR", diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index 8c28c414f..98d586355 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -1,9 +1,10 @@ -import { RecipeInterface, User } from "./types"; +import { RecipeInterface } from "./types"; import AccountLinking from "../accountlinking/recipe"; import { Querier } from "../../querier"; import NormalisedURLPath from "../../normalisedURLPath"; import { getUser, listUsersByAccountInfo } from "../.."; import EmailVerification from "../emailverification/recipe"; +import { User } from "../../types"; export default function getRecipeInterface(querier: Querier): RecipeInterface { return { @@ -17,12 +18,13 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise<{ status: "OK"; newUserCreated: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { email, password, }); if (response.status === "OK") { + let newUserCreated = true; if (doAccountLinking) { let primaryUserId = await AccountLinking.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations( { @@ -35,9 +37,15 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { userContext, } ); + if (response.user.id !== primaryUserId) { + newUserCreated = false; + } response.user.id = primaryUserId; } - return response; + return { + ...response, + newUserCreated, + }; } else { return { status: "EMAIL_ALREADY_EXISTS_ERROR", @@ -141,7 +149,11 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { email?: string; password?: string; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }> { let markEmailAsVerified = false; if (input.email !== undefined) { @@ -155,7 +167,7 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { if (primaryUserFromEmailUsers !== undefined) { if (primaryUserFromEmailUsers.id !== userForUserId.id) { return { - status: "EMAIL_CHANGE_NOT_ALLOWED", + status: "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING", }; } markEmailAsVerified = true; diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index 62116cd5a..cdfae6885 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -21,7 +21,7 @@ import { TypeInputWithService as EmailDeliveryTypeInputWithService, } from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; -import { GeneralErrorResponse, NormalisedAppinfo } from "../../types"; +import { GeneralErrorResponse, NormalisedAppinfo, User } from "../../types"; export type TypeNormalisedInput = { signUpFeature: TypeNormalisedInputSignUp; @@ -71,13 +71,6 @@ export type TypeNormalisedInputResetPasswordUsingTokenFeature = { formFieldsForPasswordResetForm: NormalisedFormField[]; }; -export type User = { - id: string; - recipeUserId: string; - email: string; - timeJoined: number; -}; - export type TypeInput = { signUpFeature?: TypeInputSignUp; emailDelivery?: EmailDeliveryTypeInput; @@ -94,9 +87,20 @@ export type RecipeInterface = { signUp(input: { email: string; password: string; + /** + * we now do account-linking in the recipe implementation of + * this function. If someone wants to call this function + * manually and wants the any other account with the same email + * to be linked automatically, all they need to do is pass this + * boolean. If the user doesn't want to do automatic account linking + * while calling this function, they can pass false. Default value + * of the parameter would be false. So if we are moving the account + * linking part to be part of this function, ideally we should keep + * this boolean parameter + */ doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise<{ status: "OK"; newUserCreated: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; signIn(input: { email: string; @@ -144,7 +148,11 @@ export type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; }; @@ -308,7 +316,7 @@ export type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; user: { id: string; - recipeUserId?: string; + recipeUserId: string; email: string; }; passwordResetLink: string; diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts index 482de1c2c..fa2aabbc5 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts @@ -1,4 +1,5 @@ -import { RecipeInterface, User } from "../../emailpassword/types"; +import { RecipeInterface } from "../../emailpassword/types"; +import { User } from "../../../types"; import { RecipeInterface as ThirdPartyEmailPasswordRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPasswordRecipeInterface): RecipeInterface { @@ -8,7 +9,7 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise<{ status: "OK"; newUserCreated: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { return await recipeInterface.emailPasswordSignUp(input); }, @@ -26,14 +27,14 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw // either user is undefined or it's a thirdparty user. return undefined; } - return user; + return user as User; }, getUserByEmail: async function (input: { email: string; userContext: any }): Promise { let result = await recipeInterface.getUsersByEmail(input); for (let i = 0; i < result.length; i++) { if (result[i].thirdParty === undefined) { - return result[i]; + return result[i] as User; } } return undefined; @@ -57,7 +58,11 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }> { return recipeInterface.updateEmailOrPassword(input); }, diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts index b67bd74a6..9ef497155 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts @@ -6,6 +6,7 @@ import { RecipeInterface as ThirdPartyRecipeInterface } from "../../thirdparty"; import { Querier } from "../../../querier"; import DerivedEP from "./emailPasswordRecipeImplementation"; import DerivedTP from "./thirdPartyRecipeImplementation"; +import { User as GlobalUser } from "../../../types"; export default function getRecipeInterface( emailPasswordQuerier: Querier, @@ -23,7 +24,9 @@ export default function getRecipeInterface( password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise< + { status: "OK"; newUserCreated: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + > { return await originalEmailPasswordImplementation.signUp.bind(DerivedEP(this))(input); }, @@ -31,7 +34,7 @@ export default function getRecipeInterface( email: string; password: string; userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }> { + }): Promise<{ status: "OK"; user: GlobalUser } | { status: "WRONG_CREDENTIALS_ERROR" }> { return originalEmailPasswordImplementation.signIn.bind(DerivedEP(this))(input); }, @@ -47,10 +50,13 @@ export default function getRecipeInterface( return originalThirdPartyImplementation.signInUp.bind(DerivedTP(this))(input); }, - getUserById: async function (input: { userId: string; userContext: any }): Promise { - let user: User | undefined = await originalEmailPasswordImplementation.getUserById.bind(DerivedEP(this))( - input - ); + getUserById: async function (input: { + userId: string; + userContext: any; + }): Promise { + let user: GlobalUser | User | undefined = await originalEmailPasswordImplementation.getUserById.bind( + DerivedEP(this) + )(input); if (user !== undefined) { return user; } @@ -60,10 +66,20 @@ export default function getRecipeInterface( return await originalThirdPartyImplementation.getUserById.bind(DerivedTP(this))(input); }, - getUsersByEmail: async function ({ email, userContext }: { email: string; userContext: any }): Promise { - let userFromEmailPass: User | undefined = await originalEmailPasswordImplementation.getUserByEmail.bind( - DerivedEP(this) - )({ email, userContext }); + getUsersByEmail: async function ({ + email, + userContext, + }: { + email: string; + userContext: any; + }): Promise<(User | GlobalUser)[]> { + let userFromEmailPass: + | GlobalUser + | User + | undefined = await originalEmailPasswordImplementation.getUserByEmail.bind(DerivedEP(this))({ + email, + userContext, + }); if (originalThirdPartyImplementation === undefined) { return userFromEmailPass === undefined ? [] : [userFromEmailPass]; @@ -110,7 +126,11 @@ export default function getRecipeInterface( userContext: any; } ): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }> { let user = await this.getUserById({ userId: input.userId, userContext: input.userContext }); if (user === undefined) { diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts index 75a8f40e7..f4b10ee82 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts @@ -50,13 +50,7 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw // either user is undefined or it's an email password user. return undefined; } - return { - email: user.email, - id: user.id, - recipeUserId: user.recipeUserId, - timeJoined: user.timeJoined, - thirdParty: user.thirdParty, - }; + return user as User; }, getUsersByEmail: async function (input: { email: string; userContext: any }): Promise { diff --git a/lib/ts/recipe/thirdpartyemailpassword/types.ts b/lib/ts/recipe/thirdpartyemailpassword/types.ts index 38b6951bf..e130b845f 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/types.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/types.ts @@ -27,7 +27,7 @@ import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService, } from "../../ingredients/emaildelivery/types"; -import { GeneralErrorResponse } from "../../types"; +import { GeneralErrorResponse, User as GlobalUser } from "../../types"; export type User = { id: string; @@ -92,9 +92,9 @@ export type TypeNormalisedInput = { }; export type RecipeInterface = { - getUserById(input: { userId: string; userContext: any }): Promise; + getUserById(input: { userId: string; userContext: any }): Promise; - getUsersByEmail(input: { email: string; userContext: any }): Promise; + getUsersByEmail(input: { email: string; userContext: any }): Promise<(User | GlobalUser)[]>; getUserByThirdPartyInfo(input: { thirdPartyId: string; @@ -114,13 +114,13 @@ export type RecipeInterface = { password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise<{ status: "OK"; newUserCreated: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; emailPasswordSignIn(input: { email: string; password: string; userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>; + }): Promise<{ status: "OK"; user: GlobalUser } | { status: "WRONG_CREDENTIALS_ERROR" }>; createResetPasswordToken(input: { userId: string; @@ -147,7 +147,11 @@ export type RecipeInterface = { password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; }; @@ -314,7 +318,7 @@ export type APIInterface = { }) => Promise< | { status: "OK"; - user: User; + user: GlobalUser; createdNewRecipeUser: boolean; session: SessionContainerInterface; wereAccountsAlreadyLinked: boolean; @@ -352,7 +356,7 @@ export type APIInterface = { }) => Promise< | { status: "OK"; - user: User; + user: GlobalUser; session: SessionContainerInterface; } | { @@ -373,7 +377,7 @@ export type APIInterface = { }) => Promise< | { status: "OK"; - user: User; + user: GlobalUser; createdNewUser: boolean; session: SessionContainerInterface; } diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index 3e6243fab..c03b346c9 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -434,11 +434,16 @@ export default class SuperTokens { const userResponse = await EmailPassword.getUserById(userId); if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "emailpassword", - }; - recipe = "emailpassword"; + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = { + ...loginMethod, + recipeId: "emailpassword", + }; + recipe = "emailpassword"; + } } } catch (e) { // No - op @@ -449,11 +454,24 @@ export default class SuperTokens { const userResponse = await ThirdPartyEmailPassword.getUserById(userId); if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "emailpassword", - }; - recipe = "thirdpartyemailpassword"; + if ("loginMethods" in userResponse) { + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = { + ...loginMethod, + recipeId: "emailpassword", + }; + recipe = "thirdpartyemailpassword"; + } + } else { + user = { + ...userResponse, + recipeId: "emailpassword", + }; + recipe = "thirdpartyemailpassword"; + } } } catch (e) { // No - op @@ -479,11 +497,24 @@ export default class SuperTokens { const userResponse = await ThirdPartyEmailPassword.getUserById(userId); if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "thirdparty", - }; - recipe = "thirdpartyemailpassword"; + if ("loginMethods" in userResponse) { + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "thirdparty" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = { + ...loginMethod, + recipeId: "thirdparty", + }; + recipe = "thirdpartyemailpassword"; + } + } else { + user = { + ...userResponse, + recipeId: "emailpassword", + }; + recipe = "thirdpartyemailpassword"; + } } } catch (e) { // No - op From 5059468da1d1c2516f172b01611f0682d9fba3b9 Mon Sep 17 00:00:00 2001 From: Bhumil Date: Sun, 12 Mar 2023 22:16:38 +0530 Subject: [PATCH 62/82] createdNewUser changes --- lib/build/recipe/emailpassword/api/implementation.js | 3 +-- lib/build/recipe/emailpassword/index.d.ts | 2 +- lib/build/recipe/emailpassword/recipeImplementation.js | 6 +++--- lib/build/recipe/emailpassword/types.d.ts | 2 +- lib/build/recipe/thirdpartyemailpassword/index.d.ts | 2 +- .../thirdpartyemailpassword/recipeImplementation/index.js | 5 ++++- lib/build/recipe/thirdpartyemailpassword/types.d.ts | 2 +- lib/ts/recipe/emailpassword/api/implementation.ts | 2 +- lib/ts/recipe/emailpassword/recipeImplementation.ts | 8 ++++---- lib/ts/recipe/emailpassword/types.ts | 2 +- .../emailPasswordRecipeImplementation.ts | 2 +- .../thirdpartyemailpassword/recipeImplementation/index.ts | 2 +- lib/ts/recipe/thirdpartyemailpassword/types.ts | 2 +- 13 files changed, 21 insertions(+), 19 deletions(-) diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index 879409a60..b3523f0f9 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -615,8 +615,7 @@ function getAPIImplementation() { status: "OK", session, user, - createdNewUser: - user.id === (recipeUser === null || recipeUser === void 0 ? void 0 : recipeUser.recipeUserId), + createdNewUser: response.createdNewUser, createdNewRecipeUser: true, }; }); diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index d92ffb6c7..37cfeb43a 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -14,7 +14,7 @@ export default class Wrapper { ): Promise< | { status: "OK"; - newUserCreated: boolean; + createdNewUser: boolean; user: User; } | { diff --git a/lib/build/recipe/emailpassword/recipeImplementation.js b/lib/build/recipe/emailpassword/recipeImplementation.js index 1f10d8f3b..cf74baef7 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -49,7 +49,7 @@ function getRecipeInterface(querier) { password, }); if (response.status === "OK") { - let newUserCreated = true; + let createdNewUser = true; if (doAccountLinking) { let primaryUserId = yield recipe_1.default .getInstanceOrThrowError() @@ -63,11 +63,11 @@ function getRecipeInterface(querier) { userContext, }); if (response.user.id !== primaryUserId) { - newUserCreated = false; + createdNewUser = false; } response.user.id = primaryUserId; } - return Object.assign(Object.assign({}, response), { newUserCreated }); + return Object.assign(Object.assign({}, response), { createdNewUser }); } else { return { status: "EMAIL_ALREADY_EXISTS_ERROR", diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index 28ea41a45..627ac35f5 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -82,7 +82,7 @@ export declare type RecipeInterface = { }): Promise< | { status: "OK"; - newUserCreated: boolean; + createdNewUser: boolean; user: User; } | { diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index dea9f8d43..672066a29 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -30,7 +30,7 @@ export default class Wrapper { ): Promise< | { status: "OK"; - newUserCreated: boolean; + createdNewUser: boolean; user: import("../emailpassword").User; } | { diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js index c66e7bb62..333844ed6 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js @@ -91,7 +91,10 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { return __awaiter(this, void 0, void 0, function* () { let userFromEmailPass = yield originalEmailPasswordImplementation.getUserByEmail.bind( emailPasswordRecipeImplementation_1.default(this) - )({ email, userContext }); + )({ + email, + userContext, + }); if (originalThirdPartyImplementation === undefined) { return userFromEmailPass === undefined ? [] : [userFromEmailPass]; } diff --git a/lib/build/recipe/thirdpartyemailpassword/types.d.ts b/lib/build/recipe/thirdpartyemailpassword/types.d.ts index fa41ded01..93c839bb0 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -95,7 +95,7 @@ export declare type RecipeInterface = { }): Promise< | { status: "OK"; - newUserCreated: boolean; + createdNewUser: boolean; user: GlobalUser; } | { diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 9596d1570..59426ec9d 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -670,7 +670,7 @@ export default function getAPIImplementation(): APIInterface { status: "OK", session, user, - createdNewUser: user.id === recipeUser?.recipeUserId, + createdNewUser: response.createdNewUser, createdNewRecipeUser: true, }; }, diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index 98d586355..787d661ce 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -18,13 +18,13 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; newUserCreated: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise<{ status: "OK"; createdNewUser: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { email, password, }); if (response.status === "OK") { - let newUserCreated = true; + let createdNewUser = true; if (doAccountLinking) { let primaryUserId = await AccountLinking.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations( { @@ -38,13 +38,13 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { } ); if (response.user.id !== primaryUserId) { - newUserCreated = false; + createdNewUser = false; } response.user.id = primaryUserId; } return { ...response, - newUserCreated, + createdNewUser, }; } else { return { diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index cdfae6885..ee3e81bed 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -100,7 +100,7 @@ export type RecipeInterface = { */ doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; newUserCreated: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise<{ status: "OK"; createdNewUser: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; signIn(input: { email: string; diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts index fa2aabbc5..e9d7d9df9 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts @@ -9,7 +9,7 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; newUserCreated: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise<{ status: "OK"; createdNewUser: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { return await recipeInterface.emailPasswordSignUp(input); }, diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts index 9ef497155..ca7bca910 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts @@ -25,7 +25,7 @@ export default function getRecipeInterface( doAccountLinking: boolean; userContext: any; }): Promise< - { status: "OK"; newUserCreated: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + { status: "OK"; createdNewUser: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } > { return await originalEmailPasswordImplementation.signUp.bind(DerivedEP(this))(input); }, diff --git a/lib/ts/recipe/thirdpartyemailpassword/types.ts b/lib/ts/recipe/thirdpartyemailpassword/types.ts index e130b845f..50b0ef329 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/types.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/types.ts @@ -114,7 +114,7 @@ export type RecipeInterface = { password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; newUserCreated: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise<{ status: "OK"; createdNewUser: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; emailPasswordSignIn(input: { email: string; From 1fc5d585f98b0d08e6e0037fd4c20efe6ad3b359 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 14 Mar 2023 17:34:55 +0530 Subject: [PATCH 63/82] adds comments --- lib/build/recipe/accountlinking/recipe.js | 9 +++++++++ lib/ts/recipe/accountlinking/recipe.ts | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 1a43205b1..c5b88f5bb 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -790,11 +790,20 @@ class Recipe extends recipeModule_1.default { userContext ); if (existingSessionClaimValue !== undefined) { + // It can come here when we are trying to link + // an account post login, and that new account just + // finished email verification. In this case, we do not + // want to change the session cause the user should + // still be logged into their original session. yield session.removeClaim( accountLinkingClaim_1.AccountLinkingClaim, userContext ); } else { + // It can come here when the user has just finished + // verifying their email (for a new recipe account), and + // now that account has been linked to another account + // so we should change the session. return { createNewSession: true, primaryUserId, diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index ffa48f996..f19ef4cec 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -846,6 +846,8 @@ export default class Recipe extends RecipeModule { userContext, }: { recipeUserId: string; + // session can be undefined if for example, the user has opened the email verification + // link in a new browser session: SessionContainer | undefined; userContext: any; }): Promise< @@ -959,8 +961,17 @@ export default class Recipe extends RecipeModule { userContext ); if (existingSessionClaimValue !== undefined) { + // It can come here when we are trying to link + // an account post login, and that new account just + // finished email verification. In this case, we do not + // want to change the session cause the user should + // still be logged into their original session. await session.removeClaim(AccountLinkingClaim, userContext); } else { + // It can come here when the user has just finished + // verifying their email (for a new recipe account), and + // now that account has been linked to another account + // so we should change the session. return { createNewSession: true, primaryUserId, From c201083e668cde34989a81d7544c8149c5927b81 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Thu, 30 Mar 2023 14:55:35 +0530 Subject: [PATCH 64/82] fixes --- lib/build/recipe/accountlinking/recipe.js | 168 +++++++------------- lib/build/recipe/accountlinking/types.d.ts | 19 +-- lib/ts/recipe/accountlinking/recipe.ts | 170 +++++++-------------- lib/ts/recipe/accountlinking/types.ts | 19 +-- 4 files changed, 122 insertions(+), 254 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index c5b88f5bb..65c4d710c 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -110,26 +110,8 @@ class Recipe extends recipeModule_1.default { }; this.isSignUpAllowed = ({ newUser, userContext }) => __awaiter(this, void 0, void 0, function* () { - let accountInfo; - if (newUser.email !== undefined) { - accountInfo = { - email: newUser.email, - }; - } else if (newUser.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: newUser.phoneNumber, - }; - } else if (newUser.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: newUser.thirdParty.id, - thirdPartyUserId: newUser.thirdParty.userId, - }; - } else { - // It's not possible to come here because all the login methods are covered above. - throw new Error("Should never come here"); - } let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: newUser, userContext, }); if (users.length === 0) { @@ -186,29 +168,14 @@ class Recipe extends recipeModule_1.default { // this function returns the user ID for which the session will be created. this.doPostSignUpAccountLinkingOperations = ({ newUser, newUserVerified, recipeUserId, userContext }) => __awaiter(this, void 0, void 0, function* () { - let accountInfo; - if (newUser.email !== undefined) { - accountInfo = { - email: newUser.email, - }; - } else if (newUser.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: newUser.phoneNumber, - }; - } else if (newUser.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: newUser.thirdParty.id, - thirdPartyUserId: newUser.thirdParty.userId, - }; - } else { - throw Error("this error should never be thrown"); - } let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: newUser, userContext, }); if (users.length === 0) { - return recipeUserId; + throw new Error( + "This is a race condition that can happen if the user is deleted right after being created, so we don't want a session to be created for this user." + ); } let primaryUser = users.find((u) => u.isPrimaryUser); let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( @@ -262,9 +229,6 @@ class Recipe extends recipeModule_1.default { let recipeUserIdsForEmailVerificationUpdate = primaryUser.loginMethods .filter((u) => u.email === newUser.email && !u.verified) .map((l) => l.recipeUserId); - recipeUserIdsForEmailVerificationUpdate = Array.from( - new Set(recipeUserIdsForEmailVerificationUpdate) - ); for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { yield this.markEmailAsVerified({ email: newUser.email, @@ -277,7 +241,13 @@ class Recipe extends recipeModule_1.default { } else if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { return result.primaryUserId; } else if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { - return result.primaryUserId; + // it can come here if somehow the account info is linked to another primary user that is not equal to the primary user we found above. This means that we will have to try again. + return yield this.doPostSignUpAccountLinkingOperations({ + newUser: newUser, + newUserVerified: newUserVerified, + recipeUserId, + userContext, + }); } else { return primaryUser.id; } @@ -406,33 +376,12 @@ class Recipe extends recipeModule_1.default { reason: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", }; } - /** - * checking if a recipe user already exists for the given - * login info - */ - let accountInfo; - if (newUser.email !== undefined) { - accountInfo = { - email: newUser.email, - }; - } else if (newUser.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: newUser.phoneNumber, - }; - } else if (newUser.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: newUser.thirdParty.id, - thirdPartyUserId: newUser.thirdParty.userId, - }; - } else { - throw Error("this error should never be thrown"); - } /** * We try and find if there is an existing recipe user for the same login method * and same identifying info as the newUser object. */ let usersArrayThatHaveSameAccountInfoAsNewUser = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: newUser, userContext, }); const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find( @@ -662,28 +611,13 @@ class Recipe extends recipeModule_1.default { } let pUser = yield this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); if (pUser !== undefined && pUser.isPrimaryUser) { + // normally isPrimaryUser should be true, but it can be false if the user used to be + // primary and then was unlinked from the primary account. return pUser; } - let accountInfo; - let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array - if (loginMethodInfo.email !== undefined) { - accountInfo = { - email: loginMethodInfo.email, - }; - } else if (loginMethodInfo.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: loginMethodInfo.phoneNumber, - }; - } else if (loginMethodInfo.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: loginMethodInfo.thirdParty.id, - thirdPartyUserId: loginMethodInfo.thirdParty.userId, - }; - } else { - throw Error("this error should never be thrown"); - } + let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: loginMethodInfo, userContext, }); return users.find((u) => u.isPrimaryUser); @@ -726,6 +660,8 @@ class Recipe extends recipeModule_1.default { if (response.status === "OK") { // remove session claim if (session !== undefined) { + // this is a no-op since the AccountLinkingClaim should never be there in the first place. + // The reason for this is that this claim is only added when wanting to link accounts, and not create a primary user. yield session.removeClaim(accountLinkingClaim_1.AccountLinkingClaim, userContext); } } else { @@ -775,41 +711,45 @@ class Recipe extends recipeModule_1.default { let primaryUserId = primaryUser.id; if ( linkAccountsResult.status === - "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + // this can come here cause of a race condition. + return yield this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + } + if ( linkAccountsResult.status === - "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" ) { primaryUserId = linkAccountsResult.primaryUserId; } - if (linkAccountsResult.status === "OK") { - // remove session claim if session claim exists - // else create a new session - if (session !== undefined) { - let existingSessionClaimValue = yield session.getClaimValue( - accountLinkingClaim_1.AccountLinkingClaim, - userContext - ); - if (existingSessionClaimValue !== undefined) { - // It can come here when we are trying to link - // an account post login, and that new account just - // finished email verification. In this case, we do not - // want to change the session cause the user should - // still be logged into their original session. - yield session.removeClaim( - accountLinkingClaim_1.AccountLinkingClaim, - userContext - ); - } else { - // It can come here when the user has just finished - // verifying their email (for a new recipe account), and - // now that account has been linked to another account - // so we should change the session. - return { - createNewSession: true, - primaryUserId, - recipeUserId, - }; - } + // remove session claim if session claim exists + // else create a new session + if (session !== undefined) { + let existingSessionClaimValue = yield session.getClaimValue( + accountLinkingClaim_1.AccountLinkingClaim, + userContext + ); + if (existingSessionClaimValue !== undefined) { + // It can come here when we are trying to link + // an account post login, and that new account just + // finished email verification. In this case, we do not + // want to change the session cause the user should + // still be logged into their original session. + yield session.removeClaim(accountLinkingClaim_1.AccountLinkingClaim, userContext); + } else { + // It can come here when the user has just finished + // verifying their email (for a new recipe account), and + // now that account has been linked to another account + // so we should change the session. + return { + createNewSession: true, + primaryUserId, + recipeUserId, + }; } } } diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index f30b37da5..3b3e0bfeb 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -214,14 +214,11 @@ export declare type AccountInfoAndEmailWithRecipeId = { userId: string; }; }; -export declare type AccountInfo = - | { - email: string; - } - | { - phoneNumber: string; - } - | { - thirdPartyId: string; - thirdPartyUserId: string; - }; +export declare type AccountInfo = { + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; +}; diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index f19ef4cec..73b3708bc 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -19,13 +19,7 @@ import normalisedURLPath from "../../normalisedURLPath"; import RecipeModule from "../../recipeModule"; import type { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction, User } from "../../types"; import { SessionContainer } from "../session"; -import type { - TypeNormalisedInput, - RecipeInterface, - TypeInput, - AccountInfoAndEmailWithRecipeId, - AccountInfo, -} from "./types"; +import type { TypeNormalisedInput, RecipeInterface, TypeInput, AccountInfoAndEmailWithRecipeId } from "./types"; import { validateAndNormaliseUserInput } from "./utils"; import { getUser } from "../.."; import OverrideableBuilder from "supertokens-js-override"; @@ -180,27 +174,8 @@ export default class Recipe extends RecipeModule { newUser: AccountInfoAndEmailWithRecipeId; userContext: any; }): Promise => { - let accountInfo: AccountInfo; - if (newUser.email !== undefined) { - accountInfo = { - email: newUser.email, - }; - } else if (newUser.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: newUser.phoneNumber, - }; - } else if (newUser.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: newUser.thirdParty.id, - thirdPartyUserId: newUser.thirdParty.userId, - }; - } else { - // It's not possible to come here because all the login methods are covered above. - throw new Error("Should never come here"); - } - let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: newUser, userContext, }); if (users.length === 0) { @@ -276,29 +251,14 @@ export default class Recipe extends RecipeModule { recipeUserId: string; userContext: any; }): Promise => { - let accountInfo: AccountInfo; - if (newUser.email !== undefined) { - accountInfo = { - email: newUser.email, - }; - } else if (newUser.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: newUser.phoneNumber, - }; - } else if (newUser.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: newUser.thirdParty.id, - thirdPartyUserId: newUser.thirdParty.userId, - }; - } else { - throw Error("this error should never be thrown"); - } let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: newUser, userContext, }); if (users.length === 0) { - return recipeUserId; + throw new Error( + "This is a race condition that can happen if the user is deleted right after being created, so we don't want a session to be created for this user." + ); } let primaryUser = users.find((u) => u.isPrimaryUser); let shouldDoAccountLinking = await this.config.shouldDoAutomaticAccountLinking( @@ -356,7 +316,6 @@ export default class Recipe extends RecipeModule { let recipeUserIdsForEmailVerificationUpdate = primaryUser.loginMethods .filter((u) => u.email === newUser.email && !u.verified) .map((l) => l.recipeUserId); - recipeUserIdsForEmailVerificationUpdate = Array.from(new Set(recipeUserIdsForEmailVerificationUpdate)); for (let i = 0; i < recipeUserIdsForEmailVerificationUpdate.length; i++) { await this.markEmailAsVerified({ @@ -370,7 +329,13 @@ export default class Recipe extends RecipeModule { } else if (result.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { return result.primaryUserId; } else if (result.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { - return result.primaryUserId; + // it can come here if somehow the account info is linked to another primary user that is not equal to the primary user we found above. This means that we will have to try again. + return await this.doPostSignUpAccountLinkingOperations({ + newUser: newUser, + newUserVerified: newUserVerified, + recipeUserId, + userContext, + }); } else { return primaryUser.id; } @@ -552,34 +517,12 @@ export default class Recipe extends RecipeModule { }; } - /** - * checking if a recipe user already exists for the given - * login info - */ - let accountInfo: AccountInfo; - if (newUser.email !== undefined) { - accountInfo = { - email: newUser.email, - }; - } else if (newUser.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: newUser.phoneNumber, - }; - } else if (newUser.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: newUser.thirdParty.id, - thirdPartyUserId: newUser.thirdParty.userId, - }; - } else { - throw Error("this error should never be thrown"); - } - /** * We try and find if there is an existing recipe user for the same login method * and same identifying info as the newUser object. */ let usersArrayThatHaveSameAccountInfoAsNewUser = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: newUser, userContext, }); @@ -812,29 +755,14 @@ export default class Recipe extends RecipeModule { } let pUser = await this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); if (pUser !== undefined && pUser.isPrimaryUser) { + // normally isPrimaryUser should be true, but it can be false if the user used to be + // primary and then was unlinked from the primary account. return pUser; } - let accountInfo: AccountInfo; - let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item in the array - if (loginMethodInfo.email !== undefined) { - accountInfo = { - email: loginMethodInfo.email, - }; - } else if (loginMethodInfo.phoneNumber !== undefined) { - accountInfo = { - phoneNumber: loginMethodInfo.phoneNumber, - }; - } else if (loginMethodInfo.thirdParty !== undefined) { - accountInfo = { - thirdPartyId: loginMethodInfo.thirdParty.id, - thirdPartyUserId: loginMethodInfo.thirdParty.userId, - }; - } else { - throw Error("this error should never be thrown"); - } + let loginMethodInfo = user.loginMethods[0]; // this is a recipe user so there will be only one item let users = await this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo, + accountInfo: loginMethodInfo, userContext, }); return users.find((u) => u.isPrimaryUser); @@ -897,6 +825,8 @@ export default class Recipe extends RecipeModule { if (response.status === "OK") { // remove session claim if (session !== undefined) { + // this is a no-op since the AccountLinkingClaim should never be there in the first place. + // The reason for this is that this claim is only added when wanting to link accounts, and not create a primary user. await session.removeClaim(AccountLinkingClaim, userContext); } } else { @@ -946,38 +876,42 @@ export default class Recipe extends RecipeModule { }); let primaryUserId = primaryUser.id; if ( - linkAccountsResult.status === - "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + linkAccountsResult.status === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + // this can come here cause of a race condition. + return await this.createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId, + session, + userContext, + }); + } + if ( linkAccountsResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" ) { primaryUserId = linkAccountsResult.primaryUserId; } - if (linkAccountsResult.status === "OK") { - // remove session claim if session claim exists - // else create a new session - if (session !== undefined) { - let existingSessionClaimValue = await session.getClaimValue( - AccountLinkingClaim, - userContext - ); - if (existingSessionClaimValue !== undefined) { - // It can come here when we are trying to link - // an account post login, and that new account just - // finished email verification. In this case, we do not - // want to change the session cause the user should - // still be logged into their original session. - await session.removeClaim(AccountLinkingClaim, userContext); - } else { - // It can come here when the user has just finished - // verifying their email (for a new recipe account), and - // now that account has been linked to another account - // so we should change the session. - return { - createNewSession: true, - primaryUserId, - recipeUserId, - }; - } + + // remove session claim if session claim exists + // else create a new session + if (session !== undefined) { + let existingSessionClaimValue = await session.getClaimValue(AccountLinkingClaim, userContext); + if (existingSessionClaimValue !== undefined) { + // It can come here when we are trying to link + // an account post login, and that new account just + // finished email verification. In this case, we do not + // want to change the session cause the user should + // still be logged into their original session. + await session.removeClaim(AccountLinkingClaim, userContext); + } else { + // It can come here when the user has just finished + // verifying their email (for a new recipe account), and + // now that account has been linked to another account + // so we should change the session. + return { + createNewSession: true, + primaryUserId, + recipeUserId, + }; } } } diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index b1c9f39f8..b04dae471 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -226,14 +226,11 @@ export type AccountInfoAndEmailWithRecipeId = { }; }; -export type AccountInfo = - | { - email: string; - } - | { - phoneNumber: string; - } - | { - thirdPartyId: string; - thirdPartyUserId: string; - }; +export type AccountInfo = { + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; +}; From 2a0fcb279ded7744baa922863a24b3c7bfc75a0c Mon Sep 17 00:00:00 2001 From: Rishabh Poddar Date: Thu, 30 Mar 2023 15:41:04 +0530 Subject: [PATCH 65/82] review changes (#511) * more changes * small changes * small changes * small changes * Update lib/ts/recipe/emailpassword/api/implementation.ts --- lib/build/recipe/dashboard/types.d.ts | 11 ++ lib/build/recipe/dashboard/utils.d.ts | 4 +- lib/build/recipe/dashboard/utils.js | 142 ++++++++++++-- .../emailpassword/api/implementation.js | 13 +- .../services/backwardCompatibility/index.d.ts | 3 +- .../services/backwardCompatibility/index.js | 37 +--- .../emailpassword/passwordResetFunctions.d.ts | 1 - lib/build/recipe/emailpassword/recipe.js | 5 +- lib/build/supertokens.d.ts | 14 -- lib/build/supertokens.js | 128 ------------- .../dashboard/api/userdetails/userGet.ts | 6 +- lib/ts/recipe/dashboard/types.ts | 12 ++ lib/ts/recipe/dashboard/utils.ts | 174 ++++++++++++++++- .../emailpassword/api/implementation.ts | 16 +- .../services/backwardCompatibility/index.ts | 42 +--- .../emailpassword/passwordResetFunctions.ts | 1 - lib/ts/recipe/emailpassword/recipe.ts | 5 +- lib/ts/supertokens.ts | 179 ------------------ 18 files changed, 365 insertions(+), 428 deletions(-) diff --git a/lib/build/recipe/dashboard/types.d.ts b/lib/build/recipe/dashboard/types.d.ts index b35894316..be7b06b28 100644 --- a/lib/build/recipe/dashboard/types.d.ts +++ b/lib/build/recipe/dashboard/types.d.ts @@ -50,6 +50,17 @@ export declare type RecipeLevelUser = { id: string; userId: string; }; +}; +export declare type RecipeLevelUserWithFirstAndLastName = { + recipeId: "emailpassword" | "thirdparty" | "passwordless"; + timeJoined: number; + recipeUserId: string; + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; firstName: string; lastName: string; }; diff --git a/lib/build/recipe/dashboard/utils.d.ts b/lib/build/recipe/dashboard/utils.d.ts index dc6d04a43..61864bada 100644 --- a/lib/build/recipe/dashboard/utils.d.ts +++ b/lib/build/recipe/dashboard/utils.d.ts @@ -2,7 +2,7 @@ import { BaseResponse } from "../../framework"; import NormalisedURLPath from "../../normalisedURLPath"; import { HTTPMethod, NormalisedAppinfo } from "../../types"; -import { RecipeIdForUser, TypeInput, TypeNormalisedInput, RecipeLevelUser } from "./types"; +import { RecipeIdForUser, TypeInput, TypeNormalisedInput, RecipeLevelUserWithFirstAndLastName } from "./types"; export declare function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput; export declare function isApiPath(path: NormalisedURLPath, appInfo: NormalisedAppinfo): boolean; export declare function getApiIdIfMatched(path: NormalisedURLPath, method: HTTPMethod): string | undefined; @@ -12,7 +12,7 @@ export declare function getUserForRecipeId( userId: string, recipeId: string ): Promise<{ - user: RecipeLevelUser | undefined; + user: RecipeLevelUserWithFirstAndLastName | undefined; recipe: | "emailpassword" | "thirdparty" diff --git a/lib/build/recipe/dashboard/utils.js b/lib/build/recipe/dashboard/utils.js index 002811dff..5e574f3d7 100644 --- a/lib/build/recipe/dashboard/utils.js +++ b/lib/build/recipe/dashboard/utils.js @@ -54,12 +54,16 @@ exports.isRecipeInitialised = exports.getUserForRecipeId = exports.isValidRecipe const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); const utils_1 = require("../../utils"); const constants_1 = require("./constants"); -const supertokens_1 = __importDefault(require("../../supertokens")); -const recipe_1 = __importDefault(require("../emailpassword/recipe")); -const recipe_2 = __importDefault(require("../thirdparty/recipe")); -const recipe_3 = __importDefault(require("../passwordless/recipe")); -const recipe_4 = __importDefault(require("../thirdpartyemailpassword/recipe")); -const recipe_5 = __importDefault(require("../thirdpartypasswordless/recipe")); +const recipe_1 = __importDefault(require("../accountlinking/recipe")); +const recipe_2 = __importDefault(require("../emailpassword/recipe")); +const recipe_3 = __importDefault(require("../thirdparty/recipe")); +const recipe_4 = __importDefault(require("../passwordless/recipe")); +const recipe_5 = __importDefault(require("../thirdpartyemailpassword/recipe")); +const recipe_6 = __importDefault(require("../thirdpartypasswordless/recipe")); +const thirdparty_1 = __importDefault(require("../thirdparty")); +const passwordless_1 = __importDefault(require("../passwordless")); +const thirdpartyemailpassword_1 = __importDefault(require("../thirdpartyemailpassword")); +const thirdpartypasswordless_1 = __importDefault(require("../thirdpartypasswordless")); function validateAndNormaliseUserInput(config) { if (config.apiKey.trim().length === 0) { throw new Error("apiKey provided to Dashboard recipe cannot be empty"); @@ -146,7 +150,7 @@ function isValidRecipeId(recipeId) { exports.isValidRecipeId = isValidRecipeId; function getUserForRecipeId(userId, recipeId) { return __awaiter(this, void 0, void 0, function* () { - let userResponse = yield supertokens_1.default.getInstanceOrThrowError()._getUserForRecipeId(userId, recipeId); + let userResponse = yield _getUserForRecipeId(userId, recipeId); let user = undefined; if (userResponse.user !== undefined) { user = Object.assign(Object.assign({}, userResponse.user), { firstName: "", lastName: "" }); @@ -158,44 +162,154 @@ function getUserForRecipeId(userId, recipeId) { }); } exports.getUserForRecipeId = getUserForRecipeId; +function _getUserForRecipeId(userId, recipeId) { + return __awaiter(this, void 0, void 0, function* () { + let user; + let recipe; + const globalUser = yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ + userId, + userContext: {}, + }); + if (recipeId === recipe_2.default.RECIPE_ID) { + try { + // we detect if this recipe has been init or not.. + recipe_2.default.getInstanceOrThrowError(); + if (globalUser !== undefined) { + let loginMethod = globalUser.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); + recipe = "emailpassword"; + } + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + if ("loginMethods" in userResponse) { + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); + recipe = "thirdpartyemailpassword"; + } + } else { + throw new Error("Should never come here. TODO remove me"); + } + } + } catch (e) { + // No - op + } + } + } else if (recipeId === recipe_3.default.RECIPE_ID) { + try { + const userResponse = yield thirdparty_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdparty"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); + if (userResponse !== undefined) { + if ("loginMethods" in userResponse) { + throw new Error("Should never come here. TODO remove me"); + } else { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdpartyemailpassword"; + } + } + } catch (e) { + // No - op + } + } + if (user === undefined) { + try { + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === recipe_4.default.RECIPE_ID) { + try { + const userResponse = yield passwordless_1.default.getUserById({ + userId, + }); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); + recipe = "passwordless"; + } + } catch (e) { + // No - op + } + if (user === undefined) { + try { + const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); + if (userResponse !== undefined) { + user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } + return { + user, + recipe, + }; + }); +} function isRecipeInitialised(recipeId) { let isRecipeInitialised = false; if (recipeId === "emailpassword") { try { - recipe_1.default.getInstanceOrThrowError(); + recipe_2.default.getInstanceOrThrowError(); isRecipeInitialised = true; } catch (_) {} if (!isRecipeInitialised) { try { - recipe_4.default.getInstanceOrThrowError(); + recipe_5.default.getInstanceOrThrowError(); isRecipeInitialised = true; } catch (_) {} } } else if (recipeId === "passwordless") { try { - recipe_3.default.getInstanceOrThrowError(); + recipe_4.default.getInstanceOrThrowError(); isRecipeInitialised = true; } catch (_) {} if (!isRecipeInitialised) { try { - recipe_5.default.getInstanceOrThrowError(); + recipe_6.default.getInstanceOrThrowError(); isRecipeInitialised = true; } catch (_) {} } } else if (recipeId === "thirdparty") { try { - recipe_2.default.getInstanceOrThrowError(); + recipe_3.default.getInstanceOrThrowError(); isRecipeInitialised = true; } catch (_) {} if (!isRecipeInitialised) { try { - recipe_4.default.getInstanceOrThrowError(); + recipe_5.default.getInstanceOrThrowError(); isRecipeInitialised = true; } catch (_) {} } if (!isRecipeInitialised) { try { - recipe_5.default.getInstanceOrThrowError(); + recipe_6.default.getInstanceOrThrowError(); isRecipeInitialised = true; } catch (_) {} } diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index b3523f0f9..0cb2aa216 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -558,11 +558,14 @@ function getAPIImplementation() { } let user = response.user; let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + if (recipeUser === undefined) { + throw new Error("Race condition error - please call this API again"); + } let session = yield session_1.default.createNewSession( options.req, options.res, user.id, - recipeUser === null || recipeUser === void 0 ? void 0 : recipeUser.recipeUserId, + recipeUser.recipeUserId, {}, {}, userContext @@ -588,7 +591,8 @@ function getAPIImplementation() { if (!isSignUpAllowed) { return { status: "SIGNUP_NOT_ALLOWED", - reason: "the sign-up info is already associated with another account where it is not verified", + reason: + "The input email is already associated with another account where it is not verified. Please disable automatic account linking, or verify the other account before trying again.", }; } let response = yield options.recipeImplementation.signUp({ @@ -602,11 +606,14 @@ function getAPIImplementation() { } let user = response.user; let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + if (recipeUser === undefined) { + throw new Error("Race condition error - please call this API again"); + } let session = yield session_1.default.createNewSession( options.req, options.res, user.id, - recipeUser === null || recipeUser === void 0 ? void 0 : recipeUser.recipeUserId, + recipeUser.recipeUserId, {}, {}, userContext diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 331fa74fd..9844769ff 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -4,11 +4,10 @@ import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; export default class BackwardCompatibilityService implements EmailDeliveryInterface { - private recipeInterfaceImpl; private isInServerlessEnv; private appInfo; private resetPasswordUsingTokenFeature; - constructor(recipeInterfaceImpl: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean); + constructor(_: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean); sendEmail: ( input: TypeEmailPasswordEmailDeliveryInput & { userContext: any; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js index fe27486c1..ffb8a6093 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -32,59 +32,28 @@ var __awaiter = }; Object.defineProperty(exports, "__esModule", { value: true }); const passwordResetFunctions_1 = require("../../../passwordResetFunctions"); -const __1 = require("../../../../.."); class BackwardCompatibilityService { - constructor(recipeInterfaceImpl, appInfo, isInServerlessEnv) { + constructor(_, appInfo, isInServerlessEnv) { this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - let user = - input.user.recipeUserId !== undefined - ? yield this.recipeInterfaceImpl.getUserById({ - userId: input.user.recipeUserId, - userContext: input.userContext, - }) - : undefined; - if (input.user.recipeUserId === undefined) { - user = yield __1.getUser(input.user.id); - } - if (user === undefined) { - throw Error("this should never come here"); - } - let recipeLoginMethod = user.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.email === input.user.email - ); - if (recipeLoginMethod === undefined) { - throw Error("this should never come here"); - } // we add this here cause the user may have overridden the sendEmail function // to change the input email and if we don't do this, the input email // will get reset by the getUserById call above. - let passwordResetEmailUser = { - id: input.user.id, - recipeUserId: recipeLoginMethod.recipeUserId, - email: input.user.email, - timeJoined: recipeLoginMethod.timeJoined, - }; try { if (!this.isInServerlessEnv) { this.resetPasswordUsingTokenFeature - .createAndSendCustomEmail( - passwordResetEmailUser, - input.passwordResetLink, - input.userContext - ) + .createAndSendCustomEmail(input.user, input.passwordResetLink, input.userContext) .catch((_) => {}); } else { // see https://github.com/supertokens/supertokens-node/pull/135 yield this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( - passwordResetEmailUser, + input.user, input.passwordResetLink, input.userContext ); } } catch (_) {} }); - this.recipeInterfaceImpl = recipeInterfaceImpl; this.isInServerlessEnv = isInServerlessEnv; this.appInfo = appInfo; { diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index c0ce6423b..ce91f4221 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -7,7 +7,6 @@ export declare function createAndSendCustomEmail( id: string; recipeUserId?: string; email: string; - timeJoined: number; }, passwordResetURLWithToken: string ) => Promise; diff --git a/lib/build/recipe/emailpassword/recipe.js b/lib/build/recipe/emailpassword/recipe.js index 879c92946..4fdf2a02c 100644 --- a/lib/build/recipe/emailpassword/recipe.js +++ b/lib/build/recipe/emailpassword/recipe.js @@ -170,7 +170,10 @@ class Recipe extends recipeModule_1.default { let recipeLevelUser = user.loginMethods.find( (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId ); - if (recipeLevelUser !== undefined && recipeLevelUser.email !== undefined) { + if (recipeLevelUser !== undefined) { + if (recipeLevelUser.email === undefined) { + throw new Error("Should never come here"); + } return { status: "OK", email: recipeLevelUser.email, diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 6035bda5a..8bdf79f64 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -4,7 +4,6 @@ import RecipeModule from "./recipeModule"; import NormalisedURLPath from "./normalisedURLPath"; import { BaseRequest, BaseResponse } from "./framework"; import { TypeFramework } from "./framework/types"; -import { RecipeLevelUser } from "./recipe/accountlinking/types"; export default class SuperTokens { private static instance; framework: TypeFramework; @@ -73,17 +72,4 @@ export default class SuperTokens { }>; middleware: (request: BaseRequest, response: BaseResponse) => Promise; errorHandler: (err: any, request: BaseRequest, response: BaseResponse) => Promise; - _getUserForRecipeId: ( - userId: string, - recipeId: string - ) => Promise<{ - user: RecipeLevelUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; - }>; } diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index 084450cdb..8b7d1c904 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -60,14 +60,6 @@ const error_1 = __importDefault(require("./error")); const logger_1 = require("./logger"); const postSuperTokensInitCallbacks_1 = require("./postSuperTokensInitCallbacks"); const recipe_1 = __importDefault(require("./recipe/accountlinking/recipe")); -const recipe_2 = __importDefault(require("./recipe/emailpassword/recipe")); -const recipe_3 = __importDefault(require("./recipe/thirdparty/recipe")); -const recipe_4 = __importDefault(require("./recipe/passwordless/recipe")); -const emailpassword_1 = __importDefault(require("./recipe/emailpassword")); -const thirdparty_1 = __importDefault(require("./recipe/thirdparty")); -const passwordless_1 = __importDefault(require("./recipe/passwordless")); -const thirdpartyemailpassword_1 = __importDefault(require("./recipe/thirdpartyemailpassword")); -const thirdpartypasswordless_1 = __importDefault(require("./recipe/thirdpartypasswordless")); class SuperTokens { constructor(config) { var _a, _b; @@ -308,126 +300,6 @@ class SuperTokens { } throw err; }); - // this is an internal use function, therefore it is prefixed with an `_` - this._getUserForRecipeId = (userId, recipeId) => - __awaiter(this, void 0, void 0, function* () { - let user; - let recipe; - if (recipeId === recipe_2.default.RECIPE_ID) { - try { - const userResponse = yield emailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); - recipe = "emailpassword"; - } - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = Object.assign(Object.assign({}, loginMethod), { - recipeId: "emailpassword", - }); - recipe = "thirdpartyemailpassword"; - } - } else { - user = Object.assign(Object.assign({}, userResponse), { - recipeId: "emailpassword", - }); - recipe = "thirdpartyemailpassword"; - } - } - } catch (e) { - // No - op - } - } - } else if (recipeId === recipe_3.default.RECIPE_ID) { - try { - const userResponse = yield thirdparty_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdparty"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "thirdparty" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = Object.assign(Object.assign({}, loginMethod), { - recipeId: "thirdparty", - }); - recipe = "thirdpartyemailpassword"; - } - } else { - user = Object.assign(Object.assign({}, userResponse), { - recipeId: "emailpassword", - }); - recipe = "thirdpartyemailpassword"; - } - } - } catch (e) { - // No - op - } - } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === recipe_4.default.RECIPE_ID) { - try { - const userResponse = yield passwordless_1.default.getUserById({ - userId, - }); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); - recipe = "passwordless"; - } - } catch (e) { - // No - op - } - if (user === undefined) { - try { - const userResponse = yield thirdpartypasswordless_1.default.getUserById(userId); - if (userResponse !== undefined) { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } - return { - user, - recipe, - }; - }); logger_1.logDebugMessage("Started SuperTokens with debug logging (supertokens.init called)"); logger_1.logDebugMessage("appInfo: " + JSON.stringify(config.appInfo)); this.framework = config.framework !== undefined ? config.framework : "express"; diff --git a/lib/ts/recipe/dashboard/api/userdetails/userGet.ts b/lib/ts/recipe/dashboard/api/userdetails/userGet.ts index ec17cb14e..372b797f3 100644 --- a/lib/ts/recipe/dashboard/api/userdetails/userGet.ts +++ b/lib/ts/recipe/dashboard/api/userdetails/userGet.ts @@ -1,4 +1,4 @@ -import { APIFunction, APIInterface, APIOptions, RecipeLevelUser } from "../../types"; +import { APIFunction, APIInterface, APIOptions, RecipeLevelUserWithFirstAndLastName } from "../../types"; import STError from "../../../../error"; import { getUserForRecipeId, isRecipeInitialised, isValidRecipeId } from "../../utils"; import UserMetaDataRecipe from "../../../usermetadata/recipe"; @@ -14,7 +14,7 @@ type Response = | { status: "OK"; recipeId: "emailpassword" | "thirdparty" | "passwordless"; - user: RecipeLevelUser; + user: RecipeLevelUserWithFirstAndLastName; }; export const userGet: APIFunction = async (_: APIInterface, options: APIOptions): Promise => { @@ -48,7 +48,7 @@ export const userGet: APIFunction = async (_: APIInterface, options: APIOptions) }; } - let user: RecipeLevelUser | undefined = (await getUserForRecipeId(userId, recipeId)).user; + let user: RecipeLevelUserWithFirstAndLastName | undefined = (await getUserForRecipeId(userId, recipeId)).user; if (user === undefined) { return { diff --git a/lib/ts/recipe/dashboard/types.ts b/lib/ts/recipe/dashboard/types.ts index 28dd4980f..ac1b7598b 100644 --- a/lib/ts/recipe/dashboard/types.ts +++ b/lib/ts/recipe/dashboard/types.ts @@ -72,6 +72,18 @@ export type RecipeLevelUser = { id: string; userId: string; }; +}; + +export type RecipeLevelUserWithFirstAndLastName = { + recipeId: "emailpassword" | "thirdparty" | "passwordless"; + timeJoined: number; + recipeUserId: string; + email?: string; + phoneNumber?: string; + thirdParty?: { + id: string; + userId: string; + }; firstName: string; lastName: string; }; diff --git a/lib/ts/recipe/dashboard/utils.ts b/lib/ts/recipe/dashboard/utils.ts index aed08ba25..992cf25d4 100644 --- a/lib/ts/recipe/dashboard/utils.ts +++ b/lib/ts/recipe/dashboard/utils.ts @@ -36,13 +36,18 @@ import { TypeInput, TypeNormalisedInput, RecipeLevelUser, + RecipeLevelUserWithFirstAndLastName, } from "./types"; -import Supertokens from "../../supertokens"; +import AccountLinking from "../accountlinking/recipe"; import EmailPasswordRecipe from "../emailpassword/recipe"; import ThirdPartyRecipe from "../thirdparty/recipe"; import PasswordlessRecipe from "../passwordless/recipe"; import ThirdPartyEmailPasswordRecipe from "../thirdpartyemailpassword/recipe"; import ThirdPartyPasswordlessRecipe from "../thirdpartypasswordless/recipe"; +import ThirdParty from "../thirdparty"; +import Passwordless from "../passwordless"; +import ThirdPartyEmailPassword from "../thirdpartyemailpassword"; +import ThirdPartyPasswordless from "../thirdpartypasswordless"; export function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput { if (config.apiKey.trim().length === 0) { @@ -144,7 +149,7 @@ export async function getUserForRecipeId( userId: string, recipeId: string ): Promise<{ - user: RecipeLevelUser | undefined; + user: RecipeLevelUserWithFirstAndLastName | undefined; recipe: | "emailpassword" | "thirdparty" @@ -153,8 +158,8 @@ export async function getUserForRecipeId( | "thirdpartypasswordless" | undefined; }> { - let userResponse = await Supertokens.getInstanceOrThrowError()._getUserForRecipeId(userId, recipeId); - let user: RecipeLevelUser | undefined = undefined; + let userResponse = await _getUserForRecipeId(userId, recipeId); + let user: RecipeLevelUserWithFirstAndLastName | undefined = undefined; if (userResponse.user !== undefined) { user = { ...userResponse.user, @@ -168,6 +173,167 @@ export async function getUserForRecipeId( }; } +async function _getUserForRecipeId( + userId: string, + recipeId: string +): Promise<{ + user: RecipeLevelUser | undefined; + recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; +}> { + let user: RecipeLevelUser | undefined; + let recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; + + const globalUser = await AccountLinking.getInstanceOrThrowError().recipeInterfaceImpl.getUser({ + userId, + userContext: {}, + }); + + if (recipeId === EmailPasswordRecipe.RECIPE_ID) { + try { + // we detect if this recipe has been init or not.. + EmailPasswordRecipe.getInstanceOrThrowError(); + if (globalUser !== undefined) { + let loginMethod = globalUser.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = { + ...loginMethod, + recipeId: "emailpassword", + }; + recipe = "emailpassword"; + } + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyEmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + if ("loginMethods" in userResponse) { + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = { + ...loginMethod, + recipeId: "emailpassword", + }; + recipe = "thirdpartyemailpassword"; + } + } else { + throw new Error("Should never come here. TODO remove me"); + } + } + } catch (e) { + // No - op + } + } + } else if (recipeId === ThirdPartyRecipe.RECIPE_ID) { + try { + const userResponse = await ThirdParty.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdparty"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyEmailPassword.getUserById(userId); + + if (userResponse !== undefined) { + if ("loginMethods" in userResponse) { + throw new Error("Should never come here. TODO remove me"); + } else { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdpartyemailpassword"; + } + } + } catch (e) { + // No - op + } + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyPasswordless.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "thirdparty", + }; + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } else if (recipeId === PasswordlessRecipe.RECIPE_ID) { + try { + const userResponse = await Passwordless.getUserById({ + userId, + }); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "passwordless", + }; + recipe = "passwordless"; + } + } catch (e) { + // No - op + } + + if (user === undefined) { + try { + const userResponse = await ThirdPartyPasswordless.getUserById(userId); + + if (userResponse !== undefined) { + user = { + ...userResponse, + recipeId: "passwordless", + }; + recipe = "thirdpartypasswordless"; + } + } catch (e) { + // No - op + } + } + } + + return { + user, + recipe, + }; +} + export function isRecipeInitialised(recipeId: RecipeIdForUser): boolean { let isRecipeInitialised = false; diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 59426ec9d..f639b8cf0 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -585,11 +585,16 @@ export default function getAPIImplementation(): APIInterface { let user = response.user; let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + + if (recipeUser === undefined) { + throw new Error("Should never come here"); + } + let session = await Session.createNewSession( options.req, options.res, user.id, - recipeUser?.recipeUserId, + recipeUser.recipeUserId, {}, {}, userContext @@ -642,7 +647,8 @@ export default function getAPIImplementation(): APIInterface { if (!isSignUpAllowed) { return { status: "SIGNUP_NOT_ALLOWED", - reason: "the sign-up info is already associated with another account where it is not verified", + reason: + "The input email is already associated with another account where it is not verified. Please disable automatic account linking, or verify the other account before trying again.", }; } let response = await options.recipeImplementation.signUp({ @@ -657,11 +663,15 @@ export default function getAPIImplementation(): APIInterface { let user = response.user; let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + if (recipeUser === undefined) { + throw new Error("Race condition error - please call this API again"); + } + let session = await Session.createNewSession( options.req, options.res, user.id, - recipeUser?.recipeUserId, + recipeUser.recipeUserId, {}, {}, userContext diff --git a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts index a36a24b05..74a0b3d22 100644 --- a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts +++ b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts @@ -14,13 +14,11 @@ */ import { TypeEmailPasswordEmailDeliveryInput, RecipeInterface } from "../../../types"; import { createAndSendCustomEmail as defaultCreateAndSendCustomEmail } from "../../../passwordResetFunctions"; -import { NormalisedAppinfo, User } from "../../../../../types"; +import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -import { getUser } from "../../../../.."; export default class BackwardCompatibilityService implements EmailDeliveryInterface { - private recipeInterfaceImpl: RecipeInterface; private isInServerlessEnv: boolean; private appInfo: NormalisedAppinfo; private resetPasswordUsingTokenFeature: { @@ -29,15 +27,13 @@ export default class BackwardCompatibilityService id: string; recipeUserId: string; email: string; - timeJoined: number; }, passwordResetURLWithToken: string, userContext: any ) => Promise; }; - constructor(recipeInterfaceImpl: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean) { - this.recipeInterfaceImpl = recipeInterfaceImpl; + constructor(_: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean) { this.isInServerlessEnv = isInServerlessEnv; this.appInfo = appInfo; { @@ -48,48 +44,18 @@ export default class BackwardCompatibilityService } sendEmail = async (input: TypeEmailPasswordEmailDeliveryInput & { userContext: any }) => { - let user: User | undefined = - input.user.recipeUserId !== undefined - ? await this.recipeInterfaceImpl.getUserById({ - userId: input.user.recipeUserId, - userContext: input.userContext, - }) - : undefined; - if (input.user.recipeUserId === undefined) { - user = await getUser(input.user.id); - } - if (user === undefined) { - throw Error("this should never come here"); - } - let recipeLoginMethod = user.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.email === input.user.email - ); - if (recipeLoginMethod === undefined) { - throw Error("this should never come here"); - } // we add this here cause the user may have overridden the sendEmail function // to change the input email and if we don't do this, the input email // will get reset by the getUserById call above. - let passwordResetEmailUser: { - id: string; - recipeUserId: string; - email: string; - timeJoined: number; - } = { - id: input.user.id, - recipeUserId: recipeLoginMethod.recipeUserId, - email: input.user.email, - timeJoined: recipeLoginMethod.timeJoined, - }; try { if (!this.isInServerlessEnv) { this.resetPasswordUsingTokenFeature - .createAndSendCustomEmail(passwordResetEmailUser, input.passwordResetLink, input.userContext) + .createAndSendCustomEmail(input.user, input.passwordResetLink, input.userContext) .catch((_) => {}); } else { // see https://github.com/supertokens/supertokens-node/pull/135 await this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( - passwordResetEmailUser, + input.user, input.passwordResetLink, input.userContext ); diff --git a/lib/ts/recipe/emailpassword/passwordResetFunctions.ts b/lib/ts/recipe/emailpassword/passwordResetFunctions.ts index c620afea5..195d82732 100644 --- a/lib/ts/recipe/emailpassword/passwordResetFunctions.ts +++ b/lib/ts/recipe/emailpassword/passwordResetFunctions.ts @@ -23,7 +23,6 @@ export function createAndSendCustomEmail(appInfo: NormalisedAppinfo) { id: string; recipeUserId?: string; email: string; - timeJoined: number; }, passwordResetURLWithToken: string ) => { diff --git a/lib/ts/recipe/emailpassword/recipe.ts b/lib/ts/recipe/emailpassword/recipe.ts index 8b6d6b16c..802680b7e 100644 --- a/lib/ts/recipe/emailpassword/recipe.ts +++ b/lib/ts/recipe/emailpassword/recipe.ts @@ -229,7 +229,10 @@ export default class Recipe extends RecipeModule { let recipeLevelUser = user.loginMethods.find( (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId ); - if (recipeLevelUser !== undefined && recipeLevelUser.email !== undefined) { + if (recipeLevelUser !== undefined) { + if (recipeLevelUser.email === undefined) { + throw new Error("Should never come here"); + } return { status: "OK", email: recipeLevelUser.email, diff --git a/lib/ts/supertokens.ts b/lib/ts/supertokens.ts index c03b346c9..19fbb59dc 100644 --- a/lib/ts/supertokens.ts +++ b/lib/ts/supertokens.ts @@ -33,15 +33,6 @@ import STError from "./error"; import { logDebugMessage } from "./logger"; import { PostSuperTokensInitCallbacks } from "./postSuperTokensInitCallbacks"; import AccountLinking from "./recipe/accountlinking/recipe"; -import { RecipeLevelUser } from "./recipe/accountlinking/types"; -import EmailPasswordRecipe from "./recipe/emailpassword/recipe"; -import ThirdPartyRecipe from "./recipe/thirdparty/recipe"; -import PasswordlessRecipe from "./recipe/passwordless/recipe"; -import EmailPassword from "./recipe/emailpassword"; -import ThirdParty from "./recipe/thirdparty"; -import Passwordless from "./recipe/passwordless"; -import ThirdPartyEmailPassword from "./recipe/thirdpartyemailpassword"; -import ThirdPartyPasswordless from "./recipe/thirdpartypasswordless"; export default class SuperTokens { private static instance: SuperTokens | undefined; @@ -405,174 +396,4 @@ export default class SuperTokens { } throw err; }; - - // this is an internal use function, therefore it is prefixed with an `_` - _getUserForRecipeId = async ( - userId: string, - recipeId: string - ): Promise<{ - user: RecipeLevelUser | undefined; - recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; - }> => { - let user: RecipeLevelUser | undefined; - let recipe: - | "emailpassword" - | "thirdparty" - | "passwordless" - | "thirdpartyemailpassword" - | "thirdpartypasswordless" - | undefined; - - if (recipeId === EmailPasswordRecipe.RECIPE_ID) { - try { - const userResponse = await EmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = { - ...loginMethod, - recipeId: "emailpassword", - }; - recipe = "emailpassword"; - } - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = { - ...loginMethod, - recipeId: "emailpassword", - }; - recipe = "thirdpartyemailpassword"; - } - } else { - user = { - ...userResponse, - recipeId: "emailpassword", - }; - recipe = "thirdpartyemailpassword"; - } - } - } catch (e) { - // No - op - } - } - } else if (recipeId === ThirdPartyRecipe.RECIPE_ID) { - try { - const userResponse = await ThirdParty.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "thirdparty", - }; - recipe = "thirdparty"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "thirdparty" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = { - ...loginMethod, - recipeId: "thirdparty", - }; - recipe = "thirdpartyemailpassword"; - } - } else { - user = { - ...userResponse, - recipeId: "emailpassword", - }; - recipe = "thirdpartyemailpassword"; - } - } - } catch (e) { - // No - op - } - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyPasswordless.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "thirdparty", - }; - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } else if (recipeId === PasswordlessRecipe.RECIPE_ID) { - try { - const userResponse = await Passwordless.getUserById({ - userId, - }); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "passwordless", - }; - recipe = "passwordless"; - } - } catch (e) { - // No - op - } - - if (user === undefined) { - try { - const userResponse = await ThirdPartyPasswordless.getUserById(userId); - - if (userResponse !== undefined) { - user = { - ...userResponse, - recipeId: "passwordless", - }; - recipe = "thirdpartypasswordless"; - } - } catch (e) { - // No - op - } - } - } - - return { - user, - recipe, - }; - }; } From 6866314b7f9a67fcea92bbd5a1d45f1c0994e168 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 18:19:33 +0530 Subject: [PATCH 66/82] more fixes - ts still not compiling --- .../emailpassword/recipeImplementation.ts | 183 +++-------- lib/ts/recipe/emailpassword/types.ts | 309 ++++++++---------- 2 files changed, 194 insertions(+), 298 deletions(-) diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index 787d661ce..5ccf9b81c 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -2,55 +2,57 @@ import { RecipeInterface } from "./types"; import AccountLinking from "../accountlinking/recipe"; import { Querier } from "../../querier"; import NormalisedURLPath from "../../normalisedURLPath"; -import { getUser, listUsersByAccountInfo } from "../.."; -import EmailVerification from "../emailverification/recipe"; +import { getUser } from "../.."; import { User } from "../../types"; export default function getRecipeInterface(querier: Querier): RecipeInterface { return { - signUp: async function ({ + signUp: async function (this: RecipeInterface, { email, password, - doAccountLinking, userContext, }: { email: string; password: string; - doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; createdNewUser: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { - let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { - email, - password, + }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + // this function does not check if there is some primary user where the email + // of that primary user is unverified (isSignUpAllowed function logic) cause + // that is checked in the API layer before calling this function. + // This is the recipe function layer which can be + // called by the user manually as well if they want to. So we allow them to do that. + let response = await this.createNewRecipeUser({ + email, password, userContext }); - if (response.status === "OK") { - let createdNewUser = true; - if (doAccountLinking) { - let primaryUserId = await AccountLinking.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations( - { - newUser: { - email, - recipeId: "emailpassword", - }, - newUserVerified: false, - recipeUserId: response.user.id, - userContext, - } - ); - if (response.user.id !== primaryUserId) { - createdNewUser = false; - } - response.user.id = primaryUserId; - } - return { - ...response, - createdNewUser, - }; - } else { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; + if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { + return response; } + + let userId = await AccountLinking.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + // we can use index 0 cause this is a new recipe user + recipeUserId: response.user.loginMethods[0].recipeUserId, + checkAccountsToLinkTableAsWell: true, + isVerified: false, + userContext, + }); + + return { + status: "OK", + user: (await getUser(userId, userContext))! + }; + }, + + createNewRecipeUser: async function (input: { + email: string; + password: string; + userContext: any; + }): Promise<{ + status: "OK"; user: User + } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + return await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { + email: input.email, + password: input.password, + }); }, signIn: async function ({ @@ -73,32 +75,6 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { } }, - getUserById: async function ({ userId }: { userId: string }): Promise { - let response = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { - userId, - }); - if (response.status === "OK") { - return { - ...response.user, - }; - } else { - return undefined; - } - }, - - getUserByEmail: async function ({ email }: { email: string }): Promise { - let response = await querier.sendGetRequest(new NormalisedURLPath("/recipe/user"), { - email, - }); - if (response.status === "OK") { - return { - ...response.user, - }; - } else { - return undefined; - } - }, - createResetPasswordToken: async function ({ userId, email, @@ -106,6 +82,7 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { userId: string; email: string; }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }> { + // the input user ID can be a recipe or a primary user ID. let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/user/password/reset/token"), { userId, email, @@ -122,26 +99,21 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { } }, - resetPasswordUsingToken: async function ({ + consumePasswordResetToken: async function ({ token, - newPassword, }: { token: string; - newPassword: string; }): Promise< | { - status: "OK"; - userId: string; - email: string; - } + status: "OK"; + userId: string; + email: string; + } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } > { - let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/user/password/reset"), { - method: "token", + return await querier.sendPostRequest(new NormalisedURLPath("/recipe/user/password/reset/token/consume"), { token, - newPassword, }); - return response; }, updateEmailOrPassword: async function (input: { @@ -150,68 +122,19 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { password?: string; }): Promise<{ status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR"; + } | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR", + reason: string }> { - let markEmailAsVerified = false; - if (input.email !== undefined) { - let userForUserId = await getUser(input.userId); - if (userForUserId !== undefined && userForUserId.isPrimaryUser) { - let usersForEmail = await listUsersByAccountInfo({ - email: input.email, - }); - if (usersForEmail !== undefined) { - let primaryUserFromEmailUsers = usersForEmail.find((u) => u.isPrimaryUser); - if (primaryUserFromEmailUsers !== undefined) { - if (primaryUserFromEmailUsers.id !== userForUserId.id) { - return { - status: "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING", - }; - } - markEmailAsVerified = true; - } - } - } - } - let response = await querier.sendPutRequest(new NormalisedURLPath("/recipe/user"), { + // the input can be primary or recipe level user id. + return await querier.sendPutRequest(new NormalisedURLPath("/recipe/user"), { userId: input.userId, email: input.email, password: input.password, }); - if (response.status === "OK") { - if (markEmailAsVerified && input.email !== undefined) { - const emailVerificationInstance = EmailVerification.getInstance(); - if (emailVerificationInstance) { - const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: input.userId, - email: input.email, - userContext: undefined, - } - ); - - if (tokenResponse.status === "OK") { - await emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ - token: tokenResponse.token, - userContext: undefined, - }); - } - } - } - return { - status: "OK", - }; - } else if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } else { - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - } }, }; } diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index 9ee6fa1d7..4fa1aa8f7 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -87,20 +87,20 @@ export type RecipeInterface = { signUp(input: { email: string; password: string; - /** - * we now do account-linking in the recipe implementation of - * this function. If someone wants to call this function - * manually and wants the any other account with the same email - * to be linked automatically, all they need to do is pass this - * boolean. If the user doesn't want to do automatic account linking - * while calling this function, they can pass false. Default value - * of the parameter would be false. So if we are moving the account - * linking part to be part of this function, ideally we should keep - * this boolean parameter - */ - doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; createdNewUser: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise<{ + status: "OK"; + user: User + } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + + // this function is meant only for creating the recipe in the core and nothing else. + createNewRecipeUser(input: { + email: string; + password: string; + userContext: any; + }): Promise<{ + status: "OK"; user: User + } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; signIn(input: { email: string; @@ -108,20 +108,10 @@ export type RecipeInterface = { userContext: any; }): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }>; - getUserById(input: { userId: string; userContext: any }): Promise; - - getUserByEmail(input: { email: string; userContext: any }): Promise; - /** - * We do not make email optional here cause we want to - * allow passing in primaryUserId. If we make email optional, - * and if the user provides a primaryUserId, then it may result in two problems: - * - there is no recipeUserId = input primaryUserId, in this case, - * this function will throw an error - * - There is a recipe userId = input primaryUserId, but that recipe has no email, - * or has wrong email compared to what the user wanted to generate a reset token for. - * - * And we want to allow primaryUserId being passed in. + * We pass in the email as well to this function cause the input userId + * may not be associated with an emailpassword account. In this case, we + * need to know which email to use to create an emailpassword account later on. */ createResetPasswordToken(input: { userId: string; // the id can be either recipeUserId or primaryUserId @@ -129,16 +119,15 @@ export type RecipeInterface = { userContext: any; }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>; - resetPasswordUsingToken(input: { + consumePasswordResetToken(input: { token: string; - newPassword: string; userContext: any; }): Promise< | { - status: "OK"; - email: string; - userId: string; - } + status: "OK"; + email: string; + userId: string; + } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } >; @@ -149,10 +138,12 @@ export type RecipeInterface = { userContext: any; }): Promise<{ status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + } | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR", + reason: string }>; }; @@ -169,154 +160,136 @@ export type APIOptions = { export type APIInterface = { emailExistsGET: - | undefined - | ((input: { - email: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + email: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >); generatePasswordResetTokenPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - } - | { - status: "PASSWORD_RESET_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + } + | { + status: "PASSWORD_RESET_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); passwordResetPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + | GeneralErrorResponse + >); signInPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + | GeneralErrorResponse + >); signUpPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewUser: boolean; - session: SessionContainerInterface; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); linkAccountToExistingAccountPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } - | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } + | { + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | GeneralErrorResponse + >); }; export type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; user: { id: string; - recipeUserId: string; email: string; }; passwordResetLink: string; From abebdb47464964a3ace42258dd6e4e8f83c0e004 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 18:41:37 +0530 Subject: [PATCH 67/82] more fixes - ts still not compiling --- lib/build/error.d.ts | 22 +- lib/build/framework/awsLambda/framework.d.ts | 23 +- lib/build/framework/awsLambda/framework.js | 205 +++-- lib/build/framework/awsLambda/index.d.ts | 4 +- lib/build/framework/express/framework.d.ts | 11 +- lib/build/framework/express/framework.js | 152 ++-- lib/build/framework/express/index.d.ts | 13 +- lib/build/framework/fastify/framework.d.ts | 11 +- lib/build/framework/fastify/framework.js | 118 ++- lib/build/framework/fastify/index.d.ts | 16 +- lib/build/framework/hapi/framework.d.ts | 18 +- lib/build/framework/hapi/framework.js | 151 ++-- lib/build/framework/index.js | 69 +- lib/build/framework/koa/framework.d.ts | 11 +- lib/build/framework/koa/framework.js | 109 ++- lib/build/framework/loopback/framework.d.ts | 11 +- lib/build/framework/loopback/framework.js | 118 ++- lib/build/framework/response.d.ts | 11 +- lib/build/framework/utils.d.ts | 53 +- lib/build/framework/utils.js | 95 ++- lib/build/index.d.ts | 42 +- lib/build/index.js | 60 +- lib/build/ingredients/emaildelivery/index.js | 8 +- .../emaildelivery/services/smtp.d.ts | 8 +- .../ingredients/emaildelivery/types.d.ts | 18 +- lib/build/ingredients/smsdelivery/index.js | 8 +- .../smsdelivery/services/twilio.d.ts | 45 +- .../smsdelivery/services/twilio.js | 9 +- lib/build/ingredients/smsdelivery/types.d.ts | 18 +- lib/build/logger.js | 14 +- lib/build/nextjs.d.ts | 6 +- lib/build/nextjs.js | 81 +- lib/build/normalisedURLDomain.js | 18 +- lib/build/normalisedURLPath.js | 18 +- lib/build/processState.d.ts | 2 +- lib/build/processState.js | 86 +- lib/build/querier.d.ts | 11 +- lib/build/querier.js | 382 +++++---- lib/build/recipe/accountlinking/index.d.ts | 170 ++-- lib/build/recipe/accountlinking/index.js | 68 +- lib/build/recipe/accountlinking/recipe.d.ts | 52 +- lib/build/recipe/accountlinking/recipe.js | 768 ++++++++++-------- .../accountlinking/recipeImplementation.js | 176 ++-- lib/build/recipe/accountlinking/types.d.ts | 199 +++-- lib/build/recipe/accountlinking/utils.js | 45 +- .../recipe/dashboard/api/apiKeyProtector.d.ts | 6 +- .../recipe/dashboard/api/apiKeyProtector.js | 40 +- lib/build/recipe/dashboard/api/dashboard.js | 40 +- .../recipe/dashboard/api/implementation.js | 55 +- .../dashboard/api/userdetails/userDelete.js | 86 +- .../api/userdetails/userEmailVerifyGet.js | 90 +- .../api/userdetails/userEmailVerifyPut.js | 116 +-- .../userdetails/userEmailVerifyTokenPost.js | 113 ++- .../dashboard/api/userdetails/userGet.js | 146 ++-- .../api/userdetails/userMetadataGet.js | 88 +- .../api/userdetails/userMetadataPut.js | 150 ++-- .../api/userdetails/userPasswordPut.d.ts | 19 +- .../api/userdetails/userPasswordPut.js | 173 ++-- .../dashboard/api/userdetails/userPut.d.ts | 31 +- .../dashboard/api/userdetails/userPut.js | 594 +++++++------- .../api/userdetails/userSessionsGet.js | 114 ++- .../api/userdetails/userSessionsPost.js | 77 +- .../recipe/dashboard/api/usersCountGet.js | 48 +- lib/build/recipe/dashboard/api/usersGet.js | 101 ++- lib/build/recipe/dashboard/api/validateKey.js | 43 +- lib/build/recipe/dashboard/index.js | 11 +- lib/build/recipe/dashboard/recipe.d.ts | 8 +- lib/build/recipe/dashboard/recipe.js | 196 +++-- .../recipe/dashboard/recipeImplementation.js | 45 +- lib/build/recipe/dashboard/types.d.ts | 25 +- lib/build/recipe/dashboard/utils.d.ts | 13 +- lib/build/recipe/dashboard/utils.js | 128 +-- .../recipe/emailpassword/api/emailExists.js | 48 +- .../api/generatePasswordResetToken.d.ts | 5 +- .../api/generatePasswordResetToken.js | 45 +- .../emailpassword/api/implementation.js | 318 +++++--- .../api/linkAccountToExistingAccount.d.ts | 5 +- .../api/linkAccountToExistingAccount.js | 66 +- .../recipe/emailpassword/api/passwordReset.js | 66 +- lib/build/recipe/emailpassword/api/signin.js | 48 +- lib/build/recipe/emailpassword/api/signup.js | 59 +- lib/build/recipe/emailpassword/api/utils.d.ts | 13 +- lib/build/recipe/emailpassword/api/utils.js | 51 +- .../services/backwardCompatibility/index.d.ts | 11 +- .../services/backwardCompatibility/index.js | 77 +- .../emaildelivery/services/index.js | 8 +- .../emaildelivery/services/smtp/index.d.ts | 8 +- .../emaildelivery/services/smtp/index.js | 63 +- .../services/smtp/passwordReset.d.ts | 4 +- .../services/smtp/passwordReset.js | 8 +- .../smtp/serviceImplementation/index.d.ts | 11 +- .../smtp/serviceImplementation/index.js | 51 +- lib/build/recipe/emailpassword/error.d.ts | 26 +- lib/build/recipe/emailpassword/error.js | 8 +- lib/build/recipe/emailpassword/index.d.ts | 95 ++- lib/build/recipe/emailpassword/index.js | 56 +- .../emailpassword/passwordResetFunctions.d.ts | 15 +- .../emailpassword/passwordResetFunctions.js | 134 +-- lib/build/recipe/emailpassword/recipe.d.ts | 20 +- lib/build/recipe/emailpassword/recipe.js | 180 ++-- .../emailpassword/recipeImplementation.js | 133 +-- lib/build/recipe/emailpassword/types.d.ts | 335 ++++---- lib/build/recipe/emailpassword/utils.d.ts | 21 +- lib/build/recipe/emailpassword/utils.js | 127 ++- .../emailverification/api/emailVerify.js | 68 +- .../api/generateEmailVerifyToken.d.ts | 5 +- .../api/generateEmailVerifyToken.js | 55 +- .../emailverification/api/implementation.js | 93 ++- .../emailVerificationClaim.js | 83 +- .../emailVerificationFunctions.d.ts | 4 +- .../emailVerificationFunctions.js | 132 +-- .../services/backwardCompatibility/index.d.ts | 21 +- .../services/backwardCompatibility/index.js | 67 +- .../emaildelivery/services/index.js | 8 +- .../services/smtp/emailVerify.js | 8 +- .../emaildelivery/services/smtp/index.d.ts | 8 +- .../emaildelivery/services/smtp/index.js | 63 +- .../services/smtp/serviceImplementation.d.ts | 11 +- .../services/smtp/serviceImplementation.js | 51 +- lib/build/recipe/emailverification/error.d.ts | 5 +- lib/build/recipe/emailverification/error.js | 8 +- lib/build/recipe/emailverification/index.d.ts | 57 +- lib/build/recipe/emailverification/index.js | 83 +- .../recipe/emailverification/recipe.d.ts | 20 +- lib/build/recipe/emailverification/recipe.js | 147 ++-- .../emailverification/recipeImplementation.js | 102 ++- lib/build/recipe/emailverification/types.d.ts | 177 ++-- lib/build/recipe/emailverification/utils.d.ts | 6 +- lib/build/recipe/emailverification/utils.js | 33 +- lib/build/recipe/jwt/api/getJWKS.js | 43 +- lib/build/recipe/jwt/api/implementation.js | 42 +- lib/build/recipe/jwt/index.d.ts | 23 +- lib/build/recipe/jwt/index.js | 48 +- lib/build/recipe/jwt/recipe.d.ts | 8 +- lib/build/recipe/jwt/recipe.js | 82 +- .../recipe/jwt/recipeImplementation.d.ts | 6 +- lib/build/recipe/jwt/recipeImplementation.js | 53 +- lib/build/recipe/jwt/types.d.ts | 44 +- lib/build/recipe/jwt/utils.d.ts | 6 +- lib/build/recipe/jwt/utils.js | 13 +- .../api/getOpenIdDiscoveryConfiguration.d.ts | 5 +- .../api/getOpenIdDiscoveryConfiguration.js | 43 +- lib/build/recipe/openid/api/implementation.js | 42 +- lib/build/recipe/openid/index.d.ts | 27 +- lib/build/recipe/openid/index.js | 8 +- lib/build/recipe/openid/recipe.d.ts | 8 +- lib/build/recipe/openid/recipe.js | 107 ++- .../recipe/openid/recipeImplementation.d.ts | 5 +- .../recipe/openid/recipeImplementation.js | 57 +- lib/build/recipe/openid/types.d.ts | 66 +- lib/build/recipe/openid/utils.d.ts | 5 +- lib/build/recipe/openid/utils.js | 16 +- .../recipe/passwordless/api/consumeCode.js | 81 +- .../recipe/passwordless/api/createCode.js | 71 +- .../recipe/passwordless/api/emailExists.js | 48 +- .../recipe/passwordless/api/implementation.js | 193 +++-- .../passwordless/api/phoneNumberExists.js | 48 +- .../recipe/passwordless/api/resendCode.js | 48 +- .../services/backwardCompatibility/index.d.ts | 31 +- .../services/backwardCompatibility/index.js | 180 ++-- .../emaildelivery/services/index.js | 8 +- .../emaildelivery/services/smtp/index.d.ts | 8 +- .../emaildelivery/services/smtp/index.js | 63 +- .../services/smtp/passwordlessLogin.d.ts | 8 +- .../services/smtp/passwordlessLogin.js | 31 +- .../services/smtp/serviceImplementation.d.ts | 11 +- .../services/smtp/serviceImplementation.js | 51 +- lib/build/recipe/passwordless/error.d.ts | 5 +- lib/build/recipe/passwordless/error.js | 8 +- lib/build/recipe/passwordless/index.d.ts | 195 +++-- lib/build/recipe/passwordless/index.js | 108 ++- lib/build/recipe/passwordless/recipe.d.ts | 58 +- lib/build/recipe/passwordless/recipe.js | 267 +++--- .../passwordless/recipeImplementation.js | 113 ++- .../services/backwardCompatibility/index.d.ts | 28 +- .../services/backwardCompatibility/index.js | 230 +++--- .../smsdelivery/services/index.js | 8 +- .../smsdelivery/services/supertokens/index.js | 146 ++-- .../smsdelivery/services/twilio/index.d.ts | 8 +- .../smsdelivery/services/twilio/index.js | 86 +- .../services/twilio/passwordlessLogin.js | 14 +- .../twilio/serviceImplementation.d.ts | 4 +- .../services/twilio/serviceImplementation.js | 51 +- lib/build/recipe/passwordless/types.d.ts | 530 ++++++------ lib/build/recipe/passwordless/utils.d.ts | 6 +- lib/build/recipe/passwordless/utils.js | 59 +- lib/build/recipe/session/accessToken.d.ts | 6 +- lib/build/recipe/session/accessToken.js | 60 +- .../recipe/session/api/implementation.js | 65 +- lib/build/recipe/session/api/refresh.js | 45 +- lib/build/recipe/session/api/signout.js | 40 +- .../session/claimBaseClasses/booleanClaim.js | 5 +- .../claimBaseClasses/primitiveArrayClaim.d.ts | 12 +- .../claimBaseClasses/primitiveArrayClaim.js | 314 ++++--- .../claimBaseClasses/primitiveClaim.d.ts | 12 +- .../claimBaseClasses/primitiveClaim.js | 108 ++- lib/build/recipe/session/claims.js | 28 +- .../recipe/session/cookieAndHeaders.d.ts | 37 +- lib/build/recipe/session/cookieAndHeaders.js | 21 +- lib/build/recipe/session/error.d.ts | 50 +- lib/build/recipe/session/error.js | 21 +- .../recipe/session/framework/awsLambda.js | 82 +- .../recipe/session/framework/express.d.ts | 4 +- lib/build/recipe/session/framework/express.js | 79 +- .../recipe/session/framework/fastify.d.ts | 4 +- lib/build/recipe/session/framework/fastify.js | 74 +- lib/build/recipe/session/framework/hapi.d.ts | 4 +- lib/build/recipe/session/framework/hapi.js | 63 +- lib/build/recipe/session/framework/index.js | 55 +- lib/build/recipe/session/framework/koa.d.ts | 4 +- lib/build/recipe/session/framework/koa.js | 63 +- .../recipe/session/framework/loopback.js | 65 +- lib/build/recipe/session/index.d.ts | 179 ++-- lib/build/recipe/session/index.js | 107 ++- lib/build/recipe/session/jwt.js | 87 +- lib/build/recipe/session/recipe.d.ts | 24 +- lib/build/recipe/session/recipe.js | 231 +++--- .../recipe/session/recipeImplementation.d.ts | 15 +- .../recipe/session/recipeImplementation.js | 435 +++++++--- lib/build/recipe/session/sessionClass.d.ts | 12 +- lib/build/recipe/session/sessionClass.js | 108 ++- .../recipe/session/sessionFunctions.d.ts | 42 +- lib/build/recipe/session/sessionFunctions.js | 175 ++-- lib/build/recipe/session/types.d.ts | 253 +++--- lib/build/recipe/session/types.js | 40 +- lib/build/recipe/session/utils.d.ts | 74 +- lib/build/recipe/session/utils.js | 195 +++-- lib/build/recipe/session/with-jwt/index.js | 8 +- .../with-jwt/recipeImplementation.d.ts | 6 +- .../session/with-jwt/recipeImplementation.js | 135 ++- .../recipe/session/with-jwt/sessionClass.d.ts | 12 +- .../recipe/session/with-jwt/sessionClass.js | 130 ++- lib/build/recipe/session/with-jwt/utils.d.ts | 9 +- lib/build/recipe/session/with-jwt/utils.js | 65 +- .../recipe/thirdparty/api/appleRedirect.js | 40 +- .../recipe/thirdparty/api/authorisationUrl.js | 48 +- .../recipe/thirdparty/api/implementation.js | 156 ++-- lib/build/recipe/thirdparty/api/signinup.js | 63 +- lib/build/recipe/thirdparty/error.d.ts | 5 +- lib/build/recipe/thirdparty/error.js | 8 +- lib/build/recipe/thirdparty/index.d.ts | 13 +- lib/build/recipe/thirdparty/index.js | 103 ++- .../recipe/thirdparty/providers/apple.js | 101 ++- .../recipe/thirdparty/providers/discord.js | 73 +- .../recipe/thirdparty/providers/facebook.js | 48 +- .../recipe/thirdparty/providers/github.js | 73 +- .../recipe/thirdparty/providers/google.js | 66 +- .../thirdparty/providers/googleWorkspaces.js | 71 +- .../recipe/thirdparty/providers/index.js | 8 +- .../recipe/thirdparty/providers/utils.d.ts | 6 +- .../recipe/thirdparty/providers/utils.js | 51 +- lib/build/recipe/thirdparty/recipe.d.ts | 17 +- lib/build/recipe/thirdparty/recipe.js | 139 ++-- .../recipe/thirdparty/recipeImplementation.js | 67 +- lib/build/recipe/thirdparty/types.d.ts | 187 +++-- lib/build/recipe/thirdparty/utils.d.ts | 11 +- lib/build/recipe/thirdparty/utils.js | 20 +- .../api/emailPasswordAPIImplementation.js | 28 +- .../api/implementation.js | 58 +- .../api/thirdPartyAPIImplementation.js | 122 ++- .../services/backwardCompatibility/index.d.ts | 17 +- .../services/backwardCompatibility/index.js | 65 +- .../emaildelivery/services/index.js | 8 +- .../emaildelivery/services/smtp/index.d.ts | 8 +- .../emaildelivery/services/smtp/index.js | 55 +- .../recipe/thirdpartyemailpassword/error.d.ts | 5 +- .../recipe/thirdpartyemailpassword/error.js | 8 +- .../recipe/thirdpartyemailpassword/index.d.ts | 108 ++- .../recipe/thirdpartyemailpassword/index.js | 111 ++- .../thirdpartyemailpassword/recipe.d.ts | 41 +- .../recipe/thirdpartyemailpassword/recipe.js | 221 +++-- .../emailPasswordRecipeImplementation.js | 40 +- .../recipeImplementation/index.js | 97 ++- .../thirdPartyRecipeImplementation.js | 40 +- .../recipe/thirdpartyemailpassword/types.d.ts | 505 +++++++----- .../recipe/thirdpartyemailpassword/utils.d.ts | 6 +- .../recipe/thirdpartyemailpassword/utils.js | 32 +- .../api/implementation.js | 58 +- .../api/passwordlessAPIImplementation.js | 24 +- .../api/thirdPartyAPIImplementation.js | 122 ++- .../services/backwardCompatibility/index.d.ts | 35 +- .../services/backwardCompatibility/index.js | 66 +- .../emaildelivery/services/index.js | 8 +- .../emaildelivery/services/smtp/index.d.ts | 8 +- .../emaildelivery/services/smtp/index.js | 63 +- .../smtp/serviceImplementation/index.d.ts | 11 +- .../smtp/serviceImplementation/index.js | 52 +- .../passwordlessServiceImplementation.d.ts | 4 +- .../passwordlessServiceImplementation.js | 40 +- .../recipe/thirdpartypasswordless/error.d.ts | 5 +- .../recipe/thirdpartypasswordless/error.js | 8 +- .../recipe/thirdpartypasswordless/index.d.ts | 193 +++-- .../recipe/thirdpartypasswordless/index.js | 163 ++-- .../recipe/thirdpartypasswordless/recipe.d.ts | 44 +- .../recipe/thirdpartypasswordless/recipe.js | 217 +++-- .../recipeImplementation/index.js | 123 ++- .../passwordlessRecipeImplementation.js | 40 +- .../thirdPartyRecipeImplementation.js | 40 +- .../services/backwardCompatibility/index.d.ts | 35 +- .../services/backwardCompatibility/index.js | 66 +- .../smsdelivery/services/index.js | 8 +- .../services/supertokens/index.d.ts | 8 +- .../smsdelivery/services/supertokens/index.js | 55 +- .../smsdelivery/services/twilio/index.d.ts | 8 +- .../smsdelivery/services/twilio/index.js | 55 +- .../recipe/thirdpartypasswordless/types.d.ts | 752 +++++++++-------- .../recipe/thirdpartypasswordless/utils.d.ts | 5 +- .../recipe/thirdpartypasswordless/utils.js | 56 +- lib/build/recipe/usermetadata/index.d.ts | 16 +- lib/build/recipe/usermetadata/index.js | 48 +- lib/build/recipe/usermetadata/recipe.d.ts | 8 +- lib/build/recipe/usermetadata/recipe.js | 66 +- .../usermetadata/recipeImplementation.js | 8 +- lib/build/recipe/usermetadata/types.d.ts | 10 +- lib/build/recipe/usermetadata/utils.d.ts | 6 +- lib/build/recipe/usermetadata/utils.js | 8 +- lib/build/recipe/userroles/index.d.ts | 105 ++- lib/build/recipe/userroles/index.js | 62 +- lib/build/recipe/userroles/permissionClaim.js | 48 +- lib/build/recipe/userroles/recipe.d.ts | 8 +- lib/build/recipe/userroles/recipe.js | 66 +- .../recipe/userroles/recipeImplementation.js | 13 +- lib/build/recipe/userroles/types.d.ts | 70 +- lib/build/recipe/userroles/userRoleClaim.js | 48 +- lib/build/recipe/userroles/utils.d.ts | 6 +- lib/build/recipe/userroles/utils.js | 14 +- lib/build/recipeModule.d.ts | 8 +- lib/build/recipeModule.js | 6 +- lib/build/supertokens.d.ts | 45 +- lib/build/supertokens.js | 371 +++++---- lib/build/utils.js | 107 ++- lib/ts/recipe/accountlinking/recipe.ts | 10 +- .../accountlinking/recipeImplementation.ts | 188 ++--- lib/ts/recipe/accountlinking/types.ts | 116 +-- .../emailpassword/recipeImplementation.ts | 76 +- lib/ts/recipe/emailpassword/types.ts | 275 ++++--- 336 files changed, 15504 insertions(+), 8372 deletions(-) diff --git a/lib/build/error.d.ts b/lib/build/error.d.ts index e41c53794..127b873e9 100644 --- a/lib/build/error.d.ts +++ b/lib/build/error.d.ts @@ -5,14 +5,18 @@ export default class SuperTokensError extends Error { payload: any; fromRecipe: string | undefined; private errMagic; - constructor(options: { - message: string; - payload?: any; - type: string; - } | { - message: string; - type: "BAD_INPUT_ERROR"; - payload: undefined; - }); + constructor( + options: + | { + message: string; + payload?: any; + type: string; + } + | { + message: string; + type: "BAD_INPUT_ERROR"; + payload: undefined; + } + ); static isErrorFromSuperTokens(obj: any): obj is SuperTokensError; } diff --git a/lib/build/framework/awsLambda/framework.d.ts b/lib/build/framework/awsLambda/framework.d.ts index 1264410e8..efd8915cd 100644 --- a/lib/build/framework/awsLambda/framework.d.ts +++ b/lib/build/framework/awsLambda/framework.d.ts @@ -1,4 +1,10 @@ -import type { APIGatewayProxyEventV2, APIGatewayProxyEvent, APIGatewayProxyResult, APIGatewayProxyStructuredResultV2, Handler } from "aws-lambda"; +import type { + APIGatewayProxyEventV2, + APIGatewayProxyEvent, + APIGatewayProxyResult, + APIGatewayProxyStructuredResultV2, + Handler, +} from "aws-lambda"; import { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; import { BaseResponse } from "../response"; @@ -51,13 +57,24 @@ export declare class AWSResponse extends BaseResponse { sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; removeHeader: (key: string) => void; - setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; + setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; /** * @param {number} statusCode */ setStatusCode: (statusCode: number) => void; sendJSONResponse: (content: any) => void; - sendResponse: (response?: APIGatewayProxyResult | APIGatewayProxyStructuredResultV2 | undefined) => APIGatewayProxyResult | APIGatewayProxyStructuredResultV2; + sendResponse: ( + response?: APIGatewayProxyResult | APIGatewayProxyStructuredResultV2 | undefined + ) => APIGatewayProxyResult | APIGatewayProxyStructuredResultV2; } export interface SessionEventV2 extends SupertokensLambdaEventV2 { session?: SessionContainerInterface; diff --git a/lib/build/framework/awsLambda/framework.js b/lib/build/framework/awsLambda/framework.js index 89d40700f..c8d01c26b 100644 --- a/lib/build/framework/awsLambda/framework.js +++ b/lib/build/framework/awsLambda/framework.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AWSWrapper = exports.middleware = exports.AWSResponse = exports.AWSRequest = void 0; const utils_1 = require("../../utils"); @@ -23,20 +47,20 @@ const querystring_1 = require("querystring"); class AWSRequest extends request_1.BaseRequest { constructor(event) { super(); - this.getFormData = () => __awaiter(this, void 0, void 0, function* () { - if (this.parsedUrlEncodedFormData === undefined) { - if (this.event.body === null || this.event.body === undefined) { - this.parsedUrlEncodedFormData = {}; - } - else { - this.parsedUrlEncodedFormData = querystring_1.parse(this.event.body); - if (this.parsedUrlEncodedFormData === undefined) { + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + if (this.parsedUrlEncodedFormData === undefined) { + if (this.event.body === null || this.event.body === undefined) { this.parsedUrlEncodedFormData = {}; + } else { + this.parsedUrlEncodedFormData = querystring_1.parse(this.event.body); + if (this.parsedUrlEncodedFormData === undefined) { + this.parsedUrlEncodedFormData = {}; + } } } - } - return this.parsedUrlEncodedFormData; - }); + return this.parsedUrlEncodedFormData; + }); this.getKeyValueFromQuery = (key) => { if (this.event.queryStringParameters === undefined || this.event.queryStringParameters === null) { return undefined; @@ -47,20 +71,20 @@ class AWSRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { - if (this.parsedJSONBody === undefined) { - if (this.event.body === null || this.event.body === undefined) { - this.parsedJSONBody = {}; - } - else { - this.parsedJSONBody = JSON.parse(this.event.body); - if (this.parsedJSONBody === undefined) { + this.getJSONBody = () => + __awaiter(this, void 0, void 0, function* () { + if (this.parsedJSONBody === undefined) { + if (this.event.body === null || this.event.body === undefined) { this.parsedJSONBody = {}; + } else { + this.parsedJSONBody = JSON.parse(this.event.body); + if (this.parsedJSONBody === undefined) { + this.parsedJSONBody = {}; + } } } - } - return this.parsedJSONBody; - }); + return this.parsedJSONBody; + }); this.getMethod = () => { let rawMethod = this.event.httpMethod; if (rawMethod !== undefined) { @@ -70,15 +94,20 @@ class AWSRequest extends request_1.BaseRequest { }; this.getCookieValue = (key) => { let cookies = this.event.cookies; - if ((this.event.headers === undefined || this.event.headers === null) && - (cookies === undefined || cookies === null)) { + if ( + (this.event.headers === undefined || this.event.headers === null) && + (cookies === undefined || cookies === null) + ) { return undefined; } let value = utils_2.getCookieValueFromHeaders(this.event.headers, key); if (value === undefined && cookies !== undefined && cookies !== null) { - value = utils_2.getCookieValueFromHeaders({ - cookie: cookies.join(";"), - }, key); + value = utils_2.getCookieValueFromHeaders( + { + cookie: cookies.join(";"), + }, + key + ); } return value; }; @@ -124,10 +153,21 @@ class AWSResponse extends response_1.BaseResponse { }); }; this.removeHeader = (key) => { - this.event.supertokens.response.headers = this.event.supertokens.response.headers.filter((header) => header.key.toLowerCase() !== key.toLowerCase()); + this.event.supertokens.response.headers = this.event.supertokens.response.headers.filter( + (header) => header.key.toLowerCase() !== key.toLowerCase() + ); }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - let serialisedCookie = utils_2.serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite); + let serialisedCookie = utils_2.serializeCookieValue( + key, + value, + domain, + secure, + httpOnly, + expires, + path, + sameSite + ); this.event.supertokens.response.cookies.push(serialisedCookie); }; /** @@ -175,8 +215,7 @@ class AWSResponse extends response_1.BaseResponse { if (supertokensHeaders[i].allowDuplicateKey && currentValue !== undefined) { let newValue = `${currentValue}, ${supertokensHeaders[i].value}`; headers[supertokensHeaders[i].key] = newValue; - } - else { + } else { headers[supertokensHeaders[i].key] = supertokensHeaders[i].value; } } @@ -186,26 +225,28 @@ class AWSResponse extends response_1.BaseResponse { cookies = []; } cookies.push(...supertokensCookies); - let result = Object.assign(Object.assign({}, response), { cookies, - body, - statusCode, - headers }); + let result = Object.assign(Object.assign({}, response), { cookies, body, statusCode, headers }); return result; - } - else { + } else { let multiValueHeaders = response.multiValueHeaders; if (multiValueHeaders === undefined) { multiValueHeaders = {}; } let headsersInMultiValueHeaders = Object.keys(multiValueHeaders); - let cookieHeader = headsersInMultiValueHeaders.find((h) => h.toLowerCase() === constants_1.COOKIE_HEADER.toLowerCase()); + let cookieHeader = headsersInMultiValueHeaders.find( + (h) => h.toLowerCase() === constants_1.COOKIE_HEADER.toLowerCase() + ); if (cookieHeader === undefined) { multiValueHeaders[constants_1.COOKIE_HEADER] = supertokensCookies; - } - else { + } else { multiValueHeaders[cookieHeader].push(...supertokensCookies); } - let result = Object.assign(Object.assign({}, response), { multiValueHeaders, body: body, statusCode: statusCode, headers }); + let result = Object.assign(Object.assign({}, response), { + multiValueHeaders, + body: body, + statusCode: statusCode, + headers, + }); return result; } }; @@ -225,37 +266,37 @@ class AWSResponse extends response_1.BaseResponse { } exports.AWSResponse = AWSResponse; const middleware = (handler) => { - return (event, context, callback) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new AWSRequest(event); - let response = new AWSResponse(event); - try { - let result = yield supertokens.middleware(request, response); - if (result) { - return response.sendResponse(); - } - if (handler !== undefined) { - let handlerResult = yield handler(event, context, callback); - return response.sendResponse(handlerResult); - } - /** - * it reaches this point only if the API route was not exposed by - * the SDK and user didn't provide a handler - */ - response.setStatusCode(404); - response.sendJSONResponse({ - error: `The middleware couldn't serve the API path ${request.getOriginalURL()}, method: ${request.getMethod()}. If this is an unexpected behaviour, please create an issue here: https://github.com/supertokens/supertokens-node/issues`, - }); - return response.sendResponse(); - } - catch (err) { - yield supertokens.errorHandler(err, request, response); - if (response.responseSet) { + return (event, context, callback) => + __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new AWSRequest(event); + let response = new AWSResponse(event); + try { + let result = yield supertokens.middleware(request, response); + if (result) { + return response.sendResponse(); + } + if (handler !== undefined) { + let handlerResult = yield handler(event, context, callback); + return response.sendResponse(handlerResult); + } + /** + * it reaches this point only if the API route was not exposed by + * the SDK and user didn't provide a handler + */ + response.setStatusCode(404); + response.sendJSONResponse({ + error: `The middleware couldn't serve the API path ${request.getOriginalURL()}, method: ${request.getMethod()}. If this is an unexpected behaviour, please create an issue here: https://github.com/supertokens/supertokens-node/issues`, + }); return response.sendResponse(); + } catch (err) { + yield supertokens.errorHandler(err, request, response); + if (response.responseSet) { + return response.sendResponse(); + } + throw err; } - throw err; - } - }); + }); }; exports.middleware = middleware; exports.AWSWrapper = { diff --git a/lib/build/framework/awsLambda/index.d.ts b/lib/build/framework/awsLambda/index.d.ts index b69a4cee2..2cd01ebff 100644 --- a/lib/build/framework/awsLambda/index.d.ts +++ b/lib/build/framework/awsLambda/index.d.ts @@ -1,4 +1,6 @@ export type { SessionEvent, SessionEventV2 } from "./framework"; -export declare const middleware: (handler?: import("aws-lambda").Handler | undefined) => import("aws-lambda").Handler; +export declare const middleware: ( + handler?: import("aws-lambda").Handler | undefined +) => import("aws-lambda").Handler; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/express/framework.d.ts b/lib/build/framework/express/framework.d.ts index 2fc4da709..7b1c67feb 100644 --- a/lib/build/framework/express/framework.d.ts +++ b/lib/build/framework/express/framework.d.ts @@ -24,7 +24,16 @@ export declare class ExpressResponse extends BaseResponse { sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; removeHeader: (key: string) => void; - setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; + setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; /** * @param {number} statusCode */ diff --git a/lib/build/framework/express/framework.js b/lib/build/framework/express/framework.js index 81b4eae26..b7201a722 100644 --- a/lib/build/framework/express/framework.js +++ b/lib/build/framework/express/framework.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ExpressWrapper = exports.errorHandler = exports.middleware = exports.ExpressResponse = exports.ExpressRequest = void 0; const utils_1 = require("../../utils"); @@ -35,13 +59,14 @@ const supertokens_1 = __importDefault(require("../../supertokens")); class ExpressRequest extends request_1.BaseRequest { constructor(request) { super(); - this.getFormData = () => __awaiter(this, void 0, void 0, function* () { - if (!this.formDataParserChecked) { - yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -52,13 +77,14 @@ class ExpressRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { - if (!this.parserChecked) { - yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); - this.parserChecked = true; - } - return this.request.body; - }); + this.getJSONBody = () => + __awaiter(this, void 0, void 0, function* () { + if (!this.parserChecked) { + yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); + this.parserChecked = true; + } + return this.request.body; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -101,7 +127,17 @@ class ExpressResponse extends response_1.BaseResponse { this.response.removeHeader(key); }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - utils_2.setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); + utils_2.setCookieForServerResponse( + this.response, + key, + value, + domain, + secure, + httpOnly, + expires, + path, + sameSite + ); }; /** * @param {number} statusCode @@ -123,45 +159,43 @@ class ExpressResponse extends response_1.BaseResponse { } exports.ExpressResponse = ExpressResponse; const middleware = () => { - return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens; - const request = new ExpressRequest(req); - const response = new ExpressResponse(res); - try { - supertokens = supertokens_1.default.getInstanceOrThrowError(); - const result = yield supertokens.middleware(request, response); - if (!result) { - return next(); - } - } - catch (err) { - if (supertokens) { - try { - yield supertokens.errorHandler(err, request, response); + return (req, res, next) => + __awaiter(void 0, void 0, void 0, function* () { + let supertokens; + const request = new ExpressRequest(req); + const response = new ExpressResponse(res); + try { + supertokens = supertokens_1.default.getInstanceOrThrowError(); + const result = yield supertokens.middleware(request, response); + if (!result) { + return next(); } - catch (_a) { + } catch (err) { + if (supertokens) { + try { + yield supertokens.errorHandler(err, request, response); + } catch (_a) { + next(err); + } + } else { next(err); } } - else { - next(err); - } - } - }); + }); }; exports.middleware = middleware; const errorHandler = () => { - return (err, req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new ExpressRequest(req); - let response = new ExpressResponse(res); - try { - yield supertokens.errorHandler(err, request, response); - } - catch (err) { - return next(err); - } - }); + return (err, req, res, next) => + __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new ExpressRequest(req); + let response = new ExpressResponse(res); + try { + yield supertokens.errorHandler(err, request, response); + } catch (err) { + return next(err); + } + }); }; exports.errorHandler = errorHandler; exports.ExpressWrapper = { diff --git a/lib/build/framework/express/index.d.ts b/lib/build/framework/express/index.d.ts index cc2b67499..d4dc8eb85 100644 --- a/lib/build/framework/express/index.d.ts +++ b/lib/build/framework/express/index.d.ts @@ -1,6 +1,15 @@ /// export type { SessionRequest } from "./framework"; -export declare const middleware: () => (req: import("express").Request, res: import("express").Response, next: import("express").NextFunction) => Promise; -export declare const errorHandler: () => (err: any, req: import("express").Request, res: import("express").Response, next: import("express").NextFunction) => Promise; +export declare const middleware: () => ( + req: import("express").Request, + res: import("express").Response, + next: import("express").NextFunction +) => Promise; +export declare const errorHandler: () => ( + err: any, + req: import("express").Request, + res: import("express").Response, + next: import("express").NextFunction +) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/fastify/framework.d.ts b/lib/build/framework/fastify/framework.d.ts index 5041488c2..7f0411283 100644 --- a/lib/build/framework/fastify/framework.d.ts +++ b/lib/build/framework/fastify/framework.d.ts @@ -22,7 +22,16 @@ export declare class FastifyResponse extends BaseResponse { sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; removeHeader: (key: string) => void; - setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; + setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; /** * @param {number} statusCode */ diff --git a/lib/build/framework/fastify/framework.js b/lib/build/framework/fastify/framework.js index 276cac7ce..54d4c879f 100644 --- a/lib/build/framework/fastify/framework.js +++ b/lib/build/framework/fastify/framework.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FastifyWrapper = exports.errorHandler = exports.FastifyResponse = exports.FastifyRequest = void 0; const utils_1 = require("../../utils"); @@ -36,9 +60,10 @@ const constants_1 = require("../constants"); class FastifyRequest extends request_1.BaseRequest { constructor(request) { super(); - this.getFormData = () => __awaiter(this, void 0, void 0, function* () { - return this.request.body; // NOTE: ask user to add require('fastify-formbody') - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + return this.request.body; // NOTE: ask user to add require('fastify-formbody') + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -49,9 +74,10 @@ class FastifyRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { - return this.request.body; - }); + this.getJSONBody = () => + __awaiter(this, void 0, void 0, function* () { + return this.request.body; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -85,16 +111,13 @@ class FastifyResponse extends response_1.BaseResponse { // we have the this.response.header for compatibility with nextJS if (existingValue === undefined) { this.response.header(key, value); - } - else if (allowDuplicateKey) { + } else if (allowDuplicateKey) { this.response.header(key, existingValue + ", " + value); - } - else { + } else { // we overwrite the current one with the new one this.response.header(key, value); } - } - catch (err) { + } catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; @@ -102,7 +125,16 @@ class FastifyResponse extends response_1.BaseResponse { this.response.removeHeader(key); }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - let serialisedCookie = utils_2.serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite); + let serialisedCookie = utils_2.serializeCookieValue( + key, + value, + domain, + secure, + httpOnly, + expires, + path, + sameSite + ); /** * lets say if current value is undefined, prev -> undefined * @@ -165,27 +197,29 @@ class FastifyResponse extends response_1.BaseResponse { } exports.FastifyResponse = FastifyResponse; function plugin(fastify, _, done) { - fastify.addHook("preHandler", (req, reply) => __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new FastifyRequest(req); - let response = new FastifyResponse(reply); - try { - yield supertokens.middleware(request, response); - } - catch (err) { - yield supertokens.errorHandler(err, request, response); - } - })); + fastify.addHook("preHandler", (req, reply) => + __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new FastifyRequest(req); + let response = new FastifyResponse(reply); + try { + yield supertokens.middleware(request, response); + } catch (err) { + yield supertokens.errorHandler(err, request, response); + } + }) + ); done(); } plugin[Symbol.for("skip-override")] = true; const errorHandler = () => { - return (err, req, res) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new FastifyRequest(req); - let response = new FastifyResponse(res); - yield supertokens.errorHandler(err, request, response); - }); + return (err, req, res) => + __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new FastifyRequest(req); + let response = new FastifyResponse(res); + yield supertokens.errorHandler(err, request, response); + }); }; exports.errorHandler = errorHandler; exports.FastifyWrapper = { diff --git a/lib/build/framework/fastify/index.d.ts b/lib/build/framework/fastify/index.d.ts index 0737a9984..fd681c6cf 100644 --- a/lib/build/framework/fastify/index.d.ts +++ b/lib/build/framework/fastify/index.d.ts @@ -1,6 +1,20 @@ /// export type { SessionRequest } from "./framework"; export declare const plugin: import("fastify").FastifyPluginCallback, import("http").Server>; -export declare const errorHandler: () => (err: any, req: import("fastify").FastifyRequest, res: import("fastify").FastifyReply) => Promise; +export declare const errorHandler: () => ( + err: any, + req: import("fastify").FastifyRequest< + import("fastify/types/route").RouteGenericInterface, + import("http").Server, + import("http").IncomingMessage + >, + res: import("fastify").FastifyReply< + import("http").Server, + import("http").IncomingMessage, + import("http").ServerResponse, + import("fastify/types/route").RouteGenericInterface, + unknown + > +) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/hapi/framework.d.ts b/lib/build/framework/hapi/framework.d.ts index 80034d219..cfa5a2c16 100644 --- a/lib/build/framework/hapi/framework.d.ts +++ b/lib/build/framework/hapi/framework.d.ts @@ -16,7 +16,12 @@ export declare class HapiRequest extends BaseRequest { getOriginalURL: () => string; } export interface ExtendedResponseToolkit extends ResponseToolkit { - lazyHeaderBindings: (h: ResponseToolkit, key: string, value: string | undefined, allowDuplicateKey: boolean) => void; + lazyHeaderBindings: ( + h: ResponseToolkit, + key: string, + value: string | undefined, + allowDuplicateKey: boolean + ) => void; } export declare class HapiResponse extends BaseResponse { private response; @@ -28,7 +33,16 @@ export declare class HapiResponse extends BaseResponse { sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; removeHeader: (key: string) => void; - setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; + setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; /** * @param {number} statusCode */ diff --git a/lib/build/framework/hapi/framework.js b/lib/build/framework/hapi/framework.js index ee266f1d8..08cd1cff8 100644 --- a/lib/build/framework/hapi/framework.js +++ b/lib/build/framework/hapi/framework.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HapiWrapper = exports.HapiResponse = exports.HapiRequest = void 0; const utils_1 = require("../../utils"); @@ -35,9 +59,10 @@ const supertokens_1 = __importDefault(require("../../supertokens")); class HapiRequest extends request_1.BaseRequest { constructor(request) { super(); - this.getFormData = () => __awaiter(this, void 0, void 0, function* () { - return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -48,9 +73,10 @@ class HapiRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { - return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; - }); + this.getJSONBody = () => + __awaiter(this, void 0, void 0, function* () { + return this.request.payload === undefined || this.request.payload === null ? {} : this.request.payload; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -82,8 +108,7 @@ class HapiResponse extends response_1.BaseResponse { this.setHeader = (key, value, allowDuplicateKey) => { try { this.response.lazyHeaderBindings(this.response, key, value, allowDuplicateKey); - } - catch (err) { + } catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; @@ -101,8 +126,7 @@ class HapiResponse extends response_1.BaseResponse { ttl: expires - now, isSameSite: sameSite === "lax" ? "Lax" : sameSite === "none" ? "None" : "Strict", }); - } - else { + } else { this.response.unstate(key); } }; @@ -144,54 +168,57 @@ const plugin = { register: function (server, _) { return __awaiter(this, void 0, void 0, function* () { let supertokens = supertokens_1.default.getInstanceOrThrowError(); - server.ext("onPreHandler", (req, h) => __awaiter(this, void 0, void 0, function* () { - let request = new HapiRequest(req); - let response = new HapiResponse(h); - let result = yield supertokens.middleware(request, response); - if (!result) { - return h.continue; - } - return response.sendResponse(); - })); - server.ext("onPreResponse", (request, h) => __awaiter(this, void 0, void 0, function* () { - (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { - if (request.response.isBoom) { - request.response.output.headers[key] = value; - } - else { - request.response.header(key, value, { append: allowDuplicateKey }); + server.ext("onPreHandler", (req, h) => + __awaiter(this, void 0, void 0, function* () { + let request = new HapiRequest(req); + let response = new HapiResponse(h); + let result = yield supertokens.middleware(request, response); + if (!result) { + return h.continue; } - }); - if (request.response.isBoom) { - let err = request.response.data || request.response; - let req = new HapiRequest(request); - let res = new HapiResponse(h); - if (err !== undefined && err !== null) { - try { - yield supertokens.errorHandler(err, req, res); - if (res.responseSet) { - let resObj = res.sendResponse(true); - (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { - resObj.header(key, value, { append: allowDuplicateKey }); - }); - return resObj.takeover(); - } - return h.continue; + return response.sendResponse(); + }) + ); + server.ext("onPreResponse", (request, h) => + __awaiter(this, void 0, void 0, function* () { + (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { + if (request.response.isBoom) { + request.response.output.headers[key] = value; + } else { + request.response.header(key, value, { append: allowDuplicateKey }); } - catch (e) { - return h.continue; + }); + if (request.response.isBoom) { + let err = request.response.data || request.response; + let req = new HapiRequest(request); + let res = new HapiResponse(h); + if (err !== undefined && err !== null) { + try { + yield supertokens.errorHandler(err, req, res); + if (res.responseSet) { + let resObj = res.sendResponse(true); + (request.app.lazyHeaders || []).forEach(({ key, value, allowDuplicateKey }) => { + resObj.header(key, value, { append: allowDuplicateKey }); + }); + return resObj.takeover(); + } + return h.continue; + } catch (e) { + return h.continue; + } } } - } - return h.continue; - })); + return h.continue; + }) + ); server.decorate("toolkit", "lazyHeaderBindings", function (h, key, value, allowDuplicateKey) { const anyApp = h.request.app; anyApp.lazyHeaders = anyApp.lazyHeaders || []; if (value === undefined) { - anyApp.lazyHeaders = anyApp.lazyHeaders.filter((header) => header.key.toLowerCase() !== key.toLowerCase()); - } - else { + anyApp.lazyHeaders = anyApp.lazyHeaders.filter( + (header) => header.key.toLowerCase() !== key.toLowerCase() + ); + } else { anyApp.lazyHeaders.push({ key, value, allowDuplicateKey }); } }); diff --git a/lib/build/framework/index.js b/lib/build/framework/index.js index f9017266b..28dc9790d 100644 --- a/lib/build/framework/index.js +++ b/lib/build/framework/index.js @@ -1,23 +1,40 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.awsLambda = exports.koa = exports.loopback = exports.hapi = exports.fastify = exports.express = exports.BaseResponse = exports.BaseRequest = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -35,9 +52,19 @@ exports.awsLambda = exports.koa = exports.loopback = exports.hapi = exports.fast * under the License. */ var request_1 = require("./request"); -Object.defineProperty(exports, "BaseRequest", { enumerable: true, get: function () { return request_1.BaseRequest; } }); +Object.defineProperty(exports, "BaseRequest", { + enumerable: true, + get: function () { + return request_1.BaseRequest; + }, +}); var response_1 = require("./response"); -Object.defineProperty(exports, "BaseResponse", { enumerable: true, get: function () { return response_1.BaseResponse; } }); +Object.defineProperty(exports, "BaseResponse", { + enumerable: true, + get: function () { + return response_1.BaseResponse; + }, +}); const expressFramework = __importStar(require("./express")); const fastifyFramework = __importStar(require("./fastify")); const hapiFramework = __importStar(require("./hapi")); diff --git a/lib/build/framework/koa/framework.d.ts b/lib/build/framework/koa/framework.d.ts index 01c4fc110..814a94b73 100644 --- a/lib/build/framework/koa/framework.d.ts +++ b/lib/build/framework/koa/framework.d.ts @@ -25,7 +25,16 @@ export declare class KoaResponse extends BaseResponse { sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; removeHeader: (key: string) => void; - setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; + setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; /** * @param {number} statusCode */ diff --git a/lib/build/framework/koa/framework.js b/lib/build/framework/koa/framework.js index 56a4a4d4e..ac611bae5 100644 --- a/lib/build/framework/koa/framework.js +++ b/lib/build/framework/koa/framework.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.KoaWrapper = exports.middleware = exports.KoaResponse = exports.KoaRequest = void 0; const utils_1 = require("../../utils"); @@ -36,12 +60,13 @@ const supertokens_1 = __importDefault(require("../../supertokens")); class KoaRequest extends request_1.BaseRequest { constructor(ctx) { super(); - this.getFormData = () => __awaiter(this, void 0, void 0, function* () { - if (this.parsedUrlEncodedFormData === undefined) { - this.parsedUrlEncodedFormData = yield parseURLEncodedFormData(this.ctx); - } - return this.parsedUrlEncodedFormData; - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + if (this.parsedUrlEncodedFormData === undefined) { + this.parsedUrlEncodedFormData = yield parseURLEncodedFormData(this.ctx); + } + return this.parsedUrlEncodedFormData; + }); this.getKeyValueFromQuery = (key) => { if (this.ctx.query === undefined) { return undefined; @@ -52,12 +77,13 @@ class KoaRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { - if (this.parsedJSONBody === undefined) { - this.parsedJSONBody = yield parseJSONBodyFromRequest(this.ctx); - } - return this.parsedJSONBody === undefined ? {} : this.parsedJSONBody; - }); + this.getJSONBody = () => + __awaiter(this, void 0, void 0, function* () { + if (this.parsedJSONBody === undefined) { + this.parsedJSONBody = yield parseJSONBodyFromRequest(this.ctx); + } + return this.parsedJSONBody === undefined ? {} : this.parsedJSONBody; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.ctx.request.method); }; @@ -111,16 +137,13 @@ class KoaResponse extends response_1.BaseResponse { let existingValue = existingHeaders[key.toLowerCase()]; if (existingValue === undefined) { this.ctx.set(key, value); - } - else if (allowDuplicateKey) { + } else if (allowDuplicateKey) { this.ctx.set(key, existingValue + ", " + value); - } - else { + } else { // we overwrite the current one with the new one this.ctx.set(key, value); } - } - catch (err) { + } catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; @@ -158,20 +181,20 @@ class KoaResponse extends response_1.BaseResponse { } exports.KoaResponse = KoaResponse; const middleware = () => { - return (ctx, next) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new KoaRequest(ctx); - let response = new KoaResponse(ctx); - try { - let result = yield supertokens.middleware(request, response); - if (!result) { - return yield next(); + return (ctx, next) => + __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new KoaRequest(ctx); + let response = new KoaResponse(ctx); + try { + let result = yield supertokens.middleware(request, response); + if (!result) { + return yield next(); + } + } catch (err) { + return yield supertokens.errorHandler(err, request, response); } - } - catch (err) { - return yield supertokens.errorHandler(err, request, response); - } - }); + }); }; exports.middleware = middleware; exports.KoaWrapper = { diff --git a/lib/build/framework/loopback/framework.d.ts b/lib/build/framework/loopback/framework.d.ts index c62de7950..51b969742 100644 --- a/lib/build/framework/loopback/framework.d.ts +++ b/lib/build/framework/loopback/framework.d.ts @@ -24,7 +24,16 @@ export declare class LoopbackResponse extends BaseResponse { sendHTMLResponse: (html: string) => void; setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; removeHeader: (key: string) => void; - setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; + setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; setStatusCode: (statusCode: number) => void; sendJSONResponse: (content: any) => void; } diff --git a/lib/build/framework/loopback/framework.js b/lib/build/framework/loopback/framework.js index 2d5157e83..7e8db8ee6 100644 --- a/lib/build/framework/loopback/framework.js +++ b/lib/build/framework/loopback/framework.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.LoopbackWrapper = exports.middleware = exports.LoopbackResponse = exports.LoopbackRequest = void 0; const utils_1 = require("../../utils"); @@ -35,13 +59,14 @@ const supertokens_1 = __importDefault(require("../../supertokens")); class LoopbackRequest extends request_1.BaseRequest { constructor(ctx) { super(); - this.getFormData = () => __awaiter(this, void 0, void 0, function* () { - if (!this.formDataParserChecked) { - yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -52,13 +77,14 @@ class LoopbackRequest extends request_1.BaseRequest { } return value; }; - this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { - if (!this.parserChecked) { - yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); - this.parserChecked = true; - } - return this.request.body; - }); + this.getJSONBody = () => + __awaiter(this, void 0, void 0, function* () { + if (!this.parserChecked) { + yield utils_2.assertThatBodyParserHasBeenUsedForExpressLikeRequest(this.getMethod(), this.request); + this.parserChecked = true; + } + return this.request.body; + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -94,7 +120,17 @@ class LoopbackResponse extends response_1.BaseResponse { this.response.removeHeader(key); }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - utils_2.setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); + utils_2.setCookieForServerResponse( + this.response, + key, + value, + domain, + secure, + httpOnly, + expires, + path, + sameSite + ); }; this.setStatusCode = (statusCode) => { if (!this.response.writableEnded) { @@ -112,21 +148,21 @@ class LoopbackResponse extends response_1.BaseResponse { } } exports.LoopbackResponse = LoopbackResponse; -const middleware = (ctx, next) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new LoopbackRequest(ctx); - let response = new LoopbackResponse(ctx); - try { - let result = yield supertokens.middleware(request, response); - if (!result) { - return yield next(); +const middleware = (ctx, next) => + __awaiter(void 0, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new LoopbackRequest(ctx); + let response = new LoopbackResponse(ctx); + try { + let result = yield supertokens.middleware(request, response); + if (!result) { + return yield next(); + } + return; + } catch (err) { + return yield supertokens.errorHandler(err, request, response); } - return; - } - catch (err) { - return yield supertokens.errorHandler(err, request, response); - } -}); + }); exports.middleware = middleware; exports.LoopbackWrapper = { middleware: exports.middleware, diff --git a/lib/build/framework/response.d.ts b/lib/build/framework/response.d.ts index e12c992b2..27f79761f 100644 --- a/lib/build/framework/response.d.ts +++ b/lib/build/framework/response.d.ts @@ -4,7 +4,16 @@ export declare abstract class BaseResponse { constructor(); abstract setHeader: (key: string, value: string, allowDuplicateKey: boolean) => void; abstract removeHeader: (key: string) => void; - abstract setCookie: (key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none") => void; + abstract setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; abstract setStatusCode: (statusCode: number) => void; abstract sendJSONResponse: (content: any) => void; abstract sendHTMLResponse: (html: string) => void; diff --git a/lib/build/framework/utils.d.ts b/lib/build/framework/utils.d.ts index a123f2507..68452dff1 100644 --- a/lib/build/framework/utils.d.ts +++ b/lib/build/framework/utils.d.ts @@ -8,13 +8,23 @@ export declare function getCookieValueFromHeaders(headers: any, key: string): st export declare function getCookieValueFromIncomingMessage(request: IncomingMessage, key: string): string | undefined; export declare function getHeaderValueFromIncomingMessage(request: IncomingMessage, key: string): string | undefined; export declare function normalizeHeaderValue(value: string | string[] | undefined): string | undefined; -export declare function assertThatBodyParserHasBeenUsedForExpressLikeRequest(method: HTTPMethod, request: (Request | NextApiRequest) & { - __supertokensFromNextJS?: true; -}): Promise; -export declare function assertFormDataBodyParserHasBeenUsedForExpressLikeRequest(request: (Request | NextApiRequest) & { - __supertokensFromNextJS?: true; -}): Promise; -export declare function setHeaderForExpressLikeResponse(res: Response, key: string, value: string, allowDuplicateKey: boolean): void; +export declare function assertThatBodyParserHasBeenUsedForExpressLikeRequest( + method: HTTPMethod, + request: (Request | NextApiRequest) & { + __supertokensFromNextJS?: true; + } +): Promise; +export declare function assertFormDataBodyParserHasBeenUsedForExpressLikeRequest( + request: (Request | NextApiRequest) & { + __supertokensFromNextJS?: true; + } +): Promise; +export declare function setHeaderForExpressLikeResponse( + res: Response, + key: string, + value: string, + allowDuplicateKey: boolean +): void; /** * * @param res @@ -26,6 +36,29 @@ export declare function setHeaderForExpressLikeResponse(res: Response, key: stri * @param expires * @param path */ -export declare function setCookieForServerResponse(res: ServerResponse, key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none"): ServerResponse; -export declare function getCookieValueToSetInHeader(prev: string | string[] | undefined, val: string | string[], key: string): string | string[]; -export declare function serializeCookieValue(key: string, value: string, domain: string | undefined, secure: boolean, httpOnly: boolean, expires: number, path: string, sameSite: "strict" | "lax" | "none"): string; +export declare function setCookieForServerResponse( + res: ServerResponse, + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" +): ServerResponse; +export declare function getCookieValueToSetInHeader( + prev: string | string[] | undefined, + val: string | string[], + key: string +): string | string[]; +export declare function serializeCookieValue( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" +): string; diff --git a/lib/build/framework/utils.js b/lib/build/framework/utils.js index d7ca8b32a..58c51cd08 100644 --- a/lib/build/framework/utils.js +++ b/lib/build/framework/utils.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.serializeCookieValue = exports.getCookieValueToSetInHeader = exports.setCookieForServerResponse = exports.setHeaderForExpressLikeResponse = exports.assertFormDataBodyParserHasBeenUsedForExpressLikeRequest = exports.assertThatBodyParserHasBeenUsedForExpressLikeRequest = exports.normalizeHeaderValue = exports.getHeaderValueFromIncomingMessage = exports.getCookieValueFromIncomingMessage = exports.getCookieValueFromHeaders = void 0; const cookie_1 = require("cookie"); @@ -80,8 +104,7 @@ function JSONCookie(str) { } try { return JSON.parse(str.slice(2)); - } - catch (err) { + } catch (err) { return undefined; } } @@ -112,22 +135,21 @@ function assertThatBodyParserHasBeenUsedForExpressLikeRequest(method, request) { if (typeof request.body === "string") { try { request.body = JSON.parse(request.body); - } - catch (err) { + } catch (err) { if (request.body === "") { request.body = {}; - } - else { + } else { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, message: "API input error: Please make sure to pass a valid JSON input in the request body", }); } } - } - else if (request.body === undefined || + } else if ( + request.body === undefined || Buffer.isBuffer(request.body) || - Object.keys(request.body).length === 0) { + Object.keys(request.body).length === 0 + ) { // parsing it again to make sure that the request is parsed atleast once by a json parser let jsonParser = body_parser_1.json(); let err = yield new Promise((resolve) => { @@ -163,8 +185,7 @@ function assertThatBodyParserHasBeenUsedForExpressLikeRequest(method, request) { }); } } - } - else if (method === "delete" || method === "get") { + } else if (method === "delete" || method === "get") { if (request.query === undefined) { let parser = body_parser_1.urlencoded({ extended: true }); let err = yield new Promise((resolve) => parser(request, new http_1.ServerResponse(request), resolve)); @@ -225,30 +246,24 @@ function setHeaderForExpressLikeResponse(res, key, value, allowDuplicateKey) { if (existingValue === undefined) { if (res.header !== undefined) { res.header(key, value); - } - else { + } else { res.setHeader(key, value); } - } - else if (allowDuplicateKey) { + } else if (allowDuplicateKey) { if (res.header !== undefined) { res.header(key, existingValue + ", " + value); - } - else { + } else { res.setHeader(key, existingValue + ", " + value); } - } - else { + } else { // we overwrite the current one with the new one if (res.header !== undefined) { res.header(key, value); - } - else { + } else { res.setHeader(key, value); } } - } - catch (err) { + } catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } } @@ -265,7 +280,12 @@ exports.setHeaderForExpressLikeResponse = setHeaderForExpressLikeResponse; * @param path */ function setCookieForServerResponse(res, key, value, domain, secure, httpOnly, expires, path, sameSite) { - return appendToServerResponse(res, constants_1.COOKIE_HEADER, serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite), key); + return appendToServerResponse( + res, + constants_1.COOKIE_HEADER, + serializeCookieValue(key, value, domain, secure, httpOnly, expires, path, sameSite), + key + ); } exports.setCookieForServerResponse = setCookieForServerResponse; /** @@ -297,8 +317,7 @@ function getCookieValueToSetInHeader(prev, val, key) { } } prev = removedDuplicate; - } - else { + } else { if (prev.startsWith(key)) { prev = undefined; } diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index fd8642a08..eb7fc8cb9 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -28,24 +28,30 @@ export default class SuperTokensWrapper { externalUserId: string; externalUserIdInfo?: string; force?: boolean; - }): Promise<{ - status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; - } | { - status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; - doesSuperTokensUserIdExist: boolean; - doesExternalUserIdExist: boolean; - }>; + }): Promise< + | { + status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; + } + | { + status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; + doesSuperTokensUserIdExist: boolean; + doesExternalUserIdExist: boolean; + } + >; static getUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; - }): Promise<{ - status: "OK"; - superTokensUserId: string; - externalUserId: string; - externalUserIdInfo: string | undefined; - } | { - status: "UNKNOWN_MAPPING_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + superTokensUserId: string; + externalUserId: string; + externalUserIdInfo: string | undefined; + } + | { + status: "UNKNOWN_MAPPING_ERROR"; + } + >; static deleteUserIdMapping(input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; @@ -63,7 +69,11 @@ export default class SuperTokensWrapper { }>; static getUser(userId: string, userContext?: any): Promise; static listUsersByAccountInfo(accountInfo: AccountInfo, userContext?: any): Promise; - static deleteUser(userId: string, removeAllLinkedAccounts?: boolean, userContext?: any): Promise<{ + static deleteUser( + userId: string, + removeAllLinkedAccounts?: boolean, + userContext?: any + ): Promise<{ status: "OK"; }>; } diff --git a/lib/build/index.js b/lib/build/index.js index a4e826811..9dd74d7f2 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Error = exports.listUsersByAccountInfo = exports.getUser = exports.updateOrDeleteUserIdMappingInfo = exports.deleteUserIdMapping = exports.getUserIdMapping = exports.createUserIdMapping = exports.deleteUser = exports.getUsersNewestFirst = exports.getUsersOldestFirst = exports.getUserCount = exports.getAllCORSHeaders = exports.init = void 0; const supertokens_1 = __importDefault(require("./supertokens")); @@ -39,10 +63,18 @@ class SuperTokensWrapper { return supertokens_1.default.getInstanceOrThrowError().getUserCount(includeRecipeIds); } static getUsersOldestFirst(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsers(Object.assign(Object.assign({ timeJoinedOrder: "ASC" }, input), { userContext: undefined })); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getUsers( + Object.assign(Object.assign({ timeJoinedOrder: "ASC" }, input), { userContext: undefined }) + ); } static getUsersNewestFirst(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsers(Object.assign(Object.assign({ timeJoinedOrder: "DESC" }, input), { userContext: undefined })); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getUsers( + Object.assign(Object.assign({ timeJoinedOrder: "DESC" }, input), { userContext: undefined }) + ); } static createUserIdMapping(input) { return supertokens_1.default.getInstanceOrThrowError().createUserIdMapping(input); diff --git a/lib/build/ingredients/emaildelivery/index.js b/lib/build/ingredients/emaildelivery/index.js index e728e628a..958cd35a2 100644 --- a/lib/build/ingredients/emaildelivery/index.js +++ b/lib/build/ingredients/emaildelivery/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); class EmailDelivery { diff --git a/lib/build/ingredients/emaildelivery/services/smtp.d.ts b/lib/build/ingredients/emaildelivery/services/smtp.d.ts index a9c836077..865c81541 100644 --- a/lib/build/ingredients/emaildelivery/services/smtp.d.ts +++ b/lib/build/ingredients/emaildelivery/services/smtp.d.ts @@ -21,9 +21,11 @@ export declare type TypeInputSendRawEmail = GetContentResult & { }; export declare type ServiceInterface = { sendRawEmail: (input: TypeInputSendRawEmail) => Promise; - getContent: (input: T & { - userContext: any; - }) => Promise; + getContent: ( + input: T & { + userContext: any; + } + ) => Promise; }; export declare type TypeInput = { smtpSettings: SMTPServiceConfig; diff --git a/lib/build/ingredients/emaildelivery/types.d.ts b/lib/build/ingredients/emaildelivery/types.d.ts index 60ed3c5dd..34cf181ab 100644 --- a/lib/build/ingredients/emaildelivery/types.d.ts +++ b/lib/build/ingredients/emaildelivery/types.d.ts @@ -1,17 +1,25 @@ import OverrideableBuilder from "supertokens-js-override"; export declare type EmailDeliveryInterface = { - sendEmail: (input: T & { - userContext: any; - }) => Promise; + sendEmail: ( + input: T & { + userContext: any; + } + ) => Promise; }; /** * config class parameter when parent Recipe create a new EmailDeliveryIngredient object via constructor */ export interface TypeInput { service?: EmailDeliveryInterface; - override?: (originalImplementation: EmailDeliveryInterface, builder: OverrideableBuilder>) => EmailDeliveryInterface; + override?: ( + originalImplementation: EmailDeliveryInterface, + builder: OverrideableBuilder> + ) => EmailDeliveryInterface; } export interface TypeInputWithService { service: EmailDeliveryInterface; - override?: (originalImplementation: EmailDeliveryInterface, builder: OverrideableBuilder>) => EmailDeliveryInterface; + override?: ( + originalImplementation: EmailDeliveryInterface, + builder: OverrideableBuilder> + ) => EmailDeliveryInterface; } diff --git a/lib/build/ingredients/smsdelivery/index.js b/lib/build/ingredients/smsdelivery/index.js index 6a0c5d4dc..a52608dc0 100644 --- a/lib/build/ingredients/smsdelivery/index.js +++ b/lib/build/ingredients/smsdelivery/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); class SmsDelivery { diff --git a/lib/build/ingredients/smsdelivery/services/twilio.d.ts b/lib/build/ingredients/smsdelivery/services/twilio.d.ts index 2a2a6aae8..03853fd32 100644 --- a/lib/build/ingredients/smsdelivery/services/twilio.d.ts +++ b/lib/build/ingredients/smsdelivery/services/twilio.d.ts @@ -8,33 +8,40 @@ import { ClientOpts } from "twilio/lib/base/BaseTwilio"; * if none of "from" and "messagingServiceSid" is passed, error * should be thrown. */ -export declare type TwilioServiceConfig = { - accountSid: string; - authToken: string; - from: string; - opts?: ClientOpts; -} | { - accountSid: string; - authToken: string; - messagingServiceSid: string; - opts?: ClientOpts; -}; +export declare type TwilioServiceConfig = + | { + accountSid: string; + authToken: string; + from: string; + opts?: ClientOpts; + } + | { + accountSid: string; + authToken: string; + messagingServiceSid: string; + opts?: ClientOpts; + }; export interface GetContentResult { body: string; toPhoneNumber: string; } export declare type TypeInputSendRawSms = GetContentResult & { userContext: any; -} & ({ - from: string; -} | { - messagingServiceSid: string; -}); +} & ( + | { + from: string; + } + | { + messagingServiceSid: string; + } + ); export declare type ServiceInterface = { sendRawSms: (input: TypeInputSendRawSms) => Promise; - getContent: (input: T & { - userContext: any; - }) => Promise; + getContent: ( + input: T & { + userContext: any; + } + ) => Promise; }; export declare type TypeInput = { twilioSettings: TwilioServiceConfig; diff --git a/lib/build/ingredients/smsdelivery/services/twilio.js b/lib/build/ingredients/smsdelivery/services/twilio.js index 05b97a999..73876eb37 100644 --- a/lib/build/ingredients/smsdelivery/services/twilio.js +++ b/lib/build/ingredients/smsdelivery/services/twilio.js @@ -3,9 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.normaliseUserInputConfig = void 0; function normaliseUserInputConfig(input) { let from = "from" in input.twilioSettings ? input.twilioSettings.from : undefined; - let messagingServiceSid = "messagingServiceSid" in input.twilioSettings ? input.twilioSettings.messagingServiceSid : undefined; - if ((from === undefined && messagingServiceSid === undefined) || - (from !== undefined && messagingServiceSid !== undefined)) { + let messagingServiceSid = + "messagingServiceSid" in input.twilioSettings ? input.twilioSettings.messagingServiceSid : undefined; + if ( + (from === undefined && messagingServiceSid === undefined) || + (from !== undefined && messagingServiceSid !== undefined) + ) { throw Error(`Please pass exactly one of "from" and "messagingServiceSid" config for twilioSettings.`); } return input; diff --git a/lib/build/ingredients/smsdelivery/types.d.ts b/lib/build/ingredients/smsdelivery/types.d.ts index 2c658feff..654a42746 100644 --- a/lib/build/ingredients/smsdelivery/types.d.ts +++ b/lib/build/ingredients/smsdelivery/types.d.ts @@ -1,17 +1,25 @@ import OverrideableBuilder from "supertokens-js-override"; export declare type SmsDeliveryInterface = { - sendSms: (input: T & { - userContext: any; - }) => Promise; + sendSms: ( + input: T & { + userContext: any; + } + ) => Promise; }; /** * config class parameter when parent Recipe create a new SmsDeliveryIngredient object via constructor */ export interface TypeInput { service?: SmsDeliveryInterface; - override?: (originalImplementation: SmsDeliveryInterface, builder: OverrideableBuilder>) => SmsDeliveryInterface; + override?: ( + originalImplementation: SmsDeliveryInterface, + builder: OverrideableBuilder> + ) => SmsDeliveryInterface; } export interface TypeInputWithService { service: SmsDeliveryInterface; - override?: (originalImplementation: SmsDeliveryInterface, builder: OverrideableBuilder>) => SmsDeliveryInterface; + override?: ( + originalImplementation: SmsDeliveryInterface, + builder: OverrideableBuilder> + ) => SmsDeliveryInterface; } diff --git a/lib/build/logger.js b/lib/build/logger.js index e90d1eb1d..520e67fc5 100644 --- a/lib/build/logger.js +++ b/lib/build/logger.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.logDebugMessage = void 0; const debug_1 = __importDefault(require("debug")); @@ -27,7 +29,11 @@ const SUPERTOKENS_DEBUG_NAMESPACE = "com.supertokens"; */ function logDebugMessage(message) { if (debug_1.default.enabled(SUPERTOKENS_DEBUG_NAMESPACE)) { - debug_1.default(SUPERTOKENS_DEBUG_NAMESPACE)(`{t: "${new Date().toISOString()}", message: \"${message}\", file: \"${getFileLocation()}\" sdkVer: "${version_1.version}"}`); + debug_1.default(SUPERTOKENS_DEBUG_NAMESPACE)( + `{t: "${new Date().toISOString()}", message: \"${message}\", file: \"${getFileLocation()}\" sdkVer: "${ + version_1.version + }"}` + ); console.log(); } } diff --git a/lib/build/nextjs.d.ts b/lib/build/nextjs.d.ts index d9474bda9..e04d3c068 100644 --- a/lib/build/nextjs.d.ts +++ b/lib/build/nextjs.d.ts @@ -1,4 +1,8 @@ export default class NextJS { - static superTokensNextWrapper(middleware: (next: (middlewareError?: any) => void) => Promise, request: any, response: any): Promise; + static superTokensNextWrapper( + middleware: (next: (middlewareError?: any) => void) => Promise, + request: any, + response: any + ): Promise; } export declare let superTokensNextWrapper: typeof NextJS.superTokensNextWrapper; diff --git a/lib/build/nextjs.js b/lib/build/nextjs.js index ac3313c21..97f8e2bad 100644 --- a/lib/build/nextjs.js +++ b/lib/build/nextjs.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.superTokensNextWrapper = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -43,27 +65,28 @@ function next(request, response, resolve, reject) { class NextJS { static superTokensNextWrapper(middleware, request, response) { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - request.__supertokensFromNextJS = true; - try { - let callbackCalled = false; - const result = yield middleware((err) => { - callbackCalled = true; - next(request, response, resolve, reject)(err); - }); - if (!callbackCalled && !response.finished && !response.headersSent) { - return resolve(result); - } - } - catch (err) { - yield express_1.errorHandler()(err, request, response, (errorHandlerError) => { - if (errorHandlerError !== undefined) { - return reject(errorHandlerError); + return new Promise((resolve, reject) => + __awaiter(this, void 0, void 0, function* () { + request.__supertokensFromNextJS = true; + try { + let callbackCalled = false; + const result = yield middleware((err) => { + callbackCalled = true; + next(request, response, resolve, reject)(err); + }); + if (!callbackCalled && !response.finished && !response.headersSent) { + return resolve(result); } - // do nothing, error handler does not resolve the promise. - }); - } - })); + } catch (err) { + yield express_1.errorHandler()(err, request, response, (errorHandlerError) => { + if (errorHandlerError !== undefined) { + return reject(errorHandlerError); + } + // do nothing, error handler does not resolve the promise. + }); + } + }) + ); }); } } diff --git a/lib/build/normalisedURLDomain.js b/lib/build/normalisedURLDomain.js index 2bc9d05aa..e4a69f7f8 100644 --- a/lib/build/normalisedURLDomain.js +++ b/lib/build/normalisedURLDomain.js @@ -35,17 +35,14 @@ function normaliseURLDomainOrThrowError(input, ignoreProtocol = false) { if (ignoreProtocol) { if (urlObj.hostname.startsWith("localhost") || utils_1.isAnIpAddress(urlObj.hostname)) { input = "http://" + urlObj.host; - } - else { + } else { input = "https://" + urlObj.host; } - } - else { + } else { input = urlObj.protocol + "//" + urlObj.host; } return input; - } - catch (err) { } + } catch (err) {} // not a valid URL if (input.startsWith("/")) { throw Error("Please provide a valid domain name"); @@ -55,16 +52,17 @@ function normaliseURLDomainOrThrowError(input, ignoreProtocol = false) { } // If the input contains a . it means they have given a domain name. // So we try assuming that they have given a domain name - if ((input.indexOf(".") !== -1 || input.startsWith("localhost")) && + if ( + (input.indexOf(".") !== -1 || input.startsWith("localhost")) && !input.startsWith("http://") && - !input.startsWith("https://")) { + !input.startsWith("https://") + ) { input = "https://" + input; // at this point, it should be a valid URL. So we test that before doing a recursive call try { new url_1.URL(input); return normaliseURLDomainOrThrowError(input, true); - } - catch (err) { } + } catch (err) {} } throw Error("Please provide a valid domain name"); } diff --git a/lib/build/normalisedURLPath.js b/lib/build/normalisedURLPath.js index 3c724145f..c254d8349 100644 --- a/lib/build/normalisedURLPath.js +++ b/lib/build/normalisedURLPath.js @@ -48,14 +48,15 @@ function normaliseURLPathOrThrowError(input) { return input.substr(0, input.length - 1); } return input; - } - catch (err) { } + } catch (err) {} // not a valid URL // If the input contains a . it means they have given a domain name. // So we try assuming that they have given a domain name + path - if ((domainGiven(input) || input.startsWith("localhost")) && + if ( + (domainGiven(input) || input.startsWith("localhost")) && !input.startsWith("http://") && - !input.startsWith("https://")) { + !input.startsWith("https://") + ) { input = "http://" + input; return normaliseURLPathOrThrowError(input); } @@ -67,8 +68,7 @@ function normaliseURLPathOrThrowError(input) { // test that we can convert this to prevent an infinite loop new url_1.URL("http://example.com" + input); return normaliseURLPathOrThrowError("http://example.com" + input); - } - catch (err) { + } catch (err) { throw Error("Please provide a valid URL path"); } } @@ -80,12 +80,10 @@ function domainGiven(input) { try { let url = new url_1.URL(input); return url.hostname.indexOf(".") !== -1; - } - catch (ignored) { } + } catch (ignored) {} try { let url = new url_1.URL("http://" + input); return url.hostname.indexOf(".") !== -1; - } - catch (ignored) { } + } catch (ignored) {} return false; } diff --git a/lib/build/processState.d.ts b/lib/build/processState.d.ts index cfbe2e5ed..1a226f8c5 100644 --- a/lib/build/processState.d.ts +++ b/lib/build/processState.d.ts @@ -2,7 +2,7 @@ export declare enum PROCESS_STATE { CALLING_SERVICE_IN_VERIFY = 0, CALLING_SERVICE_IN_GET_HANDSHAKE_INFO = 1, CALLING_SERVICE_IN_GET_API_VERSION = 2, - CALLING_SERVICE_IN_REQUEST_HELPER = 3 + CALLING_SERVICE_IN_REQUEST_HELPER = 3, } export declare class ProcessState { history: PROCESS_STATE[]; diff --git a/lib/build/processState.js b/lib/build/processState.js index 8df0d20df..cc8358844 100644 --- a/lib/build/processState.js +++ b/lib/build/processState.js @@ -13,24 +13,47 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProcessState = exports.PROCESS_STATE = void 0; var PROCESS_STATE; (function (PROCESS_STATE) { - PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_VERIFY"] = 0] = "CALLING_SERVICE_IN_VERIFY"; - PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"] = 1] = "CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"; - PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_GET_API_VERSION"] = 2] = "CALLING_SERVICE_IN_GET_API_VERSION"; - PROCESS_STATE[PROCESS_STATE["CALLING_SERVICE_IN_REQUEST_HELPER"] = 3] = "CALLING_SERVICE_IN_REQUEST_HELPER"; -})(PROCESS_STATE = exports.PROCESS_STATE || (exports.PROCESS_STATE = {})); + PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_VERIFY"] = 0)] = "CALLING_SERVICE_IN_VERIFY"; + PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"] = 1)] = + "CALLING_SERVICE_IN_GET_HANDSHAKE_INFO"; + PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_GET_API_VERSION"] = 2)] = "CALLING_SERVICE_IN_GET_API_VERSION"; + PROCESS_STATE[(PROCESS_STATE["CALLING_SERVICE_IN_REQUEST_HELPER"] = 3)] = "CALLING_SERVICE_IN_REQUEST_HELPER"; +})((PROCESS_STATE = exports.PROCESS_STATE || (exports.PROCESS_STATE = {}))); class ProcessState { constructor() { this.history = []; @@ -50,27 +73,26 @@ class ProcessState { this.reset = () => { this.history = []; }; - this.waitForEvent = (state, timeInMS = 7000) => __awaiter(this, void 0, void 0, function* () { - let startTime = Date.now(); - return new Promise((resolve) => { - let actualThis = this; - function tryAndGet() { - let result = actualThis.getEventByLastEventByName(state); - if (result === undefined) { - if (Date.now() - startTime > timeInMS) { - resolve(undefined); - } - else { - setTimeout(tryAndGet, 1000); + this.waitForEvent = (state, timeInMS = 7000) => + __awaiter(this, void 0, void 0, function* () { + let startTime = Date.now(); + return new Promise((resolve) => { + let actualThis = this; + function tryAndGet() { + let result = actualThis.getEventByLastEventByName(state); + if (result === undefined) { + if (Date.now() - startTime > timeInMS) { + resolve(undefined); + } else { + setTimeout(tryAndGet, 1000); + } + } else { + resolve(result); } } - else { - resolve(result); - } - } - tryAndGet(); + tryAndGet(); + }); }); - }); } static getInstance() { if (ProcessState.instance === undefined) { diff --git a/lib/build/querier.d.ts b/lib/build/querier.d.ts index 378421357..0a211ea06 100644 --- a/lib/build/querier.d.ts +++ b/lib/build/querier.d.ts @@ -14,10 +14,13 @@ export declare class Querier { static reset(): void; getHostsAliveForTesting: () => Set; static getNewInstanceOrThrowError(rIdToCore?: string): Querier; - static init(hosts?: { - domain: NormalisedURLDomain; - basePath: NormalisedURLPath; - }[], apiKey?: string): void; + static init( + hosts?: { + domain: NormalisedURLDomain; + basePath: NormalisedURLPath; + }[], + apiKey?: string + ): void; sendPostRequest: (path: NormalisedURLPath, body: any) => Promise; sendDeleteRequest: (path: NormalisedURLPath, body: any) => Promise; sendGetRequest: (path: NormalisedURLPath, params: any) => Promise; diff --git a/lib/build/querier.js b/lib/build/querier.js index 91e82d489..4f184e7a0 100644 --- a/lib/build/querier.js +++ b/lib/build/querier.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Querier = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -36,31 +60,44 @@ class Querier { // we have rIdToCore so that recipes can force change the rId sent to core. This is a hack until the core is able // to support multiple rIds per API constructor(hosts, rIdToCore) { - this.getAPIVersion = () => __awaiter(this, void 0, void 0, function* () { - var _a; - if (Querier.apiVersion !== undefined) { - return Querier.apiVersion; - } - processState_1.ProcessState.getInstance().addState(processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_API_VERSION); - let response = yield this.sendRequestHelper(new normalisedURLPath_1.default("/apiversion"), "GET", (url) => { - let headers = {}; - if (Querier.apiKey !== undefined) { - headers = { - "api-key": Querier.apiKey, - }; + this.getAPIVersion = () => + __awaiter(this, void 0, void 0, function* () { + var _a; + if (Querier.apiVersion !== undefined) { + return Querier.apiVersion; } - return axios_1.default.get(url, { - headers, - }); - }, ((_a = this.__hosts) === null || _a === void 0 ? void 0 : _a.length) || 0); - let cdiSupportedByServer = response.versions; - let supportedVersion = utils_1.getLargestVersionFromIntersection(cdiSupportedByServer, version_1.cdiSupported); - if (supportedVersion === undefined) { - throw Error("The running SuperTokens core version is not compatible with this NodeJS SDK. Please visit https://supertokens.io/docs/community/compatibility to find the right versions"); - } - Querier.apiVersion = supportedVersion; - return Querier.apiVersion; - }); + processState_1.ProcessState.getInstance().addState( + processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_API_VERSION + ); + let response = yield this.sendRequestHelper( + new normalisedURLPath_1.default("/apiversion"), + "GET", + (url) => { + let headers = {}; + if (Querier.apiKey !== undefined) { + headers = { + "api-key": Querier.apiKey, + }; + } + return axios_1.default.get(url, { + headers, + }); + }, + ((_a = this.__hosts) === null || _a === void 0 ? void 0 : _a.length) || 0 + ); + let cdiSupportedByServer = response.versions; + let supportedVersion = utils_1.getLargestVersionFromIntersection( + cdiSupportedByServer, + version_1.cdiSupported + ); + if (supportedVersion === undefined) { + throw Error( + "The running SuperTokens core version is not compatible with this NodeJS SDK. Please visit https://supertokens.io/docs/community/compatibility to find the right versions" + ); + } + Querier.apiVersion = supportedVersion; + return Querier.apiVersion; + }); this.getHostsAliveForTesting = () => { if (process.env.TEST_MODE !== "testing") { throw Error("calling testing function in non testing env"); @@ -68,128 +105,171 @@ class Querier { return Querier.hostsAliveForTesting; }; // path should start with "/" - this.sendPostRequest = (path, body) => __awaiter(this, void 0, void 0, function* () { - var _b; - return this.sendRequestHelper(path, "POST", (url) => __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { - "cdi-version": apiVersion, - "content-type": "application/json; charset=utf-8", - }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default({ - method: "POST", - url, - data: body, - headers, - }); - }), ((_b = this.__hosts) === null || _b === void 0 ? void 0 : _b.length) || 0); - }); + this.sendPostRequest = (path, body) => + __awaiter(this, void 0, void 0, function* () { + var _b; + return this.sendRequestHelper( + path, + "POST", + (url) => + __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { + "cdi-version": apiVersion, + "content-type": "application/json; charset=utf-8", + }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default({ + method: "POST", + url, + data: body, + headers, + }); + }), + ((_b = this.__hosts) === null || _b === void 0 ? void 0 : _b.length) || 0 + ); + }); // path should start with "/" - this.sendDeleteRequest = (path, body) => __awaiter(this, void 0, void 0, function* () { - var _c; - return this.sendRequestHelper(path, "DELETE", (url) => __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { "cdi-version": apiVersion }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey, "content-type": "application/json; charset=utf-8" }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default({ - method: "DELETE", - url, - data: body, - headers, - }); - }), ((_c = this.__hosts) === null || _c === void 0 ? void 0 : _c.length) || 0); - }); + this.sendDeleteRequest = (path, body) => + __awaiter(this, void 0, void 0, function* () { + var _c; + return this.sendRequestHelper( + path, + "DELETE", + (url) => + __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { "cdi-version": apiVersion }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { + "api-key": Querier.apiKey, + "content-type": "application/json; charset=utf-8", + }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default({ + method: "DELETE", + url, + data: body, + headers, + }); + }), + ((_c = this.__hosts) === null || _c === void 0 ? void 0 : _c.length) || 0 + ); + }); // path should start with "/" - this.sendGetRequest = (path, params) => __awaiter(this, void 0, void 0, function* () { - var _d; - return this.sendRequestHelper(path, "GET", (url) => __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { "cdi-version": apiVersion }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default.get(url, { - params, - headers, - }); - }), ((_d = this.__hosts) === null || _d === void 0 ? void 0 : _d.length) || 0); - }); + this.sendGetRequest = (path, params) => + __awaiter(this, void 0, void 0, function* () { + var _d; + return this.sendRequestHelper( + path, + "GET", + (url) => + __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { "cdi-version": apiVersion }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default.get(url, { + params, + headers, + }); + }), + ((_d = this.__hosts) === null || _d === void 0 ? void 0 : _d.length) || 0 + ); + }); // path should start with "/" - this.sendPutRequest = (path, body) => __awaiter(this, void 0, void 0, function* () { - var _e; - return this.sendRequestHelper(path, "PUT", (url) => __awaiter(this, void 0, void 0, function* () { - let apiVersion = yield this.getAPIVersion(); - let headers = { "cdi-version": apiVersion, "content-type": "application/json; charset=utf-8" }; - if (Querier.apiKey !== undefined) { - headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); - } - if (path.isARecipePath() && this.rIdToCore !== undefined) { - headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); - } - return yield axios_1.default({ - method: "PUT", - url, - data: body, - headers, - }); - }), ((_e = this.__hosts) === null || _e === void 0 ? void 0 : _e.length) || 0); - }); + this.sendPutRequest = (path, body) => + __awaiter(this, void 0, void 0, function* () { + var _e; + return this.sendRequestHelper( + path, + "PUT", + (url) => + __awaiter(this, void 0, void 0, function* () { + let apiVersion = yield this.getAPIVersion(); + let headers = { + "cdi-version": apiVersion, + "content-type": "application/json; charset=utf-8", + }; + if (Querier.apiKey !== undefined) { + headers = Object.assign(Object.assign({}, headers), { "api-key": Querier.apiKey }); + } + if (path.isARecipePath() && this.rIdToCore !== undefined) { + headers = Object.assign(Object.assign({}, headers), { rid: this.rIdToCore }); + } + return yield axios_1.default({ + method: "PUT", + url, + data: body, + headers, + }); + }), + ((_e = this.__hosts) === null || _e === void 0 ? void 0 : _e.length) || 0 + ); + }); // path should start with "/" - this.sendRequestHelper = (path, method, axiosFunction, numberOfTries) => __awaiter(this, void 0, void 0, function* () { - if (this.__hosts === undefined) { - throw Error("No SuperTokens core available to query. Please pass supertokens > connectionURI to the init function, or override all the functions of the recipe you are using."); - } - if (numberOfTries === 0) { - throw Error("No SuperTokens core available to query"); - } - let currentDomain = this.__hosts[Querier.lastTriedIndex].domain.getAsStringDangerous(); - let currentBasePath = this.__hosts[Querier.lastTriedIndex].basePath.getAsStringDangerous(); - Querier.lastTriedIndex++; - Querier.lastTriedIndex = Querier.lastTriedIndex % this.__hosts.length; - try { - processState_1.ProcessState.getInstance().addState(processState_1.PROCESS_STATE.CALLING_SERVICE_IN_REQUEST_HELPER); - let response = yield axiosFunction(currentDomain + currentBasePath + path.getAsStringDangerous()); - if (process.env.TEST_MODE === "testing") { - Querier.hostsAliveForTesting.add(currentDomain + currentBasePath); - } - if (response.status !== 200) { - throw response; + this.sendRequestHelper = (path, method, axiosFunction, numberOfTries) => + __awaiter(this, void 0, void 0, function* () { + if (this.__hosts === undefined) { + throw Error( + "No SuperTokens core available to query. Please pass supertokens > connectionURI to the init function, or override all the functions of the recipe you are using." + ); } - return response.data; - } - catch (err) { - if (err.message !== undefined && err.message.includes("ECONNREFUSED")) { - return yield this.sendRequestHelper(path, method, axiosFunction, numberOfTries - 1); - } - if (err.response !== undefined && err.response.status !== undefined && err.response.data !== undefined) { - throw new Error("SuperTokens core threw an error for a " + - method + - " request to path: '" + - path.getAsStringDangerous() + - "' with status code: " + - err.response.status + - " and message: " + - err.response.data); + if (numberOfTries === 0) { + throw Error("No SuperTokens core available to query"); } - else { - throw err; + let currentDomain = this.__hosts[Querier.lastTriedIndex].domain.getAsStringDangerous(); + let currentBasePath = this.__hosts[Querier.lastTriedIndex].basePath.getAsStringDangerous(); + Querier.lastTriedIndex++; + Querier.lastTriedIndex = Querier.lastTriedIndex % this.__hosts.length; + try { + processState_1.ProcessState.getInstance().addState( + processState_1.PROCESS_STATE.CALLING_SERVICE_IN_REQUEST_HELPER + ); + let response = yield axiosFunction(currentDomain + currentBasePath + path.getAsStringDangerous()); + if (process.env.TEST_MODE === "testing") { + Querier.hostsAliveForTesting.add(currentDomain + currentBasePath); + } + if (response.status !== 200) { + throw response; + } + return response.data; + } catch (err) { + if (err.message !== undefined && err.message.includes("ECONNREFUSED")) { + return yield this.sendRequestHelper(path, method, axiosFunction, numberOfTries - 1); + } + if ( + err.response !== undefined && + err.response.status !== undefined && + err.response.data !== undefined + ) { + throw new Error( + "SuperTokens core threw an error for a " + + method + + " request to path: '" + + path.getAsStringDangerous() + + "' with status code: " + + err.response.status + + " and message: " + + err.response.data + ); + } else { + throw err; + } } - } - }); + }); this.__hosts = hosts; this.rIdToCore = rIdToCore; } diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index b81517ae3..f509a3701 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -2,68 +2,122 @@ import Recipe from "./recipe"; import type { RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; - static getRecipeUserIdsForPrimaryUserIds(primaryUserIds: string[], userContext?: any): Promise<{ + static getRecipeUserIdsForPrimaryUserIds( + primaryUserIds: string[], + userContext?: any + ): Promise<{ [primaryUserId: string]: string[]; }>; - static getPrimaryUserIdsForRecipeUserIds(recipeUserIds: string[], userContext?: any): Promise<{ + static getPrimaryUserIdsForRecipeUserIds( + recipeUserIds: string[], + userContext?: any + ): Promise<{ [recipeUserId: string]: string | null; }>; - static canCreatePrimaryUserId(recipeUserId: string, userContext?: any): Promise<{ - status: "OK"; - wasAlreadyAPrimaryUser: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; - static createPrimaryUser(recipeUserId: string, userContext?: any): Promise<{ - status: "OK"; - user: import("../emailpassword").User; - wasAlreadyAPrimaryUser: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; - static canLinkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any): Promise<{ - status: "OK"; - accountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; - static linkAccounts(recipeUserId: string, primaryUserId: string, userContext?: any): Promise<{ - status: "OK"; - accountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; - static unlinkAccounts(recipeUserId: string, userContext?: any): Promise<{ - status: "OK"; - wasRecipeUserDeleted: boolean; - } | { - status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; - description: string; - }>; - static fetchFromAccountToLinkTable(recipeUserId: string, userContext?: any): Promise; - static storeIntoAccountToLinkTable(recipeUserId: string, primaryUserId: string, userContext?: any): Promise<{ - status: "OK"; - didInsertNewRow: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - }>; + static canCreatePrimaryUserId( + recipeUserId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + wasAlreadyAPrimaryUser: boolean; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static createPrimaryUser( + recipeUserId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + user: import("../emailpassword").User; + wasAlreadyAPrimaryUser: boolean; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static canLinkAccounts( + recipeUserId: string, + primaryUserId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + accountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static linkAccounts( + recipeUserId: string, + primaryUserId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + accountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; + static unlinkAccounts( + recipeUserId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + wasRecipeUserDeleted: boolean; + } + | { + status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; + description: string; + } + >; + static fetchFromAccountToLinkTable( + recipeUserId: string, + userContext?: any + ): Promise; + static storeIntoAccountToLinkTable( + recipeUserId: string, + primaryUserId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + didInsertNewRow: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + } + >; } export declare const init: typeof Recipe.init; export declare const getRecipeUserIdsForPrimaryUserIds: typeof Wrapper.getRecipeUserIdsForPrimaryUserIds; diff --git a/lib/build/recipe/accountlinking/index.js b/lib/build/recipe/accountlinking/index.js index 91c58d860..68d95f64d 100644 --- a/lib/build/recipe/accountlinking/index.js +++ b/lib/build/recipe/accountlinking/index.js @@ -13,36 +13,64 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.storeIntoAccountToLinkTable = exports.fetchFromAccountToLinkTable = exports.unlinkAccounts = exports.linkAccounts = exports.canLinkAccounts = exports.createPrimaryUser = exports.canCreatePrimaryUserId = exports.getPrimaryUserIdsForRecipeUserIds = exports.getRecipeUserIdsForPrimaryUserIds = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); class Wrapper { static getRecipeUserIdsForPrimaryUserIds(primaryUserIds, userContext) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getRecipeUserIdsForPrimaryUserIds({ - primaryUserIds, - userContext: userContext === undefined ? {} : userContext, - }); + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getRecipeUserIdsForPrimaryUserIds({ + primaryUserIds, + userContext: userContext === undefined ? {} : userContext, + }); }); } static getPrimaryUserIdsForRecipeUserIds(recipeUserIds, userContext) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getPrimaryUserIdsForRecipeUserIds({ - recipeUserIds, - userContext: userContext === undefined ? {} : userContext, - }); + return yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getPrimaryUserIdsForRecipeUserIds({ + recipeUserIds, + userContext: userContext === undefined ? {} : userContext, + }); }); } static canCreatePrimaryUserId(recipeUserId, userContext) { diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index e6a3f8f54..324845e3f 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -14,22 +14,39 @@ export default class Recipe extends RecipeModule { static init(config: TypeInput): RecipeListFunction; static getInstanceOrThrowError(): Recipe; getAPIsHandled(): APIHandled[]; - handleAPIRequest(_id: string, _req: BaseRequest, _response: BaseResponse, _path: normalisedURLPath, _method: HTTPMethod): Promise; + handleAPIRequest( + _id: string, + _req: BaseRequest, + _response: BaseResponse, + _path: normalisedURLPath, + _method: HTTPMethod + ): Promise; handleError(error: error, _request: BaseRequest, _response: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; - createPrimaryUserIdOrLinkAccounts: ({ recipeUserId, isVerified, checkAccountsToLinkTableAsWell, userContext, }: { + createPrimaryUserIdOrLinkAccounts: ({ + recipeUserId, + isVerified, + checkAccountsToLinkTableAsWell, + userContext, + }: { recipeUserId: string; isVerified: boolean; checkAccountsToLinkTableAsWell: boolean; userContext: any; }) => Promise; - getPrimaryUserIdThatCanBeLinkedToRecipeUserId: ({ recipeUserId, checkAccountsToLinkTableAsWell, userContext, }: { + getPrimaryUserIdThatCanBeLinkedToRecipeUserId: ({ + recipeUserId, + checkAccountsToLinkTableAsWell, + userContext, + }: { recipeUserId: string; checkAccountsToLinkTableAsWell: boolean; userContext: any; }) => Promise; - transformUserInfoIntoVerifiedAndUnverifiedBucket: (user: User) => { + transformUserInfoIntoVerifiedAndUnverifiedBucket: ( + user: User + ) => { verified: { emails: string[]; phoneNumbers: string[]; @@ -39,19 +56,30 @@ export default class Recipe extends RecipeModule { phoneNumbers: string[]; }; }; - isSignUpAllowed: ({ newUser, userContext, }: { + isSignUpAllowed: ({ + newUser, + userContext, + }: { newUser: AccountInfoWithRecipeId; userContext: any; }) => Promise; - linkAccountsWithUserFromSession: ({ session, newUser, createRecipeUserFunc, userContext, }: { + linkAccountsWithUserFromSession: ({ + session, + newUser, + createRecipeUserFunc, + userContext, + }: { session: SessionContainer; newUser: AccountInfoWithRecipeId; createRecipeUserFunc: (newUser: AccountInfoWithRecipeId) => Promise; userContext: any; - }) => Promise<{ - status: "OK" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - }>; + }) => Promise< + | { + status: "OK" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + >; } diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index 9a6e40ebd..da58201a4 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const utils_1 = require("./utils"); @@ -38,129 +62,152 @@ class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, config, _recipes, _ingredients) { super(recipeId, appInfo); // this function returns the user ID for which the session will be created. - this.createPrimaryUserIdOrLinkAccounts = ({ recipeUserId, isVerified, checkAccountsToLinkTableAsWell, userContext, }) => __awaiter(this, void 0, void 0, function* () { - let recipeUser = yield __1.getUser(recipeUserId, userContext); - if (recipeUser === undefined) { - throw Error("Race condition error. It means that the input recipeUserId was deleted"); - } - if (recipeUser.isPrimaryUser) { - return recipeUser.id; - } - // now we try and find a linking candidate. - let primaryUser = yield this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ - recipeUserId, - checkAccountsToLinkTableAsWell, - userContext, - }); - if (primaryUser === undefined) { - // this means that this can become a primary user. - // we can use the 0 index cause this user is - // not a primary user. - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(recipeUser.loginMethods[0], undefined, undefined, userContext); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return recipeUserId; + this.createPrimaryUserIdOrLinkAccounts = ({ + recipeUserId, + isVerified, + checkAccountsToLinkTableAsWell, + userContext, + }) => + __awaiter(this, void 0, void 0, function* () { + let recipeUser = yield __1.getUser(recipeUserId, userContext); + if (recipeUser === undefined) { + throw Error("Race condition error. It means that the input recipeUserId was deleted"); } - if (shouldDoAccountLinking.shouldRequireVerification && !isVerified) { - return recipeUserId; - } - let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId: recipeUserId, - userContext, - }); - if (createPrimaryUserResult.status === "OK") { - return createPrimaryUserResult.user.id; + if (recipeUser.isPrimaryUser) { + return recipeUser.id; } - // status is "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" or "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - // if it comes here, it means that the recipe - // user ID is already linked to another primary - // user id (race condition), or that some other - // primary user ID exists with the same email / phone number (again, race condition). - // So we do recursion here to try again. - return yield this.createPrimaryUserIdOrLinkAccounts({ + // now we try and find a linking candidate. + let primaryUser = yield this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId({ recipeUserId, - isVerified, checkAccountsToLinkTableAsWell, userContext, }); - } - else { - // this means that we found a primary user ID which can be linked to this recipe user ID. So we try and link them. - // we can use the 0 index cause this user is - // not a primary user. - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(recipeUser.loginMethods[0], primaryUser, undefined, userContext); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return recipeUserId; - } - if (shouldDoAccountLinking.shouldRequireVerification && !isVerified) { - return recipeUserId; - } - let linkAccountsResult = yield this.recipeInterfaceImpl.linkAccounts({ - recipeUserId: recipeUserId, - primaryUserId: primaryUser.id, - userContext, - }); - if (linkAccountsResult.status === "OK") { - return primaryUser.id; - } - else if (linkAccountsResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { - // this can happen cause of a race condition - // wherein the recipe user ID get's linked to - // some other primary user whilst this function is running. - // But this is OK cause we just care about - // returning the user ID of the linked user - // which the result has. - return linkAccountsResult.primaryUserId; - } - else { - // status is "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - // it can come here if the recipe user ID - // can't be linked to the primary user ID cause - // the email / phone number is associated with some other primary user ID. - // This can happen due to a race condition in which - // the email has changed from one primary user to another during this function call, - // or it can happen if the accounts to link table - // contains a user which this is supposed to - // be linked to, but we can't link it cause during the time the user was added to that table and now, some other primary user has - // got this email. - // So we try again, but without caring about - // the accounts to link table (cause they we will end up in an infinite recursion). + if (primaryUser === undefined) { + // this means that this can become a primary user. + // we can use the 0 index cause this user is + // not a primary user. + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + recipeUser.loginMethods[0], + undefined, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } + if (shouldDoAccountLinking.shouldRequireVerification && !isVerified) { + return recipeUserId; + } + let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: recipeUserId, + userContext, + }); + if (createPrimaryUserResult.status === "OK") { + return createPrimaryUserResult.user.id; + } + // status is "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" or "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + // if it comes here, it means that the recipe + // user ID is already linked to another primary + // user id (race condition), or that some other + // primary user ID exists with the same email / phone number (again, race condition). + // So we do recursion here to try again. return yield this.createPrimaryUserIdOrLinkAccounts({ recipeUserId, isVerified, - checkAccountsToLinkTableAsWell: false, + checkAccountsToLinkTableAsWell, + userContext, + }); + } else { + // this means that we found a primary user ID which can be linked to this recipe user ID. So we try and link them. + // we can use the 0 index cause this user is + // not a primary user. + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + recipeUser.loginMethods[0], + primaryUser, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return recipeUserId; + } + if (shouldDoAccountLinking.shouldRequireVerification && !isVerified) { + return recipeUserId; + } + let linkAccountsResult = yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: recipeUserId, + primaryUserId: primaryUser.id, userContext, }); + if (linkAccountsResult.status === "OK") { + return primaryUser.id; + } else if ( + linkAccountsResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + // this can happen cause of a race condition + // wherein the recipe user ID get's linked to + // some other primary user whilst this function is running. + // But this is OK cause we just care about + // returning the user ID of the linked user + // which the result has. + return linkAccountsResult.primaryUserId; + } else { + // status is "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + // it can come here if the recipe user ID + // can't be linked to the primary user ID cause + // the email / phone number is associated with some other primary user ID. + // This can happen due to a race condition in which + // the email has changed from one primary user to another during this function call, + // or it can happen if the accounts to link table + // contains a user which this is supposed to + // be linked to, but we can't link it cause during the time the user was added to that table and now, some other primary user has + // got this email. + // So we try again, but without caring about + // the accounts to link table (cause they we will end up in an infinite recursion). + return yield this.createPrimaryUserIdOrLinkAccounts({ + recipeUserId, + isVerified, + checkAccountsToLinkTableAsWell: false, + userContext, + }); + } } - } - }); - this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId = ({ recipeUserId, checkAccountsToLinkTableAsWell, userContext, }) => __awaiter(this, void 0, void 0, function* () { - // first we check if this user itself is a - // primary user or not. If it is, we return that. - let user = yield __1.getUser(recipeUserId, userContext); - if (user === undefined) { - return undefined; - } - if (user.isPrimaryUser) { - return user; - } - // then we check the accounts to link table. This - // table can have an entry if this user was trying - // to be linked to another user post sign in but required - // email verification. - if (checkAccountsToLinkTableAsWell) { - let pUser = yield this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ recipeUserId, userContext }); - if (pUser !== undefined && pUser.isPrimaryUser) { - return pUser; + }); + this.getPrimaryUserIdThatCanBeLinkedToRecipeUserId = ({ + recipeUserId, + checkAccountsToLinkTableAsWell, + userContext, + }) => + __awaiter(this, void 0, void 0, function* () { + // first we check if this user itself is a + // primary user or not. If it is, we return that. + let user = yield __1.getUser(recipeUserId, userContext); + if (user === undefined) { + return undefined; } - } - // finally, we try and find a primary user based on - // the email / phone number / third party ID. - let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo: user.loginMethods[0], - userContext, + if (user.isPrimaryUser) { + return user; + } + // then we check the accounts to link table. This + // table can have an entry if this user was trying + // to be linked to another user post sign in but required + // email verification. + if (checkAccountsToLinkTableAsWell) { + let pUser = yield this.recipeInterfaceImpl.fetchFromAccountToLinkTable({ + recipeUserId, + userContext, + }); + if (pUser !== undefined && pUser.isPrimaryUser) { + return pUser; + } + } + // finally, we try and find a primary user based on + // the email / phone number / third party ID. + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + accountInfo: user.loginMethods[0], + userContext, + }); + return users.find((u) => u.isPrimaryUser); }); - return users.find((u) => u.isPrimaryUser); - }); this.transformUserInfoIntoVerifiedAndUnverifiedBucket = (user) => { let identities = { verified: { @@ -177,16 +224,14 @@ class Recipe extends recipeModule_1.default { if (loginMethod.email !== undefined) { if (loginMethod.verified) { identities.verified.emails.push(loginMethod.email); - } - else { + } else { identities.unverified.emails.push(loginMethod.email); } } if (loginMethod.phoneNumber !== undefined) { if (loginMethod.verified) { identities.verified.phoneNumbers.push(loginMethod.phoneNumber); - } - else { + } else { identities.unverified.phoneNumbers.push(loginMethod.phoneNumber); } } @@ -200,262 +245,301 @@ class Recipe extends recipeModule_1.default { // one user can only have one unique thirdPart login. return identities; }; - this.isSignUpAllowed = ({ newUser, userContext, }) => __awaiter(this, void 0, void 0, function* () { - // we find other accounts based on the email / phone number. - let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo: newUser, - userContext, - }); - if (users.length === 0) { - // this is a brand new email / phone number, so we allow sign up. - return true; - } - // now we check if there exists some primary user with the same email / phone number - // such that that info is not verified for that account. In this case, we do not allow - // sign up cause we cannot link this new account to that primary account yet (since - // the email / phone is unverified), and we can't make this a primary user either (since - // then there would be two primary users with the same email / phone number - which is - // not allowed..) - let primaryUser = users.find((u) => u.isPrimaryUser); - if (primaryUser === undefined) { - // since there is no primary user, we allow the sign up.. - return true; - } - let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(newUser, primaryUser, undefined, userContext); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return true; - } - if (!shouldDoAccountLinking.shouldRequireVerification) { - // the dev says they do not care about verification before account linking - // so we can link this new user to the primary user post recipe user creation - // even if that user's email / phone number is not verified. - return true; - } - let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); - // we check the verified array and not the - // unverfied array cause we allow signing up - // even if one of the recipe accounts has the - // email / phone numbers as verified for the primary account. - if (newUser.email !== undefined) { - return identitiesForPrimaryUser.verified.emails.includes(newUser.email); - } - if (newUser.phoneNumber !== undefined) { - return identitiesForPrimaryUser.verified.phoneNumbers.includes(newUser.phoneNumber); - } - return false; - }); - this.linkAccountsWithUserFromSession = ({ session, newUser, createRecipeUserFunc, userContext, }) => __awaiter(this, void 0, void 0, function* () { - // In order to link the newUser to the session user, - // we need to first make sure that the session user - // is a primary user (or make them one if they are not). - let existingUser = yield this.recipeInterfaceImpl.getUser({ - userId: session.getUserId(), - userContext, - }); - if (existingUser === undefined) { - // this can come here if the user ID in the session belongs to a user - // that is not recognized by SuperTokens. In this case, we - // simply return the session user ID - return { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "We cannot link accounts since the session belongs to a user ID that does not exist in SuperTokens.", - }; - } - if (!existingUser.isPrimaryUser) { - // we will try and make the existing user a primary user. But before that, we must ask the - // dev if they want to allow for that. - // we ask the dev if the new user should be a candidate for account linking. - const shouldDoAccountLinkingOfNewUser = yield this.config.shouldDoAutomaticAccountLinking(newUser, undefined, session, userContext); - if (!shouldDoAccountLinkingOfNewUser.shouldAutomaticallyLink) { - return { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "Account linking not allowed by the developer for new user.", - }; + this.isSignUpAllowed = ({ newUser, userContext }) => + __awaiter(this, void 0, void 0, function* () { + // we find other accounts based on the email / phone number. + let users = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + accountInfo: newUser, + userContext, + }); + if (users.length === 0) { + // this is a brand new email / phone number, so we allow sign up. + return true; } - // we do not care about the new user's verification status here cause we are in the process of making the session user a primary user first. - // Now we ask the user if the existing login method can be linked to anything - // (since it's not a primary user) - // here we can use the index of 0 cause the existingUser is not a primary user, - // therefore it will only have one login method in the loginMethods' array. - const shouldDoAccountLinkingOfExistingUser = yield this.config.shouldDoAutomaticAccountLinking(existingUser.loginMethods[0], undefined, session, userContext); - if (!shouldDoAccountLinkingOfExistingUser.shouldAutomaticallyLink) { - return { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "Account linking not allowed by the developer for existing user.", - }; + // now we check if there exists some primary user with the same email / phone number + // such that that info is not verified for that account. In this case, we do not allow + // sign up cause we cannot link this new account to that primary account yet (since + // the email / phone is unverified), and we can't make this a primary user either (since + // then there would be two primary users with the same email / phone number - which is + // not allowed..) + let primaryUser = users.find((u) => u.isPrimaryUser); + if (primaryUser === undefined) { + // since there is no primary user, we allow the sign up.. + return true; } - if (shouldDoAccountLinkingOfExistingUser.shouldRequireVerification && - !existingUser.loginMethods[0].verified) { - // We do not allow creation of primary user - // if the existing user is not verified - // cause if we do, then it blocks sign up - // with other methods for the same email / phone number - // until this account is verified. This can be - // used by an attacker to prevent sign up from - // their victim by setting the account - // in this state and not verifying the account. - // The downside to this is that cause of this, - // in situations like MFA, we are forcing - // email verification to happen right after the user - // has finished setting up the second factor. - // This may not be something that the developer - // wants. But they can always switch this off - // by providing the right impl for shouldDoAutomaticAccountLinking - // this function will throw an email verification validation error. - yield session.assertClaims([emailVerificationClaim_1.EmailVerificationClaim.validators.isVerified(undefined, 0)]); + let shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + newUser, + primaryUser, + undefined, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { + return true; + } + if (!shouldDoAccountLinking.shouldRequireVerification) { + // the dev says they do not care about verification before account linking + // so we can link this new user to the primary user post recipe user creation + // even if that user's email / phone number is not verified. + return true; + } + let identitiesForPrimaryUser = this.transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); + // we check the verified array and not the + // unverfied array cause we allow signing up + // even if one of the recipe accounts has the + // email / phone numbers as verified for the primary account. + if (newUser.email !== undefined) { + return identitiesForPrimaryUser.verified.emails.includes(newUser.email); + } + if (newUser.phoneNumber !== undefined) { + return identitiesForPrimaryUser.verified.phoneNumbers.includes(newUser.phoneNumber); } - // now we can try and create a primary user for the existing user - let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ - recipeUserId: existingUser.loginMethods[0].recipeUserId, + return false; + }); + this.linkAccountsWithUserFromSession = ({ session, newUser, createRecipeUserFunc, userContext }) => + __awaiter(this, void 0, void 0, function* () { + // In order to link the newUser to the session user, + // we need to first make sure that the session user + // is a primary user (or make them one if they are not). + let existingUser = yield this.recipeInterfaceImpl.getUser({ + userId: session.getUserId(), userContext, }); - if (createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { - // this can happen if there is a race condition in which the - // existing user becomes a primary user ID by the time the code - // execution comes into this block. So we call the function once again. - return yield this.linkAccountsWithUserFromSession({ - session, + if (existingUser === undefined) { + // this can come here if the user ID in the session belongs to a user + // that is not recognized by SuperTokens. In this case, we + // simply return the session user ID + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: + "We cannot link accounts since the session belongs to a user ID that does not exist in SuperTokens.", + }; + } + if (!existingUser.isPrimaryUser) { + // we will try and make the existing user a primary user. But before that, we must ask the + // dev if they want to allow for that. + // we ask the dev if the new user should be a candidate for account linking. + const shouldDoAccountLinkingOfNewUser = yield this.config.shouldDoAutomaticAccountLinking( newUser, - createRecipeUserFunc, + undefined, + session, + userContext + ); + if (!shouldDoAccountLinkingOfNewUser.shouldAutomaticallyLink) { + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: "Account linking not allowed by the developer for new user.", + }; + } + // we do not care about the new user's verification status here cause we are in the process of making the session user a primary user first. + // Now we ask the user if the existing login method can be linked to anything + // (since it's not a primary user) + // here we can use the index of 0 cause the existingUser is not a primary user, + // therefore it will only have one login method in the loginMethods' array. + const shouldDoAccountLinkingOfExistingUser = yield this.config.shouldDoAutomaticAccountLinking( + existingUser.loginMethods[0], + undefined, + session, + userContext + ); + if (!shouldDoAccountLinkingOfExistingUser.shouldAutomaticallyLink) { + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: "Account linking not allowed by the developer for existing user.", + }; + } + if ( + shouldDoAccountLinkingOfExistingUser.shouldRequireVerification && + !existingUser.loginMethods[0].verified + ) { + // We do not allow creation of primary user + // if the existing user is not verified + // cause if we do, then it blocks sign up + // with other methods for the same email / phone number + // until this account is verified. This can be + // used by an attacker to prevent sign up from + // their victim by setting the account + // in this state and not verifying the account. + // The downside to this is that cause of this, + // in situations like MFA, we are forcing + // email verification to happen right after the user + // has finished setting up the second factor. + // This may not be something that the developer + // wants. But they can always switch this off + // by providing the right impl for shouldDoAutomaticAccountLinking + // this function will throw an email verification validation error. + yield session.assertClaims([ + emailVerificationClaim_1.EmailVerificationClaim.validators.isVerified(undefined, 0), + ]); + } + // now we can try and create a primary user for the existing user + let createPrimaryUserResult = yield this.recipeInterfaceImpl.createPrimaryUser({ + recipeUserId: existingUser.loginMethods[0].recipeUserId, userContext, }); - } - else if (createPrimaryUserResult.status === "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { - /* this can come here if in the following example: + if (createPrimaryUserResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { + // this can happen if there is a race condition in which the + // existing user becomes a primary user ID by the time the code + // execution comes into this block. So we call the function once again. + return yield this.linkAccountsWithUserFromSession({ + session, + newUser, + createRecipeUserFunc, + userContext, + }); + } else if ( + createPrimaryUserResult.status === + "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + /* this can come here if in the following example: - User creates a primary account (P1) using email R - User2 created another account (A2) with email R (but this is not yet linked to P1 cause maybe A2 is not a candidate for account linking) - Now User2 is logged in with A2 account, and they are trying to link with another account. - In this case, existingUser (A2 account), cannot become a primary user - So we are in a stuck state, and must ask the end user to contact support*/ + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: + "No account can be linked to the session account cause the session account is not a primary account and the account info is already associated with another primary account, so we cannot make this a primary account either. Please contact support.", + }; + } else if (createPrimaryUserResult.status === "OK") { + // this if condition is not needed, but for some reason TS complains if it's not there. + existingUser = createPrimaryUserResult.user; + } + // at this point, the existingUser is a primary user. So we can + // go ahead and attempt account linking for the new user and existingUser. + } + // before proceeding to link the two accounts, we must ask the dev if it's allowed to link them + const shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking( + newUser, + existingUser, + session, + userContext + ); + if (!shouldDoAccountLinking.shouldAutomaticallyLink) { return { status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "No account can be linked to the session account cause the session account is not a primary account and the account info is already associated with another primary account, so we cannot make this a primary account either. Please contact support.", + description: "Account linking not allowed by the developer for new user.", }; } - else if (createPrimaryUserResult.status === "OK") { - // this if condition is not needed, but for some reason TS complains if it's not there. - existingUser = createPrimaryUserResult.user; - } - // at this point, the existingUser is a primary user. So we can - // go ahead and attempt account linking for the new user and existingUser. - } - // before proceeding to link the two accounts, we must ask the dev if it's allowed to link them - const shouldDoAccountLinking = yield this.config.shouldDoAutomaticAccountLinking(newUser, existingUser, session, userContext); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - return { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "Account linking not allowed by the developer for new user.", - }; - } - // in order to link accounts, we need to have the recipe user ID of the new account. - let usersArrayThatHaveSameAccountInfoAsNewUser = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ - accountInfo: newUser, - userContext, - }); - let newUserIsVerified = false; - const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.loginMethods.find((lU) => { - let found = false; - if (lU.recipeId !== newUser.recipeId) { - return false; - } - if (newUser.recipeId === "thirdparty") { - if (lU.thirdParty === undefined) { - return false; - } - found = - lU.thirdParty.id === newUser.thirdParty.id && - lU.thirdParty.userId === newUser.thirdParty.userId; - } - else { - found = lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; - } - if (!found) { - return false; - } - newUserIsVerified = lU.verified; - return true; - })); - if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser === undefined) { - /* + // in order to link accounts, we need to have the recipe user ID of the new account. + let usersArrayThatHaveSameAccountInfoAsNewUser = yield this.recipeInterfaceImpl.listUsersByAccountInfo({ + accountInfo: newUser, + userContext, + }); + let newUserIsVerified = false; + const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find( + (u) => + u.loginMethods.find((lU) => { + let found = false; + if (lU.recipeId !== newUser.recipeId) { + return false; + } + if (newUser.recipeId === "thirdparty") { + if (lU.thirdParty === undefined) { + return false; + } + found = + lU.thirdParty.id === newUser.thirdParty.id && + lU.thirdParty.userId === newUser.thirdParty.userId; + } else { + found = lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; + } + if (!found) { + return false; + } + newUserIsVerified = lU.verified; + return true; + }) + ); + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser === undefined) { + /* Before proceeding to linking accounts, we need to create the recipe user ID associated with newUser. In order to do that we should check if there is some other primary user has the same account info - cause if there is, then linking to this existingUser will not be possible anyway, so we don't create a new recipe user cause if we did, then this recipe user will not be a candidate for automatic account linking in the future */ - let otherPrimaryUser = usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.isPrimaryUser); - if (otherPrimaryUser !== undefined && otherPrimaryUser.id !== existingUser.id) { - return { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "Not allowed because it will lead to two primary user id having same account info", - }; + let otherPrimaryUser = usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.isPrimaryUser); + if (otherPrimaryUser !== undefined && otherPrimaryUser.id !== existingUser.id) { + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: + "Not allowed because it will lead to two primary user id having same account info", + }; + } + // we create the new recipe user + yield createRecipeUserFunc(newUser); + // now when we recurse, the new recipe user will be found and we can try linking again. + return yield this.linkAccountsWithUserFromSession({ + session, + newUser, + createRecipeUserFunc, + userContext, + }); } - // we create the new recipe user - yield createRecipeUserFunc(newUser); - // now when we recurse, the new recipe user will be found and we can try linking again. - return yield this.linkAccountsWithUserFromSession({ - session, - newUser, - createRecipeUserFunc, + // now we check about the email verification of the new user. If it's verified, we proceed + // to try and link the accounts, and if not, we send email verification error ONLY if the email + // or phone number of the new account is different compared to the existing account. + if (usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.id === existingUser.id) === undefined) { + // this means that the existing user does not share anything in common with the new user + // in terms of account info. So we check for email verification status.. + if (!newUserIsVerified && shouldDoAccountLinking.shouldRequireVerification) { + // we stop the flow and ask the user to verify this email first. + return { + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + }; + } + } + const linkAccountResponse = yield this.recipeInterfaceImpl.linkAccounts({ + recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, + primaryUserId: existingUser.id, userContext, }); - } - // now we check about the email verification of the new user. If it's verified, we proceed - // to try and link the accounts, and if not, we send email verification error ONLY if the email - // or phone number of the new account is different compared to the existing account. - if (usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.id === existingUser.id) === undefined) { - // this means that the existing user does not share anything in common with the new user - // in terms of account info. So we check for email verification status.. - if (!newUserIsVerified && shouldDoAccountLinking.shouldRequireVerification) { - // we stop the flow and ask the user to verify this email first. + if (linkAccountResponse.status === "OK") { + return { + status: "OK", + }; + } else if ( + linkAccountResponse.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { + // this means that the the new user is already linked to some other primary user ID, + // so we can't link it to the existing user. + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: "New user is already linked to another account", + }; + } else { + // status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + // this means that the account info of the newUser already belongs to some other primary user ID. + // So we cannot link it to existing user. return { - status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: "Not allowed because it will lead to two primary user id having same account info", }; } - } - const linkAccountResponse = yield this.recipeInterfaceImpl.linkAccounts({ - recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, - primaryUserId: existingUser.id, - userContext, }); - if (linkAccountResponse.status === "OK") { - return { - status: "OK", - }; - } - else if (linkAccountResponse.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { - // this means that the the new user is already linked to some other primary user ID, - // so we can't link it to the existing user. - return { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "New user is already linked to another account", - }; - } - else { - // status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - // this means that the account info of the newUser already belongs to some other primary user ID. - // So we cannot link it to existing user. - return { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", - description: "Not allowed because it will lead to two primary user id having same account info", - }; - } - }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config)); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } } static init(config) { return (appInfo) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, config, {}, { - emailDelivery: undefined, - }); + Recipe.instance = new Recipe( + Recipe.RECIPE_ID, + appInfo, + config, + {}, + { + emailDelivery: undefined, + } + ); return Recipe.instance; - } - else { + } else { throw new Error("AccountLinking recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index 2a457baf1..a52e7f3c0 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -13,40 +13,70 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); const session_1 = __importDefault(require("../session")); function getRecipeImplementation(querier, config) { return { - getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds, }) { + getRecipeUserIdsForPrimaryUserIds: function ({ primaryUserIds }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { - primaryUserIds: primaryUserIds.join(","), - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/users"), + { + primaryUserIds: primaryUserIds.join(","), + } + ); return result.userIdMapping; }); }, - getPrimaryUserIdsForRecipeUserIds: function ({ recipeUserIds, }) { + getPrimaryUserIdsForRecipeUserIds: function ({ recipeUserIds }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/users"), { - recipeUserIds: recipeUserIds.join(","), - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/users"), + { + recipeUserIds: recipeUserIds.join(","), + } + ); return result.userIdMapping; }); }, - getUsers: function ({ timeJoinedOrder, limit, paginationToken, includeRecipeIds, }) { + getUsers: function ({ timeJoinedOrder, limit, paginationToken, includeRecipeIds }) { return __awaiter(this, void 0, void 0, function* () { let includeRecipeIdsStr = undefined; if (includeRecipeIds !== undefined) { @@ -64,37 +94,49 @@ function getRecipeImplementation(querier, config) { }; }); }, - canCreatePrimaryUserId: function ({ recipeUserId, }) { + canCreatePrimaryUserId: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/primary/check"), { - recipeUserId, - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/primary/check"), + { + recipeUserId, + } + ); return result; }); }, - createPrimaryUser: function ({ recipeUserId, }) { + createPrimaryUser: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), { - recipeUserId, - }); + let result = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), + { + recipeUserId, + } + ); return result; }); }, - canLinkAccounts: function ({ recipeUserId, primaryUserId, }) { + canLinkAccounts: function ({ recipeUserId, primaryUserId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/link/check"), { - recipeUserId, - primaryUserId, - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link/check"), + { + recipeUserId, + primaryUserId, + } + ); return result; }); }, - linkAccounts: function ({ recipeUserId, primaryUserId, userContext, }) { + linkAccounts: function ({ recipeUserId, primaryUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let accountsLinkingResult = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), { - recipeUserId, - primaryUserId, - }); + let accountsLinkingResult = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link"), + { + recipeUserId, + primaryUserId, + } + ); if (accountsLinkingResult.status === "OK" && !accountsLinkingResult.accountsAlreadyLinked) { yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); let user = yield this.getUser({ @@ -113,7 +155,7 @@ function getRecipeImplementation(querier, config) { return accountsLinkingResult; }); }, - unlinkAccounts: function ({ recipeUserId, userContext, }) { + unlinkAccounts: function ({ recipeUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsForRecipeUserIds({ recipeUserIds: [recipeUserId], @@ -129,7 +171,8 @@ function getRecipeImplementation(querier, config) { if (primaryUserId === null) { return { status: "PRIMARY_USER_NOT_FOUND_ERROR", - description: "The input recipeUserId is not linked to any primary user, or is not a primary user itself", + description: + "The input recipeUserId is not linked to any primary user, or is not a primary user itself", }; } if (primaryUserId === recipeUserId) { @@ -159,10 +202,13 @@ function getRecipeImplementation(querier, config) { }; } } - let accountsUnlinkingResult = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/unlink"), { - recipeUserId, - primaryUserId, - }); + let accountsUnlinkingResult = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/unlink"), + { + recipeUserId, + primaryUserId, + } + ); if (accountsUnlinkingResult.status === "OK") { yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); } @@ -171,9 +217,12 @@ function getRecipeImplementation(querier, config) { }, getUser: function ({ userId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user"), { - userId, - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user"), + { + userId, + } + ); if (result.status === "OK") { return result.user; } @@ -182,11 +231,14 @@ function getRecipeImplementation(querier, config) { }, listUsersByAccountInfo: function ({ accountInfo }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users/accountinfo"), Object.assign({}, accountInfo)); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/users/accountinfo"), + Object.assign({}, accountInfo) + ); return result.users; }); }, - deleteUser: function ({ userId, removeAllLinkedAccounts, }) { + deleteUser: function ({ userId, removeAllLinkedAccounts }) { return __awaiter(this, void 0, void 0, function* () { let result = yield querier.sendPostRequest(new normalisedURLPath_1.default("/user/remove"), { userId, @@ -195,20 +247,26 @@ function getRecipeImplementation(querier, config) { return result; }); }, - fetchFromAccountToLinkTable: function ({ recipeUserId, }) { + fetchFromAccountToLinkTable: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/link/table"), { - recipeUserId, - }); + let result = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link/table"), + { + recipeUserId, + } + ); return result.user; }); }, - storeIntoAccountToLinkTable: function ({ recipeUserId, primaryUserId, }) { + storeIntoAccountToLinkTable: function ({ recipeUserId, primaryUserId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/accountlinking/user/link/table"), { - recipeUserId, - primaryUserId, - }); + let result = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/accountlinking/user/link/table"), + { + recipeUserId, + primaryUserId, + } + ); return result; }); }, diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 2be5431d4..18f4c891b 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -3,26 +3,48 @@ import type { User } from "../../types"; import { SessionContainer } from "../session"; export declare type TypeInput = { onAccountLinked?: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - shouldDoAutomaticAccountLinking?: (newAccountInfo: AccountInfoWithRecipeId, user: User | undefined, session: SessionContainer | undefined, userContext: any) => Promise<{ - shouldAutomaticallyLink: false; - } | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - }>; + shouldDoAutomaticAccountLinking?: ( + newAccountInfo: AccountInfoWithRecipeId, + user: User | undefined, + session: SessionContainer | undefined, + userContext: any + ) => Promise< + | { + shouldAutomaticallyLink: false; + } + | { + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + } + >; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; }; }; export declare type TypeNormalisedInput = { onAccountLinked: (user: User, newAccountInfo: RecipeLevelUser, userContext: any) => Promise; - shouldDoAutomaticAccountLinking: (newAccountInfo: AccountInfoWithRecipeId, user: User | undefined, session: SessionContainer | undefined, userContext: any) => Promise<{ - shouldAutomaticallyLink: false; - } | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - }>; + shouldDoAutomaticAccountLinking: ( + newAccountInfo: AccountInfoWithRecipeId, + user: User | undefined, + session: SessionContainer | undefined, + userContext: any + ) => Promise< + | { + shouldAutomaticallyLink: false; + } + | { + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + } + >; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; }; }; export declare type RecipeInterface = { @@ -51,76 +73,91 @@ export declare type RecipeInterface = { canCreatePrimaryUserId: (input: { recipeUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - wasAlreadyAPrimaryUser: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; + }) => Promise< + | { + status: "OK"; + wasAlreadyAPrimaryUser: boolean; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; createPrimaryUser: (input: { recipeUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - wasAlreadyAPrimaryUser: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; + }) => Promise< + | { + status: "OK"; + user: User; + wasAlreadyAPrimaryUser: boolean; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; canLinkAccounts: (input: { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - accountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; + }) => Promise< + | { + status: "OK"; + accountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; linkAccounts: (input: { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - accountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - }>; + }) => Promise< + | { + status: "OK"; + accountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + >; unlinkAccounts: (input: { recipeUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - wasRecipeUserDeleted: boolean; - } | { - status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; - description: string; - }>; - getUser: (input: { - userId: string; - userContext: any; - }) => Promise; - listUsersByAccountInfo: (input: { - accountInfo: AccountInfo; - userContext: any; - }) => Promise; + }) => Promise< + | { + status: "OK"; + wasRecipeUserDeleted: boolean; + } + | { + status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; + description: string; + } + >; + getUser: (input: { userId: string; userContext: any }) => Promise; + listUsersByAccountInfo: (input: { accountInfo: AccountInfo; userContext: any }) => Promise; deleteUser: (input: { userId: string; removeAllLinkedAccounts: boolean; @@ -128,21 +165,21 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; - fetchFromAccountToLinkTable: (input: { - recipeUserId: string; - userContext: any; - }) => Promise; + fetchFromAccountToLinkTable: (input: { recipeUserId: string; userContext: any }) => Promise; storeIntoAccountToLinkTable: (input: { recipeUserId: string; primaryUserId: string; userContext: any; - }) => Promise<{ - status: "OK"; - didInsertNewRow: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - }>; + }) => Promise< + | { + status: "OK"; + didInsertNewRow: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + } + >; }; export declare type AccountInfo = { email?: string; diff --git a/lib/build/recipe/accountlinking/utils.js b/lib/build/recipe/accountlinking/utils.js index 8c40669d7..9df8364a5 100644 --- a/lib/build/recipe/accountlinking/utils.js +++ b/lib/build/recipe/accountlinking/utils.js @@ -13,19 +13,41 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAndNormaliseUserInput = void 0; function defaultOnAccountLinked(_user, _newAccountInfo, _userContext) { - return __awaiter(this, void 0, void 0, function* () { }); + return __awaiter(this, void 0, void 0, function* () {}); } function defaultShouldDoAutomaticAccountLinking(_newAccountInfo, _user, _session, _userContext) { return __awaiter(this, void 0, void 0, function* () { @@ -36,7 +58,8 @@ function defaultShouldDoAutomaticAccountLinking(_newAccountInfo, _user, _session } function validateAndNormaliseUserInput(_, config) { let onAccountLinked = config.onAccountLinked || defaultOnAccountLinked; - let shouldDoAutomaticAccountLinking = config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; + let shouldDoAutomaticAccountLinking = + config.shouldDoAutomaticAccountLinking || defaultShouldDoAutomaticAccountLinking; let override = Object.assign({ functions: (originalImplementation) => originalImplementation }, config.override); return { override, diff --git a/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts b/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts index b387e87ad..81d2cd778 100644 --- a/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts +++ b/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts @@ -1,2 +1,6 @@ import { APIFunction, APIInterface, APIOptions } from "../types"; -export default function apiKeyProtector(apiImplementation: APIInterface, options: APIOptions, apiFunction: APIFunction): Promise; +export default function apiKeyProtector( + apiImplementation: APIInterface, + options: APIOptions, + apiFunction: APIFunction +): Promise; diff --git a/lib/build/recipe/dashboard/api/apiKeyProtector.js b/lib/build/recipe/dashboard/api/apiKeyProtector.js index 6d0c9fc0e..14f446112 100644 --- a/lib/build/recipe/dashboard/api/apiKeyProtector.js +++ b/lib/build/recipe/dashboard/api/apiKeyProtector.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. * diff --git a/lib/build/recipe/dashboard/api/dashboard.js b/lib/build/recipe/dashboard/api/dashboard.js index e07eebec9..5d61bede0 100644 --- a/lib/build/recipe/dashboard/api/dashboard.js +++ b/lib/build/recipe/dashboard/api/dashboard.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); function dashboard(apiImplementation, options) { diff --git a/lib/build/recipe/dashboard/api/implementation.js b/lib/build/recipe/dashboard/api/implementation.js index 5f9a3303a..c87c7848b 100644 --- a/lib/build/recipe/dashboard/api/implementation.js +++ b/lib/build/recipe/dashboard/api/implementation.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLDomain_1 = __importDefault(require("../../../normalisedURLDomain")); const normalisedURLPath_1 = __importDefault(require("../../../normalisedURLPath")); @@ -37,7 +61,8 @@ function getAPIImplementation() { const bundleBasePathString = yield input.options.recipeImplementation.getDashboardBundleLocation({ userContext: input.userContext, }); - const bundleDomain = new normalisedURLDomain_1.default(bundleBasePathString).getAsStringDangerous() + + const bundleDomain = + new normalisedURLDomain_1.default(bundleBasePathString).getAsStringDangerous() + new normalisedURLPath_1.default(bundleBasePathString).getAsStringDangerous(); let connectionURI = ""; const superTokensInstance = supertokens_1.default.getInstanceOrThrowError(); @@ -51,8 +76,8 @@ function getAPIImplementation() { diff --git a/lib/build/recipe/dashboard/api/userdetails/userDelete.js b/lib/build/recipe/dashboard/api/userdetails/userDelete.js index 21afe16e5..72d9c907d 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userDelete.js +++ b/lib/build/recipe/dashboard/api/userdetails/userDelete.js @@ -1,36 +1,62 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userDelete = void 0; const error_1 = __importDefault(require("../../../../error")); const __1 = require("../../../.."); -const userDelete = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - let removeAllLinkedAccountsQueryValue = options.req.getKeyValueFromQuery("removeAllLinkedAccounts"); - if (removeAllLinkedAccountsQueryValue !== undefined) { - removeAllLinkedAccountsQueryValue = removeAllLinkedAccountsQueryValue.trim().toLowerCase(); - } - const removeAllLinkedAccounts = removeAllLinkedAccountsQueryValue === undefined ? undefined : removeAllLinkedAccountsQueryValue === "true"; - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - yield __1.deleteUser(userId, removeAllLinkedAccounts); - return { - status: "OK", - }; -}); +const userDelete = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + let removeAllLinkedAccountsQueryValue = options.req.getKeyValueFromQuery("removeAllLinkedAccounts"); + if (removeAllLinkedAccountsQueryValue !== undefined) { + removeAllLinkedAccountsQueryValue = removeAllLinkedAccountsQueryValue.trim().toLowerCase(); + } + const removeAllLinkedAccounts = + removeAllLinkedAccountsQueryValue === undefined ? undefined : removeAllLinkedAccountsQueryValue === "true"; + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + yield __1.deleteUser(userId, removeAllLinkedAccounts); + return { + status: "OK", + }; + }); exports.userDelete = userDelete; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js index c0bcd1c01..e835966b6 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.js @@ -1,42 +1,66 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userEmailverifyGet = void 0; const error_1 = __importDefault(require("../../../../error")); const recipe_1 = __importDefault(require("../../../emailverification/recipe")); const emailverification_1 = __importDefault(require("../../../emailverification")); -const userEmailverifyGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const req = options.req; - const userId = req.getKeyValueFromQuery("userId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - try { - recipe_1.default.getInstanceOrThrowError(); - } - catch (e) { +const userEmailverifyGet = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const req = options.req; + const userId = req.getKeyValueFromQuery("userId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + try { + recipe_1.default.getInstanceOrThrowError(); + } catch (e) { + return { + status: "FEATURE_NOT_ENABLED_ERROR", + }; + } + const response = yield emailverification_1.default.isEmailVerified(userId); return { - status: "FEATURE_NOT_ENABLED_ERROR", + status: "OK", + isVerified: response, }; - } - const response = yield emailverification_1.default.isEmailVerified(userId); - return { - status: "OK", - isVerified: response, - }; -}); + }); exports.userEmailverifyGet = userEmailverifyGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js index 5d1a0c2f9..6e8e0ed1d 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.js @@ -1,54 +1,78 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userEmailVerifyPut = void 0; const error_1 = __importDefault(require("../../../../error")); const emailverification_1 = __importDefault(require("../../../emailverification")); -const userEmailVerifyPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const verified = requestBody.verified; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (verified === undefined || typeof verified !== "boolean") { - throw new error_1.default({ - message: "Required parameter 'verified' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (verified) { - const tokenResponse = yield emailverification_1.default.createEmailVerificationToken(userId); - if (tokenResponse.status === "EMAIL_ALREADY_VERIFIED_ERROR") { - return { - status: "OK", - }; +const userEmailVerifyPut = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const verified = requestBody.verified; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - const verifyResponse = yield emailverification_1.default.verifyEmailUsingToken(tokenResponse.token); - if (verifyResponse.status === "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR") { - // This should never happen because we consume the token immediately after creating it - throw new Error("Should not come here"); + if (verified === undefined || typeof verified !== "boolean") { + throw new error_1.default({ + message: "Required parameter 'verified' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - } - else { - yield emailverification_1.default.unverifyEmail(userId); - } - return { - status: "OK", - }; -}); + if (verified) { + const tokenResponse = yield emailverification_1.default.createEmailVerificationToken(userId); + if (tokenResponse.status === "EMAIL_ALREADY_VERIFIED_ERROR") { + return { + status: "OK", + }; + } + const verifyResponse = yield emailverification_1.default.verifyEmailUsingToken(tokenResponse.token); + if (verifyResponse.status === "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR") { + // This should never happen because we consume the token immediately after creating it + throw new Error("Should not come here"); + } + } else { + yield emailverification_1.default.unverifyEmail(userId); + } + return { + status: "OK", + }; + }); exports.userEmailVerifyPut = userEmailVerifyPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js index 92ee47177..e24cd65eb 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.js @@ -1,56 +1,81 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userEmailVerifyTokenPost = void 0; const error_1 = __importDefault(require("../../../../error")); const emailverification_1 = __importDefault(require("../../../emailverification")); const recipe_1 = __importDefault(require("../../../emailverification/recipe")); const utils_1 = require("../../../emailverification/utils"); -const userEmailVerifyTokenPost = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, +const userEmailVerifyTokenPost = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + let emailResponse = yield recipe_1.default.getInstanceOrThrowError().getEmailForUserId(userId, {}); + if (emailResponse.status !== "OK") { + throw new Error("Should never come here"); + } + let emailVerificationToken = yield emailverification_1.default.createEmailVerificationToken(userId); + if (emailVerificationToken.status === "EMAIL_ALREADY_VERIFIED_ERROR") { + return { + status: "EMAIL_ALREADY_VERIFIED_ERROR", + }; + } + let emailVerifyLink = utils_1.getEmailVerifyLink({ + appInfo: options.appInfo, + token: emailVerificationToken.token, + recipeId: recipe_1.default.RECIPE_ID, + }); + yield emailverification_1.default.sendEmail({ + type: "EMAIL_VERIFICATION", + user: { + id: userId, + email: emailResponse.email, + }, + emailVerifyLink, }); - } - let emailResponse = yield recipe_1.default.getInstanceOrThrowError().getEmailForUserId(userId, {}); - if (emailResponse.status !== "OK") { - throw new Error("Should never come here"); - } - let emailVerificationToken = yield emailverification_1.default.createEmailVerificationToken(userId); - if (emailVerificationToken.status === "EMAIL_ALREADY_VERIFIED_ERROR") { return { - status: "EMAIL_ALREADY_VERIFIED_ERROR", + status: "OK", }; - } - let emailVerifyLink = utils_1.getEmailVerifyLink({ - appInfo: options.appInfo, - token: emailVerificationToken.token, - recipeId: recipe_1.default.RECIPE_ID, - }); - yield emailverification_1.default.sendEmail({ - type: "EMAIL_VERIFICATION", - user: { - id: userId, - email: emailResponse.email, - }, - emailVerifyLink, }); - return { - status: "OK", - }; -}); exports.userEmailVerifyTokenPost = userEmailVerifyTokenPost; diff --git a/lib/build/recipe/dashboard/api/userdetails/userGet.js b/lib/build/recipe/dashboard/api/userdetails/userGet.js index 31483b8b9..e5d02516a 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userGet.js @@ -1,72 +1,102 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userGet = void 0; const error_1 = __importDefault(require("../../../../error")); const utils_1 = require("../../utils"); const recipe_1 = __importDefault(require("../../../usermetadata/recipe")); const usermetadata_1 = __importDefault(require("../../../usermetadata")); -const userGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - const recipeId = options.req.getKeyValueFromQuery("recipeId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (recipeId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'recipeId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (!utils_1.isValidRecipeId(recipeId)) { - throw new error_1.default({ - message: "Invalid recipe id", - type: error_1.default.BAD_INPUT_ERROR, +const userGet = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + const recipeId = options.req.getKeyValueFromQuery("recipeId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (recipeId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'recipeId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (!utils_1.isValidRecipeId(recipeId)) { + throw new error_1.default({ + message: "Invalid recipe id", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (!utils_1.isRecipeInitialised(recipeId)) { + return { + status: "RECIPE_NOT_INITIALISED", + }; + } + let user = (yield utils_1.getUserForRecipeId(userId, recipeId)).user; + if (user === undefined) { + return { + status: "NO_USER_FOUND_ERROR", + }; + } + try { + recipe_1.default.getInstanceOrThrowError(); + } catch (_) { + user = Object.assign(Object.assign({}, user), { + firstName: "FEATURE_NOT_ENABLED", + lastName: "FEATURE_NOT_ENABLED", + }); + return { + status: "OK", + recipeId: recipeId, + user, + }; + } + const userMetaData = yield usermetadata_1.default.getUserMetadata(userId); + const { first_name, last_name } = userMetaData.metadata; + user = Object.assign(Object.assign({}, user), { + firstName: first_name === undefined ? "" : first_name, + lastName: last_name === undefined ? "" : last_name, }); - } - if (!utils_1.isRecipeInitialised(recipeId)) { - return { - status: "RECIPE_NOT_INITIALISED", - }; - } - let user = (yield utils_1.getUserForRecipeId(userId, recipeId)).user; - if (user === undefined) { - return { - status: "NO_USER_FOUND_ERROR", - }; - } - try { - recipe_1.default.getInstanceOrThrowError(); - } - catch (_) { - user = Object.assign(Object.assign({}, user), { firstName: "FEATURE_NOT_ENABLED", lastName: "FEATURE_NOT_ENABLED" }); return { status: "OK", recipeId: recipeId, user, }; - } - const userMetaData = yield usermetadata_1.default.getUserMetadata(userId); - const { first_name, last_name } = userMetaData.metadata; - user = Object.assign(Object.assign({}, user), { firstName: first_name === undefined ? "" : first_name, lastName: last_name === undefined ? "" : last_name }); - return { - status: "OK", - recipeId: recipeId, - user, - }; -}); + }); exports.userGet = userGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js index 6b632ce23..dd7165022 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.js @@ -1,41 +1,65 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userMetaDataGet = void 0; const error_1 = __importDefault(require("../../../../error")); const recipe_1 = __importDefault(require("../../../usermetadata/recipe")); const usermetadata_1 = __importDefault(require("../../../usermetadata")); -const userMetaDataGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - try { - recipe_1.default.getInstanceOrThrowError(); - } - catch (e) { +const userMetaDataGet = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + try { + recipe_1.default.getInstanceOrThrowError(); + } catch (e) { + return { + status: "FEATURE_NOT_ENABLED_ERROR", + }; + } + const metaDataResponse = usermetadata_1.default.getUserMetadata(userId); return { - status: "FEATURE_NOT_ENABLED_ERROR", + status: "OK", + data: (yield metaDataResponse).metadata, }; - } - const metaDataResponse = usermetadata_1.default.getUserMetadata(userId); - return { - status: "OK", - data: (yield metaDataResponse).metadata, - }; -}); + }); exports.userMetaDataGet = userMetaDataGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js index a882f912e..2510e32fb 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.js @@ -1,73 +1,97 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userMetadataPut = void 0; const recipe_1 = __importDefault(require("../../../usermetadata/recipe")); const usermetadata_1 = __importDefault(require("../../../usermetadata")); const error_1 = __importDefault(require("../../../../error")); -const userMetadataPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const data = requestBody.data; - // This is to throw an error early in case the recipe has not been initialised - recipe_1.default.getInstanceOrThrowError(); - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (data === undefined || typeof data !== "string") { - throw new error_1.default({ - message: "Required parameter 'data' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - // Make sure that data is a valid JSON, this will throw - try { - let parsedData = JSON.parse(data); - if (typeof parsedData !== "object") { - throw new Error(); +const userMetadataPut = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const data = requestBody.data; + // This is to throw an error early in case the recipe has not been initialised + recipe_1.default.getInstanceOrThrowError(); + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - if (Array.isArray(parsedData)) { - throw new Error(); + if (data === undefined || typeof data !== "string") { + throw new error_1.default({ + message: "Required parameter 'data' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - if (parsedData === null) { - throw new Error(); + // Make sure that data is a valid JSON, this will throw + try { + let parsedData = JSON.parse(data); + if (typeof parsedData !== "object") { + throw new Error(); + } + if (Array.isArray(parsedData)) { + throw new Error(); + } + if (parsedData === null) { + throw new Error(); + } + } catch (e) { + throw new error_1.default({ + message: "'data' must be a valid JSON body", + type: error_1.default.BAD_INPUT_ERROR, + }); } - } - catch (e) { - throw new error_1.default({ - message: "'data' must be a valid JSON body", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - /** - * This API is meant to set the user metadata of a user. We delete the existing data - * before updating it because we want to make sure that shallow merging does not result - * in the data being incorrect - * - * For example if the old data is {test: "test", test2: "test2"} and the user wants to delete - * test2 from the data simply calling updateUserMetadata with {test: "test"} would not remove - * test2 because of shallow merging. - * - * Removing first ensures that the final data is exactly what the user wanted it to be - */ - yield usermetadata_1.default.clearUserMetadata(userId); - yield usermetadata_1.default.updateUserMetadata(userId, JSON.parse(data)); - return { - status: "OK", - }; -}); + /** + * This API is meant to set the user metadata of a user. We delete the existing data + * before updating it because we want to make sure that shallow merging does not result + * in the data being incorrect + * + * For example if the old data is {test: "test", test2: "test2"} and the user wants to delete + * test2 from the data simply calling updateUserMetadata with {test: "test"} would not remove + * test2 because of shallow merging. + * + * Removing first ensures that the final data is exactly what the user wanted it to be + */ + yield usermetadata_1.default.clearUserMetadata(userId); + yield usermetadata_1.default.updateUserMetadata(userId, JSON.parse(data)); + return { + status: "OK", + }; + }); exports.userMetadataPut = userMetadataPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts index ef18b9292..d44974d2b 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts @@ -1,11 +1,14 @@ import { APIInterface, APIOptions } from "../../types"; -declare type Response = { - status: "OK"; -} | { - status: "PROVIDE_RECIPE_USER_ID_AS_USER_ID_ERROR"; -} | { - status: "INVALID_PASSWORD_ERROR"; - error: string; -}; +declare type Response = + | { + status: "OK"; + } + | { + status: "PROVIDE_RECIPE_USER_ID_AS_USER_ID_ERROR"; + } + | { + status: "INVALID_PASSWORD_ERROR"; + error: string; + }; export declare const userPasswordPut: (_: APIInterface, options: APIOptions) => Promise; export {}; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js index 4fe4bec91..43b63e871 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userPasswordPut = void 0; const error_1 = __importDefault(require("../../../../error")); @@ -19,42 +43,69 @@ const emailpassword_1 = __importDefault(require("../../../emailpassword")); const recipe_2 = __importDefault(require("../../../thirdpartyemailpassword/recipe")); const thirdpartyemailpassword_1 = __importDefault(require("../../../thirdpartyemailpassword")); const constants_1 = require("../../../emailpassword/constants"); -const userPasswordPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const email = requestBody.email; - const newPassword = requestBody.newPassword; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (newPassword === undefined || typeof newPassword !== "string") { - throw new error_1.default({ - message: "Required parameter 'newPassword' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - let recipeToUse; - try { - recipe_1.default.getInstanceOrThrowError(); - recipeToUse = "emailpassword"; - } - catch (_) { } - if (recipeToUse === undefined) { +const userPasswordPut = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const email = requestBody.email; + const newPassword = requestBody.newPassword; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + if (newPassword === undefined || typeof newPassword !== "string") { + throw new error_1.default({ + message: "Required parameter 'newPassword' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + let recipeToUse; try { - recipe_2.default.getInstanceOrThrowError(); - recipeToUse = "thirdpartyemailpassword"; + recipe_1.default.getInstanceOrThrowError(); + recipeToUse = "emailpassword"; + } catch (_) {} + if (recipeToUse === undefined) { + try { + recipe_2.default.getInstanceOrThrowError(); + recipeToUse = "thirdpartyemailpassword"; + } catch (_) {} } - catch (_) { } - } - if (recipeToUse === undefined) { - // This means that neither emailpassword or thirdpartyemailpassword is initialised - throw new Error("Should never come here"); - } - if (recipeToUse === "emailpassword") { - let passwordFormFields = recipe_1.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); + if (recipeToUse === undefined) { + // This means that neither emailpassword or thirdpartyemailpassword is initialised + throw new Error("Should never come here"); + } + if (recipeToUse === "emailpassword") { + let passwordFormFields = recipe_1.default + .getInstanceOrThrowError() + .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); + let passwordValidationError = yield passwordFormFields[0].validate(newPassword); + if (passwordValidationError !== undefined) { + return { + status: "INVALID_PASSWORD_ERROR", + error: passwordValidationError, + }; + } + const passwordResetToken = yield emailpassword_1.default.createResetPasswordToken(userId, email); + if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { + // Techincally it can but its an edge case so we assume that it wont + throw new Error("Should never come here"); + } + const passwordResetResponse = yield emailpassword_1.default.resetPasswordUsingToken( + passwordResetToken.token, + newPassword + ); + if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { + throw new Error("Should never come here"); + } + return { + status: "OK", + }; + } + let passwordFormFields = recipe_2.default + .getInstanceOrThrowError() + .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); let passwordValidationError = yield passwordFormFields[0].validate(newPassword); if (passwordValidationError !== undefined) { return { @@ -62,38 +113,20 @@ const userPasswordPut = (_, options) => __awaiter(void 0, void 0, void 0, functi error: passwordValidationError, }; } - const passwordResetToken = yield emailpassword_1.default.createResetPasswordToken(userId, email); + const passwordResetToken = yield thirdpartyemailpassword_1.default.createResetPasswordToken(userId, email); if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { // Techincally it can but its an edge case so we assume that it wont throw new Error("Should never come here"); } - const passwordResetResponse = yield emailpassword_1.default.resetPasswordUsingToken(passwordResetToken.token, newPassword); + const passwordResetResponse = yield thirdpartyemailpassword_1.default.resetPasswordUsingToken( + passwordResetToken.token, + newPassword + ); if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { throw new Error("Should never come here"); } return { status: "OK", }; - } - let passwordFormFields = recipe_2.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); - let passwordValidationError = yield passwordFormFields[0].validate(newPassword); - if (passwordValidationError !== undefined) { - return { - status: "INVALID_PASSWORD_ERROR", - error: passwordValidationError, - }; - } - const passwordResetToken = yield thirdpartyemailpassword_1.default.createResetPasswordToken(userId, email); - if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { - // Techincally it can but its an edge case so we assume that it wont - throw new Error("Should never come here"); - } - const passwordResetResponse = yield thirdpartyemailpassword_1.default.resetPasswordUsingToken(passwordResetToken.token, newPassword); - if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { - throw new Error("Should never come here"); - } - return { - status: "OK", - }; -}); + }); exports.userPasswordPut = userPasswordPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts index 4b1c52571..1a8a475e9 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts @@ -1,16 +1,21 @@ import { APIInterface, APIOptions } from "../../types"; -declare type Response = { - status: "OK"; -} | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; -} | { - status: "INVALID_EMAIL_ERROR"; - error: string; -} | { - status: "PHONE_ALREADY_EXISTS_ERROR"; -} | { - status: "INVALID_PHONE_ERROR"; - error: string; -}; +declare type Response = + | { + status: "OK"; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "INVALID_EMAIL_ERROR"; + error: string; + } + | { + status: "PHONE_ALREADY_EXISTS_ERROR"; + } + | { + status: "INVALID_PHONE_ERROR"; + error: string; + }; export declare const userPut: (_: APIInterface, options: APIOptions) => Promise; export {}; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPut.js b/lib/build/recipe/dashboard/api/userdetails/userPut.js index 99cea51fe..85907607a 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userPut.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userPut = void 0; const error_1 = __importDefault(require("../../../../error")); @@ -27,313 +51,315 @@ const recipe_5 = __importDefault(require("../../../usermetadata/recipe")); const usermetadata_1 = __importDefault(require("../../../usermetadata")); const constants_1 = require("../../../emailpassword/constants"); const utils_2 = require("../../../passwordless/utils"); -const updateEmailForRecipeId = (recipeId, userId, email) => __awaiter(void 0, void 0, void 0, function* () { - if (recipeId === "emailpassword") { - let emailFormFields = recipe_1.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); - let validationError = yield emailFormFields[0].validate(email); - if (validationError !== undefined) { - return { - status: "INVALID_EMAIL_ERROR", - error: validationError, - }; - } - const emailUpdateResponse = yield emailpassword_1.default.updateEmailOrPassword({ - userId, - email, - }); - if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } - return { - status: "OK", - }; - } - if (recipeId === "thirdpartyemailpassword") { - let emailFormFields = recipe_2.default.getInstanceOrThrowError().config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); - let validationError = yield emailFormFields[0].validate(email); - if (validationError !== undefined) { - return { - status: "INVALID_EMAIL_ERROR", - error: validationError, - }; - } - const emailUpdateResponse = yield thirdpartyemailpassword_1.default.updateEmailOrPassword({ - userId, - email, - }); - if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { +const updateEmailForRecipeId = (recipeId, userId, email) => + __awaiter(void 0, void 0, void 0, function* () { + if (recipeId === "emailpassword") { + let emailFormFields = recipe_1.default + .getInstanceOrThrowError() + .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); + let validationError = yield emailFormFields[0].validate(email); + if (validationError !== undefined) { + return { + status: "INVALID_EMAIL_ERROR", + error: validationError, + }; + } + const emailUpdateResponse = yield emailpassword_1.default.updateEmailOrPassword({ + userId, + email, + }); + if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { + return { + status: "EMAIL_ALREADY_EXISTS_ERROR", + }; + } return { - status: "EMAIL_ALREADY_EXISTS_ERROR", + status: "OK", }; } - if (emailUpdateResponse.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } - return { - status: "OK", - }; - } - if (recipeId === "passwordless") { - let isValidEmail = true; - let validationError = ""; - const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; - if (passwordlessConfig.contactMethod === "PHONE") { - const validationResult = yield utils_2.defaultValidateEmail(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; + if (recipeId === "thirdpartyemailpassword") { + let emailFormFields = recipe_2.default + .getInstanceOrThrowError() + .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_EMAIL_ID); + let validationError = yield emailFormFields[0].validate(email); + if (validationError !== undefined) { + return { + status: "INVALID_EMAIL_ERROR", + error: validationError, + }; } - } - else { - const validationResult = yield passwordlessConfig.validateEmailAddress(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; + const emailUpdateResponse = yield thirdpartyemailpassword_1.default.updateEmailOrPassword({ + userId, + email, + }); + if (emailUpdateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { + return { + status: "EMAIL_ALREADY_EXISTS_ERROR", + }; + } + if (emailUpdateResponse.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); } - } - if (!isValidEmail) { return { - status: "INVALID_EMAIL_ERROR", - error: validationError, + status: "OK", }; } - const updateResult = yield passwordless_1.default.updateUser({ - userId, - email, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } - if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { + if (recipeId === "passwordless") { + let isValidEmail = true; + let validationError = ""; + const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; + if (passwordlessConfig.contactMethod === "PHONE") { + const validationResult = yield utils_2.defaultValidateEmail(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; + } + } else { + const validationResult = yield passwordlessConfig.validateEmailAddress(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; + } + } + if (!isValidEmail) { + return { + status: "INVALID_EMAIL_ERROR", + error: validationError, + }; + } + const updateResult = yield passwordless_1.default.updateUser({ + userId, + email, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); + } + if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { + return { + status: "EMAIL_ALREADY_EXISTS_ERROR", + }; + } return { - status: "EMAIL_ALREADY_EXISTS_ERROR", + status: "OK", }; } - return { - status: "OK", - }; - } - if (recipeId === "thirdpartypasswordless") { - let isValidEmail = true; - let validationError = ""; - const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; - if (passwordlessConfig.contactMethod === "PHONE") { - const validationResult = yield utils_2.defaultValidateEmail(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; + if (recipeId === "thirdpartypasswordless") { + let isValidEmail = true; + let validationError = ""; + const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; + if (passwordlessConfig.contactMethod === "PHONE") { + const validationResult = yield utils_2.defaultValidateEmail(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; + } + } else { + const validationResult = yield passwordlessConfig.validateEmailAddress(email); + if (validationResult !== undefined) { + isValidEmail = false; + validationError = validationResult; + } } - } - else { - const validationResult = yield passwordlessConfig.validateEmailAddress(email); - if (validationResult !== undefined) { - isValidEmail = false; - validationError = validationResult; + if (!isValidEmail) { + return { + status: "INVALID_EMAIL_ERROR", + error: validationError, + }; + } + const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ + userId, + email, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); + } + if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { + return { + status: "EMAIL_ALREADY_EXISTS_ERROR", + }; } - } - if (!isValidEmail) { return { - status: "INVALID_EMAIL_ERROR", - error: validationError, + status: "OK", }; } - const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ - userId, - email, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } - if (updateResult.status === "EMAIL_ALREADY_EXISTS_ERROR") { + /** + * If it comes here then the user is a third party user in which case the UI should not have allowed this + */ + throw new Error("Should never come here"); + }); +const updatePhoneForRecipeId = (recipeId, userId, phone) => + __awaiter(void 0, void 0, void 0, function* () { + if (recipeId === "passwordless") { + let isValidPhone = true; + let validationError = ""; + const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; + if (passwordlessConfig.contactMethod === "EMAIL") { + const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; + } + } else { + const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; + } + } + if (!isValidPhone) { + return { + status: "INVALID_PHONE_ERROR", + error: validationError, + }; + } + const updateResult = yield passwordless_1.default.updateUser({ + userId, + phoneNumber: phone, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); + } + if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { + return { + status: "PHONE_ALREADY_EXISTS_ERROR", + }; + } return { - status: "EMAIL_ALREADY_EXISTS_ERROR", + status: "OK", }; } - return { - status: "OK", - }; - } - /** - * If it comes here then the user is a third party user in which case the UI should not have allowed this - */ - throw new Error("Should never come here"); -}); -const updatePhoneForRecipeId = (recipeId, userId, phone) => __awaiter(void 0, void 0, void 0, function* () { - if (recipeId === "passwordless") { - let isValidPhone = true; - let validationError = ""; - const passwordlessConfig = recipe_3.default.getInstanceOrThrowError().config; - if (passwordlessConfig.contactMethod === "EMAIL") { - const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; + if (recipeId === "thirdpartypasswordless") { + let isValidPhone = true; + let validationError = ""; + const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; + if (passwordlessConfig.contactMethod === "EMAIL") { + const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; + } + } else { + const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); + if (validationResult !== undefined) { + isValidPhone = false; + validationError = validationResult; + } } - } - else { - const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; + if (!isValidPhone) { + return { + status: "INVALID_PHONE_ERROR", + error: validationError, + }; + } + const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ + userId, + phoneNumber: phone, + }); + if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { + throw new Error("Should never come here"); + } + if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { + return { + status: "PHONE_ALREADY_EXISTS_ERROR", + }; } - } - if (!isValidPhone) { return { - status: "INVALID_PHONE_ERROR", - error: validationError, + status: "OK", }; } - const updateResult = yield passwordless_1.default.updateUser({ - userId, - phoneNumber: phone, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); + /** + * If it comes here then the user is a not a passwordless user in which case the UI should not have allowed this + */ + throw new Error("Should never come here"); + }); +const userPut = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const userId = requestBody.userId; + const recipeId = requestBody.recipeId; + const firstName = requestBody.firstName; + const lastName = requestBody.lastName; + const email = requestBody.email; + const phone = requestBody.phone; + if (userId === undefined || typeof userId !== "string") { + throw new error_1.default({ + message: "Required parameter 'userId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { - return { - status: "PHONE_ALREADY_EXISTS_ERROR", - }; + if (recipeId === undefined || typeof recipeId !== "string") { + throw new error_1.default({ + message: "Required parameter 'recipeId' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - return { - status: "OK", - }; - } - if (recipeId === "thirdpartypasswordless") { - let isValidPhone = true; - let validationError = ""; - const passwordlessConfig = recipe_4.default.getInstanceOrThrowError().passwordlessRecipe.config; - if (passwordlessConfig.contactMethod === "EMAIL") { - const validationResult = yield utils_2.defaultValidatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; - } + if (!utils_1.isValidRecipeId(recipeId)) { + throw new error_1.default({ + message: "Invalid recipe id", + type: error_1.default.BAD_INPUT_ERROR, + }); } - else { - const validationResult = yield passwordlessConfig.validatePhoneNumber(phone); - if (validationResult !== undefined) { - isValidPhone = false; - validationError = validationResult; - } + if (firstName === undefined || typeof firstName !== "string") { + throw new error_1.default({ + message: "Required parameter 'firstName' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - if (!isValidPhone) { - return { - status: "INVALID_PHONE_ERROR", - error: validationError, - }; + if (lastName === undefined || typeof lastName !== "string") { + throw new error_1.default({ + message: "Required parameter 'lastName' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - const updateResult = yield thirdpartypasswordless_1.default.updatePasswordlessUser({ - userId, - phoneNumber: phone, - }); - if (updateResult.status === "UNKNOWN_USER_ID_ERROR") { - throw new Error("Should never come here"); - } - if (updateResult.status === "PHONE_NUMBER_ALREADY_EXISTS_ERROR") { - return { - status: "PHONE_ALREADY_EXISTS_ERROR", - }; + if (email === undefined || typeof email !== "string") { + throw new error_1.default({ + message: "Required parameter 'email' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - return { - status: "OK", - }; - } - /** - * If it comes here then the user is a not a passwordless user in which case the UI should not have allowed this - */ - throw new Error("Should never come here"); -}); -const userPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const userId = requestBody.userId; - const recipeId = requestBody.recipeId; - const firstName = requestBody.firstName; - const lastName = requestBody.lastName; - const email = requestBody.email; - const phone = requestBody.phone; - if (userId === undefined || typeof userId !== "string") { - throw new error_1.default({ - message: "Required parameter 'userId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (recipeId === undefined || typeof recipeId !== "string") { - throw new error_1.default({ - message: "Required parameter 'recipeId' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (!utils_1.isValidRecipeId(recipeId)) { - throw new error_1.default({ - message: "Invalid recipe id", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (firstName === undefined || typeof firstName !== "string") { - throw new error_1.default({ - message: "Required parameter 'firstName' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (lastName === undefined || typeof lastName !== "string") { - throw new error_1.default({ - message: "Required parameter 'lastName' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (email === undefined || typeof email !== "string") { - throw new error_1.default({ - message: "Required parameter 'email' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - if (phone === undefined || typeof phone !== "string") { - throw new error_1.default({ - message: "Required parameter 'phone' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - let userResponse = yield utils_1.getUserForRecipeId(userId, recipeId); - if (userResponse.user === undefined || userResponse.recipe === undefined) { - throw new Error("Should never come here"); - } - if (firstName.trim() !== "" || lastName.trim() !== "") { - let isRecipeInitialised = false; - try { - recipe_5.default.getInstanceOrThrowError(); - isRecipeInitialised = true; + if (phone === undefined || typeof phone !== "string") { + throw new error_1.default({ + message: "Required parameter 'phone' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); } - catch (_) { - // no op + let userResponse = yield utils_1.getUserForRecipeId(userId, recipeId); + if (userResponse.user === undefined || userResponse.recipe === undefined) { + throw new Error("Should never come here"); } - if (isRecipeInitialised) { - let metaDataUpdate = {}; - if (firstName.trim() !== "") { - metaDataUpdate["first_name"] = firstName.trim(); + if (firstName.trim() !== "" || lastName.trim() !== "") { + let isRecipeInitialised = false; + try { + recipe_5.default.getInstanceOrThrowError(); + isRecipeInitialised = true; + } catch (_) { + // no op } - if (lastName.trim() !== "") { - metaDataUpdate["last_name"] = lastName.trim(); + if (isRecipeInitialised) { + let metaDataUpdate = {}; + if (firstName.trim() !== "") { + metaDataUpdate["first_name"] = firstName.trim(); + } + if (lastName.trim() !== "") { + metaDataUpdate["last_name"] = lastName.trim(); + } + yield usermetadata_1.default.updateUserMetadata(userId, metaDataUpdate); } - yield usermetadata_1.default.updateUserMetadata(userId, metaDataUpdate); } - } - if (email.trim() !== "") { - const emailUpdateResponse = yield updateEmailForRecipeId(userResponse.recipe, userId, email.trim()); - if (emailUpdateResponse.status !== "OK") { - return emailUpdateResponse; + if (email.trim() !== "") { + const emailUpdateResponse = yield updateEmailForRecipeId(userResponse.recipe, userId, email.trim()); + if (emailUpdateResponse.status !== "OK") { + return emailUpdateResponse; + } } - } - if (phone.trim() !== "") { - const phoneUpdateResponse = yield updatePhoneForRecipeId(userResponse.recipe, userId, phone.trim()); - if (phoneUpdateResponse.status !== "OK") { - return phoneUpdateResponse; + if (phone.trim() !== "") { + const phoneUpdateResponse = yield updatePhoneForRecipeId(userResponse.recipe, userId, phone.trim()); + if (phoneUpdateResponse.status !== "OK") { + return phoneUpdateResponse; + } } - } - return { - status: "OK", - }; -}); + return { + status: "OK", + }; + }); exports.userPut = userPut; diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js index 4f22c14a3..6cae91b07 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.js @@ -1,49 +1,77 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.userSessionsGet = void 0; -const error_1 = __importDefault(require("../../../../error")); -const session_1 = __importDefault(require("../../../session")); -const userSessionsGet = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const userId = options.req.getKeyValueFromQuery("userId"); - if (userId === undefined) { - throw new error_1.default({ - message: "Missing required parameter 'userId'", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - const response = yield session_1.default.getAllSessionHandlesForUser(userId); - let sessions = []; - let sessionInfoPromises = []; - for (let i = 0; i < response.length; i++) { - sessionInfoPromises.push(new Promise((res, rej) => __awaiter(void 0, void 0, void 0, function* () { - try { - const sessionResponse = yield session_1.default.getSessionInformation(response[i]); - if (sessionResponse !== undefined) { - sessions[i] = sessionResponse; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } - res(); } - catch (e) { - rej(e); + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - }))); - } - yield Promise.all(sessionInfoPromises); - return { - status: "OK", - sessions, + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; }; -}); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.userSessionsGet = void 0; +const error_1 = __importDefault(require("../../../../error")); +const session_1 = __importDefault(require("../../../session")); +const userSessionsGet = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const userId = options.req.getKeyValueFromQuery("userId"); + if (userId === undefined) { + throw new error_1.default({ + message: "Missing required parameter 'userId'", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + const response = yield session_1.default.getAllSessionHandlesForUser(userId); + let sessions = []; + let sessionInfoPromises = []; + for (let i = 0; i < response.length; i++) { + sessionInfoPromises.push( + new Promise((res, rej) => + __awaiter(void 0, void 0, void 0, function* () { + try { + const sessionResponse = yield session_1.default.getSessionInformation(response[i]); + if (sessionResponse !== undefined) { + sessions[i] = sessionResponse; + } + res(); + } catch (e) { + rej(e); + } + }) + ) + ); + } + yield Promise.all(sessionInfoPromises); + return { + status: "OK", + sessions, + }; + }); exports.userSessionsGet = userSessionsGet; diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js index dff2fefae..a65859ca9 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.js @@ -1,32 +1,57 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userSessionsPost = void 0; const error_1 = __importDefault(require("../../../../error")); const session_1 = __importDefault(require("../../../session")); -const userSessionsPost = (_, options) => __awaiter(void 0, void 0, void 0, function* () { - const requestBody = yield options.req.getJSONBody(); - const sessionHandles = requestBody.sessionHandles; - if (sessionHandles === undefined || !Array.isArray(sessionHandles)) { - throw new error_1.default({ - message: "Required parameter 'sessionHandles' is missing or has an invalid type", - type: error_1.default.BAD_INPUT_ERROR, - }); - } - yield session_1.default.revokeMultipleSessions(sessionHandles); - return { - status: "OK", - }; -}); +const userSessionsPost = (_, options) => + __awaiter(void 0, void 0, void 0, function* () { + const requestBody = yield options.req.getJSONBody(); + const sessionHandles = requestBody.sessionHandles; + if (sessionHandles === undefined || !Array.isArray(sessionHandles)) { + throw new error_1.default({ + message: "Required parameter 'sessionHandles' is missing or has an invalid type", + type: error_1.default.BAD_INPUT_ERROR, + }); + } + yield session_1.default.revokeMultipleSessions(sessionHandles); + return { + status: "OK", + }; + }); exports.userSessionsPost = userSessionsPost; diff --git a/lib/build/recipe/dashboard/api/usersCountGet.js b/lib/build/recipe/dashboard/api/usersCountGet.js index 1174c1075..59b8f8f74 100644 --- a/lib/build/recipe/dashboard/api/usersCountGet.js +++ b/lib/build/recipe/dashboard/api/usersCountGet.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_1 = __importDefault(require("../../../supertokens")); function usersCountGet(_, __) { diff --git a/lib/build/recipe/dashboard/api/usersGet.js b/lib/build/recipe/dashboard/api/usersGet.js index 6a368dea6..0a194009d 100644 --- a/lib/build/recipe/dashboard/api/usersGet.js +++ b/lib/build/recipe/dashboard/api/usersGet.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../../error")); const __1 = require("../../.."); @@ -37,20 +61,20 @@ function usersGet(_, options) { }); } let paginationToken = options.req.getKeyValueFromQuery("paginationToken"); - let usersResponse = timeJoinedOrder === "DESC" - ? yield __1.getUsersNewestFirst({ - limit: parseInt(limit), - paginationToken, - }) - : yield __1.getUsersOldestFirst({ - limit: parseInt(limit), - paginationToken, - }); + let usersResponse = + timeJoinedOrder === "DESC" + ? yield __1.getUsersNewestFirst({ + limit: parseInt(limit), + paginationToken, + }) + : yield __1.getUsersOldestFirst({ + limit: parseInt(limit), + paginationToken, + }); // If the UserMetaData recipe has been initialised, fetch first and last name try { recipe_1.default.getInstanceOrThrowError(); - } - catch (e) { + } catch (e) { // Recipe has not been initialised, return without first name and last name return { status: "OK", @@ -62,18 +86,25 @@ function usersGet(_, options) { let metaDataFetchPromises = []; for (let i = 0; i < usersResponse.users.length; i++) { const userObj = usersResponse.users[i]; - metaDataFetchPromises.push(() => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - try { - const userMetaDataResponse = yield usermetadata_1.default.getUserMetadata(userObj.id); - const { first_name, last_name } = userMetaDataResponse.metadata; - updatedUsersArray[i] = Object.assign(Object.assign({}, userObj), { firstName: first_name, lastName: last_name }); - resolve(true); - } - catch (e) { - // Something went wrong when fetching user meta data - reject(e); - } - }))); + metaDataFetchPromises.push( + () => + new Promise((resolve, reject) => + __awaiter(this, void 0, void 0, function* () { + try { + const userMetaDataResponse = yield usermetadata_1.default.getUserMetadata(userObj.id); + const { first_name, last_name } = userMetaDataResponse.metadata; + updatedUsersArray[i] = Object.assign(Object.assign({}, userObj), { + firstName: first_name, + lastName: last_name, + }); + resolve(true); + } catch (e) { + // Something went wrong when fetching user meta data + reject(e); + } + }) + ) + ); } let promiseArrayStartPosition = 0; let batchSize = 5; diff --git a/lib/build/recipe/dashboard/api/validateKey.js b/lib/build/recipe/dashboard/api/validateKey.js index 3662e6fb4..f805ab857 100644 --- a/lib/build/recipe/dashboard/api/validateKey.js +++ b/lib/build/recipe/dashboard/api/validateKey.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../utils"); @@ -34,8 +56,7 @@ function validateKey(_, options) { }); if (!shouldAllowAccess) { utils_2.sendUnauthorisedAccess(options.res); - } - else { + } else { options.res.sendJSONResponse({ status: "OK", }); diff --git a/lib/build/recipe/dashboard/index.js b/lib/build/recipe/dashboard/index.js index 772d2760c..7ad60228f 100644 --- a/lib/build/recipe/dashboard/index.js +++ b/lib/build/recipe/dashboard/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.init = void 0; /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. @@ -19,8 +21,7 @@ exports.init = void 0; * under the License. */ const recipe_1 = __importDefault(require("./recipe")); -class Wrapper { -} +class Wrapper {} exports.default = Wrapper; Wrapper.init = recipe_1.default.init; exports.init = Wrapper.init; diff --git a/lib/build/recipe/dashboard/recipe.d.ts b/lib/build/recipe/dashboard/recipe.d.ts index 03fb0827b..8ef5265fd 100644 --- a/lib/build/recipe/dashboard/recipe.d.ts +++ b/lib/build/recipe/dashboard/recipe.d.ts @@ -16,7 +16,13 @@ export default class Recipe extends RecipeModule { static init(config: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, __: NormalisedURLPath, ___: HTTPMethod) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + __: NormalisedURLPath, + ___: HTTPMethod + ) => Promise; handleError: (err: error, _: BaseRequest, __: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is error; diff --git a/lib/build/recipe/dashboard/recipe.js b/lib/build/recipe/dashboard/recipe.js index 20712cf0f..a73359714 100644 --- a/lib/build/recipe/dashboard/recipe.js +++ b/lib/build/recipe/dashboard/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const recipeModule_1 = __importDefault(require("../../recipeModule")); @@ -65,81 +89,76 @@ class Recipe extends recipeModule_1.default { */ return []; }; - this.handleAPIRequest = (id, req, res, __, ___) => __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - isInServerlessEnv: this.isInServerlessEnv, - appInfo: this.getAppInfo(), - }; - // For these APIs we dont need API key validation - if (id === constants_1.DASHBOARD_API) { - return yield dashboard_1.default(this.apiImpl, options); - } - if (id === constants_1.VALIDATE_KEY_API) { - return yield validateKey_1.default(this.apiImpl, options); - } - // Do API key validation for the remaining APIs - let apiFunction; - if (id === constants_1.USERS_LIST_GET_API) { - apiFunction = usersGet_1.default; - } - else if (id === constants_1.USERS_COUNT_API) { - apiFunction = usersCountGet_1.default; - } - else if (id === constants_1.USER_API) { - if (req.getMethod() === "get") { - apiFunction = userGet_1.userGet; - } - if (req.getMethod() === "delete") { - apiFunction = userDelete_1.userDelete; - } - if (req.getMethod() === "put") { - apiFunction = userPut_1.userPut; + this.handleAPIRequest = (id, req, res, __, ___) => + __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + isInServerlessEnv: this.isInServerlessEnv, + appInfo: this.getAppInfo(), + }; + // For these APIs we dont need API key validation + if (id === constants_1.DASHBOARD_API) { + return yield dashboard_1.default(this.apiImpl, options); } - } - else if (id === constants_1.USER_EMAIL_VERIFY_API) { - if (req.getMethod() === "get") { - apiFunction = userEmailVerifyGet_1.userEmailverifyGet; - } - if (req.getMethod() === "put") { - apiFunction = userEmailVerifyPut_1.userEmailVerifyPut; + if (id === constants_1.VALIDATE_KEY_API) { + return yield validateKey_1.default(this.apiImpl, options); } - } - else if (id === constants_1.USER_METADATA_API) { - if (req.getMethod() === "get") { - apiFunction = userMetadataGet_1.userMetaDataGet; + // Do API key validation for the remaining APIs + let apiFunction; + if (id === constants_1.USERS_LIST_GET_API) { + apiFunction = usersGet_1.default; + } else if (id === constants_1.USERS_COUNT_API) { + apiFunction = usersCountGet_1.default; + } else if (id === constants_1.USER_API) { + if (req.getMethod() === "get") { + apiFunction = userGet_1.userGet; + } + if (req.getMethod() === "delete") { + apiFunction = userDelete_1.userDelete; + } + if (req.getMethod() === "put") { + apiFunction = userPut_1.userPut; + } + } else if (id === constants_1.USER_EMAIL_VERIFY_API) { + if (req.getMethod() === "get") { + apiFunction = userEmailVerifyGet_1.userEmailverifyGet; + } + if (req.getMethod() === "put") { + apiFunction = userEmailVerifyPut_1.userEmailVerifyPut; + } + } else if (id === constants_1.USER_METADATA_API) { + if (req.getMethod() === "get") { + apiFunction = userMetadataGet_1.userMetaDataGet; + } + if (req.getMethod() === "put") { + apiFunction = userMetadataPut_1.userMetadataPut; + } + } else if (id === constants_1.USER_SESSIONS_API) { + if (req.getMethod() === "get") { + apiFunction = userSessionsGet_1.userSessionsGet; + } + if (req.getMethod() === "post") { + apiFunction = userSessionsPost_1.userSessionsPost; + } + } else if (id === constants_1.USER_PASSWORD_API) { + apiFunction = userPasswordPut_1.userPasswordPut; + } else if (id === constants_1.USER_EMAIL_VERIFY_TOKEN_API) { + apiFunction = userEmailVerifyTokenPost_1.userEmailVerifyTokenPost; } - if (req.getMethod() === "put") { - apiFunction = userMetadataPut_1.userMetadataPut; + // If the id doesnt match any APIs return false + if (apiFunction === undefined) { + return false; } - } - else if (id === constants_1.USER_SESSIONS_API) { - if (req.getMethod() === "get") { - apiFunction = userSessionsGet_1.userSessionsGet; - } - if (req.getMethod() === "post") { - apiFunction = userSessionsPost_1.userSessionsPost; - } - } - else if (id === constants_1.USER_PASSWORD_API) { - apiFunction = userPasswordPut_1.userPasswordPut; - } - else if (id === constants_1.USER_EMAIL_VERIFY_TOKEN_API) { - apiFunction = userEmailVerifyTokenPost_1.userEmailVerifyTokenPost; - } - // If the id doesnt match any APIs return false - if (apiFunction === undefined) { - return false; - } - return yield apiKeyProtector_1.default(this.apiImpl, options, apiFunction); - }); - this.handleError = (err, _, __) => __awaiter(this, void 0, void 0, function* () { - throw err; - }); + return yield apiKeyProtector_1.default(this.apiImpl, options, apiFunction); + }); + this.handleError = (err, _, __) => + __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; @@ -147,7 +166,9 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; this.returnAPIIdIfCanHandleRequest = (path, method) => { - const dashboardBundlePath = this.getAppInfo().apiBasePath.appendPath(new normalisedURLPath_1.default(constants_1.DASHBOARD_API)); + const dashboardBundlePath = this.getAppInfo().apiBasePath.appendPath( + new normalisedURLPath_1.default(constants_1.DASHBOARD_API) + ); if (utils_1.isApiPath(path, this.getAppInfo())) { return utils_1.getApiIdIfMatched(path, method); } @@ -178,9 +199,10 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } - else { - throw new Error("Emailverification recipe has already been initialised. Please check your code for bugs."); + } else { + throw new Error( + "Emailverification recipe has already been initialised. Please check your code for bugs." + ); } }; } diff --git a/lib/build/recipe/dashboard/recipeImplementation.js b/lib/build/recipe/dashboard/recipeImplementation.js index 2a3de05e4..6f231cd85 100644 --- a/lib/build/recipe/dashboard/recipeImplementation.js +++ b/lib/build/recipe/dashboard/recipeImplementation.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const version_1 = require("../../version"); function getRecipeImplementation() { @@ -35,7 +57,10 @@ function getRecipeImplementation() { return __awaiter(this, void 0, void 0, function* () { let apiKeyHeaderValue = input.req.getHeaderValue("authorization"); // We receieve the api key as `Bearer API_KEY`, this retrieves just the key - apiKeyHeaderValue = apiKeyHeaderValue === null || apiKeyHeaderValue === void 0 ? void 0 : apiKeyHeaderValue.split(" ")[1]; + apiKeyHeaderValue = + apiKeyHeaderValue === null || apiKeyHeaderValue === void 0 + ? void 0 + : apiKeyHeaderValue.split(" ")[1]; if (apiKeyHeaderValue === undefined) { return false; } diff --git a/lib/build/recipe/dashboard/types.d.ts b/lib/build/recipe/dashboard/types.d.ts index cf3b03892..8dc459baf 100644 --- a/lib/build/recipe/dashboard/types.d.ts +++ b/lib/build/recipe/dashboard/types.d.ts @@ -4,26 +4,26 @@ import { NormalisedAppinfo } from "../../types"; export declare type TypeInput = { apiKey: string; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { apiKey: string; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getDashboardBundleLocation(input: { - userContext: any; - }): Promise; - shouldAllowAccess(input: { - req: BaseRequest; - config: TypeNormalisedInput; - userContext: any; - }): Promise; + getDashboardBundleLocation(input: { userContext: any }): Promise; + shouldAllowAccess(input: { req: BaseRequest; config: TypeNormalisedInput; userContext: any }): Promise; }; export declare type APIOptions = { recipeImplementation: RecipeInterface; @@ -35,10 +35,7 @@ export declare type APIOptions = { appInfo: NormalisedAppinfo; }; export declare type APIInterface = { - dashboardGET: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise); + dashboardGET: undefined | ((input: { options: APIOptions; userContext: any }) => Promise); }; export declare type APIFunction = (apiImplementation: APIInterface, options: APIOptions) => Promise; export declare type RecipeIdForUser = "emailpassword" | "thirdparty" | "passwordless"; diff --git a/lib/build/recipe/dashboard/utils.d.ts b/lib/build/recipe/dashboard/utils.d.ts index 297e84570..5431adffe 100644 --- a/lib/build/recipe/dashboard/utils.d.ts +++ b/lib/build/recipe/dashboard/utils.d.ts @@ -7,8 +7,17 @@ export declare function isApiPath(path: NormalisedURLPath, appInfo: NormalisedAp export declare function getApiIdIfMatched(path: NormalisedURLPath, method: HTTPMethod): string | undefined; export declare function sendUnauthorisedAccess(res: BaseResponse): void; export declare function isValidRecipeId(recipeId: string): recipeId is RecipeIdForUser; -export declare function getUserForRecipeId(userId: string, recipeId: string): Promise<{ +export declare function getUserForRecipeId( + userId: string, + recipeId: string +): Promise<{ user: RecipeLevelUserWithFirstAndLastName | undefined; - recipe: "emailpassword" | "thirdparty" | "passwordless" | "thirdpartyemailpassword" | "thirdpartypasswordless" | undefined; + recipe: + | "emailpassword" + | "thirdparty" + | "passwordless" + | "thirdpartyemailpassword" + | "thirdpartypasswordless" + | undefined; }>; export declare function isRecipeInitialised(recipeId: RecipeIdForUser): boolean; diff --git a/lib/build/recipe/dashboard/utils.js b/lib/build/recipe/dashboard/utils.js index b2d9899a9..5e574f3d7 100644 --- a/lib/build/recipe/dashboard/utils.js +++ b/lib/build/recipe/dashboard/utils.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isRecipeInitialised = exports.getUserForRecipeId = exports.isValidRecipeId = exports.sendUnauthorisedAccess = exports.getApiIdIfMatched = exports.isApiPath = exports.validateAndNormaliseUserInput = void 0; const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); @@ -44,7 +68,13 @@ function validateAndNormaliseUserInput(config) { if (config.apiKey.trim().length === 0) { throw new Error("apiKey provided to Dashboard recipe cannot be empty"); } - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config.override + ); return { apiKey: config.apiKey, override, @@ -52,7 +82,9 @@ function validateAndNormaliseUserInput(config) { } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function isApiPath(path, appInfo) { - const dashboardRecipeBasePath = appInfo.apiBasePath.appendPath(new normalisedURLPath_1.default(constants_1.DASHBOARD_API)); + const dashboardRecipeBasePath = appInfo.apiBasePath.appendPath( + new normalisedURLPath_1.default(constants_1.DASHBOARD_API) + ); if (!path.startsWith(dashboardRecipeBasePath)) { return false; } @@ -143,14 +175,15 @@ function _getUserForRecipeId(userId, recipeId) { // we detect if this recipe has been init or not.. recipe_2.default.getInstanceOrThrowError(); if (globalUser !== undefined) { - let loginMethod = globalUser.loginMethods.find((u) => u.recipeId === "emailpassword" && u.recipeUserId === userId); + let loginMethod = globalUser.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); if (loginMethod !== undefined) { user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); recipe = "emailpassword"; } } - } - catch (e) { + } catch (e) { // No - op } if (user === undefined) { @@ -158,31 +191,29 @@ function _getUserForRecipeId(userId, recipeId) { const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); if (userResponse !== undefined) { if ("loginMethods" in userResponse) { - let loginMethod = userResponse.loginMethods.find((u) => u.recipeId === "emailpassword" && u.recipeUserId === userId); + let loginMethod = userResponse.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); if (loginMethod !== undefined) { user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); recipe = "thirdpartyemailpassword"; } - } - else { + } else { throw new Error("Should never come here. TODO remove me"); } } - } - catch (e) { + } catch (e) { // No - op } } - } - else if (recipeId === recipe_3.default.RECIPE_ID) { + } else if (recipeId === recipe_3.default.RECIPE_ID) { try { const userResponse = yield thirdparty_1.default.getUserById(userId); if (userResponse !== undefined) { user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); recipe = "thirdparty"; } - } - catch (e) { + } catch (e) { // No - op } if (user === undefined) { @@ -191,14 +222,12 @@ function _getUserForRecipeId(userId, recipeId) { if (userResponse !== undefined) { if ("loginMethods" in userResponse) { throw new Error("Should never come here. TODO remove me"); - } - else { + } else { user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); recipe = "thirdpartyemailpassword"; } } - } - catch (e) { + } catch (e) { // No - op } } @@ -209,13 +238,11 @@ function _getUserForRecipeId(userId, recipeId) { user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); recipe = "thirdpartypasswordless"; } - } - catch (e) { + } catch (e) { // No - op } } - } - else if (recipeId === recipe_4.default.RECIPE_ID) { + } else if (recipeId === recipe_4.default.RECIPE_ID) { try { const userResponse = yield passwordless_1.default.getUserById({ userId, @@ -224,8 +251,7 @@ function _getUserForRecipeId(userId, recipeId) { user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); recipe = "passwordless"; } - } - catch (e) { + } catch (e) { // No - op } if (user === undefined) { @@ -235,8 +261,7 @@ function _getUserForRecipeId(userId, recipeId) { user = Object.assign(Object.assign({}, userResponse), { recipeId: "passwordless" }); recipe = "thirdpartypasswordless"; } - } - catch (e) { + } catch (e) { // No - op } } @@ -253,49 +278,40 @@ function isRecipeInitialised(recipeId) { try { recipe_2.default.getInstanceOrThrowError(); isRecipeInitialised = true; - } - catch (_) { } + } catch (_) {} if (!isRecipeInitialised) { try { recipe_5.default.getInstanceOrThrowError(); isRecipeInitialised = true; - } - catch (_) { } + } catch (_) {} } - } - else if (recipeId === "passwordless") { + } else if (recipeId === "passwordless") { try { recipe_4.default.getInstanceOrThrowError(); isRecipeInitialised = true; - } - catch (_) { } + } catch (_) {} if (!isRecipeInitialised) { try { recipe_6.default.getInstanceOrThrowError(); isRecipeInitialised = true; - } - catch (_) { } + } catch (_) {} } - } - else if (recipeId === "thirdparty") { + } else if (recipeId === "thirdparty") { try { recipe_3.default.getInstanceOrThrowError(); isRecipeInitialised = true; - } - catch (_) { } + } catch (_) {} if (!isRecipeInitialised) { try { recipe_5.default.getInstanceOrThrowError(); isRecipeInitialised = true; - } - catch (_) { } + } catch (_) {} } if (!isRecipeInitialised) { try { recipe_6.default.getInstanceOrThrowError(); isRecipeInitialised = true; - } - catch (_) { } + } catch (_) {} } } return isRecipeInitialised; diff --git a/lib/build/recipe/emailpassword/api/emailExists.js b/lib/build/recipe/emailpassword/api/emailExists.js index 598a71166..2c99dc317 100644 --- a/lib/build/recipe/emailpassword/api/emailExists.js +++ b/lib/build/recipe/emailpassword/api/emailExists.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); diff --git a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts index 02820a357..3e0bfbb08 100644 --- a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts +++ b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts @@ -1,2 +1,5 @@ import { APIInterface, APIOptions } from "../"; -export default function generatePasswordResetToken(apiImplementation: APIInterface, options: APIOptions): Promise; +export default function generatePasswordResetToken( + apiImplementation: APIInterface, + options: APIOptions +): Promise; diff --git a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js index d4e88af7a..3fa0fad07 100644 --- a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js +++ b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -33,7 +55,10 @@ function generatePasswordResetToken(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.resetPasswordUsingTokenFeature.formFieldsForGenerateTokenForm, (yield options.req.getJSONBody()).formFields); + let formFields = yield utils_2.validateFormFieldsOrThrowError( + options.config.resetPasswordUsingTokenFeature.formFieldsForGenerateTokenForm, + (yield options.req.getJSONBody()).formFields + ); let result = yield apiImplementation.generatePasswordResetTokenPOST({ formFields, options, diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index 78180b85b..b57843e3c 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -1,35 +1,76 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const session_1 = __importStar(require("../../session")); @@ -42,7 +83,7 @@ const emailVerificationClaim_1 = require("../../emailverification/emailVerificat const utils_1 = require("../../emailverification/utils"); function getAPIImplementation() { return { - linkAccountToExistingAccountPOST: function ({ formFields, session, options, userContext, }) { + linkAccountToExistingAccountPOST: function ({ formFields, session, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ @@ -64,19 +105,26 @@ function getAPIImplementation() { userContext, }); if (response.status !== "OK") { - throw Error(`this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}`); + throw Error( + `this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}` + ); } createdNewRecipeUser = true; if (result.updateAccountLinkingClaim === "ADD_CLAIM") { const emailVerificationInstance = recipe_2.default.getInstance(); if (emailVerificationInstance !== undefined) { - let emailVerificationResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ - userId: response.user.id, - email, - userContext, - }); + let emailVerificationResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: response.user.id, + email, + userContext, + } + ); if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { - yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); + yield session.fetchAndSetClaim( + emailVerificationClaim_1.EmailVerificationClaim, + userContext + ); let emailVerifyLink = utils_1.getEmailVerifyLink({ appInfo: options.appInfo, token: emailVerificationResponse.token, @@ -93,14 +141,17 @@ function getAPIImplementation() { }); } } - yield session.setClaimValue(accountLinkingClaim_1.AccountLinkingClaim, response.user.id, userContext); + yield session.setClaimValue( + accountLinkingClaim_1.AccountLinkingClaim, + response.user.id, + userContext + ); return { status: "ACCOUNT_NOT_VERIFIED_ERROR", isNotVerifiedAccountFromInputSession: false, description: "", }; - } - else { + } else { result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ session, newUser: { @@ -113,19 +164,26 @@ function getAPIImplementation() { } } if (result.createRecipeUser) { - throw Error(`this error should never be thrown after creating a new user during accountLinkPostSignInViaSession flow`); + throw Error( + `this error should never be thrown after creating a new user during accountLinkPostSignInViaSession flow` + ); } if (!result.accountsLinked && "reason" in result) { if (result.reason === "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { const emailVerificationInstance = recipe_2.default.getInstance(); if (emailVerificationInstance !== undefined) { - let emailVerificationResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ - userId: result.userId, - email, - userContext, - }); + let emailVerificationResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: result.userId, + email, + userContext, + } + ); if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { - yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); + yield session.fetchAndSetClaim( + emailVerificationClaim_1.EmailVerificationClaim, + userContext + ); let emailVerifyLink = utils_1.getEmailVerifyLink({ appInfo: options.appInfo, token: emailVerificationResponse.token, @@ -148,8 +206,10 @@ function getAPIImplementation() { description: "", }; } - if (result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || - result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { + if ( + result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || + result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" + ) { return { status: result.reason, description: "", @@ -164,13 +224,14 @@ function getAPIImplementation() { let wereAccountsAlreadyLinked = false; if (result.updateAccountLinkingClaim === "REMOVE_CLAIM") { yield session.removeClaim(accountLinkingClaim_1.AccountLinkingClaim, userContext); - } - else { + } else { wereAccountsAlreadyLinked = true; } let user = yield __1.getUser(session.getUserId()); if (user === undefined) { - throw Error("this error should never be thrown. Can't find primary user with userId: " + session.getUserId()); + throw Error( + "this error should never be thrown. Can't find primary user with userId: " + session.getUserId() + ); } return { status: "OK", @@ -181,7 +242,7 @@ function getAPIImplementation() { }; }); }, - emailExistsGET: function ({ email, options, userContext, }) { + emailExistsGET: function ({ email, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let user = yield options.recipeImplementation.getUserByEmail({ email, userContext }); return { @@ -190,7 +251,7 @@ function getAPIImplementation() { }; }); }, - generatePasswordResetTokenPOST: function ({ formFields, options, userContext, }) { + generatePasswordResetTokenPOST: function ({ formFields, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let userIdForPasswordReset = undefined; @@ -214,16 +275,25 @@ function getAPIImplementation() { * has the input email as identifying info * now checking if emailpassword user exists for the input email */ - let epRecipeUser = users.find((u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined); + let epRecipeUser = users.find( + (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + ); if (epRecipeUser === undefined) { /** * this means that there is no emailpassword recipe user for the input email * so we check is account linking is enabled for the given email and primaryUserId */ - let shouldDoAccountLinking = yield recipe_1.default.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking({ - email, - recipeId: "emailpassword", - }, primaryUser, undefined, userContext); + let shouldDoAccountLinking = yield recipe_1.default + .getInstanceOrThrowError() + .config.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); if (!shouldDoAccountLinking.shouldAutomaticallyLink) { /** * here, reset password token generation is not allowed @@ -233,7 +303,9 @@ function getAPIImplementation() { status: "OK", }; } - let identitiesForPrimaryUser = recipe_1.default.getInstanceOrThrowError().transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); + let identitiesForPrimaryUser = recipe_1.default + .getInstanceOrThrowError() + .transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); /** * if input email doens't belong to the verified indentity for the primaryUser, * we need to check shouldRequireVerification boolean @@ -251,8 +323,7 @@ function getAPIImplementation() { } userIdForPasswordReset = primaryUser.id; recipeUserId = primaryUser.id; - } - else { + } else { /** * this means emailpassword user associated with the input email exists but it * is currently not associated with the primaryUserId we found in the @@ -261,8 +332,7 @@ function getAPIImplementation() { userIdForPasswordReset = epRecipeUser.id; recipeUserId = epRecipeUser.id; } - } - else { + } else { /** * the primaryUserId associated with the email has a linked * emailpassword recipe user with same email @@ -271,10 +341,17 @@ function getAPIImplementation() { /** * checking for shouldDoAccountLinking */ - let shouldDoAccountLinking = yield recipe_1.default.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking({ - email, - recipeId: "emailpassword", - }, primaryUser, undefined, userContext); + let shouldDoAccountLinking = yield recipe_1.default + .getInstanceOrThrowError() + .config.shouldDoAutomaticAccountLinking( + { + email, + recipeId: "emailpassword", + }, + primaryUser, + undefined, + userContext + ); let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink ? shouldDoAccountLinking.shouldRequireVerification : false; @@ -288,14 +365,18 @@ function getAPIImplementation() { * checking if the email belongs to the verified identities for the * primary user */ - let identitiesForPrimaryUser = recipe_1.default.getInstanceOrThrowError().transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); + let identitiesForPrimaryUser = recipe_1.default + .getInstanceOrThrowError() + .transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); if (!identitiesForPrimaryUser.verified.emails.includes(email)) { /** * the email is not verified for any account linked to the primary user. * so we check if there exists any account linked with the primary user * which doesn't have this email as identifying info */ - let differentIdentityUser = primaryUser.loginMethods.find((u) => u.email !== email); + let differentIdentityUser = primaryUser.loginMethods.find( + (u) => u.email !== email + ); if (differentIdentityUser !== undefined) { /** * if any such user found, we return status to contact support @@ -310,13 +391,14 @@ function getAPIImplementation() { } userIdForPasswordReset = primaryUser.id; } - } - else { + } else { /** * no primaryUser exists for the given email. So we just find the * associated emailpasword user, if exists */ - let epRecipeUser = users.find((u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined); + let epRecipeUser = users.find( + (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + ); if (epRecipeUser === undefined) { return { status: "OK", @@ -325,8 +407,7 @@ function getAPIImplementation() { userIdForPasswordReset = epRecipeUser.id; recipeUserId = epRecipeUser.id; } - } - else { + } else { return { status: "OK", }; @@ -337,12 +418,15 @@ function getAPIImplementation() { userContext, }); if (response.status === "UNKNOWN_USER_ID_ERROR") { - logger_1.logDebugMessage(`Password reset email not sent, unknown user id: ${userIdForPasswordReset}`); + logger_1.logDebugMessage( + `Password reset email not sent, unknown user id: ${userIdForPasswordReset}` + ); return { status: "OK", }; } - let passwordResetLink = options.appInfo.websiteDomain.getAsStringDangerous() + + let passwordResetLink = + options.appInfo.websiteDomain.getAsStringDangerous() + options.appInfo.websiteBasePath.getAsStringDangerous() + "/reset-password?token=" + response.token + @@ -364,7 +448,7 @@ function getAPIImplementation() { }; }); }, - passwordResetPOST: function ({ formFields, token, options, userContext, }) { + passwordResetPOST: function ({ formFields, token, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let newPassword = formFields.filter((f) => f.id === "password")[0].value; let response = yield options.recipeImplementation.resetPasswordUsingToken({ @@ -379,11 +463,13 @@ function getAPIImplementation() { return __awaiter(this, void 0, void 0, function* () { const emailVerificationInstance = recipe_2.default.getInstance(); if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ - userId: rUserId, - email, - userContext, - }); + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: rUserId, + email, + userContext, + } + ); if (tokenResponse.status === "OK") { yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ token: tokenResponse.token, @@ -423,33 +509,46 @@ function getAPIImplementation() { let recipeUser = response.user; yield verifyUser(response.user.id); yield accountlinking_1.linkAccounts(recipeUser.id, user.id, userContext); - } - else if (!epUser.verified) { + } else if (!epUser.verified) { yield verifyUser(epUser.recipeUserId); } - } - else { + } else { /** * it's a recipe user */ if (!user.loginMethods[0].verified) { yield verifyUser(user.loginMethods[0].recipeUserId); } - const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [], sessionRequired: false }, userContext); - let result = yield recipe_1.default.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ - recipeUserId: user.id, - session, - userContext, - }); + const session = yield session_1.default.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [], sessionRequired: false }, + userContext + ); + let result = yield recipe_1.default + .getInstanceOrThrowError() + .createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ + recipeUserId: user.id, + session, + userContext, + }); if (result.createNewSession) { - yield session_1.createNewSession(options.req, options.res, result.primaryUserId, result.recipeUserId, {}, {}, userContext); + yield session_1.createNewSession( + options.req, + options.res, + result.primaryUserId, + result.recipeUserId, + {}, + {}, + userContext + ); } } } return response; }); }, - signInPOST: function ({ formFields, options, userContext, }) { + signInPOST: function ({ formFields, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; @@ -462,7 +561,15 @@ function getAPIImplementation() { if (recipeUser === undefined) { throw new Error("Should never come here"); } - let session = yield session_1.default.createNewSession(options.req, options.res, user.id, recipeUser.recipeUserId, {}, {}, userContext); + let session = yield session_1.default.createNewSession( + options.req, + options.res, + user.id, + recipeUser.recipeUserId, + {}, + {}, + userContext + ); return { status: "OK", session, @@ -470,7 +577,7 @@ function getAPIImplementation() { }; }); }, - signUpPOST: function ({ formFields, options, userContext, }) { + signUpPOST: function ({ formFields, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let email = formFields.filter((f) => f.id === "email")[0].value; let password = formFields.filter((f) => f.id === "password")[0].value; @@ -484,7 +591,8 @@ function getAPIImplementation() { if (!isSignUpAllowed) { return { status: "SIGNUP_NOT_ALLOWED", - reason: "The input email is already associated with another account where it is not verified. Please disable automatic account linking, or verify the other account before trying again.", + reason: + "The input email is already associated with another account where it is not verified. Please disable automatic account linking, or verify the other account before trying again.", }; } let response = yield options.recipeImplementation.signUp({ @@ -501,7 +609,15 @@ function getAPIImplementation() { if (recipeUser === undefined) { throw new Error("Race condition error - please call this API again"); } - let session = yield session_1.default.createNewSession(options.req, options.res, user.id, recipeUser.recipeUserId, {}, {}, userContext); + let session = yield session_1.default.createNewSession( + options.req, + options.res, + user.id, + recipeUser.recipeUserId, + {}, + {}, + userContext + ); return { status: "OK", session, diff --git a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts index 9d8e73b50..a7439fe8c 100644 --- a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts +++ b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts @@ -1,2 +1,5 @@ import { APIInterface, APIOptions } from ".."; -export default function linkAccountToExistingAccountAPI(apiImplementation: APIInterface, options: APIOptions): Promise; +export default function linkAccountToExistingAccountAPI( + apiImplementation: APIInterface, + options: APIOptions +): Promise; diff --git a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js index a83157db3..84e6de768 100644 --- a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js +++ b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -38,9 +62,17 @@ function linkAccountToExistingAccountAPI(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.signUpFeature.formFields, (yield options.req.getJSONBody()).formFields); + let formFields = yield utils_2.validateFormFieldsOrThrowError( + options.config.signUpFeature.formFields, + (yield options.req.getJSONBody()).formFields + ); let userContext = utils_3.makeDefaultUserContextFromAPI(options.req); - const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [] }, userContext); + const session = yield session_1.default.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [] }, + userContext + ); let result = yield apiImplementation.linkAccountToExistingAccountPOST({ formFields, session: session, @@ -52,11 +84,9 @@ function linkAccountToExistingAccountAPI(apiImplementation, options) { status: "OK", user: result.user, }); - } - else if (result.status === "GENERAL_ERROR") { + } else if (result.status === "GENERAL_ERROR") { utils_1.send200Response(options.res, result); - } - else { + } else { throw new error_1.default({ type: error_1.default.FIELD_ERROR, payload: [ diff --git a/lib/build/recipe/emailpassword/api/passwordReset.js b/lib/build/recipe/emailpassword/api/passwordReset.js index d7877d650..dc8c29d4f 100644 --- a/lib/build/recipe/emailpassword/api/passwordReset.js +++ b/lib/build/recipe/emailpassword/api/passwordReset.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -37,7 +61,10 @@ function passwordReset(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.resetPasswordUsingTokenFeature.formFieldsForPasswordResetForm, (yield options.req.getJSONBody()).formFields); + let formFields = yield utils_2.validateFormFieldsOrThrowError( + options.config.resetPasswordUsingTokenFeature.formFieldsForPasswordResetForm, + (yield options.req.getJSONBody()).formFields + ); let token = (yield options.req.getJSONBody()).token; if (token === undefined) { throw new error_1.default({ @@ -57,11 +84,14 @@ function passwordReset(apiImplementation, options) { options, userContext: utils_3.makeDefaultUserContextFromAPI(options.req), }); - utils_1.send200Response(options.res, result.status === "OK" - ? { - status: "OK", - } - : result); + utils_1.send200Response( + options.res, + result.status === "OK" + ? { + status: "OK", + } + : result + ); return true; }); } diff --git a/lib/build/recipe/emailpassword/api/signin.js b/lib/build/recipe/emailpassword/api/signin.js index 039b3beda..971c51911 100644 --- a/lib/build/recipe/emailpassword/api/signin.js +++ b/lib/build/recipe/emailpassword/api/signin.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -33,7 +55,10 @@ function signInAPI(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.signInFeature.formFields, (yield options.req.getJSONBody()).formFields); + let formFields = yield utils_2.validateFormFieldsOrThrowError( + options.config.signInFeature.formFields, + (yield options.req.getJSONBody()).formFields + ); let result = yield apiImplementation.signInPOST({ formFields, options, @@ -44,8 +69,7 @@ function signInAPI(apiImplementation, options) { status: "OK", user: result.user, }); - } - else { + } else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/emailpassword/api/signup.js b/lib/build/recipe/emailpassword/api/signup.js index c5fbd417c..986be1fe2 100644 --- a/lib/build/recipe/emailpassword/api/signup.js +++ b/lib/build/recipe/emailpassword/api/signup.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); @@ -37,7 +61,10 @@ function signUpAPI(apiImplementation, options) { return false; } // step 1 - let formFields = yield utils_2.validateFormFieldsOrThrowError(options.config.signUpFeature.formFields, (yield options.req.getJSONBody()).formFields); + let formFields = yield utils_2.validateFormFieldsOrThrowError( + options.config.signUpFeature.formFields, + (yield options.req.getJSONBody()).formFields + ); let result = yield apiImplementation.signUpPOST({ formFields, options, @@ -48,11 +75,9 @@ function signUpAPI(apiImplementation, options) { status: "OK", user: result.user, }); - } - else if (result.status === "GENERAL_ERROR") { + } else if (result.status === "GENERAL_ERROR") { utils_1.send200Response(options.res, result); - } - else { + } else { throw new error_1.default({ type: error_1.default.FIELD_ERROR, payload: [ diff --git a/lib/build/recipe/emailpassword/api/utils.d.ts b/lib/build/recipe/emailpassword/api/utils.d.ts index d028348e5..055c33ac0 100644 --- a/lib/build/recipe/emailpassword/api/utils.d.ts +++ b/lib/build/recipe/emailpassword/api/utils.d.ts @@ -1,5 +1,10 @@ import { NormalisedFormField } from "../types"; -export declare function validateFormFieldsOrThrowError(configFormFields: NormalisedFormField[], formFieldsRaw: any): Promise<{ - id: string; - value: string; -}[]>; +export declare function validateFormFieldsOrThrowError( + configFormFields: NormalisedFormField[], + formFieldsRaw: any +): Promise< + { + id: string; + value: string; + }[] +>; diff --git a/lib/build/recipe/emailpassword/api/utils.js b/lib/build/recipe/emailpassword/api/utils.js index 009d0127e..bbf03c787 100644 --- a/lib/build/recipe/emailpassword/api/utils.js +++ b/lib/build/recipe/emailpassword/api/utils.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateFormFieldsOrThrowError = void 0; const error_1 = __importDefault(require("../error")); @@ -73,8 +97,7 @@ function validateFormOrThrowError(inputs, configFormFields) { error: "Field is not optional", id: field.id, }); - } - else { + } else { // Otherwise, use validate function. const error = yield field.validate(input.value); // If error, add it. diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index c57c14c4d..866c74e34 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,12 +1,15 @@ import { TypeEmailPasswordEmailDeliveryInput, RecipeInterface } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService implements EmailDeliveryInterface { +export default class BackwardCompatibilityService + implements EmailDeliveryInterface { private isInServerlessEnv; private appInfo; private resetPasswordUsingTokenFeature; constructor(_: RecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean); - sendEmail: (input: TypeEmailPasswordEmailDeliveryInput & { - userContext: any; - }) => Promise; + sendEmail: ( + input: TypeEmailPasswordEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js index b47681029..ffb8a6093 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -1,34 +1,59 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const passwordResetFunctions_1 = require("../../../passwordResetFunctions"); -class BackwardCompatibilityService { - constructor(_, appInfo, isInServerlessEnv) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - // we add this here cause the user may have overridden the sendEmail function - // to change the input email and if we don't do this, the input email - // will get reset by the getUserById call above. - try { - if (!this.isInServerlessEnv) { - this.resetPasswordUsingTokenFeature - .createAndSendCustomEmail(input.user, input.passwordResetLink, input.userContext) - .catch((_) => { }); +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - else { - // see https://github.com/supertokens/supertokens-node/pull/135 - yield this.resetPasswordUsingTokenFeature.createAndSendCustomEmail(input.user, input.passwordResetLink, input.userContext); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - catch (_) { } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); + }; +Object.defineProperty(exports, "__esModule", { value: true }); +const passwordResetFunctions_1 = require("../../../passwordResetFunctions"); +class BackwardCompatibilityService { + constructor(_, appInfo, isInServerlessEnv) { + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + // we add this here cause the user may have overridden the sendEmail function + // to change the input email and if we don't do this, the input email + // will get reset by the getUserById call above. + try { + if (!this.isInServerlessEnv) { + this.resetPasswordUsingTokenFeature + .createAndSendCustomEmail(input.user, input.passwordResetLink, input.userContext) + .catch((_) => {}); + } else { + // see https://github.com/supertokens/supertokens-node/pull/135 + yield this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( + input.user, + input.passwordResetLink, + input.userContext + ); + } + } catch (_) {} + }); this.isInServerlessEnv = isInServerlessEnv; this.appInfo = appInfo; { diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/index.js index d648973c6..91700aeaf 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/index.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SMTPService = void 0; const smtp_1 = __importDefault(require("./smtp")); diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts index d6b78e973..01e4dcb3f 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts @@ -4,7 +4,9 @@ import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery export default class SMTPService implements EmailDeliveryInterface { serviceImpl: ServiceInterface; constructor(config: TypeInput); - sendEmail: (input: TypeEmailPasswordEmailDeliveryInput & { - userContext: any; - }) => Promise; + sendEmail: ( + input: TypeEmailPasswordEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js index b96042bcd..e917fb0fe 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.js @@ -1,26 +1,53 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const serviceImplementation_1 = require("./serviceImplementation"); class SMTPService { constructor(config) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - yield this.serviceImpl.sendRawEmail(Object.assign(Object.assign({}, content), { userContext: input.userContext })); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + yield this.serviceImpl.sendRawEmail( + Object.assign(Object.assign({}, content), { userContext: input.userContext }) + ); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -30,7 +57,9 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); + let builder = new supertokens_js_override_1.default( + serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) + ); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts index 403345e85..f551ad8f5 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts @@ -1,4 +1,6 @@ import { TypeEmailPasswordPasswordResetEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; -export default function getPasswordResetEmailContent(input: TypeEmailPasswordPasswordResetEmailDeliveryInput): GetContentResult; +export default function getPasswordResetEmailContent( + input: TypeEmailPasswordPasswordResetEmailDeliveryInput +): GetContentResult; export declare function getPasswordResetEmailHTML(appName: string, email: string, resetLink: string): string; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js index 3bd967134..65fb03c6c 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPasswordResetEmailHTML = void 0; const supertokens_1 = __importDefault(require("../../../../../supertokens")); diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts index 8336455b9..c80e6ba57 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts @@ -1,7 +1,10 @@ import { TypeEmailPasswordEmailDeliveryInput } from "../../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation(transporter: Transporter, from: { - name: string; - email: string; -}): ServiceInterface; +export declare function getServiceImplementation( + transporter: Transporter, + from: { + name: string; + email: string; + } +): ServiceInterface; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js index 4957c1cb7..f4ebb5266 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getServiceImplementation = void 0; const passwordReset_1 = __importDefault(require("../passwordReset")); @@ -39,8 +63,7 @@ function getServiceImplementation(transporter, from) { subject: input.subject, html: input.body, }); - } - else { + } else { yield transporter.sendMail({ from: `${from.name} <${from.email}>`, to: input.toEmail, diff --git a/lib/build/recipe/emailpassword/error.d.ts b/lib/build/recipe/emailpassword/error.d.ts index a96613142..e55ae7b3f 100644 --- a/lib/build/recipe/emailpassword/error.d.ts +++ b/lib/build/recipe/emailpassword/error.d.ts @@ -1,15 +1,19 @@ import STError from "../../error"; export default class SessionError extends STError { static FIELD_ERROR: "FIELD_ERROR"; - constructor(options: { - type: "FIELD_ERROR"; - payload: { - id: string; - error: string; - }[]; - message: string; - } | { - type: "BAD_INPUT_ERROR"; - message: string; - }); + constructor( + options: + | { + type: "FIELD_ERROR"; + payload: { + id: string; + error: string; + }[]; + message: string; + } + | { + type: "BAD_INPUT_ERROR"; + message: string; + } + ); } diff --git a/lib/build/recipe/emailpassword/error.js b/lib/build/recipe/emailpassword/error.js index 8a9e8ef0e..ce0b25647 100644 --- a/lib/build/recipe/emailpassword/error.js +++ b/lib/build/recipe/emailpassword/error.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); class SessionError extends error_1.default { diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index e7d191fa5..867460d1d 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -5,19 +5,34 @@ import { User } from "../../types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static signUp(email: string, password: string, doAccountLinking?: boolean, userContext?: any): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - }>; - static signIn(email: string, password: string, userContext?: any): Promise<{ - status: "OK"; - user: User; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - }>; + static signUp( + email: string, + password: string, + doAccountLinking?: boolean, + userContext?: any + ): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >; + static signIn( + email: string, + password: string, + userContext?: any + ): Promise< + | { + status: "OK"; + user: User; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + >; static getUserById(userId: string, userContext?: any): Promise; static getUserByEmail(email: string, userContext?: any): Promise; /** @@ -31,30 +46,50 @@ export default class Wrapper { * * And we want to allow primaryUserId being passed in. */ - static createResetPasswordToken(userId: string, email: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "UNKNOWN_USER_ID_ERROR"; - }>; - static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ - status: "OK"; - email: string; - userId: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + static createResetPasswordToken( + userId: string, + email: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "UNKNOWN_USER_ID_ERROR"; + } + >; + static resetPasswordUsingToken( + token: string, + newPassword: string, + userContext?: any + ): Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; static updateEmailOrPassword(input: { userId: string; email?: string; password?: string; userContext?: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; - static sendEmail(input: TypeEmailPasswordEmailDeliveryInput & { - userContext?: any; - }): Promise; + static sendEmail( + input: TypeEmailPasswordEmailDeliveryInput & { + userContext?: any; + } + ): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/emailpassword/index.js b/lib/build/recipe/emailpassword/index.js index a68cfe6ec..0e31a7b7a 100644 --- a/lib/build/recipe/emailpassword/index.js +++ b/lib/build/recipe/emailpassword/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sendEmail = exports.updateEmailOrPassword = exports.resetPasswordUsingToken = exports.createResetPasswordToken = exports.getUserByEmail = exports.getUserById = exports.signIn = exports.signUp = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); @@ -83,12 +107,16 @@ class Wrapper { }); } static updateEmailOrPassword(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); } static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { let recipeInstance = recipe_1.default.getInstanceOrThrowError(); - return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail( + Object.assign({ userContext: {} }, input) + ); }); } } diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index eef4d30ee..a1c21861b 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -1,6 +1,11 @@ import { NormalisedAppinfo } from "../../types"; -export declare function createAndSendCustomEmail(appInfo: NormalisedAppinfo): (user: { - id: string; - recipeUserId?: string; - email: string; -}, passwordResetURLWithToken: string) => Promise; +export declare function createAndSendCustomEmail( + appInfo: NormalisedAppinfo +): ( + user: { + id: string; + recipeUserId?: string; + email: string; + }, + passwordResetURLWithToken: string +) => Promise; diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.js b/lib/build/recipe/emailpassword/passwordResetFunctions.js index e6f598f8e..535499e39 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.js +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.js @@ -13,65 +13,93 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createAndSendCustomEmail = void 0; const axios_1 = __importDefault(require("axios")); const logger_1 = require("../../logger"); function createAndSendCustomEmail(appInfo) { - return (user, passwordResetURLWithToken) => __awaiter(this, void 0, void 0, function* () { - // related issue: https://github.com/supertokens/supertokens-node/issues/38 - if (process.env.TEST_MODE === "testing") { - return; - } - try { - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.io/0/st/auth/password/reset", - data: { - email: user.email, - appName: appInfo.appName, - passwordResetURL: passwordResetURLWithToken, - }, - headers: { - "api-version": 0, - }, - }); - logger_1.logDebugMessage(`Password reset email sent to ${user.email}`); - } - catch (error) { - logger_1.logDebugMessage("Error sending password reset email"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } - else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } + return (user, passwordResetURLWithToken) => + __awaiter(this, void 0, void 0, function* () { + // related issue: https://github.com/supertokens/supertokens-node/issues/38 + if (process.env.TEST_MODE === "testing") { + return; } - else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + try { + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.io/0/st/auth/password/reset", + data: { + email: user.email, + appName: appInfo.appName, + passwordResetURL: passwordResetURLWithToken, + }, + headers: { + "api-version": 0, + }, + }); + logger_1.logDebugMessage(`Password reset email sent to ${user.email}`); + } catch (error) { + logger_1.logDebugMessage("Error sending password reset email"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + } else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + } else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + } + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage( + JSON.stringify( + { + email: user.email, + appName: appInfo.appName, + passwordResetURL: passwordResetURLWithToken, + }, + null, + 2 + ) + ); } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage(JSON.stringify({ - email: user.email, - appName: appInfo.appName, - passwordResetURL: passwordResetURLWithToken, - }, null, 2)); - } - }); + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; diff --git a/lib/build/recipe/emailpassword/recipe.d.ts b/lib/build/recipe/emailpassword/recipe.d.ts index 1592f333d..fb78464d3 100644 --- a/lib/build/recipe/emailpassword/recipe.d.ts +++ b/lib/build/recipe/emailpassword/recipe.d.ts @@ -15,14 +15,26 @@ export default class Recipe extends RecipeModule { apiImpl: APIInterface; isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput | undefined, ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput | undefined, + ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + } + ); static getInstanceOrThrowError(): Recipe; static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _path: NormalisedURLPath, _method: HTTPMethod) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + _path: NormalisedURLPath, + _method: HTTPMethod + ) => Promise; handleError: (err: STError, _request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/emailpassword/recipe.js b/lib/build/recipe/emailpassword/recipe.js index 94d756447..4fdf2a02c 100644 --- a/lib/build/recipe/emailpassword/recipe.js +++ b/lib/build/recipe/emailpassword/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const error_1 = __importDefault(require("./error")); @@ -64,7 +88,9 @@ class Recipe extends recipeModule_1.default { }, { method: "post", - pathWithoutApiBasePath: new normalisedURLPath_1.default(constants_1.GENERATE_PASSWORD_RESET_TOKEN_API), + pathWithoutApiBasePath: new normalisedURLPath_1.default( + constants_1.GENERATE_PASSWORD_RESET_TOKEN_API + ), id: constants_1.GENERATE_PASSWORD_RESET_TOKEN_API, disabled: this.apiImpl.generatePasswordResetTokenPOST === undefined, }, @@ -82,56 +108,54 @@ class Recipe extends recipeModule_1.default { }, { method: "post", - pathWithoutApiBasePath: new normalisedURLPath_1.default(constants_1.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API), + pathWithoutApiBasePath: new normalisedURLPath_1.default( + constants_1.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API + ), id: constants_1.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API, disabled: this.apiImpl.linkAccountToExistingAccountPOST === undefined, }, ]; }; - this.handleAPIRequest = (id, req, res, _path, _method) => __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - emailDelivery: this.emailDelivery, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.SIGN_UP_API) { - return yield signup_1.default(this.apiImpl, options); - } - else if (id === constants_1.SIGN_IN_API) { - return yield signin_1.default(this.apiImpl, options); - } - else if (id === constants_1.GENERATE_PASSWORD_RESET_TOKEN_API) { - return yield generatePasswordResetToken_1.default(this.apiImpl, options); - } - else if (id === constants_1.PASSWORD_RESET_API) { - return yield passwordReset_1.default(this.apiImpl, options); - } - else if (id === constants_1.SIGNUP_EMAIL_EXISTS_API) { - return yield emailExists_1.default(this.apiImpl, options); - } - return false; - }); - this.handleError = (err, _request, response) => __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - if (err.type === error_1.default.FIELD_ERROR) { - return utils_2.send200Response(response, { - status: "FIELD_ERROR", - formFields: err.payload, - }); + this.handleAPIRequest = (id, req, res, _path, _method) => + __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + emailDelivery: this.emailDelivery, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.SIGN_UP_API) { + return yield signup_1.default(this.apiImpl, options); + } else if (id === constants_1.SIGN_IN_API) { + return yield signin_1.default(this.apiImpl, options); + } else if (id === constants_1.GENERATE_PASSWORD_RESET_TOKEN_API) { + return yield generatePasswordResetToken_1.default(this.apiImpl, options); + } else if (id === constants_1.PASSWORD_RESET_API) { + return yield passwordReset_1.default(this.apiImpl, options); + } else if (id === constants_1.SIGNUP_EMAIL_EXISTS_API) { + return yield emailExists_1.default(this.apiImpl, options); } - else { + return false; + }); + this.handleError = (err, _request, response) => + __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + if (err.type === error_1.default.FIELD_ERROR) { + return utils_2.send200Response(response, { + status: "FIELD_ERROR", + formFields: err.payload, + }); + } else { + throw err; + } + } else { throw err; } - } - else { - throw err; - } - }); + }); this.getAllCORSHeaders = () => { return []; }; @@ -139,28 +163,33 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; // extra instance functions below............... - this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let user = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (user !== undefined) { - let recipeLevelUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.recipeUserId === userId); - if (recipeLevelUser !== undefined) { - if (recipeLevelUser.email === undefined) { - throw new Error("Should never come here"); + this.getEmailForUserId = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + let user = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (user !== undefined) { + let recipeLevelUser = user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (recipeLevelUser !== undefined) { + if (recipeLevelUser.email === undefined) { + throw new Error("Should never come here"); + } + return { + status: "OK", + email: recipeLevelUser.email, + }; } - return { - status: "OK", - email: recipeLevelUser.email, - }; } - } - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - }); + return { + status: "UNKNOWN_USER_ID_ERROR", + }; + }); this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -173,7 +202,9 @@ class Recipe extends recipeModule_1.default { */ this.emailDelivery = ingredients.emailDelivery === undefined - ? new emaildelivery_1.default(this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv)) + ? new emaildelivery_1.default( + this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) + ) : ingredients.emailDelivery; postSuperTokensInitCallbacks_1.PostSuperTokensInitCallbacks.addPostInitCallback(() => { const emailVerificationRecipe = recipe_1.default.getInstance(); @@ -195,8 +226,7 @@ class Recipe extends recipeModule_1.default { emailDelivery: undefined, }); return Recipe.instance; - } - else { + } else { throw new Error("Emailpassword recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/emailpassword/recipeImplementation.js b/lib/build/recipe/emailpassword/recipeImplementation.js index 672ca95b7..cf74baef7 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipe_1 = __importDefault(require("../accountlinking/recipe")); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); @@ -18,7 +42,7 @@ const __1 = require("../.."); const recipe_2 = __importDefault(require("../emailverification/recipe")); function getRecipeInterface(querier) { return { - signUp: function ({ email, password, doAccountLinking, userContext, }) { + signUp: function ({ email, password, doAccountLinking, userContext }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signup"), { email, @@ -27,30 +51,31 @@ function getRecipeInterface(querier) { if (response.status === "OK") { let createdNewUser = true; if (doAccountLinking) { - let primaryUserId = yield recipe_1.default.getInstanceOrThrowError().doPostSignUpAccountLinkingOperations({ - newUser: { - email, - recipeId: "emailpassword", - }, - newUserVerified: false, - recipeUserId: response.user.id, - userContext, - }); + let primaryUserId = yield recipe_1.default + .getInstanceOrThrowError() + .doPostSignUpAccountLinkingOperations({ + newUser: { + email, + recipeId: "emailpassword", + }, + newUserVerified: false, + recipeUserId: response.user.id, + userContext, + }); if (response.user.id !== primaryUserId) { createdNewUser = false; } response.user.id = primaryUserId; } return Object.assign(Object.assign({}, response), { createdNewUser }); - } - else { + } else { return { status: "EMAIL_ALREADY_EXISTS_ERROR", }; } }); }, - signIn: function ({ email, password, }) { + signIn: function ({ email, password }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signin"), { email, @@ -58,8 +83,7 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return response; - } - else { + } else { return { status: "WRONG_CREDENTIALS_ERROR", }; @@ -73,8 +97,7 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } - else { + } else { return undefined; } }); @@ -86,38 +109,42 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } - else { + } else { return undefined; } }); }, - createResetPasswordToken: function ({ userId, email, }) { + createResetPasswordToken: function ({ userId, email }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/password/reset/token"), { - userId, - email, - }); + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/user/password/reset/token"), + { + userId, + email, + } + ); if (response.status === "OK") { return { status: "OK", token: response.token, }; - } - else { + } else { return { status: "UNKNOWN_USER_ID_ERROR", }; } }); }, - resetPasswordUsingToken: function ({ token, newPassword, }) { + resetPasswordUsingToken: function ({ token, newPassword }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/password/reset"), { - method: "token", - token, - newPassword, - }); + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/user/password/reset"), + { + method: "token", + token, + newPassword, + } + ); return response; }); }, @@ -152,11 +179,13 @@ function getRecipeInterface(querier) { if (markEmailAsVerified && input.email !== undefined) { const emailVerificationInstance = recipe_2.default.getInstance(); if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ - userId: input.userId, - email: input.email, - userContext: undefined, - }); + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: input.userId, + email: input.email, + userContext: undefined, + } + ); if (tokenResponse.status === "OK") { yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ token: tokenResponse.token, @@ -168,13 +197,11 @@ function getRecipeInterface(querier) { return { status: "OK", }; - } - else if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { + } else if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return { status: "EMAIL_ALREADY_EXISTS_ERROR", }; - } - else { + } else { return { status: "UNKNOWN_USER_ID_ERROR", }; diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index ff1ad42f5..a5080bbbc 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -1,16 +1,25 @@ import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; +import { + TypeInput as EmailDeliveryTypeInput, + TypeInputWithService as EmailDeliveryTypeInputWithService, +} from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; import { GeneralErrorResponse, NormalisedAppinfo, User } from "../../types"; export declare type TypeNormalisedInput = { signUpFeature: TypeNormalisedInputSignUp; signInFeature: TypeNormalisedInputSignIn; - getEmailDeliveryConfig: (recipeImpl: RecipeInterface, isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; + getEmailDeliveryConfig: ( + recipeImpl: RecipeInterface, + isInServerlessEnv: boolean + ) => EmailDeliveryTypeInputWithService; resetPasswordUsingTokenFeature: TypeNormalisedInputResetPasswordUsingTokenFeature; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -45,7 +54,10 @@ export declare type TypeInput = { signUpFeature?: TypeInputSignUp; emailDelivery?: EmailDeliveryTypeInput; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -66,31 +78,31 @@ export declare type RecipeInterface = { */ doAccountLinking: boolean; userContext: any; - }): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >; signIn(input: { email: string; password: string; userContext: any; - }): Promise<{ - status: "OK"; - user: User; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - }>; - getUserById(input: { - userId: string; - userContext: any; - }): Promise; - getUserByEmail(input: { - email: string; - userContext: any; - }): Promise; + }): Promise< + | { + status: "OK"; + user: User; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + >; + getUserById(input: { userId: string; userContext: any }): Promise; + getUserByEmail(input: { email: string; userContext: any }): Promise; /** * We do not make email optional here cause we want to * allow passing in primaryUserId. If we make email optional, @@ -106,30 +118,40 @@ export declare type RecipeInterface = { userId: string; email: string; userContext: any; - }): Promise<{ - status: "OK"; - token: string; - } | { - status: "UNKNOWN_USER_ID_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "UNKNOWN_USER_ID_ERROR"; + } + >; resetPasswordUsingToken(input: { token: string; newPassword: string; userContext: any; - }): Promise<{ - status: "OK"; - email: string; - userId: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; updateEmailOrPassword(input: { userId: string; email?: string; password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; }; export declare type APIOptions = { @@ -143,104 +165,143 @@ export declare type APIOptions = { emailDelivery: EmailDeliveryIngredient; }; export declare type APIInterface = { - emailExistsGET: undefined | ((input: { - email: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - } | GeneralErrorResponse>); - generatePasswordResetTokenPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - } | { - status: "PASSWORD_RESET_NOT_ALLOWED"; - reason: string; - } | GeneralErrorResponse>); - passwordResetPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - email: string; - userId: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } | GeneralErrorResponse>); - signInPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - session: SessionContainerInterface; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - } | GeneralErrorResponse>); - signUpPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - createdNewUser: boolean; - session: SessionContainerInterface; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } | GeneralErrorResponse>); - linkAccountToExistingAccountPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } | GeneralErrorResponse>); + emailExistsGET: + | undefined + | ((input: { + email: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >); + generatePasswordResetTokenPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + } + | { + status: "PASSWORD_RESET_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); + passwordResetPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + | GeneralErrorResponse + >); + signInPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + | GeneralErrorResponse + >); + signUpPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + createdNewUser: boolean; + session: SessionContainerInterface; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); + linkAccountToExistingAccountPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } + | GeneralErrorResponse + >); }; export declare type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; diff --git a/lib/build/recipe/emailpassword/utils.d.ts b/lib/build/recipe/emailpassword/utils.d.ts index 21051df4b..3440d4251 100644 --- a/lib/build/recipe/emailpassword/utils.d.ts +++ b/lib/build/recipe/emailpassword/utils.d.ts @@ -1,7 +1,22 @@ import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput, NormalisedFormField, TypeInputFormField } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + recipeInstance: Recipe, + appInfo: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; export declare function normaliseSignUpFormFields(formFields?: TypeInputFormField[]): NormalisedFormField[]; -export declare function defaultPasswordValidator(value: any): Promise<"Development bug: Please make sure the password field yields a string" | "Password must contain at least 8 characters, including a number" | "Password's length must be lesser than 100 characters" | "Password must contain at least one alphabet" | "Password must contain at least one number" | undefined>; -export declare function defaultEmailValidator(value: any): Promise<"Development bug: Please make sure the email field yields a string" | "Email is invalid" | undefined>; +export declare function defaultPasswordValidator( + value: any +): Promise< + | "Development bug: Please make sure the password field yields a string" + | "Password must contain at least 8 characters, including a number" + | "Password's length must be lesser than 100 characters" + | "Password must contain at least one alphabet" + | "Password must contain at least one number" + | undefined +>; +export declare function defaultEmailValidator( + value: any +): Promise<"Development bug: Please make sure the email field yields a string" | "Email is invalid" | undefined>; diff --git a/lib/build/recipe/emailpassword/utils.js b/lib/build/recipe/emailpassword/utils.js index a0c201629..374770e87 100644 --- a/lib/build/recipe/emailpassword/utils.js +++ b/lib/build/recipe/emailpassword/utils.js @@ -13,30 +13,67 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultEmailValidator = exports.defaultPasswordValidator = exports.normaliseSignUpFormFields = exports.validateAndNormaliseUserInput = void 0; const constants_1 = require("./constants"); const backwardCompatibility_1 = __importDefault(require("./emaildelivery/services/backwardCompatibility")); function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { - let signUpFeature = validateAndNormaliseSignupConfig(recipeInstance, appInfo, config === undefined ? undefined : config.signUpFeature); + let signUpFeature = validateAndNormaliseSignupConfig( + recipeInstance, + appInfo, + config === undefined ? undefined : config.signUpFeature + ); let signInFeature = validateAndNormaliseSignInConfig(recipeInstance, appInfo, signUpFeature); let resetPasswordUsingTokenFeature = validateAndNormaliseResetPasswordUsingTokenConfig(signUpFeature); - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); function getEmailDeliveryConfig(recipeImpl, isInServerlessEnv) { var _a; - let emailService = (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; + let emailService = + (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 + ? void 0 + : _a.service; /** * If the user has not passed even that config, we use the default * createAndSendCustomEmail implementation which calls our supertokens API @@ -44,7 +81,7 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { if (emailService === undefined) { emailService = new backwardCompatibility_1.default(recipeImpl, appInfo, isInServerlessEnv); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -56,7 +93,8 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService }); + service: emailService, + }); } return { signUpFeature, @@ -71,21 +109,21 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(signUpConfig) { let formFieldsForPasswordResetForm = signUpConfig.formFields .filter((filter) => filter.id === constants_1.FORM_FIELD_PASSWORD_ID) .map((field) => { - return { - id: field.id, - validate: field.validate, - optional: false, - }; - }); + return { + id: field.id, + validate: field.validate, + optional: false, + }; + }); let formFieldsForGenerateTokenForm = signUpConfig.formFields .filter((filter) => filter.id === constants_1.FORM_FIELD_EMAIL_ID) .map((field) => { - return { - id: field.id, - validate: field.validate, - optional: false, - }; - }); + return { + id: field.id, + validate: field.validate, + optional: false, + }; + }); return { formFieldsForPasswordResetForm, formFieldsForGenerateTokenForm, @@ -93,15 +131,18 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(signUpConfig) { } function normaliseSignInFormFields(formFields) { return formFields - .filter((filter) => filter.id === constants_1.FORM_FIELD_EMAIL_ID || filter.id === constants_1.FORM_FIELD_PASSWORD_ID) + .filter( + (filter) => + filter.id === constants_1.FORM_FIELD_EMAIL_ID || filter.id === constants_1.FORM_FIELD_PASSWORD_ID + ) .map((field) => { - return { - id: field.id, - // see issue: https://github.com/supertokens/supertokens-node/issues/36 - validate: field.id === constants_1.FORM_FIELD_EMAIL_ID ? field.validate : defaultValidator, - optional: false, - }; - }); + return { + id: field.id, + // see issue: https://github.com/supertokens/supertokens-node/issues/36 + validate: field.id === constants_1.FORM_FIELD_EMAIL_ID ? field.validate : defaultValidator, + optional: false, + }; + }); } function validateAndNormaliseSignInConfig(_, __, signUpConfig) { let formFields = normaliseSignInFormFields(signUpConfig.formFields); @@ -119,15 +160,13 @@ function normaliseSignUpFormFields(formFields) { validate: field.validate === undefined ? defaultPasswordValidator : field.validate, optional: false, }); - } - else if (field.id === constants_1.FORM_FIELD_EMAIL_ID) { + } else if (field.id === constants_1.FORM_FIELD_EMAIL_ID) { normalisedFormFields.push({ id: field.id, validate: field.validate === undefined ? defaultEmailValidator : field.validate, optional: false, }); - } - else { + } else { normalisedFormFields.push({ id: field.id, validate: field.validate === undefined ? defaultValidator : field.validate, @@ -198,7 +237,11 @@ function defaultEmailValidator(value) { if (typeof value !== "string") { return "Development bug: Please make sure the email field yields a string"; } - if (value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/) === null) { + if ( + value.match( + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ + ) === null + ) { return "Email is invalid"; } return undefined; diff --git a/lib/build/recipe/emailverification/api/emailVerify.js b/lib/build/recipe/emailverification/api/emailVerify.js index d140ac9bc..ef258de97 100644 --- a/lib/build/recipe/emailverification/api/emailVerify.js +++ b/lib/build/recipe/emailverification/api/emailVerify.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); @@ -52,7 +76,12 @@ function emailVerify(apiImplementation, options) { message: "The email verification token must be a string", }); } - const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [], sessionRequired: false }, userContext); + const session = yield session_1.default.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [], sessionRequired: false }, + userContext + ); let response = yield apiImplementation.verifyEmailPOST({ token, options, @@ -61,16 +90,19 @@ function emailVerify(apiImplementation, options) { }); if (response.status === "OK") { result = { status: "OK" }; - } - else { + } else { result = response; } - } - else { + } else { if (apiImplementation.isEmailVerifiedGET === undefined) { return false; } - const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [] }, userContext); + const session = yield session_1.default.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [] }, + userContext + ); result = yield apiImplementation.isEmailVerifiedGET({ options, session: session, diff --git a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts index d321fa1a9..fb90e6d31 100644 --- a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts +++ b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts @@ -1,2 +1,5 @@ import { APIInterface, APIOptions } from "../"; -export default function generateEmailVerifyToken(apiImplementation: APIInterface, options: APIOptions): Promise; +export default function generateEmailVerifyToken( + apiImplementation: APIInterface, + options: APIOptions +): Promise; diff --git a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js index 43b7ef528..a1c6f3784 100644 --- a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js +++ b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); @@ -36,7 +60,12 @@ function generateEmailVerifyToken(apiImplementation, options) { return false; } const userContext = utils_2.makeDefaultUserContextFromAPI(options.req); - const session = yield session_1.default.getSession(options.req, options.res, { overrideGlobalClaimValidators: () => [] }, userContext); + const session = yield session_1.default.getSession( + options.req, + options.res, + { overrideGlobalClaimValidators: () => [] }, + userContext + ); const result = yield apiImplementation.generateEmailVerifyTokenPOST({ options, session: session, diff --git a/lib/build/recipe/emailverification/api/implementation.js b/lib/build/recipe/emailverification/api/implementation.js index b4fd8b6ee..0c0e84cf7 100644 --- a/lib/build/recipe/emailverification/api/implementation.js +++ b/lib/build/recipe/emailverification/api/implementation.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const recipe_1 = __importDefault(require("../recipe")); @@ -19,14 +43,13 @@ const error_1 = __importDefault(require("../../session/error")); const utils_1 = require("../utils"); function getAPIInterface() { return { - verifyEmailPOST: function ({ token, options, session, userContext, }) { + verifyEmailPOST: function ({ token, options, session, userContext }) { return __awaiter(this, void 0, void 0, function* () { const res = yield options.recipeImplementation.verifyEmailUsingToken({ token, userContext }); if (res.status === "OK" && session !== undefined) { try { yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); - } - catch (err) { + } catch (err) { // This should never happen, since we've just set the status above. if (err.message === "UNKNOWN_USER_ID") { throw new error_1.default({ @@ -40,15 +63,14 @@ function getAPIInterface() { return res; }); }, - isEmailVerifiedGET: function ({ userContext, session, }) { + isEmailVerifiedGET: function ({ userContext, session }) { return __awaiter(this, void 0, void 0, function* () { if (session === undefined) { throw new Error("Session is undefined. Should not come here."); } try { yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); - } - catch (err) { + } catch (err) { if (err.message === "UNKNOWN_USER_ID") { throw new error_1.default({ type: error_1.default.UNAUTHORISED, @@ -57,7 +79,10 @@ function getAPIInterface() { } throw err; } - const isVerified = yield session.getClaimValue(emailVerificationClaim_1.EmailVerificationClaim, userContext); + const isVerified = yield session.getClaimValue( + emailVerificationClaim_1.EmailVerificationClaim, + userContext + ); if (isVerified === undefined) { throw new Error("Should never come here: EmailVerificationClaim failed to set value"); } @@ -67,20 +92,23 @@ function getAPIInterface() { }; }); }, - generateEmailVerifyTokenPOST: function ({ options, userContext, session, }) { + generateEmailVerifyTokenPOST: function ({ options, userContext, session }) { return __awaiter(this, void 0, void 0, function* () { if (session === undefined) { throw new Error("Session is undefined. Should not come here."); } const userId = session.getUserId(); - const emailInfo = yield recipe_1.default.getInstanceOrThrowError().getEmailForUserId(userId, userContext); + const emailInfo = yield recipe_1.default + .getInstanceOrThrowError() + .getEmailForUserId(userId, userContext); if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { - logger_1.logDebugMessage(`Email verification email not sent to user ${userId} because it doesn't have an email address.`); + logger_1.logDebugMessage( + `Email verification email not sent to user ${userId} because it doesn't have an email address.` + ); return { status: "EMAIL_ALREADY_VERIFIED_ERROR", }; - } - else if (emailInfo.status === "OK") { + } else if (emailInfo.status === "OK") { let response = yield options.recipeImplementation.createEmailVerificationToken({ userId, email: emailInfo.email, @@ -91,9 +119,14 @@ function getAPIInterface() { // this can happen if the email was verified in another browser // and this session is still outdated - and the user has not // called the get email verification API yet. - yield session.fetchAndSetClaim(emailVerificationClaim_1.EmailVerificationClaim, userContext); + yield session.fetchAndSetClaim( + emailVerificationClaim_1.EmailVerificationClaim, + userContext + ); } - logger_1.logDebugMessage(`Email verification email not sent to ${emailInfo.email} because it is already verified.`); + logger_1.logDebugMessage( + `Email verification email not sent to ${emailInfo.email} because it is already verified.` + ); return response; } if ((yield session.getClaimValue(emailVerificationClaim_1.EmailVerificationClaim)) !== false) { @@ -120,9 +153,11 @@ function getAPIInterface() { return { status: "OK", }; - } - else { - throw new error_1.default({ type: error_1.default.UNAUTHORISED, message: "Unknown User ID provided" }); + } else { + throw new error_1.default({ + type: error_1.default.UNAUTHORISED, + message: "Unknown User ID provided", + }); } }); }, diff --git a/lib/build/recipe/emailverification/emailVerificationClaim.js b/lib/build/recipe/emailverification/emailVerificationClaim.js index a4eb17ecc..b7375ac7a 100644 --- a/lib/build/recipe/emailverification/emailVerificationClaim.js +++ b/lib/build/recipe/emailverification/emailVerificationClaim.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.EmailVerificationClaim = exports.EmailVerificationClaimClass = void 0; const recipe_1 = __importDefault(require("./recipe")); @@ -27,27 +51,36 @@ class EmailVerificationClaimClass extends claims_1.BooleanClaim { const recipe = recipe_1.default.getInstanceOrThrowError(); let emailInfo = yield recipe.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { - return recipe.recipeInterfaceImpl.isEmailVerified({ userId, email: emailInfo.email, userContext }); - } - else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + return recipe.recipeInterfaceImpl.isEmailVerified({ + userId, + email: emailInfo.email, + userContext, + }); + } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { // We consider people without email addresses as validated return true; - } - else { + } else { throw new Error("UNKNOWN_USER_ID"); } }); }, defaultMaxAgeInSeconds: 300, }); - this.validators = Object.assign(Object.assign({}, this.validators), { isVerified: (refetchTimeOnFalseInSeconds = 10, maxAgeInSeconds = 300) => (Object.assign(Object.assign({}, this.validators.hasValue(true, maxAgeInSeconds)), { shouldRefetch: (payload, userContext) => { - const value = this.getValueFromPayload(payload, userContext); - return (value === undefined || - this.getLastRefetchTime(payload, userContext) < Date.now() - maxAgeInSeconds * 1000 || - (value === false && - this.getLastRefetchTime(payload, userContext) < - Date.now() - refetchTimeOnFalseInSeconds * 1000)); - } })) }); + this.validators = Object.assign(Object.assign({}, this.validators), { + isVerified: (refetchTimeOnFalseInSeconds = 10, maxAgeInSeconds = 300) => + Object.assign(Object.assign({}, this.validators.hasValue(true, maxAgeInSeconds)), { + shouldRefetch: (payload, userContext) => { + const value = this.getValueFromPayload(payload, userContext); + return ( + value === undefined || + this.getLastRefetchTime(payload, userContext) < Date.now() - maxAgeInSeconds * 1000 || + (value === false && + this.getLastRefetchTime(payload, userContext) < + Date.now() - refetchTimeOnFalseInSeconds * 1000) + ); + }, + }), + }); } } exports.EmailVerificationClaimClass = EmailVerificationClaimClass; diff --git a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts index e13e29369..8f13c4e0a 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts @@ -1,3 +1,5 @@ import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function createAndSendCustomEmail(appInfo: NormalisedAppinfo): (user: User, emailVerifyURLWithToken: string) => Promise; +export declare function createAndSendCustomEmail( + appInfo: NormalisedAppinfo +): (user: User, emailVerifyURLWithToken: string) => Promise; diff --git a/lib/build/recipe/emailverification/emailVerificationFunctions.js b/lib/build/recipe/emailverification/emailVerificationFunctions.js index 4d7c8deff..29b7b92a2 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.js +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.js @@ -13,64 +13,92 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createAndSendCustomEmail = void 0; const axios_1 = __importDefault(require("axios")); const logger_1 = require("../../logger"); function createAndSendCustomEmail(appInfo) { - return (user, emailVerifyURLWithToken) => __awaiter(this, void 0, void 0, function* () { - if (process.env.TEST_MODE === "testing") { - return; - } - try { - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.io/0/st/auth/email/verify", - data: { - email: user.email, - appName: appInfo.appName, - emailVerifyURL: emailVerifyURLWithToken, - }, - headers: { - "api-version": 0, - }, - }); - logger_1.logDebugMessage(`Email sent to ${user.email}`); - } - catch (error) { - logger_1.logDebugMessage("Error sending verification email"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } - else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } + return (user, emailVerifyURLWithToken) => + __awaiter(this, void 0, void 0, function* () { + if (process.env.TEST_MODE === "testing") { + return; } - else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + try { + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.io/0/st/auth/email/verify", + data: { + email: user.email, + appName: appInfo.appName, + emailVerifyURL: emailVerifyURLWithToken, + }, + headers: { + "api-version": 0, + }, + }); + logger_1.logDebugMessage(`Email sent to ${user.email}`); + } catch (error) { + logger_1.logDebugMessage("Error sending verification email"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + } else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + } else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + } + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage( + JSON.stringify( + { + email: user.email, + appName: appInfo.appName, + emailVerifyURL: emailVerifyURLWithToken, + }, + null, + 2 + ) + ); } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage(JSON.stringify({ - email: user.email, - appName: appInfo.appName, - emailVerifyURL: emailVerifyURLWithToken, - }, null, 2)); - } - }); + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts index 1ab8e9294..6a608cfe0 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,12 +1,23 @@ import { TypeEmailVerificationEmailDeliveryInput, User } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService implements EmailDeliveryInterface { +export default class BackwardCompatibilityService + implements EmailDeliveryInterface { private appInfo; private isInServerlessEnv; private createAndSendCustomEmail; - constructor(appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, createAndSendCustomEmail?: (user: User, emailVerificationURLWithToken: string, userContext: any) => Promise); - sendEmail: (input: TypeEmailVerificationEmailDeliveryInput & { - userContext: any; - }) => Promise; + constructor( + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + createAndSendCustomEmail?: ( + user: User, + emailVerificationURLWithToken: string, + userContext: any + ) => Promise + ); + sendEmail: ( + input: TypeEmailVerificationEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js index dd2ba732b..67e5311b1 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.js @@ -1,29 +1,54 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const emailVerificationFunctions_1 = require("../../../emailVerificationFunctions"); -class BackwardCompatibilityService { - constructor(appInfo, isInServerlessEnv, createAndSendCustomEmail) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - try { - if (!this.isInServerlessEnv) { - this.createAndSendCustomEmail(input.user, input.emailVerifyLink, input.userContext).catch((_) => { }); +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - else { - // see https://github.com/supertokens/supertokens-node/pull/135 - yield this.createAndSendCustomEmail(input.user, input.emailVerifyLink, input.userContext); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - catch (_) { } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); + }; +Object.defineProperty(exports, "__esModule", { value: true }); +const emailVerificationFunctions_1 = require("../../../emailVerificationFunctions"); +class BackwardCompatibilityService { + constructor(appInfo, isInServerlessEnv, createAndSendCustomEmail) { + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + try { + if (!this.isInServerlessEnv) { + this.createAndSendCustomEmail( + input.user, + input.emailVerifyLink, + input.userContext + ).catch((_) => {}); + } else { + // see https://github.com/supertokens/supertokens-node/pull/135 + yield this.createAndSendCustomEmail(input.user, input.emailVerifyLink, input.userContext); + } + } catch (_) {} + }); this.appInfo = appInfo; this.isInServerlessEnv = isInServerlessEnv; this.createAndSendCustomEmail = diff --git a/lib/build/recipe/emailverification/emaildelivery/services/index.js b/lib/build/recipe/emailverification/emaildelivery/services/index.js index d648973c6..91700aeaf 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/index.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/index.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SMTPService = void 0; const smtp_1 = __importDefault(require("./smtp")); diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js index 44c092a9b..7523109e9 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getEmailVerifyEmailHTML = void 0; const supertokens_1 = __importDefault(require("../../../../../supertokens")); diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts index 28d36d828..cffcbda91 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts @@ -4,7 +4,9 @@ import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; export default class SMTPService implements EmailDeliveryInterface { serviceImpl: ServiceInterface; constructor(config: TypeInput); - sendEmail: (input: TypeEmailVerificationEmailDeliveryInput & { - userContext: any; - }) => Promise; + sendEmail: ( + input: TypeEmailVerificationEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js index b96042bcd..e917fb0fe 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.js @@ -1,26 +1,53 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const serviceImplementation_1 = require("./serviceImplementation"); class SMTPService { constructor(config) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - yield this.serviceImpl.sendRawEmail(Object.assign(Object.assign({}, content), { userContext: input.userContext })); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + yield this.serviceImpl.sendRawEmail( + Object.assign(Object.assign({}, content), { userContext: input.userContext }) + ); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -30,7 +57,9 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); + let builder = new supertokens_js_override_1.default( + serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) + ); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts index 01ad49a79..162505801 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts @@ -1,7 +1,10 @@ import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation(transporter: Transporter, from: { - name: string; - email: string; -}): ServiceInterface; +export declare function getServiceImplementation( + transporter: Transporter, + from: { + name: string; + email: string; + } +): ServiceInterface; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js index 3faf65387..8efb6167a 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getServiceImplementation = void 0; const emailVerify_1 = __importDefault(require("./emailVerify")); @@ -39,8 +63,7 @@ function getServiceImplementation(transporter, from) { subject: input.subject, html: input.body, }); - } - else { + } else { yield transporter.sendMail({ from: `${from.name} <${from.email}>`, to: input.toEmail, diff --git a/lib/build/recipe/emailverification/error.d.ts b/lib/build/recipe/emailverification/error.d.ts index 71d57623f..2eab0a85f 100644 --- a/lib/build/recipe/emailverification/error.d.ts +++ b/lib/build/recipe/emailverification/error.d.ts @@ -1,7 +1,4 @@ import STError from "../../error"; export default class SessionError extends STError { - constructor(options: { - type: "BAD_INPUT_ERROR"; - message: string; - }); + constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); } diff --git a/lib/build/recipe/emailverification/error.js b/lib/build/recipe/emailverification/error.js index 4f3bedcb7..b0baf2c94 100644 --- a/lib/build/recipe/emailverification/error.js +++ b/lib/build/recipe/emailverification/error.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); class SessionError extends error_1.default { diff --git a/lib/build/recipe/emailverification/index.d.ts b/lib/build/recipe/emailverification/index.d.ts index dc3e5bdb8..a29e6affb 100644 --- a/lib/build/recipe/emailverification/index.d.ts +++ b/lib/build/recipe/emailverification/index.d.ts @@ -5,28 +5,51 @@ export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; static EmailVerificationClaim: import("./emailVerificationClaim").EmailVerificationClaimClass; - static createEmailVerificationToken(userId: string, email?: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - }>; - static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ - status: "OK"; - user: User; - } | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - }>; + static createEmailVerificationToken( + userId: string, + email?: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + } + >; + static verifyEmailUsingToken( + token: string, + userContext?: any + ): Promise< + | { + status: "OK"; + user: User; + } + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + >; static isEmailVerified(userId: string, email?: string, userContext?: any): Promise; - static revokeEmailVerificationTokens(userId: string, email?: string, userContext?: any): Promise<{ + static revokeEmailVerificationTokens( + userId: string, + email?: string, + userContext?: any + ): Promise<{ status: string; }>; - static unverifyEmail(userId: string, email?: string, userContext?: any): Promise<{ + static unverifyEmail( + userId: string, + email?: string, + userContext?: any + ): Promise<{ status: string; }>; - static sendEmail(input: TypeEmailVerificationEmailDeliveryInput & { - userContext?: any; - }): Promise; + static sendEmail( + input: TypeEmailVerificationEmailDeliveryInput & { + userContext?: any; + } + ): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/emailverification/index.js b/lib/build/recipe/emailverification/index.js index 39c330abb..162e73e33 100644 --- a/lib/build/recipe/emailverification/index.js +++ b/lib/build/recipe/emailverification/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.EmailVerificationClaim = exports.sendEmail = exports.unverifyEmail = exports.revokeEmailVerificationTokens = exports.isEmailVerified = exports.verifyEmailUsingToken = exports.createEmailVerificationToken = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); @@ -38,13 +62,11 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } - else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { return { status: "EMAIL_ALREADY_VERIFIED_ERROR", }; - } - else { + } else { throw new global.Error("Unknown User ID provided without email"); } } @@ -70,11 +92,9 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } - else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { return true; - } - else { + } else { throw new global.Error("Unknown User ID provided without email"); } } @@ -95,16 +115,14 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } - else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { // This only happens for phone based passwordless users (or if the user added a custom getEmailForUserId) // We can return OK here, since there is no way to create an email verification token // if getEmailForUserId returns EMAIL_DOES_NOT_EXIST_ERROR. return { status: "OK", }; - } - else { + } else { throw new global.Error("Unknown User ID provided without email"); } } @@ -122,14 +140,12 @@ class Wrapper { const emailInfo = yield recipeInstance.getEmailForUserId(userId, userContext); if (emailInfo.status === "OK") { email = emailInfo.email; - } - else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { + } else if (emailInfo.status === "EMAIL_DOES_NOT_EXIST_ERROR") { // Here we are returning OK since that's how it used to work, but a later call to isVerified will still return true return { status: "OK", }; - } - else { + } else { throw new global.Error("Unknown User ID provided without email"); } } @@ -143,7 +159,9 @@ class Wrapper { static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { let recipeInstance = recipe_1.default.getInstanceOrThrowError(); - return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipeInstance.emailDelivery.ingredientInterfaceImpl.sendEmail( + Object.assign({ userContext: {} }, input) + ); }); } } @@ -160,4 +178,9 @@ exports.revokeEmailVerificationTokens = Wrapper.revokeEmailVerificationTokens; exports.unverifyEmail = Wrapper.unverifyEmail; exports.sendEmail = Wrapper.sendEmail; var emailVerificationClaim_2 = require("./emailVerificationClaim"); -Object.defineProperty(exports, "EmailVerificationClaim", { enumerable: true, get: function () { return emailVerificationClaim_2.EmailVerificationClaim; } }); +Object.defineProperty(exports, "EmailVerificationClaim", { + enumerable: true, + get: function () { + return emailVerificationClaim_2.EmailVerificationClaim; + }, +}); diff --git a/lib/build/recipe/emailverification/recipe.d.ts b/lib/build/recipe/emailverification/recipe.d.ts index e5db23be4..e8eb36583 100644 --- a/lib/build/recipe/emailverification/recipe.d.ts +++ b/lib/build/recipe/emailverification/recipe.d.ts @@ -15,15 +15,27 @@ export default class Recipe extends RecipeModule { isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; getEmailForUserIdFuncsFromOtherRecipes: GetEmailForUserIdFunc[]; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + } + ); static getInstanceOrThrowError(): Recipe; static getInstance(): Recipe | undefined; static init(config: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _: NormalisedURLPath, __: HTTPMethod) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + _: NormalisedURLPath, + __: HTTPMethod + ) => Promise; handleError: (err: STError, _: BaseRequest, __: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/emailverification/recipe.js b/lib/build/recipe/emailverification/recipe.js index d6109dadf..398fef214 100644 --- a/lib/build/recipe/emailverification/recipe.js +++ b/lib/build/recipe/emailverification/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const error_1 = __importDefault(require("./error")); @@ -50,7 +74,9 @@ class Recipe extends recipeModule_1.default { return [ { method: "post", - pathWithoutApiBasePath: new normalisedURLPath_1.default(constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API), + pathWithoutApiBasePath: new normalisedURLPath_1.default( + constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API + ), id: constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API, disabled: this.apiImpl.generateEmailVerifyTokenPOST === undefined, }, @@ -68,57 +94,61 @@ class Recipe extends recipeModule_1.default { }, ]; }; - this.handleAPIRequest = (id, req, res, _, __) => __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - emailDelivery: this.emailDelivery, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API) { - return yield generateEmailVerifyToken_1.default(this.apiImpl, options); - } - else { - return yield emailVerify_1.default(this.apiImpl, options); - } - }); - this.handleError = (err, _, __) => __awaiter(this, void 0, void 0, function* () { - throw err; - }); + this.handleAPIRequest = (id, req, res, _, __) => + __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + emailDelivery: this.emailDelivery, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.GENERATE_EMAIL_VERIFY_TOKEN_API) { + return yield generateEmailVerifyToken_1.default(this.apiImpl, options); + } else { + return yield emailVerify_1.default(this.apiImpl, options); + } + }); + this.handleError = (err, _, __) => + __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; this.isErrorFromThisRecipe = (err) => { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; - this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - if (this.config.getEmailForUserId !== undefined) { - const userRes = yield this.config.getEmailForUserId(userId, userContext); - if (userRes.status !== "UNKNOWN_USER_ID_ERROR") { - return userRes; + this.getEmailForUserId = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + if (this.config.getEmailForUserId !== undefined) { + const userRes = yield this.config.getEmailForUserId(userId, userContext); + if (userRes.status !== "UNKNOWN_USER_ID_ERROR") { + return userRes; + } } - } - for (const getEmailForUserId of this.getEmailForUserIdFuncsFromOtherRecipes) { - const res = yield getEmailForUserId(userId, userContext); - if (res.status !== "UNKNOWN_USER_ID_ERROR") { - return res; + for (const getEmailForUserId of this.getEmailForUserIdFuncsFromOtherRecipes) { + const res = yield getEmailForUserId(userId, userContext); + if (res.status !== "UNKNOWN_USER_ID_ERROR") { + return res; + } } - } - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - }); + return { + status: "UNKNOWN_USER_ID_ERROR", + }; + }); this.addGetEmailForUserIdFunc = (func) => { this.getEmailForUserIdFuncsFromOtherRecipes.push(func); }; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -150,15 +180,22 @@ class Recipe extends recipeModule_1.default { emailDelivery: undefined, }); postSuperTokensInitCallbacks_1.PostSuperTokensInitCallbacks.addPostInitCallback(() => { - recipe_1.default.getInstanceOrThrowError().addClaimFromOtherRecipe(emailVerificationClaim_1.EmailVerificationClaim); + recipe_1.default + .getInstanceOrThrowError() + .addClaimFromOtherRecipe(emailVerificationClaim_1.EmailVerificationClaim); if (config.mode === "REQUIRED") { - recipe_1.default.getInstanceOrThrowError().addClaimValidatorFromOtherRecipe(emailVerificationClaim_1.EmailVerificationClaim.validators.isVerified()); + recipe_1.default + .getInstanceOrThrowError() + .addClaimValidatorFromOtherRecipe( + emailVerificationClaim_1.EmailVerificationClaim.validators.isVerified() + ); } }); return Recipe.instance; - } - else { - throw new Error("Emailverification recipe has already been initialised. Please check your code for bugs."); + } else { + throw new Error( + "Emailverification recipe has already been initialised. Please check your code for bugs." + ); } }; } diff --git a/lib/build/recipe/emailverification/recipeImplementation.js b/lib/build/recipe/emailverification/recipeImplementation.js index c4a91e4f3..99489ca51 100644 --- a/lib/build/recipe/emailverification/recipeImplementation.js +++ b/lib/build/recipe/emailverification/recipeImplementation.js @@ -1,45 +1,74 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); function getRecipeInterface(querier) { return { - createEmailVerificationToken: function ({ userId, email, }) { + createEmailVerificationToken: function ({ userId, email }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/email/verify/token"), { - userId, - email, - }); + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/user/email/verify/token"), + { + userId, + email, + } + ); if (response.status === "OK") { return { status: "OK", token: response.token, }; - } - else { + } else { return { status: "EMAIL_ALREADY_VERIFIED_ERROR", }; } }); }, - verifyEmailUsingToken: function ({ token, }) { + verifyEmailUsingToken: function ({ token }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/email/verify"), { - method: "token", - token, - }); + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/user/email/verify"), + { + method: "token", + token, + } + ); if (response.status === "OK") { return { status: "OK", @@ -48,8 +77,7 @@ function getRecipeInterface(querier) { email: response.email, }, }; - } - else { + } else { return { status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR", }; @@ -58,19 +86,25 @@ function getRecipeInterface(querier) { }, isEmailVerified: function ({ userId, email }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user/email/verify"), { - userId, - email, - }); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/user/email/verify"), + { + userId, + email, + } + ); return response.isVerified; }); }, revokeEmailVerificationTokens: function (input) { return __awaiter(this, void 0, void 0, function* () { - yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/email/verify/token/remove"), { - userId: input.userId, - email: input.email, - }); + yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/user/email/verify/token/remove"), + { + userId: input.userId, + email: input.email, + } + ); return { status: "OK" }; }); }, diff --git a/lib/build/recipe/emailverification/types.d.ts b/lib/build/recipe/emailverification/types.d.ts index 48b6d100f..afcefff4e 100644 --- a/lib/build/recipe/emailverification/types.d.ts +++ b/lib/build/recipe/emailverification/types.d.ts @@ -1,38 +1,61 @@ import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; -import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; +import { + TypeInput as EmailDeliveryTypeInput, + TypeInputWithService as EmailDeliveryTypeInputWithService, +} from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; import { GeneralErrorResponse, NormalisedAppinfo } from "../../types"; import { SessionContainerInterface } from "../session/types"; export declare type TypeInput = { mode: "REQUIRED" | "OPTIONAL"; emailDelivery?: EmailDeliveryTypeInput; - getEmailForUserId?: (userId: string, userContext: any) => Promise<{ - status: "OK"; - email: string; - } | { - status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; - }>; + getEmailForUserId?: ( + userId: string, + userContext: any + ) => Promise< + | { + status: "OK"; + email: string; + } + | { + status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; + } + >; /** * @deprecated Please use emailDelivery config instead */ createAndSendCustomEmail?: (user: User, emailVerificationURLWithToken: string, userContext: any) => Promise; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { mode: "REQUIRED" | "OPTIONAL"; - getEmailDeliveryConfig: (isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; - getEmailForUserId?: (userId: string, userContext: any) => Promise<{ - status: "OK"; - email: string; - } | { - status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; - }>; + getEmailDeliveryConfig: ( + isInServerlessEnv: boolean + ) => EmailDeliveryTypeInputWithService; + getEmailForUserId?: ( + userId: string, + userContext: any + ) => Promise< + | { + status: "OK"; + email: string; + } + | { + status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; + } + >; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -45,26 +68,28 @@ export declare type RecipeInterface = { userId: string; email: string; userContext: any; - }): Promise<{ - status: "OK"; - token: string; - } | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + } + >; verifyEmailUsingToken(input: { token: string; userContext: any; - }): Promise<{ - status: "OK"; - user: User; - } | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - }>; - isEmailVerified(input: { - userId: string; - email: string; - userContext: any; - }): Promise; + }): Promise< + | { + status: "OK"; + user: User; + } + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + >; + isEmailVerified(input: { userId: string; email: string; userContext: any }): Promise; revokeEmailVerificationTokens(input: { userId: string; email: string; @@ -91,32 +116,48 @@ export declare type APIOptions = { emailDelivery: EmailDeliveryIngredient; }; export declare type APIInterface = { - verifyEmailPOST: undefined | ((input: { - token: string; - options: APIOptions; - userContext: any; - session?: SessionContainerInterface; - }) => Promise<{ - status: "OK"; - user: User; - } | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } | GeneralErrorResponse>); - isEmailVerifiedGET: undefined | ((input: { - options: APIOptions; - userContext: any; - session: SessionContainerInterface; - }) => Promise<{ - status: "OK"; - isVerified: boolean; - } | GeneralErrorResponse>); - generateEmailVerifyTokenPOST: undefined | ((input: { - options: APIOptions; - userContext: any; - session: SessionContainerInterface; - }) => Promise<{ - status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; - } | GeneralErrorResponse>); + verifyEmailPOST: + | undefined + | ((input: { + token: string; + options: APIOptions; + userContext: any; + session?: SessionContainerInterface; + }) => Promise< + | { + status: "OK"; + user: User; + } + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + | GeneralErrorResponse + >); + isEmailVerifiedGET: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + session: SessionContainerInterface; + }) => Promise< + | { + status: "OK"; + isVerified: boolean; + } + | GeneralErrorResponse + >); + generateEmailVerifyTokenPOST: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + session: SessionContainerInterface; + }) => Promise< + | { + status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; + } + | GeneralErrorResponse + >); }; export declare type TypeEmailVerificationEmailDeliveryInput = { type: "EMAIL_VERIFICATION"; @@ -126,9 +167,15 @@ export declare type TypeEmailVerificationEmailDeliveryInput = { }; emailVerifyLink: string; }; -export declare type GetEmailForUserIdFunc = (userId: string, userContext: any) => Promise<{ - status: "OK"; - email: string; -} | { - status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; -}>; +export declare type GetEmailForUserIdFunc = ( + userId: string, + userContext: any +) => Promise< + | { + status: "OK"; + email: string; + } + | { + status: "EMAIL_DOES_NOT_EXIST_ERROR" | "UNKNOWN_USER_ID_ERROR"; + } +>; diff --git a/lib/build/recipe/emailverification/utils.d.ts b/lib/build/recipe/emailverification/utils.d.ts index 91dc7b197..9f8e73229 100644 --- a/lib/build/recipe/emailverification/utils.d.ts +++ b/lib/build/recipe/emailverification/utils.d.ts @@ -1,7 +1,11 @@ import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function validateAndNormaliseUserInput(_: Recipe, appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + _: Recipe, + appInfo: NormalisedAppinfo, + config: TypeInput +): TypeNormalisedInput; export declare function getEmailVerifyLink(input: { appInfo: NormalisedAppinfo; token: string; diff --git a/lib/build/recipe/emailverification/utils.js b/lib/build/recipe/emailverification/utils.js index e82551f28..26dc9f073 100644 --- a/lib/build/recipe/emailverification/utils.js +++ b/lib/build/recipe/emailverification/utils.js @@ -13,14 +13,22 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getEmailVerifyLink = exports.validateAndNormaliseUserInput = void 0; const backwardCompatibility_1 = __importDefault(require("./emaildelivery/services/backwardCompatibility")); function validateAndNormaliseUserInput(_, appInfo, config) { - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config.override + ); function getEmailDeliveryConfig(isInServerlessEnv) { var _a; let emailService = (_a = config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; @@ -32,9 +40,13 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * createAndSendCustomEmail implementation which calls our supertokens API */ if (emailService === undefined) { - emailService = new backwardCompatibility_1.default(appInfo, isInServerlessEnv, config.createAndSendCustomEmail); + emailService = new backwardCompatibility_1.default( + appInfo, + isInServerlessEnv, + config.createAndSendCustomEmail + ); } - return Object.assign(Object.assign({}, config.emailDelivery), { + return Object.assign(Object.assign({}, config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -46,7 +58,8 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService }); + service: emailService, + }); } return { mode: config.mode, @@ -57,12 +70,14 @@ function validateAndNormaliseUserInput(_, appInfo, config) { } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function getEmailVerifyLink(input) { - return (input.appInfo.websiteDomain.getAsStringDangerous() + + return ( + input.appInfo.websiteDomain.getAsStringDangerous() + input.appInfo.websiteBasePath.getAsStringDangerous() + "/verify-email" + "?token=" + input.token + "&rid=" + - input.recipeId); + input.recipeId + ); } exports.getEmailVerifyLink = getEmailVerifyLink; diff --git a/lib/build/recipe/jwt/api/getJWKS.js b/lib/build/recipe/jwt/api/getJWKS.js index 5caf51870..b2e33b23b 100644 --- a/lib/build/recipe/jwt/api/getJWKS.js +++ b/lib/build/recipe/jwt/api/getJWKS.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); @@ -37,8 +59,7 @@ function getJWKS(apiImplementation, options) { if (result.status === "OK") { options.res.setHeader("Access-Control-Allow-Origin", "*", false); utils_1.send200Response(options.res, { keys: result.keys }); - } - else { + } else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/jwt/api/implementation.js b/lib/build/recipe/jwt/api/implementation.js index c4a859036..88600ac6e 100644 --- a/lib/build/recipe/jwt/api/implementation.js +++ b/lib/build/recipe/jwt/api/implementation.js @@ -13,19 +13,41 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getAPIImplementation() { return { - getJWKSGET: function ({ options, userContext, }) { + getJWKSGET: function ({ options, userContext }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.getJWKS({ userContext }); }); diff --git a/lib/build/recipe/jwt/index.d.ts b/lib/build/recipe/jwt/index.d.ts index 7b001eb8c..7bc4880c9 100644 --- a/lib/build/recipe/jwt/index.d.ts +++ b/lib/build/recipe/jwt/index.d.ts @@ -2,13 +2,22 @@ import Recipe from "./recipe"; import { APIInterface, RecipeInterface, APIOptions, JsonWebKey } from "./types"; export default class Wrapper { static init: typeof Recipe.init; - static createJWT(payload: any, validitySeconds?: number, userContext?: any): Promise<{ - status: "OK"; - jwt: string; - } | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - }>; - static getJWKS(userContext?: any): Promise<{ + static createJWT( + payload: any, + validitySeconds?: number, + userContext?: any + ): Promise< + | { + status: "OK"; + jwt: string; + } + | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + } + >; + static getJWKS( + userContext?: any + ): Promise<{ status: "OK"; keys: JsonWebKey[]; }>; diff --git a/lib/build/recipe/jwt/index.js b/lib/build/recipe/jwt/index.js index bfd39cb40..7b1184695 100644 --- a/lib/build/recipe/jwt/index.js +++ b/lib/build/recipe/jwt/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getJWKS = exports.createJWT = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); diff --git a/lib/build/recipe/jwt/recipe.d.ts b/lib/build/recipe/jwt/recipe.d.ts index 54e486c45..4bdb2f164 100644 --- a/lib/build/recipe/jwt/recipe.d.ts +++ b/lib/build/recipe/jwt/recipe.d.ts @@ -16,7 +16,13 @@ export default class Recipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled(): APIHandled[]; - handleAPIRequest: (_: string, req: BaseRequest, res: BaseResponse, __: normalisedURLPath, ___: HTTPMethod) => Promise; + handleAPIRequest: ( + _: string, + req: BaseRequest, + res: BaseResponse, + __: normalisedURLPath, + ___: HTTPMethod + ) => Promise; handleError(error: error, _: BaseRequest, __: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; diff --git a/lib/build/recipe/jwt/recipe.js b/lib/build/recipe/jwt/recipe.js index da4edb4d4..acf557c24 100644 --- a/lib/build/recipe/jwt/recipe.js +++ b/lib/build/recipe/jwt/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); @@ -39,21 +63,28 @@ const supertokens_js_override_1 = __importDefault(require("supertokens-js-overri class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config) { super(recipeId, appInfo); - this.handleAPIRequest = (_, req, res, __, ___) => __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - }; - return yield getJWKS_1.default(this.apiImpl, options); - }); + this.handleAPIRequest = (_, req, res, __, ___) => + __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + }; + return yield getJWKS_1.default(this.apiImpl, options); + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config, appInfo)); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default( + querier_1.Querier.getNewInstanceOrThrowError(recipeId), + this.config, + appInfo + ) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -73,8 +104,7 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } - else { + } else { throw new Error("JWT recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/jwt/recipeImplementation.d.ts b/lib/build/recipe/jwt/recipeImplementation.d.ts index 8af46b085..198e4d95f 100644 --- a/lib/build/recipe/jwt/recipeImplementation.d.ts +++ b/lib/build/recipe/jwt/recipeImplementation.d.ts @@ -1,4 +1,8 @@ import { Querier } from "../../querier"; import { NormalisedAppinfo } from "../../types"; import { RecipeInterface, TypeNormalisedInput } from "./types"; -export default function getRecipeInterface(querier: Querier, config: TypeNormalisedInput, appInfo: NormalisedAppinfo): RecipeInterface; +export default function getRecipeInterface( + querier: Querier, + config: TypeNormalisedInput, + appInfo: NormalisedAppinfo +): RecipeInterface; diff --git a/lib/build/recipe/jwt/recipeImplementation.js b/lib/build/recipe/jwt/recipeImplementation.js index 5204b0c13..3b4f0aff8 100644 --- a/lib/build/recipe/jwt/recipeImplementation.js +++ b/lib/build/recipe/jwt/recipeImplementation.js @@ -13,23 +13,47 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); function getRecipeInterface(querier, config, appInfo) { return { - createJWT: function ({ payload, validitySeconds, }) { + createJWT: function ({ payload, validitySeconds }) { return __awaiter(this, void 0, void 0, function* () { if (validitySeconds === undefined) { // If the user does not provide a validity to this function and the config validity is also undefined, use 100 years (in seconds) @@ -46,8 +70,7 @@ function getRecipeInterface(querier, config, appInfo) { status: "OK", jwt: response.jwt, }; - } - else { + } else { return { status: "UNSUPPORTED_ALGORITHM_ERROR", }; diff --git a/lib/build/recipe/jwt/types.d.ts b/lib/build/recipe/jwt/types.d.ts index 914cffa8c..96e29ea20 100644 --- a/lib/build/recipe/jwt/types.d.ts +++ b/lib/build/recipe/jwt/types.d.ts @@ -12,14 +12,20 @@ export declare type JsonWebKey = { export declare type TypeInput = { jwtValiditySeconds?: number; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { jwtValiditySeconds: number; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -36,12 +42,15 @@ export declare type RecipeInterface = { payload?: any; validitySeconds?: number; userContext: any; - }): Promise<{ - status: "OK"; - jwt: string; - } | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + jwt: string; + } + | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + } + >; getJWKS(input: { userContext: any; }): Promise<{ @@ -50,11 +59,16 @@ export declare type RecipeInterface = { }>; }; export declare type APIInterface = { - getJWKSGET: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - keys: JsonWebKey[]; - } | GeneralErrorResponse>); + getJWKSGET: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + keys: JsonWebKey[]; + } + | GeneralErrorResponse + >); }; diff --git a/lib/build/recipe/jwt/utils.d.ts b/lib/build/recipe/jwt/utils.d.ts index 371d85a96..e368bc539 100644 --- a/lib/build/recipe/jwt/utils.d.ts +++ b/lib/build/recipe/jwt/utils.d.ts @@ -1,4 +1,8 @@ import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput(_: Recipe, __: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + _: Recipe, + __: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; diff --git a/lib/build/recipe/jwt/utils.js b/lib/build/recipe/jwt/utils.js index f3383e481..9c38d23ce 100644 --- a/lib/build/recipe/jwt/utils.js +++ b/lib/build/recipe/jwt/utils.js @@ -17,9 +17,18 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(_, __, config) { var _a; - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); return { - jwtValiditySeconds: (_a = config === null || config === void 0 ? void 0 : config.jwtValiditySeconds) !== null && _a !== void 0 ? _a : 3153600000, + jwtValiditySeconds: + (_a = config === null || config === void 0 ? void 0 : config.jwtValiditySeconds) !== null && _a !== void 0 + ? _a + : 3153600000, override, }; } diff --git a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts index 2f25a26d2..1bdb0fcdb 100644 --- a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts +++ b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts @@ -1,2 +1,5 @@ import { APIInterface, APIOptions } from "../types"; -export default function getOpenIdDiscoveryConfiguration(apiImplementation: APIInterface, options: APIOptions): Promise; +export default function getOpenIdDiscoveryConfiguration( + apiImplementation: APIInterface, + options: APIOptions +): Promise; diff --git a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js index 4c4434613..9fd8c6e31 100644 --- a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js +++ b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -40,8 +62,7 @@ function getOpenIdDiscoveryConfiguration(apiImplementation, options) { issuer: result.issuer, jwks_uri: result.jwks_uri, }); - } - else { + } else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/openid/api/implementation.js b/lib/build/recipe/openid/api/implementation.js index 7afccd7b5..81609c3b2 100644 --- a/lib/build/recipe/openid/api/implementation.js +++ b/lib/build/recipe/openid/api/implementation.js @@ -1,17 +1,39 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getAPIImplementation() { return { - getOpenIdDiscoveryConfigurationGET: function ({ options, userContext, }) { + getOpenIdDiscoveryConfigurationGET: function ({ options, userContext }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.getOpenIdDiscoveryConfiguration({ userContext }); }); diff --git a/lib/build/recipe/openid/index.d.ts b/lib/build/recipe/openid/index.d.ts index af0b20dc3..5eddbb0ef 100644 --- a/lib/build/recipe/openid/index.d.ts +++ b/lib/build/recipe/openid/index.d.ts @@ -1,18 +1,29 @@ import OpenIdRecipe from "./recipe"; export default class OpenIdRecipeWrapper { static init: typeof OpenIdRecipe.init; - static getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ + static getOpenIdDiscoveryConfiguration( + userContext?: any + ): Promise<{ status: "OK"; issuer: string; jwks_uri: string; }>; - static createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ - status: "OK"; - jwt: string; - } | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - }>; - static getJWKS(userContext?: any): Promise<{ + static createJWT( + payload?: any, + validitySeconds?: number, + userContext?: any + ): Promise< + | { + status: "OK"; + jwt: string; + } + | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + } + >; + static getJWKS( + userContext?: any + ): Promise<{ status: "OK"; keys: import("../jwt").JsonWebKey[]; }>; diff --git a/lib/build/recipe/openid/index.js b/lib/build/recipe/openid/index.js index eeeb88f9b..83903ab76 100644 --- a/lib/build/recipe/openid/index.js +++ b/lib/build/recipe/openid/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getJWKS = exports.createJWT = exports.getOpenIdDiscoveryConfiguration = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); diff --git a/lib/build/recipe/openid/recipe.d.ts b/lib/build/recipe/openid/recipe.d.ts index f8c4677af..e6431dc5e 100644 --- a/lib/build/recipe/openid/recipe.d.ts +++ b/lib/build/recipe/openid/recipe.d.ts @@ -17,7 +17,13 @@ export default class OpenIdRecipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, response: BaseResponse, path: normalisedURLPath, method: HTTPMethod) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + response: BaseResponse, + path: normalisedURLPath, + method: HTTPMethod + ) => Promise; handleError: (error: STError, request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/openid/recipe.js b/lib/build/recipe/openid/recipe.js index 3355a416d..baf6bc665 100644 --- a/lib/build/recipe/openid/recipe.js +++ b/lib/build/recipe/openid/recipe.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -50,42 +74,46 @@ class OpenIdRecipe extends recipeModule_1.default { ...this.jwtRecipe.getAPIsHandled(), ]; }; - this.handleAPIRequest = (id, req, response, path, method) => __awaiter(this, void 0, void 0, function* () { - let apiOptions = { - recipeImplementation: this.recipeImplementation, - config: this.config, - recipeId: this.getRecipeId(), - req, - res: response, - }; - if (id === constants_1.GET_DISCOVERY_CONFIG_URL) { - return yield getOpenIdDiscoveryConfiguration_1.default(this.apiImpl, apiOptions); - } - else { - return this.jwtRecipe.handleAPIRequest(id, req, response, path, method); - } - }); - this.handleError = (error, request, response) => __awaiter(this, void 0, void 0, function* () { - if (error.fromRecipe === OpenIdRecipe.RECIPE_ID) { - throw error; - } - else { - return yield this.jwtRecipe.handleError(error, request, response); - } - }); + this.handleAPIRequest = (id, req, response, path, method) => + __awaiter(this, void 0, void 0, function* () { + let apiOptions = { + recipeImplementation: this.recipeImplementation, + config: this.config, + recipeId: this.getRecipeId(), + req, + res: response, + }; + if (id === constants_1.GET_DISCOVERY_CONFIG_URL) { + return yield getOpenIdDiscoveryConfiguration_1.default(this.apiImpl, apiOptions); + } else { + return this.jwtRecipe.handleAPIRequest(id, req, response, path, method); + } + }); + this.handleError = (error, request, response) => + __awaiter(this, void 0, void 0, function* () { + if (error.fromRecipe === OpenIdRecipe.RECIPE_ID) { + throw error; + } else { + return yield this.jwtRecipe.handleError(error, request, response); + } + }); this.getAllCORSHeaders = () => { return [...this.jwtRecipe.getAllCORSHeaders()]; }; this.isErrorFromThisRecipe = (err) => { - return ((error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === OpenIdRecipe.RECIPE_ID) || - this.jwtRecipe.isErrorFromThisRecipe(err)); + return ( + (error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === OpenIdRecipe.RECIPE_ID) || + this.jwtRecipe.isErrorFromThisRecipe(err) + ); }; this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); this.jwtRecipe = new recipe_1.default(recipeId, appInfo, isInServerlessEnv, { jwtValiditySeconds: this.config.jwtValiditySeconds, override: this.config.override.jwtFeature, }); - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(this.config, this.jwtRecipe.recipeInterfaceImpl)); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(this.config, this.jwtRecipe.recipeInterfaceImpl) + ); this.recipeImplementation = builder.override(this.config.override.functions).build(); let apiBuilder = new supertokens_js_override_1.default(implementation_1.default()); this.apiImpl = apiBuilder.override(this.config.override.apis).build(); @@ -101,8 +129,7 @@ class OpenIdRecipe extends recipeModule_1.default { if (OpenIdRecipe.instance === undefined) { OpenIdRecipe.instance = new OpenIdRecipe(OpenIdRecipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return OpenIdRecipe.instance; - } - else { + } else { throw new Error("OpenId recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/openid/recipeImplementation.d.ts b/lib/build/recipe/openid/recipeImplementation.d.ts index 5c27012a7..4136ac535 100644 --- a/lib/build/recipe/openid/recipeImplementation.d.ts +++ b/lib/build/recipe/openid/recipeImplementation.d.ts @@ -1,3 +1,6 @@ import { RecipeInterface, TypeNormalisedInput } from "./types"; import { RecipeInterface as JWTRecipeInterface } from "../jwt/types"; -export default function getRecipeInterface(config: TypeNormalisedInput, jwtRecipeImplementation: JWTRecipeInterface): RecipeInterface; +export default function getRecipeInterface( + config: TypeNormalisedInput, + jwtRecipeImplementation: JWTRecipeInterface +): RecipeInterface; diff --git a/lib/build/recipe/openid/recipeImplementation.js b/lib/build/recipe/openid/recipeImplementation.js index af2a9dcc5..efa935aaa 100644 --- a/lib/build/recipe/openid/recipeImplementation.js +++ b/lib/build/recipe/openid/recipeImplementation.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); const constants_1 = require("../jwt/constants"); @@ -19,8 +43,11 @@ function getRecipeInterface(config, jwtRecipeImplementation) { getOpenIdDiscoveryConfiguration: function () { return __awaiter(this, void 0, void 0, function* () { let issuer = config.issuerDomain.getAsStringDangerous() + config.issuerPath.getAsStringDangerous(); - let jwks_uri = config.issuerDomain.getAsStringDangerous() + - config.issuerPath.appendPath(new normalisedURLPath_1.default(constants_1.GET_JWKS_API)).getAsStringDangerous(); + let jwks_uri = + config.issuerDomain.getAsStringDangerous() + + config.issuerPath + .appendPath(new normalisedURLPath_1.default(constants_1.GET_JWKS_API)) + .getAsStringDangerous(); return { status: "OK", issuer, @@ -28,7 +55,7 @@ function getRecipeInterface(config, jwtRecipeImplementation) { }; }); }, - createJWT: function ({ payload, validitySeconds, userContext, }) { + createJWT: function ({ payload, validitySeconds, userContext }) { return __awaiter(this, void 0, void 0, function* () { payload = payload === undefined || payload === null ? {} : payload; let issuer = config.issuerDomain.getAsStringDangerous() + config.issuerPath.getAsStringDangerous(); diff --git a/lib/build/recipe/openid/types.d.ts b/lib/build/recipe/openid/types.d.ts index 95149cd80..d3105193b 100644 --- a/lib/build/recipe/openid/types.d.ts +++ b/lib/build/recipe/openid/types.d.ts @@ -8,11 +8,20 @@ export declare type TypeInput = { issuer?: string; jwtValiditySeconds?: number; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; jwtFeature?: { - functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; - apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; + functions?: ( + originalImplementation: JWTRecipeInterface, + builder?: OverrideableBuilder + ) => JWTRecipeInterface; + apis?: ( + originalImplementation: JWTAPIInterface, + builder?: OverrideableBuilder + ) => JWTAPIInterface; }; }; }; @@ -21,11 +30,20 @@ export declare type TypeNormalisedInput = { issuerPath: NormalisedURLPath; jwtValiditySeconds?: number; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; jwtFeature?: { - functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; - apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; + functions?: ( + originalImplementation: JWTRecipeInterface, + builder?: OverrideableBuilder + ) => JWTRecipeInterface; + apis?: ( + originalImplementation: JWTAPIInterface, + builder?: OverrideableBuilder + ) => JWTAPIInterface; }; }; }; @@ -37,14 +55,19 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - getOpenIdDiscoveryConfigurationGET: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - issuer: string; - jwks_uri: string; - } | GeneralErrorResponse>); + getOpenIdDiscoveryConfigurationGET: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + issuer: string; + jwks_uri: string; + } + | GeneralErrorResponse + >); }; export declare type RecipeInterface = { getOpenIdDiscoveryConfiguration(input: { @@ -58,12 +81,15 @@ export declare type RecipeInterface = { payload?: any; validitySeconds?: number; userContext: any; - }): Promise<{ - status: "OK"; - jwt: string; - } | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + jwt: string; + } + | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + } + >; getJWKS(input: { userContext: any; }): Promise<{ diff --git a/lib/build/recipe/openid/utils.d.ts b/lib/build/recipe/openid/utils.d.ts index 238a8cda5..79c8d178d 100644 --- a/lib/build/recipe/openid/utils.d.ts +++ b/lib/build/recipe/openid/utils.d.ts @@ -1,3 +1,6 @@ import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput(appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + appInfo: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; diff --git a/lib/build/recipe/openid/utils.js b/lib/build/recipe/openid/utils.js index 54c270ad7..fac3a3f43 100644 --- a/lib/build/recipe/openid/utils.js +++ b/lib/build/recipe/openid/utils.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAndNormaliseUserInput = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -32,7 +34,13 @@ function validateAndNormaliseUserInput(appInfo, config) { throw new Error("The path of the issuer URL must be equal to the apiBasePath. The default value is /auth"); } } - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); return { issuerDomain, issuerPath, diff --git a/lib/build/recipe/passwordless/api/consumeCode.js b/lib/build/recipe/passwordless/api/consumeCode.js index f1a01169a..27cd79132 100644 --- a/lib/build/recipe/passwordless/api/consumeCode.js +++ b/lib/build/recipe/passwordless/api/consumeCode.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); @@ -58,28 +82,29 @@ function consumeCode(apiImplementation, options) { message: "Please provide both deviceId and userInputCode", }); } - } - else if (linkCode === undefined) { + } else if (linkCode === undefined) { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, message: "Please provide one of (linkCode) or (deviceId+userInputCode) and not both", }); } const userContext = utils_2.makeDefaultUserContextFromAPI(options.req); - let result = yield apiImplementation.consumeCodePOST(deviceId !== undefined - ? { - deviceId, - userInputCode, - preAuthSessionId, - options, - userContext, - } - : { - linkCode, - options, - preAuthSessionId, - userContext, - }); + let result = yield apiImplementation.consumeCodePOST( + deviceId !== undefined + ? { + deviceId, + userInputCode, + preAuthSessionId, + options, + userContext, + } + : { + linkCode, + options, + preAuthSessionId, + userContext, + } + ); if (result.status === "OK") { delete result.session; } diff --git a/lib/build/recipe/passwordless/api/createCode.js b/lib/build/recipe/passwordless/api/createCode.js index d8b92f64c..83e8388a8 100644 --- a/lib/build/recipe/passwordless/api/createCode.js +++ b/lib/build/recipe/passwordless/api/createCode.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); @@ -57,8 +81,10 @@ function createCode(apiImplementation, options) { }); } // normalise and validate format of input - if (email !== undefined && - (options.config.contactMethod === "EMAIL" || options.config.contactMethod === "EMAIL_OR_PHONE")) { + if ( + email !== undefined && + (options.config.contactMethod === "EMAIL" || options.config.contactMethod === "EMAIL_OR_PHONE") + ) { email = email.trim(); const validateError = yield options.config.validateEmailAddress(email); if (validateError !== undefined) { @@ -69,8 +95,10 @@ function createCode(apiImplementation, options) { return true; } } - if (phoneNumber !== undefined && - (options.config.contactMethod === "PHONE" || options.config.contactMethod === "EMAIL_OR_PHONE")) { + if ( + phoneNumber !== undefined && + (options.config.contactMethod === "PHONE" || options.config.contactMethod === "EMAIL_OR_PHONE") + ) { const validateError = yield options.config.validatePhoneNumber(phoneNumber); if (validateError !== undefined) { utils_1.send200Response(options.res, { @@ -84,14 +112,15 @@ function createCode(apiImplementation, options) { // this can come here if the user has provided their own impl of validatePhoneNumber and // the phone number is valid according to their impl, but not according to the libphonenumber-js lib. phoneNumber = phoneNumber.trim(); - } - else { + } else { phoneNumber = parsedPhoneNumber.format("E.164"); } } - let result = yield apiImplementation.createCodePOST(email !== undefined - ? { email, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) } - : { phoneNumber: phoneNumber, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) }); + let result = yield apiImplementation.createCodePOST( + email !== undefined + ? { email, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) } + : { phoneNumber: phoneNumber, options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) } + ); utils_1.send200Response(options.res, result); return true; }); diff --git a/lib/build/recipe/passwordless/api/emailExists.js b/lib/build/recipe/passwordless/api/emailExists.js index 2aff0a25a..e1fe058a4 100644 --- a/lib/build/recipe/passwordless/api/emailExists.js +++ b/lib/build/recipe/passwordless/api/emailExists.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); diff --git a/lib/build/recipe/passwordless/api/implementation.js b/lib/build/recipe/passwordless/api/implementation.js index 513aad791..920dbaf3a 100644 --- a/lib/build/recipe/passwordless/api/implementation.js +++ b/lib/build/recipe/passwordless/api/implementation.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); const recipe_1 = __importDefault(require("../../emailverification/recipe")); @@ -19,18 +43,20 @@ function getAPIImplementation() { return { consumeCodePOST: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield input.options.recipeImplementation.consumeCode("deviceId" in input - ? { - preAuthSessionId: input.preAuthSessionId, - deviceId: input.deviceId, - userInputCode: input.userInputCode, - userContext: input.userContext, - } - : { - preAuthSessionId: input.preAuthSessionId, - linkCode: input.linkCode, - userContext: input.userContext, - }); + let response = yield input.options.recipeImplementation.consumeCode( + "deviceId" in input + ? { + preAuthSessionId: input.preAuthSessionId, + deviceId: input.deviceId, + userInputCode: input.userInputCode, + userContext: input.userContext, + } + : { + preAuthSessionId: input.preAuthSessionId, + linkCode: input.linkCode, + userContext: input.userContext, + } + ); if (response.status !== "OK") { return response; } @@ -38,11 +64,13 @@ function getAPIImplementation() { if (user.email !== undefined) { const emailVerificationInstance = recipe_1.default.getInstance(); if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ - userId: user.recipeUserId, - email: user.email, - userContext: input.userContext, - }); + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: user.recipeUserId, + email: user.email, + userContext: input.userContext, + } + ); if (tokenResponse.status === "OK") { yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ token: tokenResponse.token, @@ -51,7 +79,15 @@ function getAPIImplementation() { } } } - const session = yield session_1.default.createNewSession(input.options.req, input.options.res, user.id, user.recipeUserId, {}, {}, input.userContext); + const session = yield session_1.default.createNewSession( + input.options.req, + input.options.res, + user.id, + user.recipeUserId, + {}, + {}, + input.userContext + ); return { status: "OK", createdNewUser: response.createdNewUser, @@ -63,21 +99,25 @@ function getAPIImplementation() { }, createCodePOST: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield input.options.recipeImplementation.createCode("email" in input - ? { - userContext: input.userContext, - email: input.email, - userInputCode: input.options.config.getCustomUserInputCode === undefined - ? undefined - : yield input.options.config.getCustomUserInputCode(input.userContext), - } - : { - userContext: input.userContext, - phoneNumber: input.phoneNumber, - userInputCode: input.options.config.getCustomUserInputCode === undefined - ? undefined - : yield input.options.config.getCustomUserInputCode(input.userContext), - }); + let response = yield input.options.recipeImplementation.createCode( + "email" in input + ? { + userContext: input.userContext, + email: input.email, + userInputCode: + input.options.config.getCustomUserInputCode === undefined + ? undefined + : yield input.options.config.getCustomUserInputCode(input.userContext), + } + : { + userContext: input.userContext, + phoneNumber: input.phoneNumber, + userInputCode: + input.options.config.getCustomUserInputCode === undefined + ? undefined + : yield input.options.config.getCustomUserInputCode(input.userContext), + } + ); // now we send the email / text message. let magicLink = undefined; let userInputCode = undefined; @@ -85,14 +125,14 @@ function getAPIImplementation() { if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = input.options.appInfo.websiteDomain.getAsStringDangerous() + - input.options.appInfo.websiteBasePath.getAsStringDangerous() + - "/verify" + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + input.options.appInfo.websiteBasePath.getAsStringDangerous() + + "/verify" + + "?rid=" + + input.options.recipeId + + "&preAuthSessionId=" + + response.preAuthSessionId + + "#" + + response.linkCode; } if (flowType === "USER_INPUT_CODE" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { userInputCode = response.userInputCode; @@ -100,8 +140,10 @@ function getAPIImplementation() { // we don't do something special for serverless env here // cause we want to wait for service's reply since it can show // a UI error message for if sending an SMS / email failed or not. - if (input.options.config.contactMethod === "PHONE" || - (input.options.config.contactMethod === "EMAIL_OR_PHONE" && "phoneNumber" in input)) { + if ( + input.options.config.contactMethod === "PHONE" || + (input.options.config.contactMethod === "EMAIL_OR_PHONE" && "phoneNumber" in input) + ) { logger_1.logDebugMessage(`Sending passwordless login SMS to ${input.phoneNumber}`); yield input.options.smsDelivery.ingredientInterfaceImpl.sendSms({ type: "PASSWORDLESS_LOGIN", @@ -112,8 +154,7 @@ function getAPIImplementation() { userInputCode, userContext: input.userContext, }); - } - else { + } else { logger_1.logDebugMessage(`Sending passwordless login email to ${input.email}`); yield input.options.emailDelivery.ingredientInterfaceImpl.sendEmail({ type: "PASSWORDLESS_LOGIN", @@ -168,8 +209,10 @@ function getAPIImplementation() { status: "RESTART_FLOW_ERROR", }; } - if ((input.options.config.contactMethod === "PHONE" && deviceInfo.phoneNumber === undefined) || - (input.options.config.contactMethod === "EMAIL" && deviceInfo.email === undefined)) { + if ( + (input.options.config.contactMethod === "PHONE" && deviceInfo.phoneNumber === undefined) || + (input.options.config.contactMethod === "EMAIL" && deviceInfo.email === undefined) + ) { return { status: "RESTART_FLOW_ERROR", }; @@ -180,9 +223,10 @@ function getAPIImplementation() { let response = yield input.options.recipeImplementation.createNewCodeForDevice({ userContext: input.userContext, deviceId: input.deviceId, - userInputCode: input.options.config.getCustomUserInputCode === undefined - ? undefined - : yield input.options.config.getCustomUserInputCode(input.userContext), + userInputCode: + input.options.config.getCustomUserInputCode === undefined + ? undefined + : yield input.options.config.getCustomUserInputCode(input.userContext), }); if (response.status === "USER_INPUT_CODE_ALREADY_USED_ERROR") { if (numberOfTriesToCreateNewCode >= 3) { @@ -201,14 +245,14 @@ function getAPIImplementation() { if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = input.options.appInfo.websiteDomain.getAsStringDangerous() + - input.options.appInfo.websiteBasePath.getAsStringDangerous() + - "/verify" + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + input.options.appInfo.websiteBasePath.getAsStringDangerous() + + "/verify" + + "?rid=" + + input.options.recipeId + + "&preAuthSessionId=" + + response.preAuthSessionId + + "#" + + response.linkCode; } if (flowType === "USER_INPUT_CODE" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { userInputCode = response.userInputCode; @@ -216,9 +260,11 @@ function getAPIImplementation() { // we don't do something special for serverless env here // cause we want to wait for service's reply since it can show // a UI error message for if sending an SMS / email failed or not. - if (input.options.config.contactMethod === "PHONE" || + if ( + input.options.config.contactMethod === "PHONE" || (input.options.config.contactMethod === "EMAIL_OR_PHONE" && - deviceInfo.phoneNumber !== undefined)) { + deviceInfo.phoneNumber !== undefined) + ) { logger_1.logDebugMessage(`Sending passwordless login SMS to ${input.phoneNumber}`); yield input.options.smsDelivery.ingredientInterfaceImpl.sendSms({ type: "PASSWORDLESS_LOGIN", @@ -229,8 +275,7 @@ function getAPIImplementation() { userInputCode, userContext: input.userContext, }); - } - else { + } else { logger_1.logDebugMessage(`Sending passwordless login email to ${input.email}`); yield input.options.emailDelivery.ingredientInterfaceImpl.sendEmail({ type: "PASSWORDLESS_LOGIN", diff --git a/lib/build/recipe/passwordless/api/phoneNumberExists.js b/lib/build/recipe/passwordless/api/phoneNumberExists.js index 2fc8d9636..64db5374f 100644 --- a/lib/build/recipe/passwordless/api/phoneNumberExists.js +++ b/lib/build/recipe/passwordless/api/phoneNumberExists.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); diff --git a/lib/build/recipe/passwordless/api/resendCode.js b/lib/build/recipe/passwordless/api/resendCode.js index 588d37a10..9fad206c2 100644 --- a/lib/build/recipe/passwordless/api/resendCode.js +++ b/lib/build/recipe/passwordless/api/resendCode.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); diff --git a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts index 539d63aa8..76bfdb50f 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,16 +1,25 @@ import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; -export default class BackwardCompatibilityService implements EmailDeliveryInterface { +export default class BackwardCompatibilityService + implements EmailDeliveryInterface { private createAndSendCustomEmail; - constructor(appInfo: NormalisedAppinfo, createAndSendCustomEmail?: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise); - sendEmail: (input: TypePasswordlessEmailDeliveryInput & { - userContext: any; - }) => Promise; + constructor( + appInfo: NormalisedAppinfo, + createAndSendCustomEmail?: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise + ); + sendEmail: ( + input: TypePasswordlessEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js index da6596b98..241629b1a 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.js @@ -1,88 +1,120 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const axios_1 = __importDefault(require("axios")); -const logger_1 = require("../../../../../logger"); -function defaultCreateAndSendCustomEmail(appInfo) { - return (input, _) => __awaiter(this, void 0, void 0, function* () { - if (process.env.TEST_MODE === "testing") { - return; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); } - try { - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.io/0/st/auth/passwordless/login", - data: { - email: input.email, - appName: appInfo.appName, - codeLifetime: input.codeLifetime, - urlWithLinkCode: input.urlWithLinkCode, - userInputCode: input.userInputCode, - }, - headers: { - "api-version": 0, - }, - }); - logger_1.logDebugMessage(`Email sent to ${input.email}`); - } - catch (error) { - logger_1.logDebugMessage("Error sending passwordless login email"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } - else { - logger_1.logDebugMessage(`Error: ${err.message}`); + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); } } - else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, "__esModule", { value: true }); +const axios_1 = __importDefault(require("axios")); +const logger_1 = require("../../../../../logger"); +function defaultCreateAndSendCustomEmail(appInfo) { + return (input, _) => + __awaiter(this, void 0, void 0, function* () { + if (process.env.TEST_MODE === "testing") { + return; } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage(JSON.stringify({ - email: input.email, - appName: appInfo.appName, - codeLifetime: input.codeLifetime, - urlWithLinkCode: input.urlWithLinkCode, - userInputCode: input.userInputCode, - }, null, 2)); - /** - * if the error is thrown from API, the response object - * will be of type `{err: string}` - */ - if (axios_1.default.isAxiosError(error) && error.response !== undefined) { - if (error.response.data.err !== undefined) { - throw Error(error.response.data.err); + try { + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.io/0/st/auth/passwordless/login", + data: { + email: input.email, + appName: appInfo.appName, + codeLifetime: input.codeLifetime, + urlWithLinkCode: input.urlWithLinkCode, + userInputCode: input.userInputCode, + }, + headers: { + "api-version": 0, + }, + }); + logger_1.logDebugMessage(`Email sent to ${input.email}`); + } catch (error) { + logger_1.logDebugMessage("Error sending passwordless login email"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + } else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + } else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + } + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage( + JSON.stringify( + { + email: input.email, + appName: appInfo.appName, + codeLifetime: input.codeLifetime, + urlWithLinkCode: input.urlWithLinkCode, + userInputCode: input.userInputCode, + }, + null, + 2 + ) + ); + /** + * if the error is thrown from API, the response object + * will be of type `{err: string}` + */ + if (axios_1.default.isAxiosError(error) && error.response !== undefined) { + if (error.response.data.err !== undefined) { + throw Error(error.response.data.err); + } } + throw error; } - throw error; - } - }); + }); } class BackwardCompatibilityService { constructor(appInfo, createAndSendCustomEmail) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.createAndSendCustomEmail({ - email: input.email, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - preAuthSessionId: input.preAuthSessionId, - codeLifetime: input.codeLifetime, - }, input.userContext); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.createAndSendCustomEmail( + { + email: input.email, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + preAuthSessionId: input.preAuthSessionId, + codeLifetime: input.codeLifetime, + }, + input.userContext + ); + }); this.createAndSendCustomEmail = createAndSendCustomEmail === undefined ? defaultCreateAndSendCustomEmail(appInfo) diff --git a/lib/build/recipe/passwordless/emaildelivery/services/index.js b/lib/build/recipe/passwordless/emaildelivery/services/index.js index 3e4b76c1d..7e07f6706 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/index.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SMTPService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts index 0e9b7843e..726501ec8 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts @@ -4,7 +4,9 @@ import { TypePasswordlessEmailDeliveryInput } from "../../../types"; export default class SMTPService implements EmailDeliveryInterface { serviceImpl: ServiceInterface; constructor(config: TypeInput); - sendEmail: (input: TypePasswordlessEmailDeliveryInput & { - userContext: any; - }) => Promise; + sendEmail: ( + input: TypePasswordlessEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js index b96042bcd..e917fb0fe 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.js @@ -1,26 +1,53 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const serviceImplementation_1 = require("./serviceImplementation"); class SMTPService { constructor(config) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - yield this.serviceImpl.sendRawEmail(Object.assign(Object.assign({}, content), { userContext: input.userContext })); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + yield this.serviceImpl.sendRawEmail( + Object.assign(Object.assign({}, content), { userContext: input.userContext }) + ); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -30,7 +57,9 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); + let builder = new supertokens_js_override_1.default( + serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) + ); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts index dadee437f..4007a0589 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts @@ -1,4 +1,10 @@ import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; export default function getPasswordlessLoginEmailContent(input: TypePasswordlessEmailDeliveryInput): GetContentResult; -export declare function getPasswordlessLoginEmailHTML(appName: string, email: string, codeLifetime: number, urlWithLinkCode?: string, userInputCode?: string): string; +export declare function getPasswordlessLoginEmailHTML( + appName: string, + email: string, + codeLifetime: number, + urlWithLinkCode?: string, + userInputCode?: string +): string; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js index fc2c1f68d..2bb81add4 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPasswordlessLoginEmailHTML = void 0; const supertokens_1 = __importDefault(require("../../../../../supertokens")); @@ -9,7 +11,13 @@ const utils_1 = require("../../../../../utils"); function getPasswordlessLoginEmailContent(input) { let supertokens = supertokens_1.default.getInstanceOrThrowError(); let appName = supertokens.appInfo.appName; - let body = getPasswordlessLoginEmailHTML(appName, input.email, input.codeLifetime, input.urlWithLinkCode, input.userInputCode); + let body = getPasswordlessLoginEmailHTML( + appName, + input.email, + input.codeLifetime, + input.urlWithLinkCode, + input.userInputCode + ); return { body, toEmail: input.email, @@ -2835,13 +2843,24 @@ function getPasswordlessLoginOTPAndURLLinkBody(appName, email, codeLifetime, url } function getPasswordlessLoginEmailHTML(appName, email, codeLifetime, urlWithLinkCode, userInputCode) { if (urlWithLinkCode !== undefined && userInputCode !== undefined) { - return getPasswordlessLoginOTPAndURLLinkBody(appName, email, utils_1.humaniseMilliseconds(codeLifetime), urlWithLinkCode, userInputCode); + return getPasswordlessLoginOTPAndURLLinkBody( + appName, + email, + utils_1.humaniseMilliseconds(codeLifetime), + urlWithLinkCode, + userInputCode + ); } if (userInputCode !== undefined) { return getPasswordlessLoginOTPBody(appName, email, utils_1.humaniseMilliseconds(codeLifetime), userInputCode); } if (urlWithLinkCode !== undefined) { - return getPasswordlessLoginURLLinkBody(appName, email, utils_1.humaniseMilliseconds(codeLifetime), urlWithLinkCode); + return getPasswordlessLoginURLLinkBody( + appName, + email, + utils_1.humaniseMilliseconds(codeLifetime), + urlWithLinkCode + ); } throw Error("this should never be thrown"); } diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts index c6827160f..dc22e6060 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts @@ -1,7 +1,10 @@ import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation(transporter: Transporter, from: { - name: string; - email: string; -}): ServiceInterface; +export declare function getServiceImplementation( + transporter: Transporter, + from: { + name: string; + email: string; + } +): ServiceInterface; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js index cb938c406..dfffb9e5d 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getServiceImplementation = void 0; const passwordlessLogin_1 = __importDefault(require("./passwordlessLogin")); @@ -39,8 +63,7 @@ function getServiceImplementation(transporter, from) { subject: input.subject, html: input.body, }); - } - else { + } else { yield transporter.sendMail({ from: `${from.name} <${from.email}>`, to: input.toEmail, diff --git a/lib/build/recipe/passwordless/error.d.ts b/lib/build/recipe/passwordless/error.d.ts index 71d57623f..2eab0a85f 100644 --- a/lib/build/recipe/passwordless/error.d.ts +++ b/lib/build/recipe/passwordless/error.d.ts @@ -1,7 +1,4 @@ import STError from "../../error"; export default class SessionError extends STError { - constructor(options: { - type: "BAD_INPUT_ERROR"; - message: string; - }); + constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); } diff --git a/lib/build/recipe/passwordless/error.js b/lib/build/recipe/passwordless/error.js index 3748d17e3..852278b6d 100644 --- a/lib/build/recipe/passwordless/error.js +++ b/lib/build/recipe/passwordless/error.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); class SessionError extends error_1.default { diff --git a/lib/build/recipe/passwordless/index.d.ts b/lib/build/recipe/passwordless/index.d.ts index 94a150866..01affcbe9 100644 --- a/lib/build/recipe/passwordless/index.d.ts +++ b/lib/build/recipe/passwordless/index.d.ts @@ -1,17 +1,29 @@ import Recipe from "./recipe"; import SuperTokensError from "./error"; -import { RecipeInterface, User, APIOptions, APIInterface, TypePasswordlessEmailDeliveryInput, TypePasswordlessSmsDeliveryInput } from "./types"; +import { + RecipeInterface, + User, + APIOptions, + APIInterface, + TypePasswordlessEmailDeliveryInput, + TypePasswordlessSmsDeliveryInput, +} from "./types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static createCode(input: ({ - email: string; - } | { - phoneNumber: string; - }) & { - userInputCode?: string; - userContext?: any; - }): Promise<{ + static createCode( + input: ( + | { + email: string; + } + | { + phoneNumber: string; + } + ) & { + userInputCode?: string; + userContext?: any; + } + ): Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -25,50 +37,52 @@ export default class Wrapper { deviceId: string; userInputCode?: string; userContext?: any; - }): Promise<{ - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - }>; - static consumeCode(input: { - preAuthSessionId: string; - userInputCode: string; - deviceId: string; - userContext?: any; - } | { - preAuthSessionId: string; - linkCode: string; - userContext?: any; - }): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | { - status: "RESTART_FLOW_ERROR"; - }>; - static getUserById(input: { - userId: string; - userContext?: any; - }): Promise; - static getUserByEmail(input: { - email: string; - userContext?: any; - }): Promise; - static getUserByPhoneNumber(input: { - phoneNumber: string; - userContext?: any; - }): Promise; + }): Promise< + | { + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } + | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + } + >; + static consumeCode( + input: + | { + preAuthSessionId: string; + userInputCode: string; + deviceId: string; + userContext?: any; + } + | { + preAuthSessionId: string; + linkCode: string; + userContext?: any; + } + ): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | { + status: "RESTART_FLOW_ERROR"; + } + >; + static getUserById(input: { userId: string; userContext?: any }): Promise; + static getUserByEmail(input: { email: string; userContext?: any }): Promise; + static getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise; static updateUser(input: { userId: string; email?: string | null; @@ -77,13 +91,17 @@ export default class Wrapper { }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - static revokeAllCodes(input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }): Promise<{ + static revokeAllCodes( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ): Promise<{ status: "OK"; }>; static revokeCode(input: { @@ -92,10 +110,7 @@ export default class Wrapper { }): Promise<{ status: "OK"; }>; - static listCodesByEmail(input: { - email: string; - userContext?: any; - }): Promise; + static listCodesByEmail(input: { email: string; userContext?: any }): Promise; static listCodesByPhoneNumber(input: { phoneNumber: string; userContext?: any; @@ -108,30 +123,42 @@ export default class Wrapper { preAuthSessionId: string; userContext?: any; }): Promise; - static createMagicLink(input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }): Promise; - static signInUp(input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }): Promise<{ + static createMagicLink( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ): Promise; + static signInUp( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ): Promise<{ status: string; createdNewUser: boolean; user: User; }>; - static sendEmail(input: TypePasswordlessEmailDeliveryInput & { - userContext?: any; - }): Promise; - static sendSms(input: TypePasswordlessSmsDeliveryInput & { - userContext?: any; - }): Promise; + static sendEmail( + input: TypePasswordlessEmailDeliveryInput & { + userContext?: any; + } + ): Promise; + static sendSms( + input: TypePasswordlessSmsDeliveryInput & { + userContext?: any; + } + ): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/passwordless/index.js b/lib/build/recipe/passwordless/index.js index 2de5fc4ea..4b86a87b7 100644 --- a/lib/build/recipe/passwordless/index.js +++ b/lib/build/recipe/passwordless/index.js @@ -13,61 +13,111 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sendSms = exports.sendEmail = exports.signInUp = exports.createMagicLink = exports.revokeCode = exports.revokeAllCodes = exports.updateUser = exports.createNewCodeForDevice = exports.listCodesByPreAuthSessionId = exports.listCodesByPhoneNumber = exports.listCodesByEmail = exports.listCodesByDeviceId = exports.getUserByPhoneNumber = exports.getUserById = exports.getUserByEmail = exports.consumeCode = exports.createCode = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); const error_1 = __importDefault(require("./error")); class Wrapper { static createCode(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); } static createNewCodeForDevice(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); } static consumeCode(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); } static getUserById(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserById(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getUserById(Object.assign({ userContext: {} }, input)); } static getUserByEmail(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByEmail(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getUserByEmail(Object.assign({ userContext: {} }, input)); } static getUserByPhoneNumber(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); } static updateUser(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updateUser(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.updateUser(Object.assign({ userContext: {} }, input)); } static revokeAllCodes(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); } static revokeCode(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); } static listCodesByEmail(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); } static listCodesByPhoneNumber(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); } static listCodesByDeviceId(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); } static listCodesByPreAuthSessionId(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); } static createMagicLink(input) { return recipe_1.default.getInstanceOrThrowError().createMagicLink(Object.assign({ userContext: {} }, input)); @@ -77,12 +127,16 @@ class Wrapper { } static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default + .getInstanceOrThrowError() + .emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } static sendSms(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default + .getInstanceOrThrowError() + .smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); }); } } diff --git a/lib/build/recipe/passwordless/recipe.d.ts b/lib/build/recipe/passwordless/recipe.d.ts index 8d038dba9..ce7fedcb1 100644 --- a/lib/build/recipe/passwordless/recipe.d.ts +++ b/lib/build/recipe/passwordless/recipe.d.ts @@ -17,32 +17,52 @@ export default class Recipe extends RecipeModule { isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; smsDelivery: SmsDeliveryIngredient; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - smsDelivery: SmsDeliveryIngredient | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + smsDelivery: SmsDeliveryIngredient | undefined; + } + ); static getInstanceOrThrowError(): Recipe; static init(config: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _: NormalisedURLPath, __: HTTPMethod) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + _: NormalisedURLPath, + __: HTTPMethod + ) => Promise; handleError: (err: STError, _: BaseRequest, __: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; - createMagicLink: (input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }) => Promise; - signInUp: (input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }) => Promise<{ + createMagicLink: ( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ) => Promise; + signInUp: ( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ) => Promise<{ status: string; createdNewUser: boolean; user: import("./types").User; diff --git a/lib/build/recipe/passwordless/recipe.js b/lib/build/recipe/passwordless/recipe.js index d6e2e8d59..5f3720526 100644 --- a/lib/build/recipe/passwordless/recipe.js +++ b/lib/build/recipe/passwordless/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const error_1 = __importDefault(require("./error")); @@ -82,37 +106,35 @@ class Recipe extends recipeModule_1.default { }, ]; }; - this.handleAPIRequest = (id, req, res, _, __) => __awaiter(this, void 0, void 0, function* () { - const options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - emailDelivery: this.emailDelivery, - smsDelivery: this.smsDelivery, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.CONSUME_CODE_API) { - return yield consumeCode_1.default(this.apiImpl, options); - } - else if (id === constants_1.CREATE_CODE_API) { - return yield createCode_1.default(this.apiImpl, options); - } - else if (id === constants_1.DOES_EMAIL_EXIST_API) { - return yield emailExists_1.default(this.apiImpl, options); - } - else if (id === constants_1.DOES_PHONE_NUMBER_EXIST_API) { - return yield phoneNumberExists_1.default(this.apiImpl, options); - } - else { - return yield resendCode_1.default(this.apiImpl, options); - } - }); - this.handleError = (err, _, __) => __awaiter(this, void 0, void 0, function* () { - throw err; - }); + this.handleAPIRequest = (id, req, res, _, __) => + __awaiter(this, void 0, void 0, function* () { + const options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + emailDelivery: this.emailDelivery, + smsDelivery: this.smsDelivery, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.CONSUME_CODE_API) { + return yield consumeCode_1.default(this.apiImpl, options); + } else if (id === constants_1.CREATE_CODE_API) { + return yield createCode_1.default(this.apiImpl, options); + } else if (id === constants_1.DOES_EMAIL_EXIST_API) { + return yield emailExists_1.default(this.apiImpl, options); + } else if (id === constants_1.DOES_PHONE_NUMBER_EXIST_API) { + return yield phoneNumberExists_1.default(this.apiImpl, options); + } else { + return yield resendCode_1.default(this.apiImpl, options); + } + }); + this.handleError = (err, _, __) => + __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; @@ -120,88 +142,100 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; // helper functions below... - this.createMagicLink = (input) => __awaiter(this, void 0, void 0, function* () { - let userInputCode = this.config.getCustomUserInputCode !== undefined - ? yield this.config.getCustomUserInputCode(input.userContext) - : undefined; - const codeInfo = yield this.recipeInterfaceImpl.createCode("email" in input - ? { - email: input.email, - userInputCode, - userContext: input.userContext, - } - : { - phoneNumber: input.phoneNumber, - userInputCode, - userContext: input.userContext, - }); - const appInfo = this.getAppInfo(); - let magicLink = appInfo.websiteDomain.getAsStringDangerous() + - appInfo.websiteBasePath.getAsStringDangerous() + - "/verify" + - "?rid=" + - this.getRecipeId() + - "&preAuthSessionId=" + - codeInfo.preAuthSessionId + - "#" + - codeInfo.linkCode; - return magicLink; - }); - this.signInUp = (input) => __awaiter(this, void 0, void 0, function* () { - let codeInfo = yield this.recipeInterfaceImpl.createCode("email" in input - ? { - email: input.email, - userContext: input.userContext, - } - : { - phoneNumber: input.phoneNumber, - userContext: input.userContext, - }); - let consumeCodeResponse = yield this.recipeInterfaceImpl.consumeCode(this.config.flowType === "MAGIC_LINK" - ? { - preAuthSessionId: codeInfo.preAuthSessionId, - linkCode: codeInfo.linkCode, - userContext: input.userContext, + this.createMagicLink = (input) => + __awaiter(this, void 0, void 0, function* () { + let userInputCode = + this.config.getCustomUserInputCode !== undefined + ? yield this.config.getCustomUserInputCode(input.userContext) + : undefined; + const codeInfo = yield this.recipeInterfaceImpl.createCode( + "email" in input + ? { + email: input.email, + userInputCode, + userContext: input.userContext, + } + : { + phoneNumber: input.phoneNumber, + userInputCode, + userContext: input.userContext, + } + ); + const appInfo = this.getAppInfo(); + let magicLink = + appInfo.websiteDomain.getAsStringDangerous() + + appInfo.websiteBasePath.getAsStringDangerous() + + "/verify" + + "?rid=" + + this.getRecipeId() + + "&preAuthSessionId=" + + codeInfo.preAuthSessionId + + "#" + + codeInfo.linkCode; + return magicLink; + }); + this.signInUp = (input) => + __awaiter(this, void 0, void 0, function* () { + let codeInfo = yield this.recipeInterfaceImpl.createCode( + "email" in input + ? { + email: input.email, + userContext: input.userContext, + } + : { + phoneNumber: input.phoneNumber, + userContext: input.userContext, + } + ); + let consumeCodeResponse = yield this.recipeInterfaceImpl.consumeCode( + this.config.flowType === "MAGIC_LINK" + ? { + preAuthSessionId: codeInfo.preAuthSessionId, + linkCode: codeInfo.linkCode, + userContext: input.userContext, + } + : { + preAuthSessionId: codeInfo.preAuthSessionId, + deviceId: codeInfo.deviceId, + userInputCode: codeInfo.userInputCode, + userContext: input.userContext, + } + ); + if (consumeCodeResponse.status === "OK") { + return { + status: "OK", + createdNewUser: consumeCodeResponse.createdNewUser, + user: consumeCodeResponse.user, + }; + } else { + throw new Error("Failed to create user. Please retry"); } - : { - preAuthSessionId: codeInfo.preAuthSessionId, - deviceId: codeInfo.deviceId, - userInputCode: codeInfo.userInputCode, - userContext: input.userContext, - }); - if (consumeCodeResponse.status === "OK") { - return { - status: "OK", - createdNewUser: consumeCodeResponse.createdNewUser, - user: consumeCodeResponse.user, - }; - } - else { - throw new Error("Failed to create user. Please retry"); - } - }); + }); // helper functions... - this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo !== undefined) { - if (userInfo.email !== undefined) { + this.getEmailForUserId = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo !== undefined) { + if (userInfo.email !== undefined) { + return { + status: "OK", + email: userInfo.email, + }; + } return { - status: "OK", - email: userInfo.email, + status: "EMAIL_DOES_NOT_EXIST_ERROR", }; } return { - status: "EMAIL_DOES_NOT_EXIST_ERROR", + status: "UNKNOWN_USER_ID_ERROR", }; - } - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - }); + }); this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -241,8 +275,7 @@ class Recipe extends recipeModule_1.default { smsDelivery: undefined, }); return Recipe.instance; - } - else { + } else { throw new Error("Passwordless recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/passwordless/recipeImplementation.js b/lib/build/recipe/passwordless/recipeImplementation.js index 178734937..50296548b 100644 --- a/lib/build/recipe/passwordless/recipeImplementation.js +++ b/lib/build/recipe/passwordless/recipeImplementation.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); function getRecipeInterface(querier) { @@ -22,25 +46,37 @@ function getRecipeInterface(querier) { return { consumeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code/consume"), copyAndRemoveUserContext(input)); + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/signinup/code/consume"), + copyAndRemoveUserContext(input) + ); return response; }); }, createCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code"), copyAndRemoveUserContext(input)); + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/signinup/code"), + copyAndRemoveUserContext(input) + ); return response; }); }, createNewCodeForDevice: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code"), copyAndRemoveUserContext(input)); + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/signinup/code"), + copyAndRemoveUserContext(input) + ); return response; }); }, getUserByEmail: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/user"), + copyAndRemoveUserContext(input) + ); if (response.status === "OK") { return response.user; } @@ -49,7 +85,10 @@ function getRecipeInterface(querier) { }, getUserById: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/user"), + copyAndRemoveUserContext(input) + ); if (response.status === "OK") { return response.user; } @@ -58,7 +97,10 @@ function getRecipeInterface(querier) { }, getUserByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/user"), + copyAndRemoveUserContext(input) + ); if (response.status === "OK") { return response.user; } @@ -67,31 +109,46 @@ function getRecipeInterface(querier) { }, listCodesByDeviceId: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/signinup/codes"), + copyAndRemoveUserContext(input) + ); return response.devices.length === 1 ? response.devices[0] : undefined; }); }, listCodesByEmail: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/signinup/codes"), + copyAndRemoveUserContext(input) + ); return response.devices; }); }, listCodesByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/signinup/codes"), + copyAndRemoveUserContext(input) + ); return response.devices; }); }, listCodesByPreAuthSessionId: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/signinup/codes"), copyAndRemoveUserContext(input)); + let response = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/signinup/codes"), + copyAndRemoveUserContext(input) + ); return response.devices.length === 1 ? response.devices[0] : undefined; }); }, revokeAllCodes: function (input) { return __awaiter(this, void 0, void 0, function* () { - yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/codes/remove"), copyAndRemoveUserContext(input)); + yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/signinup/codes/remove"), + copyAndRemoveUserContext(input) + ); return { status: "OK", }; @@ -99,13 +156,19 @@ function getRecipeInterface(querier) { }, revokeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup/code/remove"), copyAndRemoveUserContext(input)); + yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/signinup/code/remove"), + copyAndRemoveUserContext(input) + ); return { status: "OK" }; }); }, updateUser: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/user"), copyAndRemoveUserContext(input)); + let response = yield querier.sendPutRequest( + new normalisedURLPath_1.default("/recipe/user"), + copyAndRemoveUserContext(input) + ); return response; }); }, diff --git a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts index cf45ff3d4..df93bfd39 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts @@ -3,14 +3,22 @@ import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/typ import { NormalisedAppinfo } from "../../../../../types"; export default class BackwardCompatibilityService implements SmsDeliveryInterface { private createAndSendCustomSms; - constructor(appInfo: NormalisedAppinfo, createAndSendCustomSms?: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise); - sendSms: (input: TypePasswordlessSmsDeliveryInput & { - userContext: any; - }) => Promise; + constructor( + appInfo: NormalisedAppinfo, + createAndSendCustomSms?: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise + ); + sendSms: ( + input: TypePasswordlessSmsDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js index 6e91fa9e4..887b67227 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.js @@ -1,120 +1,146 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); const supertokens_1 = require("../../../../../ingredients/smsdelivery/services/supertokens"); const supertokens_2 = __importDefault(require("../../../../../supertokens")); const logger_1 = require("../../../../../logger"); function defaultCreateAndSendCustomSms(_) { - return (input, _) => __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_2.default.getInstanceOrThrowError(); - let appName = supertokens.appInfo.appName; - try { - yield axios_1.default({ - method: "post", - url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, - data: { - smsInput: { - appName, - type: "PASSWORDLESS_LOGIN", - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - codeLifetime: input.codeLifetime, + return (input, _) => + __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_2.default.getInstanceOrThrowError(); + let appName = supertokens.appInfo.appName; + try { + yield axios_1.default({ + method: "post", + url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, + data: { + smsInput: { + appName, + type: "PASSWORDLESS_LOGIN", + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + codeLifetime: input.codeLifetime, + }, }, - }, - headers: { - "api-version": "0", - }, - }); - logger_1.logDebugMessage(`Passwordless login SMS sent to ${input.phoneNumber}`); - return; - } - catch (error) { - logger_1.logDebugMessage("Error sending passwordless login SMS"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } - else { - logger_1.logDebugMessage(`Error: ${err.message}`); - } - if (err.response) { - if (err.response.status !== 429) { - /** - * if the error is thrown from API, the response object - * will be of type `{err: string}` - */ - if (err.response.data.err !== undefined) { - throw Error(err.response.data.err); - } - else { - throw err; + headers: { + "api-version": "0", + }, + }); + logger_1.logDebugMessage(`Passwordless login SMS sent to ${input.phoneNumber}`); + return; + } catch (error) { + logger_1.logDebugMessage("Error sending passwordless login SMS"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + } else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + if (err.response) { + if (err.response.status !== 429) { + /** + * if the error is thrown from API, the response object + * will be of type `{err: string}` + */ + if (err.response.data.err !== undefined) { + throw Error(err.response.data.err); + } else { + throw err; + } } + } else { + throw err; } - } - else { - throw err; + } else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); + throw error; } } - else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); - throw error; - } - } - console.log("Free daily SMS quota reached. If you want to use SuperTokens to send SMS, please sign up on supertokens.com to get your SMS API key, else you can also define your own method by overriding the service. For now, we are logging it below:"); - /** - * if we do console.log(`SMS content: ${input}`); - * Output would be: - * SMS content: [object Object] - */ - /** - * JSON.stringify takes 3 inputs - * - value: usually an object or array, to be converted - * - replacer: An array of strings and numbers that acts - * as an approved list for selecting the object - * properties that will be stringified - * - space: Adds indentation, white space, and line break characters - * to the return-value JSON text to make it easier to read - * - * console.log(JSON.stringify({"a": 1, "b": 2})) - * Output: - * {"a":1,"b":2} - * - * console.log(JSON.stringify({"a": 1, "b": 2}, null, 2)) - * Output: - * { - * "a": 1, - * "b": 2 - * } - */ - console.log(`\nSMS content: ${JSON.stringify(input, null, 2)}`); - }); + console.log( + "Free daily SMS quota reached. If you want to use SuperTokens to send SMS, please sign up on supertokens.com to get your SMS API key, else you can also define your own method by overriding the service. For now, we are logging it below:" + ); + /** + * if we do console.log(`SMS content: ${input}`); + * Output would be: + * SMS content: [object Object] + */ + /** + * JSON.stringify takes 3 inputs + * - value: usually an object or array, to be converted + * - replacer: An array of strings and numbers that acts + * as an approved list for selecting the object + * properties that will be stringified + * - space: Adds indentation, white space, and line break characters + * to the return-value JSON text to make it easier to read + * + * console.log(JSON.stringify({"a": 1, "b": 2})) + * Output: + * {"a":1,"b":2} + * + * console.log(JSON.stringify({"a": 1, "b": 2}, null, 2)) + * Output: + * { + * "a": 1, + * "b": 2 + * } + */ + console.log(`\nSMS content: ${JSON.stringify(input, null, 2)}`); + }); } class BackwardCompatibilityService { constructor(appInfo, createAndSendCustomSms) { - this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.createAndSendCustomSms({ - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - preAuthSessionId: input.preAuthSessionId, - codeLifetime: input.codeLifetime, - }, input.userContext); - }); + this.sendSms = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.createAndSendCustomSms( + { + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + preAuthSessionId: input.preAuthSessionId, + codeLifetime: input.codeLifetime, + }, + input.userContext + ); + }); this.createAndSendCustomSms = createAndSendCustomSms === undefined ? defaultCreateAndSendCustomSms(appInfo) : createAndSendCustomSms; } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/index.js b/lib/build/recipe/passwordless/smsdelivery/services/index.js index c4ba9a912..f85fb8900 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SupertokensService = exports.TwilioService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. diff --git a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js index 761a672d4..712ce00bd 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -32,56 +56,60 @@ const supertokens_2 = __importDefault(require("../../../../../supertokens")); const logger_1 = require("../../../../../logger"); class SupertokensService { constructor(apiKey) { - this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_2.default.getInstanceOrThrowError(); - let appName = supertokens.appInfo.appName; - try { - yield axios_1.default({ - method: "post", - url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, - data: { - apiKey: this.apiKey, - smsInput: { - type: input.type, - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - codeLifetime: input.codeLifetime, - appName, + this.sendSms = (input) => + __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_2.default.getInstanceOrThrowError(); + let appName = supertokens.appInfo.appName; + try { + yield axios_1.default({ + method: "post", + url: supertokens_1.SUPERTOKENS_SMS_SERVICE_URL, + data: { + apiKey: this.apiKey, + smsInput: { + type: input.type, + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + codeLifetime: input.codeLifetime, + appName, + }, }, - }, - headers: { - "api-version": "0", - }, - }); - } - catch (error) { - logger_1.logDebugMessage("Error sending SMS"); - if (axios_1.default.isAxiosError(error)) { - const err = error; - if (err.response) { - logger_1.logDebugMessage(`Error status: ${err.response.status}`); - logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); - } - else { - logger_1.logDebugMessage(`Error: ${err.message}`); + headers: { + "api-version": "0", + }, + }); + } catch (error) { + logger_1.logDebugMessage("Error sending SMS"); + if (axios_1.default.isAxiosError(error)) { + const err = error; + if (err.response) { + logger_1.logDebugMessage(`Error status: ${err.response.status}`); + logger_1.logDebugMessage(`Error response: ${JSON.stringify(err.response.data)}`); + } else { + logger_1.logDebugMessage(`Error: ${err.message}`); + } + } else { + logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); } + logger_1.logDebugMessage("Logging the input below:"); + logger_1.logDebugMessage( + JSON.stringify( + { + type: input.type, + phoneNumber: input.phoneNumber, + userInputCode: input.userInputCode, + urlWithLinkCode: input.urlWithLinkCode, + codeLifetime: input.codeLifetime, + appName, + }, + null, + 2 + ) + ); + throw error; } - else { - logger_1.logDebugMessage(`Error: ${JSON.stringify(error)}`); - } - logger_1.logDebugMessage("Logging the input below:"); - logger_1.logDebugMessage(JSON.stringify({ - type: input.type, - phoneNumber: input.phoneNumber, - userInputCode: input.userInputCode, - urlWithLinkCode: input.urlWithLinkCode, - codeLifetime: input.codeLifetime, - appName, - }, null, 2)); - throw error; - } - }); + }); this.apiKey = apiKey; } } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts index 0e767ac70..00262c904 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts @@ -5,7 +5,9 @@ export default class TwilioService implements SmsDeliveryInterface; private config; constructor(config: TypeInput); - sendSms: (input: TypePasswordlessSmsDeliveryInput & { - userContext: any; - }) => Promise; + sendSms: ( + input: TypePasswordlessSmsDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js index 9ba5e119c..96a763dc0 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -32,18 +56,34 @@ const supertokens_js_override_1 = __importDefault(require("supertokens-js-overri const serviceImplementation_1 = require("./serviceImplementation"); class TwilioService { constructor(config) { - this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { - let content = yield this.serviceImpl.getContent(input); - if ("from" in this.config.twilioSettings) { - yield this.serviceImpl.sendRawSms(Object.assign(Object.assign({}, content), { userContext: input.userContext, from: this.config.twilioSettings.from })); - } - else { - yield this.serviceImpl.sendRawSms(Object.assign(Object.assign({}, content), { userContext: input.userContext, messagingServiceSid: this.config.twilioSettings.messagingServiceSid })); - } - }); + this.sendSms = (input) => + __awaiter(this, void 0, void 0, function* () { + let content = yield this.serviceImpl.getContent(input); + if ("from" in this.config.twilioSettings) { + yield this.serviceImpl.sendRawSms( + Object.assign(Object.assign({}, content), { + userContext: input.userContext, + from: this.config.twilioSettings.from, + }) + ); + } else { + yield this.serviceImpl.sendRawSms( + Object.assign(Object.assign({}, content), { + userContext: input.userContext, + messagingServiceSid: this.config.twilioSettings.messagingServiceSid, + }) + ); + } + }); this.config = twilio_1.normaliseUserInputConfig(config); - const twilioClient = twilio_2.default(config.twilioSettings.accountSid, config.twilioSettings.authToken, config.twilioSettings.opts); - let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(twilioClient)); + const twilioClient = twilio_2.default( + config.twilioSettings.accountSid, + config.twilioSettings.authToken, + config.twilioSettings.opts + ); + let builder = new supertokens_js_override_1.default( + serviceImplementation_1.getServiceImplementation(twilioClient) + ); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js index 2d6f5ce47..070ca9c75 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../../../utils"); const supertokens_1 = __importDefault(require("../../../../../supertokens")); @@ -19,11 +21,9 @@ function getPasswordlessLoginSmsBody(appName, codeLifetime, urlWithLinkCode, use let message = ""; if (urlWithLinkCode !== undefined && userInputCode !== undefined) { message += `OTP to login is ${userInputCode} for ${appName}\n\nOR click ${urlWithLinkCode} to login.\n\n`; - } - else if (urlWithLinkCode !== undefined) { + } else if (urlWithLinkCode !== undefined) { message += `Click ${urlWithLinkCode} to login to ${appName}\n\n`; - } - else { + } else { message += `OTP to login is ${userInputCode} for ${appName}\n\n`; } const humanisedCodeLifetime = utils_1.humaniseMilliseconds(codeLifetime); diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts index cd330745c..70b3c34d3 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts @@ -1,4 +1,6 @@ import { TypePasswordlessSmsDeliveryInput } from "../../../types"; import Twilio from "twilio/lib/rest/Twilio"; import { ServiceInterface } from "../../../../../ingredients/smsdelivery/services/twilio"; -export declare function getServiceImplementation(twilioClient: Twilio): ServiceInterface; +export declare function getServiceImplementation( + twilioClient: Twilio +): ServiceInterface; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js index f39b14d31..f41680526 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getServiceImplementation = void 0; const passwordlessLogin_1 = __importDefault(require("./passwordlessLogin")); @@ -38,8 +62,7 @@ function getServiceImplementation(twilioClient) { body: input.body, from: input.from, }); - } - else { + } else { yield twilioClient.messages.create({ to: input.toPhoneNumber, body: input.body, diff --git a/lib/build/recipe/passwordless/types.d.ts b/lib/build/recipe/passwordless/types.d.ts index 8f7d55864..e478f625c 100644 --- a/lib/build/recipe/passwordless/types.d.ts +++ b/lib/build/recipe/passwordless/types.d.ts @@ -1,9 +1,15 @@ import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; +import { + TypeInput as EmailDeliveryTypeInput, + TypeInputWithService as EmailDeliveryTypeInputWithService, +} from "../../ingredients/emaildelivery/types"; import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; -import { TypeInput as SmsDeliveryTypeInput, TypeInputWithService as SmsDeliveryTypeInputWithService } from "../../ingredients/smsdelivery/types"; +import { + TypeInput as SmsDeliveryTypeInput, + TypeInputWithService as SmsDeliveryTypeInputWithService, +} from "../../ingredients/smsdelivery/types"; import SmsDeliveryIngredient from "../../ingredients/smsdelivery"; import { GeneralErrorResponse, NormalisedAppinfo } from "../../types"; export declare type User = { @@ -13,95 +19,126 @@ export declare type User = { phoneNumber?: string; timeJoined: number; }; -export declare type TypeInput = ({ - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -}) & { +export declare type TypeInput = ( + | { + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } +) & { flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; emailDelivery?: EmailDeliveryTypeInput; smsDelivery?: SmsDeliveryTypeInput; getCustomUserInputCode?: (userContext: any) => Promise | string; override?: { - functions?: (originalImplementation: RecipeInterface, builder: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder: OverrideableBuilder) => APIInterface; }; }; -export declare type TypeNormalisedInput = ({ - contactMethod: "PHONE"; - validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; -} | { - contactMethod: "EMAIL"; - validateEmailAddress: (email: string) => Promise | string | undefined; -} | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress: (email: string) => Promise | string | undefined; - validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; -}) & { +export declare type TypeNormalisedInput = ( + | { + contactMethod: "PHONE"; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress: (email: string) => Promise | string | undefined; + } + | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress: (email: string) => Promise | string | undefined; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; + } +) & { flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; getCustomUserInputCode?: (userContext: any) => Promise | string; getSmsDeliveryConfig: () => SmsDeliveryTypeInputWithService; getEmailDeliveryConfig: () => EmailDeliveryTypeInputWithService; override: { - functions: (originalImplementation: RecipeInterface, builder: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - createCode: (input: ({ - email: string; - } | { - phoneNumber: string; - }) & { - userInputCode?: string; - userContext: any; - }) => Promise<{ + createCode: ( + input: ( + | { + email: string; + } + | { + phoneNumber: string; + } + ) & { + userInputCode?: string; + userContext: any; + } + ) => Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -115,50 +152,52 @@ export declare type RecipeInterface = { deviceId: string; userInputCode?: string; userContext: any; - }) => Promise<{ - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - }>; - consumeCode: (input: { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - userContext: any; - } | { - linkCode: string; - preAuthSessionId: string; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | { - status: "RESTART_FLOW_ERROR"; - }>; - getUserById: (input: { - userId: string; - userContext: any; - }) => Promise; - getUserByEmail: (input: { - email: string; - userContext: any; - }) => Promise; - getUserByPhoneNumber: (input: { - phoneNumber: string; - userContext: any; - }) => Promise; + }) => Promise< + | { + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } + | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + } + >; + consumeCode: ( + input: + | { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + userContext: any; + } + | { + linkCode: string; + preAuthSessionId: string; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | { + status: "RESTART_FLOW_ERROR"; + } + >; + getUserById: (input: { userId: string; userContext: any }) => Promise; + getUserByEmail: (input: { email: string; userContext: any }) => Promise; + getUserByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; updateUser: (input: { userId: string; email?: string | null; @@ -167,13 +206,17 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - revokeAllCodes: (input: { - email: string; - userContext: any; - } | { - phoneNumber: string; - userContext: any; - }) => Promise<{ + revokeAllCodes: ( + input: + | { + email: string; + userContext: any; + } + | { + phoneNumber: string; + userContext: any; + } + ) => Promise<{ status: "OK"; }>; revokeCode: (input: { @@ -182,18 +225,9 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; - listCodesByEmail: (input: { - email: string; - userContext: any; - }) => Promise; - listCodesByPhoneNumber: (input: { - phoneNumber: string; - userContext: any; - }) => Promise; - listCodesByDeviceId: (input: { - deviceId: string; - userContext: any; - }) => Promise; + listCodesByEmail: (input: { email: string; userContext: any }) => Promise; + listCodesByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; + listCodesByDeviceId: (input: { deviceId: string; userContext: any }) => Promise; listCodesByPreAuthSessionId: (input: { preAuthSessionId: string; userContext: any; @@ -222,103 +256,147 @@ export declare type APIOptions = { smsDelivery: SmsDeliveryIngredient; }; export declare type APIInterface = { - createCodePOST?: (input: ({ - email: string; - } | { - phoneNumber: string; - }) & { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - deviceId: string; - preAuthSessionId: string; - flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; - } | GeneralErrorResponse>; - resendCodePOST?: (input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: APIOptions; - userContext: any; - }) => Promise; - consumeCodePOST?: (input: ({ - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } | { - linkCode: string; - preAuthSessionId: string; - }) & { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | GeneralErrorResponse | { - status: "RESTART_FLOW_ERROR"; - } | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - }>; - linkAccountToExistingAccountPOST: undefined | ((input: ({ - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } | { - linkCode: string; - preAuthSessionId: string; - }) & { - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } | GeneralErrorResponse>); + createCodePOST?: ( + input: ( + | { + email: string; + } + | { + phoneNumber: string; + } + ) & { + options: APIOptions; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + deviceId: string; + preAuthSessionId: string; + flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; + } + | GeneralErrorResponse + >; + resendCodePOST?: ( + input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: APIOptions; + userContext: any; + } + ) => Promise< + | GeneralErrorResponse + | { + status: "RESTART_FLOW_ERROR" | "OK"; + } + >; + consumeCodePOST?: ( + input: ( + | { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } + | { + linkCode: string; + preAuthSessionId: string; + } + ) & { + options: APIOptions; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | GeneralErrorResponse + | { + status: "RESTART_FLOW_ERROR"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + >; + linkAccountToExistingAccountPOST: + | undefined + | (( + input: ( + | { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } + | { + linkCode: string; + preAuthSessionId: string; + } + ) & { + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } + | GeneralErrorResponse + >); emailExistsGET?: (input: { email: string; options: APIOptions; userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - } | GeneralErrorResponse>; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >; phoneNumberExistsGET?: (input: { phoneNumber: string; options: APIOptions; userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - } | GeneralErrorResponse>; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >; }; export declare type TypePasswordlessEmailDeliveryInput = { type: "PASSWORDLESS_LOGIN"; diff --git a/lib/build/recipe/passwordless/utils.d.ts b/lib/build/recipe/passwordless/utils.d.ts index 99ab887b6..9a19050d3 100644 --- a/lib/build/recipe/passwordless/utils.d.ts +++ b/lib/build/recipe/passwordless/utils.d.ts @@ -1,6 +1,10 @@ import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; import { NormalisedAppinfo } from "../../types"; -export declare function validateAndNormaliseUserInput(_: Recipe, appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + _: Recipe, + appInfo: NormalisedAppinfo, + config: TypeInput +): TypeNormalisedInput; export declare function defaultValidatePhoneNumber(value: string): Promise | string | undefined; export declare function defaultValidateEmail(value: string): Promise | string | undefined; diff --git a/lib/build/recipe/passwordless/utils.js b/lib/build/recipe/passwordless/utils.js index 82039d5f6..2bbe5e2e2 100644 --- a/lib/build/recipe/passwordless/utils.js +++ b/lib/build/recipe/passwordless/utils.js @@ -13,24 +13,34 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultValidateEmail = exports.defaultValidatePhoneNumber = exports.validateAndNormaliseUserInput = void 0; const max_1 = __importDefault(require("libphonenumber-js/max")); const backwardCompatibility_1 = __importDefault(require("./emaildelivery/services/backwardCompatibility")); const backwardCompatibility_2 = __importDefault(require("./smsdelivery/services/backwardCompatibility")); function validateAndNormaliseUserInput(_, appInfo, config) { - if (config.contactMethod !== "PHONE" && + if ( + config.contactMethod !== "PHONE" && config.contactMethod !== "EMAIL" && - config.contactMethod !== "EMAIL_OR_PHONE") { + config.contactMethod !== "EMAIL_OR_PHONE" + ) { throw new Error('Please pass one of "PHONE", "EMAIL" or "EMAIL_OR_PHONE" as the contactMethod'); } if (config.flowType === undefined) { throw new Error("Please pass flowType argument in the config"); } - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config.override + ); function getEmailDeliveryConfig() { var _a; let emailService = (_a = config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; @@ -45,7 +55,7 @@ function validateAndNormaliseUserInput(_, appInfo, config) { if (emailService === undefined) { emailService = new backwardCompatibility_1.default(appInfo, createAndSendCustomEmail); } - let emailDelivery = Object.assign(Object.assign({}, config.emailDelivery), { + let emailDelivery = Object.assign(Object.assign({}, config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -57,13 +67,15 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService }); + service: emailService, + }); return emailDelivery; } function getSmsDeliveryConfig() { var _a; let smsService = (_a = config.smsDelivery) === null || _a === void 0 ? void 0 : _a.service; - let createAndSendCustomTextMessage = config.contactMethod === "EMAIL" ? undefined : config.createAndSendCustomTextMessage; + let createAndSendCustomTextMessage = + config.contactMethod === "EMAIL" ? undefined : config.createAndSendCustomTextMessage; /** * following code is for backward compatibility. * if user has not passed emailDelivery config, we @@ -74,7 +86,7 @@ function validateAndNormaliseUserInput(_, appInfo, config) { if (smsService === undefined) { smsService = new backwardCompatibility_2.default(appInfo, createAndSendCustomTextMessage); } - let smsDelivery = Object.assign(Object.assign({}, config.smsDelivery), { + let smsDelivery = Object.assign(Object.assign({}, config.smsDelivery), { /** * if we do * let smsDelivery = { @@ -86,7 +98,8 @@ function validateAndNormaliseUserInput(_, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: smsService }); + service: smsService, + }); return smsDelivery; } if (config.contactMethod === "EMAIL") { @@ -96,30 +109,32 @@ function validateAndNormaliseUserInput(_, appInfo, config) { getSmsDeliveryConfig, flowType: config.flowType, contactMethod: "EMAIL", - validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + validateEmailAddress: + config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, getCustomUserInputCode: config.getCustomUserInputCode, }; - } - else if (config.contactMethod === "PHONE") { + } else if (config.contactMethod === "PHONE") { return { override, getEmailDeliveryConfig, getSmsDeliveryConfig, flowType: config.flowType, contactMethod: "PHONE", - validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + validatePhoneNumber: + config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; - } - else { + } else { return { override, getEmailDeliveryConfig, getSmsDeliveryConfig, flowType: config.flowType, contactMethod: "EMAIL_OR_PHONE", - validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, - validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + validateEmailAddress: + config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + validatePhoneNumber: + config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; } @@ -144,7 +159,11 @@ function defaultValidateEmail(value) { if (typeof value !== "string") { return "Development bug: Please make sure the email field is a string"; } - if (value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/) === null) { + if ( + value.match( + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ + ) === null + ) { return "Email is invalid"; } return undefined; diff --git a/lib/build/recipe/session/accessToken.d.ts b/lib/build/recipe/session/accessToken.d.ts index cc0f114c1..236137ec2 100644 --- a/lib/build/recipe/session/accessToken.d.ts +++ b/lib/build/recipe/session/accessToken.d.ts @@ -1,5 +1,9 @@ import { ParsedJWTInfo } from "./jwt"; -export declare function getInfoFromAccessToken(jwtInfo: ParsedJWTInfo, jwtSigningPublicKey: string, doAntiCsrfCheck: boolean): Promise<{ +export declare function getInfoFromAccessToken( + jwtInfo: ParsedJWTInfo, + jwtSigningPublicKey: string, + doAntiCsrfCheck: boolean +): Promise<{ sessionHandle: string; userId: string; recipeUserId: string; diff --git a/lib/build/recipe/session/accessToken.js b/lib/build/recipe/session/accessToken.js index 0647f38c1..ac9a6938b 100644 --- a/lib/build/recipe/session/accessToken.js +++ b/lib/build/recipe/session/accessToken.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sanitizeNumberInput = exports.validateAccessTokenStructure = exports.getInfoFromAccessToken = void 0; const error_1 = __importDefault(require("./error")); @@ -63,8 +87,7 @@ function getInfoFromAccessToken(jwtInfo, jwtSigningPublicKey, doAntiCsrfCheck) { timeCreated, recipeUserId, }; - } - catch (err) { + } catch (err) { throw new error_1.default({ message: "Failed to verify access token", type: error_1.default.TRY_REFRESH_TOKEN, @@ -74,13 +97,15 @@ function getInfoFromAccessToken(jwtInfo, jwtSigningPublicKey, doAntiCsrfCheck) { } exports.getInfoFromAccessToken = getInfoFromAccessToken; function validateAccessTokenStructure(payload) { - if (typeof payload.sessionHandle !== "string" || + if ( + typeof payload.sessionHandle !== "string" || typeof payload.userId !== "string" || typeof payload.recipeUserId !== "string" || typeof payload.refreshTokenHash1 !== "string" || payload.userData === undefined || typeof payload.expiryTime !== "number" || - typeof payload.timeCreated !== "number") { + typeof payload.timeCreated !== "number" + ) { // it would come here if we change the structure of the JWT. throw Error("Access token does not contain all the information. Maybe the structure has changed?"); } @@ -96,8 +121,7 @@ function sanitizeStringInput(field) { try { let result = field.trim(); return result; - } - catch (err) { } + } catch (err) {} return undefined; } function sanitizeNumberInput(field) { diff --git a/lib/build/recipe/session/api/implementation.js b/lib/build/recipe/session/api/implementation.js index fb1e54738..517833f85 100644 --- a/lib/build/recipe/session/api/implementation.js +++ b/lib/build/recipe/session/api/implementation.js @@ -1,23 +1,47 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const normalisedURLPath_1 = __importDefault(require("../../../normalisedURLPath")); const utils_2 = require("../utils"); function getAPIInterface() { return { - refreshPOST: function ({ options, userContext, }) { + refreshPOST: function ({ options, userContext }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.refreshSession({ req: options.req, @@ -26,7 +50,7 @@ function getAPIInterface() { }); }); }, - verifySession: function ({ verifySessionOptions, options, userContext, }) { + verifySession: function ({ verifySessionOptions, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let method = utils_1.normaliseHttpMethod(options.req.getMethod()); if (method === "options" || method === "trace") { @@ -40,8 +64,7 @@ function getAPIInterface() { res: options.res, userContext, }); - } - else { + } else { const session = yield options.recipeImplementation.getSession({ req: options.req, res: options.res, @@ -49,14 +72,20 @@ function getAPIInterface() { userContext, }); if (session !== undefined) { - const claimValidators = yield utils_2.getRequiredClaimValidators(session, verifySessionOptions === null || verifySessionOptions === void 0 ? void 0 : verifySessionOptions.overrideGlobalClaimValidators, userContext); + const claimValidators = yield utils_2.getRequiredClaimValidators( + session, + verifySessionOptions === null || verifySessionOptions === void 0 + ? void 0 + : verifySessionOptions.overrideGlobalClaimValidators, + userContext + ); yield session.assertClaims(claimValidators, userContext); } return session; } }); }, - signOutPOST: function ({ session, userContext, }) { + signOutPOST: function ({ session, userContext }) { return __awaiter(this, void 0, void 0, function* () { if (session !== undefined) { yield session.revokeSession(userContext); diff --git a/lib/build/recipe/session/api/refresh.js b/lib/build/recipe/session/api/refresh.js index b65d91e1b..6ae4b4a31 100644 --- a/lib/build/recipe/session/api/refresh.js +++ b/lib/build/recipe/session/api/refresh.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); @@ -30,7 +52,10 @@ function handleRefreshAPI(apiImplementation, options) { if (apiImplementation.refreshPOST === undefined) { return false; } - yield apiImplementation.refreshPOST({ options, userContext: utils_2.makeDefaultUserContextFromAPI(options.req) }); + yield apiImplementation.refreshPOST({ + options, + userContext: utils_2.makeDefaultUserContextFromAPI(options.req), + }); utils_1.send200Response(options.res, {}); return true; }); diff --git a/lib/build/recipe/session/api/signout.js b/lib/build/recipe/session/api/signout.js index 6fc07fa62..d0ca3e50c 100644 --- a/lib/build/recipe/session/api/signout.js +++ b/lib/build/recipe/session/api/signout.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("../../../utils"); diff --git a/lib/build/recipe/session/claimBaseClasses/booleanClaim.js b/lib/build/recipe/session/claimBaseClasses/booleanClaim.js index f3d21b4de..37e233d3f 100644 --- a/lib/build/recipe/session/claimBaseClasses/booleanClaim.js +++ b/lib/build/recipe/session/claimBaseClasses/booleanClaim.js @@ -5,7 +5,10 @@ const primitiveClaim_1 = require("./primitiveClaim"); class BooleanClaim extends primitiveClaim_1.PrimitiveClaim { constructor(conf) { super(conf); - this.validators = Object.assign(Object.assign({}, this.validators), { isTrue: (maxAge, id) => this.validators.hasValue(true, maxAge, id), isFalse: (maxAge, id) => this.validators.hasValue(false, maxAge, id) }); + this.validators = Object.assign(Object.assign({}, this.validators), { + isTrue: (maxAge, id) => this.validators.hasValue(true, maxAge, id), + isFalse: (maxAge, id) => this.validators.hasValue(false, maxAge, id), + }); } } exports.BooleanClaim = BooleanClaim; diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts index 2a841563b..5c70b4785 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts @@ -1,13 +1,13 @@ import { JSONPrimitive } from "../../../types"; import { SessionClaim, SessionClaimValidator } from "../types"; export declare class PrimitiveArrayClaim extends SessionClaim { - readonly fetchValue: (userId: string, recipeUserId: string, userContext: any) => Promise | T[] | undefined; + readonly fetchValue: ( + userId: string, + recipeUserId: string, + userContext: any + ) => Promise | T[] | undefined; readonly defaultMaxAgeInSeconds: number | undefined; - constructor(config: { - key: string; - fetchValue: SessionClaim["fetchValue"]; - defaultMaxAgeInSeconds?: number; - }); + constructor(config: { key: string; fetchValue: SessionClaim["fetchValue"]; defaultMaxAgeInSeconds?: number }); addToPayload_internal(payload: any, value: T[], _userContext: any): any; removeFromPayloadByMerge_internal(payload: any, _userContext?: any): any; removeFromPayload(payload: any, _userContext?: any): any; diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js index ec14d7569..1b95308b2 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js +++ b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrimitiveArrayClaim = void 0; const types_1 = require("../types"); @@ -19,154 +41,178 @@ class PrimitiveArrayClaim extends types_1.SessionClaim { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => + this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { message: "value does not exist", expectedToInclude: val, actualValue: claimVal }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - if (!claimVal.includes(val)) { - return { - isValid: false, - reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, - }; - } - return { isValid: true }; - }), + validate: (payload, ctx) => + __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { + message: "value does not exist", + expectedToInclude: val, + actualValue: claimVal, + }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + if (!claimVal.includes(val)) { + return { + isValid: false, + reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, + }; + } + return { isValid: true }; + }), }; }, excludes: (val, maxAgeInSeconds = this.defaultMaxAgeInSeconds, id) => { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => + this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { - message: "value does not exist", - expectedToNotInclude: val, - actualValue: claimVal, - }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - if (claimVal.includes(val)) { - return { - isValid: false, - reason: { message: "wrong value", expectedToNotInclude: val, actualValue: claimVal }, - }; - } - return { isValid: true }; - }), + validate: (payload, ctx) => + __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { + message: "value does not exist", + expectedToNotInclude: val, + actualValue: claimVal, + }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + if (claimVal.includes(val)) { + return { + isValid: false, + reason: { + message: "wrong value", + expectedToNotInclude: val, + actualValue: claimVal, + }, + }; + } + return { isValid: true }; + }), }; }, includesAll: (val, maxAgeInSeconds = this.defaultMaxAgeInSeconds, id) => { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => + this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { message: "value does not exist", expectedToInclude: val, actualValue: claimVal }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - const claimSet = new Set(claimVal); - const isValid = val.every((v) => claimSet.has(v)); - return isValid - ? { isValid } - : { - isValid, - reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, - }; - }), + validate: (payload, ctx) => + __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { + message: "value does not exist", + expectedToInclude: val, + actualValue: claimVal, + }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + const claimSet = new Set(claimVal); + const isValid = val.every((v) => claimSet.has(v)); + return isValid + ? { isValid } + : { + isValid, + reason: { message: "wrong value", expectedToInclude: val, actualValue: claimVal }, + }; + }), }; }, excludesAll: (val, maxAgeInSeconds = this.defaultMaxAgeInSeconds, id) => { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => + this.getValueFromPayload(payload, ctx) === undefined || // We know payload[this.id] is defined since the value is not undefined in this branch (maxAgeInSeconds !== undefined && payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { - message: "value does not exist", - expectedToNotInclude: val, - actualValue: claimVal, - }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - const claimSet = new Set(claimVal); - const isValid = val.every((v) => !claimSet.has(v)); - return isValid - ? { isValid: isValid } - : { - isValid, - reason: { message: "wrong value", expectedToNotInclude: val, actualValue: claimVal }, - }; - }), + validate: (payload, ctx) => + __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { + message: "value does not exist", + expectedToNotInclude: val, + actualValue: claimVal, + }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + const claimSet = new Set(claimVal); + const isValid = val.every((v) => !claimSet.has(v)); + return isValid + ? { isValid: isValid } + : { + isValid, + reason: { + message: "wrong value", + expectedToNotInclude: val, + actualValue: claimVal, + }, + }; + }), }; }, }; @@ -174,10 +220,12 @@ class PrimitiveArrayClaim extends types_1.SessionClaim { this.defaultMaxAgeInSeconds = config.defaultMaxAgeInSeconds; } addToPayload_internal(payload, value, _userContext) { - return Object.assign(Object.assign({}, payload), { [this.key]: { + return Object.assign(Object.assign({}, payload), { + [this.key]: { v: value, t: Date.now(), - } }); + }, + }); } removeFromPayloadByMerge_internal(payload, _userContext) { const res = Object.assign(Object.assign({}, payload), { [this.key]: null }); diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts index c51c640ac..ff14b35ca 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts @@ -1,13 +1,13 @@ import { JSONPrimitive } from "../../../types"; import { SessionClaim, SessionClaimValidator } from "../types"; export declare class PrimitiveClaim extends SessionClaim { - readonly fetchValue: (userId: string, recipeUserId: string, userContext: any) => Promise | T | undefined; + readonly fetchValue: ( + userId: string, + recipeUserId: string, + userContext: any + ) => Promise | T | undefined; readonly defaultMaxAgeInSeconds: number | undefined; - constructor(config: { - key: string; - fetchValue: SessionClaim["fetchValue"]; - defaultMaxAgeInSeconds?: number; - }); + constructor(config: { key: string; fetchValue: SessionClaim["fetchValue"]; defaultMaxAgeInSeconds?: number }); addToPayload_internal(payload: any, value: T, _userContext: any): any; removeFromPayloadByMerge_internal(payload: any, _userContext?: any): any; removeFromPayload(payload: any, _userContext?: any): any; diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js index e3abfb5cc..ff72f2b4e 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js +++ b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrimitiveClaim = void 0; const types_1 = require("../types"); @@ -19,36 +41,42 @@ class PrimitiveClaim extends types_1.SessionClaim { return { claim: this, id: id !== null && id !== void 0 ? id : this.key, - shouldRefetch: (payload, ctx) => this.getValueFromPayload(payload, ctx) === undefined || + shouldRefetch: (payload, ctx) => + this.getValueFromPayload(payload, ctx) === undefined || (maxAgeInSeconds !== undefined && // We know payload[this.id] is defined since the value is not undefined in this branch payload[this.key].t < Date.now() - maxAgeInSeconds * 1000), - validate: (payload, ctx) => __awaiter(this, void 0, void 0, function* () { - const claimVal = this.getValueFromPayload(payload, ctx); - if (claimVal === undefined) { - return { - isValid: false, - reason: { message: "value does not exist", expectedValue: val, actualValue: claimVal }, - }; - } - const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; - if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { - return { - isValid: false, - reason: { - message: "expired", - ageInSeconds, - maxAgeInSeconds, - }, - }; - } - if (claimVal !== val) { - return { - isValid: false, - reason: { message: "wrong value", expectedValue: val, actualValue: claimVal }, - }; - } - return { isValid: true }; - }), + validate: (payload, ctx) => + __awaiter(this, void 0, void 0, function* () { + const claimVal = this.getValueFromPayload(payload, ctx); + if (claimVal === undefined) { + return { + isValid: false, + reason: { + message: "value does not exist", + expectedValue: val, + actualValue: claimVal, + }, + }; + } + const ageInSeconds = (Date.now() - this.getLastRefetchTime(payload, ctx)) / 1000; + if (maxAgeInSeconds !== undefined && ageInSeconds > maxAgeInSeconds) { + return { + isValid: false, + reason: { + message: "expired", + ageInSeconds, + maxAgeInSeconds, + }, + }; + } + if (claimVal !== val) { + return { + isValid: false, + reason: { message: "wrong value", expectedValue: val, actualValue: claimVal }, + }; + } + return { isValid: true }; + }), }; }, }; @@ -56,10 +84,12 @@ class PrimitiveClaim extends types_1.SessionClaim { this.defaultMaxAgeInSeconds = config.defaultMaxAgeInSeconds; } addToPayload_internal(payload, value, _userContext) { - return Object.assign(Object.assign({}, payload), { [this.key]: { + return Object.assign(Object.assign({}, payload), { + [this.key]: { v: value, t: Date.now(), - } }); + }, + }); } removeFromPayloadByMerge_internal(payload, _userContext) { const res = Object.assign(Object.assign({}, payload), { [this.key]: null }); diff --git a/lib/build/recipe/session/claims.js b/lib/build/recipe/session/claims.js index 4a547fb2e..30fae1663 100644 --- a/lib/build/recipe/session/claims.js +++ b/lib/build/recipe/session/claims.js @@ -2,10 +2,30 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.BooleanClaim = exports.PrimitiveArrayClaim = exports.PrimitiveClaim = exports.SessionClaim = void 0; var types_1 = require("./types"); -Object.defineProperty(exports, "SessionClaim", { enumerable: true, get: function () { return types_1.SessionClaim; } }); +Object.defineProperty(exports, "SessionClaim", { + enumerable: true, + get: function () { + return types_1.SessionClaim; + }, +}); var primitiveClaim_1 = require("./claimBaseClasses/primitiveClaim"); -Object.defineProperty(exports, "PrimitiveClaim", { enumerable: true, get: function () { return primitiveClaim_1.PrimitiveClaim; } }); +Object.defineProperty(exports, "PrimitiveClaim", { + enumerable: true, + get: function () { + return primitiveClaim_1.PrimitiveClaim; + }, +}); var primitiveArrayClaim_1 = require("./claimBaseClasses/primitiveArrayClaim"); -Object.defineProperty(exports, "PrimitiveArrayClaim", { enumerable: true, get: function () { return primitiveArrayClaim_1.PrimitiveArrayClaim; } }); +Object.defineProperty(exports, "PrimitiveArrayClaim", { + enumerable: true, + get: function () { + return primitiveArrayClaim_1.PrimitiveArrayClaim; + }, +}); var booleanClaim_1 = require("./claimBaseClasses/booleanClaim"); -Object.defineProperty(exports, "BooleanClaim", { enumerable: true, get: function () { return booleanClaim_1.BooleanClaim; } }); +Object.defineProperty(exports, "BooleanClaim", { + enumerable: true, + get: function () { + return booleanClaim_1.BooleanClaim; + }, +}); diff --git a/lib/build/recipe/session/cookieAndHeaders.d.ts b/lib/build/recipe/session/cookieAndHeaders.d.ts index d83e96310..80d115180 100644 --- a/lib/build/recipe/session/cookieAndHeaders.d.ts +++ b/lib/build/recipe/session/cookieAndHeaders.d.ts @@ -1,13 +1,33 @@ import { BaseRequest, BaseResponse } from "../../framework"; import { TokenTransferMethod, TokenType, TypeNormalisedInput } from "./types"; export declare function clearSessionFromAllTokenTransferMethods(config: TypeNormalisedInput, res: BaseResponse): void; -export declare function clearSession(config: TypeNormalisedInput, res: BaseResponse, transferMethod: TokenTransferMethod): void; +export declare function clearSession( + config: TypeNormalisedInput, + res: BaseResponse, + transferMethod: TokenTransferMethod +): void; export declare function getAntiCsrfTokenFromHeaders(req: BaseRequest): string | undefined; export declare function setAntiCsrfTokenInHeaders(res: BaseResponse, antiCsrfToken: string): void; -export declare function setFrontTokenInHeaders(res: BaseResponse, userId: string, atExpiry: number, accessTokenPayload: any): void; +export declare function setFrontTokenInHeaders( + res: BaseResponse, + userId: string, + atExpiry: number, + accessTokenPayload: any +): void; export declare function getCORSAllowedHeaders(): string[]; -export declare function getToken(req: BaseRequest, tokenType: TokenType, transferMethod: TokenTransferMethod): string | undefined; -export declare function setToken(config: TypeNormalisedInput, res: BaseResponse, tokenType: TokenType, value: string, expires: number, transferMethod: TokenTransferMethod): void; +export declare function getToken( + req: BaseRequest, + tokenType: TokenType, + transferMethod: TokenTransferMethod +): string | undefined; +export declare function setToken( + config: TypeNormalisedInput, + res: BaseResponse, + tokenType: TokenType, + value: string, + expires: number, + transferMethod: TokenTransferMethod +): void; export declare function setHeader(res: BaseResponse, name: string, value: string): void; /** * @@ -20,5 +40,12 @@ export declare function setHeader(res: BaseResponse, name: string, value: string * @param expires * @param path */ -export declare function setCookie(config: TypeNormalisedInput, res: BaseResponse, name: string, value: string, expires: number, pathType: "refreshTokenPath" | "accessTokenPath"): void; +export declare function setCookie( + config: TypeNormalisedInput, + res: BaseResponse, + name: string, + value: string, + expires: number, + pathType: "refreshTokenPath" | "accessTokenPath" +): void; export declare function getAuthModeFromHeader(req: BaseRequest): string | undefined; diff --git a/lib/build/recipe/session/cookieAndHeaders.js b/lib/build/recipe/session/cookieAndHeaders.js index f86e11765..4a26d6437 100644 --- a/lib/build/recipe/session/cookieAndHeaders.js +++ b/lib/build/recipe/session/cookieAndHeaders.js @@ -95,24 +95,28 @@ function getResponseHeaderNameForTokenType(tokenType) { function getToken(req, tokenType, transferMethod) { if (transferMethod === "cookie") { return req.getCookieValue(getCookieNameFromTokenType(tokenType)); - } - else if (transferMethod === "header") { + } else if (transferMethod === "header") { const value = req.getHeaderValue(authorizationHeaderKey); if (value === undefined || !value.startsWith("Bearer ")) { return undefined; } return value.replace(/^Bearer /, "").trim(); - } - else { + } else { throw new Error("Should never happen: Unknown transferMethod: " + transferMethod); } } exports.getToken = getToken; function setToken(config, res, tokenType, value, expires, transferMethod) { if (transferMethod === "cookie") { - setCookie(config, res, getCookieNameFromTokenType(tokenType), value, expires, tokenType === "refresh" ? "refreshTokenPath" : "accessTokenPath"); - } - else if (transferMethod === "header") { + setCookie( + config, + res, + getCookieNameFromTokenType(tokenType), + value, + expires, + tokenType === "refresh" ? "refreshTokenPath" : "accessTokenPath" + ); + } else if (transferMethod === "header") { setHeader(res, getResponseHeaderNameForTokenType(tokenType), value); } } @@ -140,8 +144,7 @@ function setCookie(config, res, name, value, expires, pathType) { let path = ""; if (pathType === "refreshTokenPath") { path = config.refreshTokenPath.getAsStringDangerous(); - } - else if (pathType === "accessTokenPath") { + } else if (pathType === "accessTokenPath") { path = "/"; } let httpOnly = true; diff --git a/lib/build/recipe/session/error.d.ts b/lib/build/recipe/session/error.d.ts index 6c26bb4a9..8daee8eab 100644 --- a/lib/build/recipe/session/error.d.ts +++ b/lib/build/recipe/session/error.d.ts @@ -5,26 +5,32 @@ export default class SessionError extends STError { static TRY_REFRESH_TOKEN: "TRY_REFRESH_TOKEN"; static TOKEN_THEFT_DETECTED: "TOKEN_THEFT_DETECTED"; static INVALID_CLAIMS: "INVALID_CLAIMS"; - constructor(options: { - message: string; - type: "UNAUTHORISED"; - payload?: { - clearTokens: boolean; - }; - } | { - message: string; - type: "TRY_REFRESH_TOKEN"; - } | { - message: string; - type: "TOKEN_THEFT_DETECTED"; - payload: { - userId: string; - recipeUserId: string; - sessionHandle: string; - }; - } | { - message: string; - type: "INVALID_CLAIMS"; - payload: ClaimValidationError[]; - }); + constructor( + options: + | { + message: string; + type: "UNAUTHORISED"; + payload?: { + clearTokens: boolean; + }; + } + | { + message: string; + type: "TRY_REFRESH_TOKEN"; + } + | { + message: string; + type: "TOKEN_THEFT_DETECTED"; + payload: { + userId: string; + recipeUserId: string; + sessionHandle: string; + }; + } + | { + message: string; + type: "INVALID_CLAIMS"; + payload: ClaimValidationError[]; + } + ); } diff --git a/lib/build/recipe/session/error.js b/lib/build/recipe/session/error.js index e1440e252..24c92ef59 100644 --- a/lib/build/recipe/session/error.js +++ b/lib/build/recipe/session/error.js @@ -13,17 +13,24 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); class SessionError extends error_1.default { constructor(options) { - super(options.type === "UNAUTHORISED" && options.payload === undefined - ? Object.assign(Object.assign({}, options), { payload: { - clearTokens: true, - } }) : Object.assign({}, options)); + super( + options.type === "UNAUTHORISED" && options.payload === undefined + ? Object.assign(Object.assign({}, options), { + payload: { + clearTokens: true, + }, + }) + : Object.assign({}, options) + ); this.fromRecipe = "session"; } } diff --git a/lib/build/recipe/session/framework/awsLambda.js b/lib/build/recipe/session/framework/awsLambda.js index 63f967900..ea8086157 100644 --- a/lib/build/recipe/session/framework/awsLambda.js +++ b/lib/build/recipe/session/framework/awsLambda.js @@ -1,39 +1,63 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySession = void 0; const framework_1 = require("../../../framework/awsLambda/framework"); const supertokens_1 = __importDefault(require("../../../supertokens")); const recipe_1 = __importDefault(require("../recipe")); function verifySession(handler, verifySessionOptions) { - return (event, context, callback) => __awaiter(this, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new framework_1.AWSRequest(event); - let response = new framework_1.AWSResponse(event); - try { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - event.session = yield sessionRecipe.verifySession(verifySessionOptions, request, response); - let handlerResult = yield handler(event, context, callback); - return response.sendResponse(handlerResult); - } - catch (err) { - yield supertokens.errorHandler(err, request, response); - if (response.responseSet) { - return response.sendResponse({}); + return (event, context, callback) => + __awaiter(this, void 0, void 0, function* () { + let supertokens = supertokens_1.default.getInstanceOrThrowError(); + let request = new framework_1.AWSRequest(event); + let response = new framework_1.AWSResponse(event); + try { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + event.session = yield sessionRecipe.verifySession(verifySessionOptions, request, response); + let handlerResult = yield handler(event, context, callback); + return response.sendResponse(handlerResult); + } catch (err) { + yield supertokens.errorHandler(err, request, response); + if (response.responseSet) { + return response.sendResponse({}); + } + throw err; } - throw err; - } - }); + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/express.d.ts b/lib/build/recipe/session/framework/express.d.ts index f9242acc5..b8623860f 100644 --- a/lib/build/recipe/session/framework/express.d.ts +++ b/lib/build/recipe/session/framework/express.d.ts @@ -1,4 +1,6 @@ import type { VerifySessionOptions } from ".."; import type { SessionRequest } from "../../../framework/express/framework"; import type { NextFunction, Response } from "express"; -export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, res: Response, next: NextFunction) => Promise; +export declare function verifySession( + options?: VerifySessionOptions +): (req: SessionRequest, res: Response, next: NextFunction) => Promise; diff --git a/lib/build/recipe/session/framework/express.js b/lib/build/recipe/session/framework/express.js index 28e7be15f..94346e430 100644 --- a/lib/build/recipe/session/framework/express.js +++ b/lib/build/recipe/session/framework/express.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -31,23 +55,22 @@ const recipe_1 = __importDefault(require("../recipe")); const framework_1 = require("../../../framework/express/framework"); const supertokens_1 = __importDefault(require("../../../supertokens")); function verifySession(options) { - return (req, res, next) => __awaiter(this, void 0, void 0, function* () { - const request = new framework_1.ExpressRequest(req); - const response = new framework_1.ExpressResponse(res); - try { - const sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - req.session = yield sessionRecipe.verifySession(options, request, response); - next(); - } - catch (err) { + return (req, res, next) => + __awaiter(this, void 0, void 0, function* () { + const request = new framework_1.ExpressRequest(req); + const response = new framework_1.ExpressResponse(res); try { - const supertokens = supertokens_1.default.getInstanceOrThrowError(); - yield supertokens.errorHandler(err, request, response); - } - catch (_a) { - next(err); + const sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + req.session = yield sessionRecipe.verifySession(options, request, response); + next(); + } catch (err) { + try { + const supertokens = supertokens_1.default.getInstanceOrThrowError(); + yield supertokens.errorHandler(err, request, response); + } catch (_a) { + next(err); + } } - } - }); + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/fastify.d.ts b/lib/build/recipe/session/framework/fastify.d.ts index 4b9b31671..be858806b 100644 --- a/lib/build/recipe/session/framework/fastify.d.ts +++ b/lib/build/recipe/session/framework/fastify.d.ts @@ -1,4 +1,6 @@ import { VerifySessionOptions } from ".."; import { SessionRequest } from "../../../framework/fastify/framework"; import { FastifyReply } from "fastify"; -export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, res: FastifyReply) => Promise; +export declare function verifySession( + options?: VerifySessionOptions +): (req: SessionRequest, res: FastifyReply) => Promise; diff --git a/lib/build/recipe/session/framework/fastify.js b/lib/build/recipe/session/framework/fastify.js index 5b61ee8b2..2a361bb97 100644 --- a/lib/build/recipe/session/framework/fastify.js +++ b/lib/build/recipe/session/framework/fastify.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -31,18 +55,18 @@ const recipe_1 = __importDefault(require("../recipe")); const framework_1 = require("../../../framework/fastify/framework"); const supertokens_1 = __importDefault(require("../../../supertokens")); function verifySession(options) { - return (req, res) => __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let request = new framework_1.FastifyRequest(req); - let response = new framework_1.FastifyResponse(res); - try { - req.session = yield sessionRecipe.verifySession(options, request, response); - } - catch (err) { - const supertokens = supertokens_1.default.getInstanceOrThrowError(); - yield supertokens.errorHandler(err, request, response); - throw err; - } - }); + return (req, res) => + __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let request = new framework_1.FastifyRequest(req); + let response = new framework_1.FastifyResponse(res); + try { + req.session = yield sessionRecipe.verifySession(options, request, response); + } catch (err) { + const supertokens = supertokens_1.default.getInstanceOrThrowError(); + yield supertokens.errorHandler(err, request, response); + throw err; + } + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/hapi.d.ts b/lib/build/recipe/session/framework/hapi.d.ts index 86a67c0ff..8f00dad02 100644 --- a/lib/build/recipe/session/framework/hapi.d.ts +++ b/lib/build/recipe/session/framework/hapi.d.ts @@ -1,4 +1,6 @@ import { VerifySessionOptions } from ".."; import { ResponseToolkit } from "@hapi/hapi"; import { SessionRequest } from "../../../framework/hapi/framework"; -export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, h: ResponseToolkit) => Promise; +export declare function verifySession( + options?: VerifySessionOptions +): (req: SessionRequest, h: ResponseToolkit) => Promise; diff --git a/lib/build/recipe/session/framework/hapi.js b/lib/build/recipe/session/framework/hapi.js index 81b9665ad..369f6069a 100644 --- a/lib/build/recipe/session/framework/hapi.js +++ b/lib/build/recipe/session/framework/hapi.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -30,12 +54,13 @@ exports.verifySession = void 0; const recipe_1 = __importDefault(require("../recipe")); const framework_1 = require("../../../framework/hapi/framework"); function verifySession(options) { - return (req, h) => __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let request = new framework_1.HapiRequest(req); - let response = new framework_1.HapiResponse(h); - req.session = yield sessionRecipe.verifySession(options, request, response); - return h.continue; - }); + return (req, h) => + __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let request = new framework_1.HapiRequest(req); + let response = new framework_1.HapiResponse(h); + req.session = yield sessionRecipe.verifySession(options, request, response); + return h.continue; + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/index.js b/lib/build/recipe/session/framework/index.js index a5541f367..8aa3b653e 100644 --- a/lib/build/recipe/session/framework/index.js +++ b/lib/build/recipe/session/framework/index.js @@ -1,23 +1,40 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.awsLambda = exports.koa = exports.loopback = exports.hapi = exports.fastify = exports.express = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. diff --git a/lib/build/recipe/session/framework/koa.d.ts b/lib/build/recipe/session/framework/koa.d.ts index 11b54f3b1..e961a524b 100644 --- a/lib/build/recipe/session/framework/koa.d.ts +++ b/lib/build/recipe/session/framework/koa.d.ts @@ -1,4 +1,6 @@ import type { VerifySessionOptions } from ".."; import type { Next } from "koa"; import type { SessionContext } from "../../../framework/koa/framework"; -export declare function verifySession(options?: VerifySessionOptions): (ctx: SessionContext, next: Next) => Promise; +export declare function verifySession( + options?: VerifySessionOptions +): (ctx: SessionContext, next: Next) => Promise; diff --git a/lib/build/recipe/session/framework/koa.js b/lib/build/recipe/session/framework/koa.js index 4fa1ab279..74b51cf3c 100644 --- a/lib/build/recipe/session/framework/koa.js +++ b/lib/build/recipe/session/framework/koa.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -30,12 +54,13 @@ exports.verifySession = void 0; const recipe_1 = __importDefault(require("../recipe")); const framework_1 = require("../../../framework/koa/framework"); function verifySession(options) { - return (ctx, next) => __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let request = new framework_1.KoaRequest(ctx); - let response = new framework_1.KoaResponse(ctx); - ctx.session = yield sessionRecipe.verifySession(options, request, response); - yield next(); - }); + return (ctx, next) => + __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let request = new framework_1.KoaRequest(ctx); + let response = new framework_1.KoaResponse(ctx); + ctx.session = yield sessionRecipe.verifySession(options, request, response); + yield next(); + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/framework/loopback.js b/lib/build/recipe/session/framework/loopback.js index 9fc5f60ea..d43ae15d4 100644 --- a/lib/build/recipe/session/framework/loopback.js +++ b/lib/build/recipe/session/framework/loopback.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifySession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -30,13 +54,14 @@ exports.verifySession = void 0; const recipe_1 = __importDefault(require("../recipe")); const framework_1 = require("../../../framework/loopback/framework"); function verifySession(options) { - return (ctx, next) => __awaiter(this, void 0, void 0, function* () { - let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); - let middlewareCtx = yield ctx.get("middleware.http.context"); - let request = new framework_1.LoopbackRequest(middlewareCtx); - let response = new framework_1.LoopbackResponse(middlewareCtx); - middlewareCtx.session = yield sessionRecipe.verifySession(options, request, response); - return yield next(); - }); + return (ctx, next) => + __awaiter(this, void 0, void 0, function* () { + let sessionRecipe = recipe_1.default.getInstanceOrThrowError(); + let middlewareCtx = yield ctx.get("middleware.http.context"); + let request = new framework_1.LoopbackRequest(middlewareCtx); + let response = new framework_1.LoopbackResponse(middlewareCtx); + middlewareCtx.session = yield sessionRecipe.verifySession(options, request, response); + return yield next(); + }); } exports.verifySession = verifySession; diff --git a/lib/build/recipe/session/index.d.ts b/lib/build/recipe/session/index.d.ts index 09db79bfa..4705fd7c3 100644 --- a/lib/build/recipe/session/index.d.ts +++ b/lib/build/recipe/session/index.d.ts @@ -1,24 +1,63 @@ import SuperTokensError from "./error"; -import { VerifySessionOptions, RecipeInterface, SessionContainerInterface as SessionContainer, SessionInformation, APIInterface, APIOptions, SessionClaimValidator, SessionClaim, ClaimValidationError } from "./types"; +import { + VerifySessionOptions, + RecipeInterface, + SessionContainerInterface as SessionContainer, + SessionInformation, + APIInterface, + APIOptions, + SessionClaimValidator, + SessionClaim, + ClaimValidationError, +} from "./types"; import Recipe from "./recipe"; import { JSONObject } from "../../types"; export default class SessionWrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static createNewSession(req: any, res: any, userId: string, recipeUserId?: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise; - static validateClaimsForSessionHandle(sessionHandle: string, overrideGlobalClaimValidators?: (globalClaimValidators: SessionClaimValidator[], sessionInfo: SessionInformation, userContext: any) => Promise | SessionClaimValidator[], userContext?: any): Promise<{ - status: "SESSION_DOES_NOT_EXIST_ERROR"; - } | { - status: "OK"; - invalidClaims: ClaimValidationError[]; - }>; + static createNewSession( + req: any, + res: any, + userId: string, + recipeUserId?: string, + accessTokenPayload?: any, + sessionData?: any, + userContext?: any + ): Promise; + static validateClaimsForSessionHandle( + sessionHandle: string, + overrideGlobalClaimValidators?: ( + globalClaimValidators: SessionClaimValidator[], + sessionInfo: SessionInformation, + userContext: any + ) => Promise | SessionClaimValidator[], + userContext?: any + ): Promise< + | { + status: "SESSION_DOES_NOT_EXIST_ERROR"; + } + | { + status: "OK"; + invalidClaims: ClaimValidationError[]; + } + >; static getSession(req: any, res: any): Promise; - static getSession(req: any, res: any, options?: VerifySessionOptions & { - sessionRequired?: true; - }, userContext?: any): Promise; - static getSession(req: any, res: any, options?: VerifySessionOptions & { - sessionRequired: false; - }, userContext?: any): Promise; + static getSession( + req: any, + res: any, + options?: VerifySessionOptions & { + sessionRequired?: true; + }, + userContext?: any + ): Promise; + static getSession( + req: any, + res: any, + options?: VerifySessionOptions & { + sessionRequired: false; + }, + userContext?: any + ): Promise; static getSessionInformation(sessionHandle: string, userContext?: any): Promise; static refreshSession(req: any, res: any, userContext?: any): Promise; static revokeAllSessionsForUser(userId: string, userContext?: any): Promise; @@ -26,45 +65,85 @@ export default class SessionWrapper { static revokeSession(sessionHandle: string, userContext?: any): Promise; static revokeMultipleSessions(sessionHandles: string[], userContext?: any): Promise; static updateSessionData(sessionHandle: string, newSessionData: any, userContext?: any): Promise; - static regenerateAccessToken(accessToken: string, newAccessTokenPayload?: any, userContext?: any): Promise<{ - status: "OK"; - session: { - handle: string; - userId: string; - recipeUserId: string; - userDataInJWT: any; - }; - accessToken?: { - token: string; - expiry: number; - createdTime: number; - } | undefined; - } | undefined>; - static updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, userContext?: any): Promise; - static mergeIntoAccessTokenPayload(sessionHandle: string, accessTokenPayloadUpdate: JSONObject, userContext?: any): Promise; - static createJWT(payload?: any, validitySeconds?: number, userContext?: any): Promise<{ - status: "OK"; - jwt: string; - } | { - status: "UNSUPPORTED_ALGORITHM_ERROR"; - }>; - static getJWKS(userContext?: any): Promise<{ + static regenerateAccessToken( + accessToken: string, + newAccessTokenPayload?: any, + userContext?: any + ): Promise< + | { + status: "OK"; + session: { + handle: string; + userId: string; + recipeUserId: string; + userDataInJWT: any; + }; + accessToken?: + | { + token: string; + expiry: number; + createdTime: number; + } + | undefined; + } + | undefined + >; + static updateAccessTokenPayload( + sessionHandle: string, + newAccessTokenPayload: any, + userContext?: any + ): Promise; + static mergeIntoAccessTokenPayload( + sessionHandle: string, + accessTokenPayloadUpdate: JSONObject, + userContext?: any + ): Promise; + static createJWT( + payload?: any, + validitySeconds?: number, + userContext?: any + ): Promise< + | { + status: "OK"; + jwt: string; + } + | { + status: "UNSUPPORTED_ALGORITHM_ERROR"; + } + >; + static getJWKS( + userContext?: any + ): Promise<{ status: "OK"; keys: import("../jwt").JsonWebKey[]; }>; - static getOpenIdDiscoveryConfiguration(userContext?: any): Promise<{ + static getOpenIdDiscoveryConfiguration( + userContext?: any + ): Promise<{ status: "OK"; issuer: string; jwks_uri: string; }>; static fetchAndSetClaim(sessionHandle: string, claim: SessionClaim, userContext?: any): Promise; - static setClaimValue(sessionHandle: string, claim: SessionClaim, value: T, userContext?: any): Promise; - static getClaimValue(sessionHandle: string, claim: SessionClaim, userContext?: any): Promise<{ - status: "SESSION_DOES_NOT_EXIST_ERROR"; - } | { - status: "OK"; - value: T | undefined; - }>; + static setClaimValue( + sessionHandle: string, + claim: SessionClaim, + value: T, + userContext?: any + ): Promise; + static getClaimValue( + sessionHandle: string, + claim: SessionClaim, + userContext?: any + ): Promise< + | { + status: "SESSION_DOES_NOT_EXIST_ERROR"; + } + | { + status: "OK"; + value: T | undefined; + } + >; static removeClaim(sessionHandle: string, claim: SessionClaim, userContext?: any): Promise; } export declare let init: typeof Recipe.init; @@ -88,4 +167,12 @@ export declare let Error: typeof SuperTokensError; export declare let createJWT: typeof SessionWrapper.createJWT; export declare let getJWKS: typeof SessionWrapper.getJWKS; export declare let getOpenIdDiscoveryConfiguration: typeof SessionWrapper.getOpenIdDiscoveryConfiguration; -export type { VerifySessionOptions, RecipeInterface, SessionContainer, APIInterface, APIOptions, SessionInformation, SessionClaimValidator, }; +export type { + VerifySessionOptions, + RecipeInterface, + SessionContainer, + APIInterface, + APIOptions, + SessionInformation, + SessionClaimValidator, +}; diff --git a/lib/build/recipe/session/index.js b/lib/build/recipe/session/index.js index 4c7733709..84bddc02d 100644 --- a/lib/build/recipe/session/index.js +++ b/lib/build/recipe/session/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getOpenIdDiscoveryConfiguration = exports.getJWKS = exports.createJWT = exports.Error = exports.validateClaimsForSessionHandle = exports.removeClaim = exports.getClaimValue = exports.setClaimValue = exports.fetchAndSetClaim = exports.mergeIntoAccessTokenPayload = exports.updateAccessTokenPayload = exports.updateSessionData = exports.revokeMultipleSessions = exports.revokeSession = exports.getAllSessionHandlesForUser = exports.revokeAllSessionsForUser = exports.refreshSession = exports.getSessionInformation = exports.getSession = exports.createNewSession = exports.init = void 0; const error_1 = __importDefault(require("./error")); @@ -34,7 +58,15 @@ const supertokens_1 = __importDefault(require("../../supertokens")); const utils_1 = require("./utils"); // For Express class SessionWrapper { - static createNewSession(req, res, userId, recipeUserId, accessTokenPayload = {}, sessionData = {}, userContext = {}) { + static createNewSession( + req, + res, + userId, + recipeUserId, + accessTokenPayload = {}, + sessionData = {}, + userContext = {} + ) { return __awaiter(this, void 0, void 0, function* () { const claimsAddedByOtherRecipes = recipe_1.default.getInstanceOrThrowError().getClaimsAddedByOtherRecipes(); let finalAccessTokenPayload = accessTokenPayload; @@ -71,16 +103,19 @@ class SessionWrapper { status: "SESSION_DOES_NOT_EXIST_ERROR", }; } - const claimValidatorsAddedByOtherRecipes = recipe_1.default.getInstanceOrThrowError().getClaimValidatorsAddedByOtherRecipes(); + const claimValidatorsAddedByOtherRecipes = recipe_1.default + .getInstanceOrThrowError() + .getClaimValidatorsAddedByOtherRecipes(); const globalClaimValidators = yield recipeImpl.getGlobalClaimValidators({ userId: sessionInfo.userId, recipeUserId: sessionInfo.recipeUserId, claimValidatorsAddedByOtherRecipes, userContext, }); - const claimValidators = overrideGlobalClaimValidators !== undefined - ? yield overrideGlobalClaimValidators(globalClaimValidators, sessionInfo, userContext) - : globalClaimValidators; + const claimValidators = + overrideGlobalClaimValidators !== undefined + ? yield overrideGlobalClaimValidators(globalClaimValidators, sessionInfo, userContext) + : globalClaimValidators; let claimValidationResponse = yield recipeImpl.validateClaims({ userId: sessionInfo.userId, recipeUserId: sessionInfo.recipeUserId, @@ -89,11 +124,13 @@ class SessionWrapper { userContext, }); if (claimValidationResponse.accessTokenPayloadUpdate !== undefined) { - if (!(yield recipeImpl.mergeIntoAccessTokenPayload({ - sessionHandle, - accessTokenPayloadUpdate: claimValidationResponse.accessTokenPayloadUpdate, - userContext, - }))) { + if ( + !(yield recipeImpl.mergeIntoAccessTokenPayload({ + sessionHandle, + accessTokenPayloadUpdate: claimValidationResponse.accessTokenPayloadUpdate, + userContext, + })) + ) { return { status: "SESSION_DOES_NOT_EXIST_ERROR", }; @@ -116,7 +153,11 @@ class SessionWrapper { const recipeInterfaceImpl = recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl; const session = yield recipeInterfaceImpl.getSession({ req, res, options, userContext }); if (session !== undefined) { - const claimValidators = yield utils_1.getRequiredClaimValidators(session, options === null || options === void 0 ? void 0 : options.overrideGlobalClaimValidators, userContext); + const claimValidators = yield utils_1.getRequiredClaimValidators( + session, + options === null || options === void 0 ? void 0 : options.overrideGlobalClaimValidators, + userContext + ); yield session.assertClaims(claimValidators, userContext); } return session; @@ -138,7 +179,9 @@ class SessionWrapper { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.refreshSession({ req, res, userContext }); } static revokeAllSessionsForUser(userId, userContext = {}) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeAllSessionsForUser({ userId, userContext }); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.revokeAllSessionsForUser({ userId, userContext }); } static getAllSessionHandlesForUser(userId, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getAllSessionHandlesForUser({ @@ -147,7 +190,9 @@ class SessionWrapper { }); } static revokeSession(sessionHandle, userContext = {}) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeSession({ sessionHandle, userContext }); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.revokeSession({ sessionHandle, userContext }); } static revokeMultipleSessions(sessionHandles, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeMultipleSessions({ @@ -188,21 +233,27 @@ class SessionWrapper { if (openIdRecipe !== undefined) { return openIdRecipe.recipeImplementation.createJWT({ payload, validitySeconds, userContext }); } - throw new global.Error("createJWT cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe"); + throw new global.Error( + "createJWT cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe" + ); } static getJWKS(userContext = {}) { let openIdRecipe = recipe_1.default.getInstanceOrThrowError().openIdRecipe; if (openIdRecipe !== undefined) { return openIdRecipe.recipeImplementation.getJWKS({ userContext }); } - throw new global.Error("getJWKS cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe"); + throw new global.Error( + "getJWKS cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe" + ); } static getOpenIdDiscoveryConfiguration(userContext = {}) { let openIdRecipe = recipe_1.default.getInstanceOrThrowError().openIdRecipe; if (openIdRecipe !== undefined) { return openIdRecipe.recipeImplementation.getOpenIdDiscoveryConfiguration({ userContext }); } - throw new global.Error("getOpenIdDiscoveryConfiguration cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe"); + throw new global.Error( + "getOpenIdDiscoveryConfiguration cannot be used without enabling the JWT feature. Please set 'enableJWT: true' when initialising the Session recipe" + ); } static fetchAndSetClaim(sessionHandle, claim, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.fetchAndSetClaim({ diff --git a/lib/build/recipe/session/jwt.js b/lib/build/recipe/session/jwt.js index 9bf3dd044..d13a9c7ad 100644 --- a/lib/build/recipe/session/jwt.js +++ b/lib/build/recipe/session/jwt.js @@ -1,23 +1,40 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyJWT = exports.parseJWTWithoutSignatureVerification = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -36,16 +53,20 @@ exports.verifyJWT = exports.parseJWTWithoutSignatureVerification = void 0; */ const crypto = __importStar(require("crypto")); const HEADERS = new Set([ - Buffer.from(JSON.stringify({ - alg: "RS256", - typ: "JWT", - version: "1", - })).toString("base64"), - Buffer.from(JSON.stringify({ - alg: "RS256", - typ: "JWT", - version: "2", - })).toString("base64"), + Buffer.from( + JSON.stringify({ + alg: "RS256", + typ: "JWT", + version: "1", + }) + ).toString("base64"), + Buffer.from( + JSON.stringify({ + alg: "RS256", + typ: "JWT", + version: "2", + }) + ).toString("base64"), ]); function parseJWTWithoutSignatureVerification(jwt) { const splittedInput = jwt.split("."); @@ -71,7 +92,13 @@ function verifyJWT({ header, rawPayload, signature }, jwtSigningPublicKey) { let verifier = crypto.createVerify("sha256"); // convert the jwtSigningPublicKey into .pem format verifier.update(header + "." + rawPayload); - if (!verifier.verify("-----BEGIN PUBLIC KEY-----\n" + jwtSigningPublicKey + "\n-----END PUBLIC KEY-----", signature, "base64")) { + if ( + !verifier.verify( + "-----BEGIN PUBLIC KEY-----\n" + jwtSigningPublicKey + "\n-----END PUBLIC KEY-----", + signature, + "base64" + ) + ) { throw new Error("JWT verification failed"); } } diff --git a/lib/build/recipe/session/recipe.d.ts b/lib/build/recipe/session/recipe.d.ts index 7970908f7..bc06fe050 100644 --- a/lib/build/recipe/session/recipe.d.ts +++ b/lib/build/recipe/session/recipe.d.ts @@ -1,5 +1,13 @@ import RecipeModule from "../../recipeModule"; -import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, VerifySessionOptions, SessionClaimValidator, SessionClaim } from "./types"; +import { + TypeInput, + TypeNormalisedInput, + RecipeInterface, + APIInterface, + VerifySessionOptions, + SessionClaimValidator, + SessionClaim, +} from "./types"; import STError from "./error"; import { NormalisedAppinfo, RecipeListFunction, APIHandled, HTTPMethod } from "../../types"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -24,9 +32,19 @@ export default class SessionRecipe extends RecipeModule { addClaimValidatorFromOtherRecipe: (builder: SessionClaimValidator) => void; getClaimValidatorsAddedByOtherRecipes: () => SessionClaimValidator[]; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + path: NormalisedURLPath, + method: HTTPMethod + ) => Promise; handleError: (err: STError, request: BaseRequest, response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; - verifySession: (options: VerifySessionOptions | undefined, request: BaseRequest, response: BaseResponse) => Promise; + verifySession: ( + options: VerifySessionOptions | undefined, + request: BaseRequest, + response: BaseResponse + ) => Promise; } diff --git a/lib/build/recipe/session/recipe.js b/lib/build/recipe/session/recipe.js index efa81fb44..7798b4814 100644 --- a/lib/build/recipe/session/recipe.js +++ b/lib/build/recipe/session/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const error_1 = __importDefault(require("./error")); @@ -87,64 +111,67 @@ class SessionRecipe extends recipeModule_1.default { } return apisHandled; }; - this.handleAPIRequest = (id, req, res, path, method) => __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - req, - res, - }; - if (id === constants_1.REFRESH_API_PATH) { - return yield refresh_1.default(this.apiImpl, options); - } - else if (id === constants_1.SIGNOUT_API_PATH) { - return yield signout_1.default(this.apiImpl, options); - } - else if (this.openIdRecipe !== undefined) { - return yield this.openIdRecipe.handleAPIRequest(id, req, res, path, method); - } - else { - return false; - } - }); - this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === SessionRecipe.RECIPE_ID) { - if (err.type === error_1.default.UNAUTHORISED) { - logger_1.logDebugMessage("errorHandler: returning UNAUTHORISED"); - if (err.payload === undefined || - err.payload.clearTokens === undefined || - err.payload.clearTokens === true) { - logger_1.logDebugMessage("errorHandler: Clearing tokens because of UNAUTHORISED response"); + this.handleAPIRequest = (id, req, res, path, method) => + __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + req, + res, + }; + if (id === constants_1.REFRESH_API_PATH) { + return yield refresh_1.default(this.apiImpl, options); + } else if (id === constants_1.SIGNOUT_API_PATH) { + return yield signout_1.default(this.apiImpl, options); + } else if (this.openIdRecipe !== undefined) { + return yield this.openIdRecipe.handleAPIRequest(id, req, res, path, method); + } else { + return false; + } + }); + this.handleError = (err, request, response) => + __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === SessionRecipe.RECIPE_ID) { + if (err.type === error_1.default.UNAUTHORISED) { + logger_1.logDebugMessage("errorHandler: returning UNAUTHORISED"); + if ( + err.payload === undefined || + err.payload.clearTokens === undefined || + err.payload.clearTokens === true + ) { + logger_1.logDebugMessage("errorHandler: Clearing tokens because of UNAUTHORISED response"); + cookieAndHeaders_1.clearSessionFromAllTokenTransferMethods(this.config, response); + } + return yield this.config.errorHandlers.onUnauthorised(err.message, request, response); + } else if (err.type === error_1.default.TRY_REFRESH_TOKEN) { + logger_1.logDebugMessage("errorHandler: returning TRY_REFRESH_TOKEN"); + return yield this.config.errorHandlers.onTryRefreshToken(err.message, request, response); + } else if (err.type === error_1.default.TOKEN_THEFT_DETECTED) { + logger_1.logDebugMessage("errorHandler: returning TOKEN_THEFT_DETECTED"); + logger_1.logDebugMessage( + "errorHandler: Clearing tokens because of TOKEN_THEFT_DETECTED response" + ); cookieAndHeaders_1.clearSessionFromAllTokenTransferMethods(this.config, response); + return yield this.config.errorHandlers.onTokenTheftDetected( + err.payload.sessionHandle, + err.payload.userId, + err.payload.recipeUserId, + request, + response + ); + } else if (err.type === error_1.default.INVALID_CLAIMS) { + return yield this.config.errorHandlers.onInvalidClaim(err.payload, request, response); + } else { + throw err; } - return yield this.config.errorHandlers.onUnauthorised(err.message, request, response); - } - else if (err.type === error_1.default.TRY_REFRESH_TOKEN) { - logger_1.logDebugMessage("errorHandler: returning TRY_REFRESH_TOKEN"); - return yield this.config.errorHandlers.onTryRefreshToken(err.message, request, response); - } - else if (err.type === error_1.default.TOKEN_THEFT_DETECTED) { - logger_1.logDebugMessage("errorHandler: returning TOKEN_THEFT_DETECTED"); - logger_1.logDebugMessage("errorHandler: Clearing tokens because of TOKEN_THEFT_DETECTED response"); - cookieAndHeaders_1.clearSessionFromAllTokenTransferMethods(this.config, response); - return yield this.config.errorHandlers.onTokenTheftDetected(err.payload.sessionHandle, err.payload.userId, err.payload.recipeUserId, request, response); - } - else if (err.type === error_1.default.INVALID_CLAIMS) { - return yield this.config.errorHandlers.onInvalidClaim(err.payload, request, response); - } - else { + } else if (this.openIdRecipe !== undefined) { + return yield this.openIdRecipe.handleError(err, request, response); + } else { throw err; } - } - else if (this.openIdRecipe !== undefined) { - return yield this.openIdRecipe.handleError(err, request, response); - } - else { - throw err; - } - }); + }); this.getAllCORSHeaders = () => { let corsHeaders = [...cookieAndHeaders_1.getCORSAllowedHeaders()]; if (this.openIdRecipe !== undefined) { @@ -153,30 +180,35 @@ class SessionRecipe extends recipeModule_1.default { return corsHeaders; }; this.isErrorFromThisRecipe = (err) => { - return (error_1.default.isErrorFromSuperTokens(err) && + return ( + error_1.default.isErrorFromSuperTokens(err) && (err.fromRecipe === SessionRecipe.RECIPE_ID || - (this.openIdRecipe !== undefined && this.openIdRecipe.isErrorFromThisRecipe(err)))); + (this.openIdRecipe !== undefined && this.openIdRecipe.isErrorFromThisRecipe(err))) + ); }; - this.verifySession = (options, request, response) => __awaiter(this, void 0, void 0, function* () { - return yield this.apiImpl.verifySession({ - verifySessionOptions: options, - options: { - config: this.config, - req: request, - res: response, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - }, - userContext: utils_2.makeDefaultUserContextFromAPI(request), + this.verifySession = (options, request, response) => + __awaiter(this, void 0, void 0, function* () { + return yield this.apiImpl.verifySession({ + verifySessionOptions: options, + options: { + config: this.config, + req: request, + res: response, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + }, + userContext: utils_2.makeDefaultUserContextFromAPI(request), + }); }); - }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); logger_1.logDebugMessage("session init: antiCsrf: " + this.config.antiCsrf); logger_1.logDebugMessage("session init: cookieDomain: " + this.config.cookieDomain); logger_1.logDebugMessage("session init: cookieSameSite: " + this.config.cookieSameSite); logger_1.logDebugMessage("session init: cookieSecure: " + this.config.cookieSecure); - logger_1.logDebugMessage("session init: refreshTokenPath: " + this.config.refreshTokenPath.getAsStringDangerous()); + logger_1.logDebugMessage( + "session init: refreshTokenPath: " + this.config.refreshTokenPath.getAsStringDangerous() + ); logger_1.logDebugMessage("session init: sessionExpiredStatusCode: " + this.config.sessionExpiredStatusCode); this.isInServerlessEnv = isInServerlessEnv; if (this.config.jwt.enable === true) { @@ -184,19 +216,35 @@ class SessionRecipe extends recipeModule_1.default { issuer: this.config.jwt.issuer, override: this.config.override.openIdFeature, }); - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config, this.getAppInfo(), () => this.recipeInterfaceImpl)); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default( + querier_1.Querier.getNewInstanceOrThrowError(recipeId), + this.config, + this.getAppInfo(), + () => this.recipeInterfaceImpl + ) + ); this.recipeInterfaceImpl = builder .override((oI) => { - return with_jwt_1.default(oI, - // this.jwtRecipe is never undefined here - this.openIdRecipe.recipeImplementation, this.config); - }) + return with_jwt_1.default( + oI, + // this.jwtRecipe is never undefined here + this.openIdRecipe.recipeImplementation, + this.config + ); + }) .override(this.config.override.functions) .build(); - } - else { + } else { { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config, this.getAppInfo(), () => this.recipeInterfaceImpl)); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default( + querier_1.Querier.getNewInstanceOrThrowError(recipeId), + this.config, + this.getAppInfo(), + () => this.recipeInterfaceImpl + ) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } } @@ -216,8 +264,7 @@ class SessionRecipe extends recipeModule_1.default { if (SessionRecipe.instance === undefined) { SessionRecipe.instance = new SessionRecipe(SessionRecipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return SessionRecipe.instance; - } - else { + } else { throw new Error("Session recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/session/recipeImplementation.d.ts b/lib/build/recipe/session/recipeImplementation.d.ts index bdda2ad96..e15f04fd6 100644 --- a/lib/build/recipe/session/recipeImplementation.d.ts +++ b/lib/build/recipe/session/recipeImplementation.d.ts @@ -7,7 +7,13 @@ export declare class HandshakeInfo { accessTokenValidity: number; refreshTokenValidity: number; private rawJwtSigningPublicKeyList; - constructor(antiCsrf: AntiCsrfType, accessTokenBlacklistingEnabled: boolean, accessTokenValidity: number, refreshTokenValidity: number, rawJwtSigningPublicKeyList: KeyInfo[]); + constructor( + antiCsrf: AntiCsrfType, + accessTokenBlacklistingEnabled: boolean, + accessTokenValidity: number, + refreshTokenValidity: number, + rawJwtSigningPublicKeyList: KeyInfo[] + ); setJwtSigningPublicKeyList(updatedList: KeyInfo[]): void; getJwtSigningPublicKeyList(): KeyInfo[]; clone(): HandshakeInfo; @@ -20,4 +26,9 @@ export declare type Helpers = { appInfo: NormalisedAppinfo; getRecipeImpl: () => RecipeInterface; }; -export default function getRecipeInterface(querier: Querier, config: TypeNormalisedInput, appInfo: NormalisedAppinfo, getRecipeImplAfterOverrides: () => RecipeInterface): RecipeInterface; +export default function getRecipeInterface( + querier: Querier, + config: TypeNormalisedInput, + appInfo: NormalisedAppinfo, + getRecipeImplAfterOverrides: () => RecipeInterface +): RecipeInterface; diff --git a/lib/build/recipe/session/recipeImplementation.js b/lib/build/recipe/session/recipeImplementation.js index 3e0c09cea..32d708e40 100644 --- a/lib/build/recipe/session/recipeImplementation.js +++ b/lib/build/recipe/session/recipeImplementation.js @@ -1,35 +1,76 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HandshakeInfo = void 0; const SessionFunctions = __importStar(require("./sessionFunctions")); @@ -45,7 +86,13 @@ const constants_1 = require("./constants"); const jwt_1 = require("./jwt"); const accessToken_1 = require("./accessToken"); class HandshakeInfo { - constructor(antiCsrf, accessTokenBlacklistingEnabled, accessTokenValidity, refreshTokenValidity, rawJwtSigningPublicKeyList) { + constructor( + antiCsrf, + accessTokenBlacklistingEnabled, + accessTokenValidity, + refreshTokenValidity, + rawJwtSigningPublicKeyList + ) { this.antiCsrf = antiCsrf; this.accessTokenBlacklistingEnabled = accessTokenBlacklistingEnabled; this.accessTokenValidity = accessTokenValidity; @@ -59,7 +106,13 @@ class HandshakeInfo { return this.rawJwtSigningPublicKeyList.filter((key) => key.expiryTime > Date.now()); } clone() { - return new HandshakeInfo(this.antiCsrf, this.accessTokenBlacklistingEnabled, this.accessTokenValidity, this.refreshTokenValidity, this.rawJwtSigningPublicKeyList); + return new HandshakeInfo( + this.antiCsrf, + this.accessTokenBlacklistingEnabled, + this.accessTokenValidity, + this.refreshTokenValidity, + this.rawJwtSigningPublicKeyList + ); } } exports.HandshakeInfo = HandshakeInfo; @@ -69,12 +122,28 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride let handshakeInfo; function getHandshakeInfo(forceRefetch = false) { return __awaiter(this, void 0, void 0, function* () { - if (handshakeInfo === undefined || handshakeInfo.getJwtSigningPublicKeyList().length === 0 || forceRefetch) { + if ( + handshakeInfo === undefined || + handshakeInfo.getJwtSigningPublicKeyList().length === 0 || + forceRefetch + ) { let antiCsrf = config.antiCsrf; - processState_1.ProcessState.getInstance().addState(processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_HANDSHAKE_INFO); + processState_1.ProcessState.getInstance().addState( + processState_1.PROCESS_STATE.CALLING_SERVICE_IN_GET_HANDSHAKE_INFO + ); let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/handshake"), {}); - handshakeInfo = new HandshakeInfo(antiCsrf, response.accessTokenBlacklistingEnabled, response.accessTokenValidity, response.refreshTokenValidity, response.jwtSigningPublicKeyList); - updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); + handshakeInfo = new HandshakeInfo( + antiCsrf, + response.accessTokenBlacklistingEnabled, + response.accessTokenValidity, + response.refreshTokenValidity, + response.jwtSigningPublicKeyList + ); + updateJwtSigningPublicKeyInfo( + response.jwtSigningPublicKeyList, + response.jwtSigningPublicKey, + response.jwtSigningPublicKeyExpiryTime + ); } return handshakeInfo; }); @@ -89,34 +158,72 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride } } let obj = { - createNewSession: function ({ req, res, userId, recipeUserId, accessTokenPayload = {}, sessionData = {}, userContext, }) { + createNewSession: function ({ + req, + res, + userId, + recipeUserId, + accessTokenPayload = {}, + sessionData = {}, + userContext, + }) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("createNewSession: Started"); - let outputTransferMethod = config.getTokenTransferMethod({ req, forCreateNewSession: true, userContext }); + let outputTransferMethod = config.getTokenTransferMethod({ + req, + forCreateNewSession: true, + userContext, + }); if (outputTransferMethod === "any") { outputTransferMethod = "header"; } logger_1.logDebugMessage("createNewSession: using transfer method " + outputTransferMethod); - if (outputTransferMethod === "cookie" && + if ( + outputTransferMethod === "cookie" && helpers.config.cookieSameSite === "none" && !helpers.config.cookieSecure && - !((helpers.appInfo.topLevelAPIDomain === "localhost" || - utils_2.isAnIpAddress(helpers.appInfo.topLevelAPIDomain)) && + !( + (helpers.appInfo.topLevelAPIDomain === "localhost" || + utils_2.isAnIpAddress(helpers.appInfo.topLevelAPIDomain)) && (helpers.appInfo.topLevelWebsiteDomain === "localhost" || - utils_2.isAnIpAddress(helpers.appInfo.topLevelWebsiteDomain)))) { + utils_2.isAnIpAddress(helpers.appInfo.topLevelWebsiteDomain)) + ) + ) { // We can allow insecure cookie when both website & API domain are localhost or an IP // When either of them is a different domain, API domain needs to have https and a secure cookie to work - throw new Error("Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false."); + throw new Error( + "Since your API and website domain are different, for sessions to work, please use https on your apiDomain and dont set cookieSecure to false." + ); } const disableAntiCSRF = outputTransferMethod === "header"; - let response = yield SessionFunctions.createNewSession(helpers, userId, disableAntiCSRF, recipeUserId, accessTokenPayload, sessionData); + let response = yield SessionFunctions.createNewSession( + helpers, + userId, + disableAntiCSRF, + recipeUserId, + accessTokenPayload, + sessionData + ); for (const transferMethod of constants_1.availableTokenTransferMethods) { - if (transferMethod !== outputTransferMethod && cookieAndHeaders_1.getToken(req, "access", transferMethod) !== undefined) { + if ( + transferMethod !== outputTransferMethod && + cookieAndHeaders_1.getToken(req, "access", transferMethod) !== undefined + ) { cookieAndHeaders_1.clearSession(config, res, transferMethod); } } utils_1.attachTokensToResponse(config, res, response, outputTransferMethod); - return new sessionClass_1.default(helpers, response.accessToken.token, response.session.handle, response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, res, req, outputTransferMethod); + return new sessionClass_1.default( + helpers, + response.accessToken.token, + response.session.handle, + response.session.userId, + response.session.recipeUserId, + response.session.userDataInJWT, + res, + req, + outputTransferMethod + ); }); }, getGlobalClaimValidators: function (input) { @@ -127,7 +234,7 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride /* In all cases if sIdRefreshToken token exists (so it's a legacy session) we return TRY_REFRESH_TOKEN. The refresh endpoint will clear this cookie and try to upgrade the session. Check https://supertokens.com/docs/contribute/decisions/session/0007 for further details and a table of expected behaviours */ - getSession: function ({ req, res, options, userContext, }) { + getSession: function ({ req, res, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("getSession: Started"); // This token isn't handled by getToken to limit the scope of this legacy/migration code @@ -138,7 +245,8 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride type: error_1.default.TRY_REFRESH_TOKEN, }); } - const sessionOptional = (options === null || options === void 0 ? void 0 : options.sessionRequired) === false; + const sessionOptional = + (options === null || options === void 0 ? void 0 : options.sessionRequired) === false; logger_1.logDebugMessage("getSession: optional validation: " + sessionOptional); const accessTokens = {}; // We check all token transfer methods for available access tokens @@ -150,9 +258,10 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride accessToken_1.validateAccessTokenStructure(info.payload); logger_1.logDebugMessage("getSession: got access token from " + transferMethod); accessTokens[transferMethod] = info; - } - catch (_a) { - logger_1.logDebugMessage(`getSession: ignoring token in ${transferMethod}, because it doesn't match our access token structure`); + } catch (_a) { + logger_1.logDebugMessage( + `getSession: ignoring token in ${transferMethod}, because it doesn't match our access token structure` + ); } } } @@ -163,28 +272,33 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride }); let requestTransferMethod; let accessToken; - if ((allowedTransferMethod === "any" || allowedTransferMethod === "header") && - accessTokens["header"] !== undefined) { + if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "header") && + accessTokens["header"] !== undefined + ) { logger_1.logDebugMessage("getSession: using header transfer method"); requestTransferMethod = "header"; accessToken = accessTokens["header"]; - } - else if ((allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && - accessTokens["cookie"] !== undefined) { + } else if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && + accessTokens["cookie"] !== undefined + ) { logger_1.logDebugMessage("getSession: using cookie transfer method"); requestTransferMethod = "cookie"; accessToken = accessTokens["cookie"]; - } - else { + } else { if (sessionOptional) { - logger_1.logDebugMessage("getSession: returning undefined because accessToken is undefined and sessionRequired is false"); + logger_1.logDebugMessage( + "getSession: returning undefined because accessToken is undefined and sessionRequired is false" + ); // there is no session that exists here, and the user wants session verification // to be optional. So we return undefined. return undefined; } logger_1.logDebugMessage("getSession: UNAUTHORISED because accessToken in request is undefined"); throw new error_1.default({ - message: "Session does not exist. Are you sending the session tokens in the request with the appropriate token transfer method?", + message: + "Session does not exist. Are you sending the session tokens in the request with the appropriate token transfer method?", type: error_1.default.UNAUTHORISED, payload: { // we do not clear the session here because of a @@ -202,20 +316,47 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride doAntiCsrfCheck = false; } logger_1.logDebugMessage("getSession: Value of doAntiCsrfCheck is: " + doAntiCsrfCheck); - let response = yield SessionFunctions.getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, utils_2.getRidFromHeader(req) !== undefined); + let response = yield SessionFunctions.getSession( + helpers, + accessToken, + antiCsrfToken, + doAntiCsrfCheck, + utils_2.getRidFromHeader(req) !== undefined + ); let accessTokenString = accessToken.rawTokenString; if (response.accessToken !== undefined) { - cookieAndHeaders_1.setFrontTokenInHeaders(res, response.session.userId, response.accessToken.expiry, response.session.userDataInJWT); - cookieAndHeaders_1.setToken(config, res, "access", response.accessToken.token, - // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. - // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. - // Even if the token is expired the presence of the token indicates that the user could have a valid refresh - // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. - Date.now() + 3153600000000, requestTransferMethod); + cookieAndHeaders_1.setFrontTokenInHeaders( + res, + response.session.userId, + response.accessToken.expiry, + response.session.userDataInJWT + ); + cookieAndHeaders_1.setToken( + config, + res, + "access", + response.accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, + requestTransferMethod + ); accessTokenString = response.accessToken.token; } logger_1.logDebugMessage("getSession: Success!"); - const session = new sessionClass_1.default(helpers, accessTokenString, response.session.handle, response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, res, req, requestTransferMethod); + const session = new sessionClass_1.default( + helpers, + accessTokenString, + response.session.handle, + response.session.userId, + response.session.recipeUserId, + response.session.userDataInJWT, + res, + req, + requestTransferMethod + ); return session; }); }, @@ -225,27 +366,46 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride let accessTokenPayloadUpdate = undefined; const origSessionClaimPayloadJSON = JSON.stringify(accessTokenPayload); for (const validator of input.claimValidators) { - logger_1.logDebugMessage("updateClaimsInPayloadIfNeeded checking shouldRefetch for " + validator.id); - if ("claim" in validator && (yield validator.shouldRefetch(accessTokenPayload, input.userContext))) { + logger_1.logDebugMessage( + "updateClaimsInPayloadIfNeeded checking shouldRefetch for " + validator.id + ); + if ( + "claim" in validator && + (yield validator.shouldRefetch(accessTokenPayload, input.userContext)) + ) { logger_1.logDebugMessage("updateClaimsInPayloadIfNeeded refetching " + validator.id); - const value = yield validator.claim.fetchValue(input.userId, input.recipeUserId, input.userContext); - logger_1.logDebugMessage("updateClaimsInPayloadIfNeeded " + validator.id + " refetch result " + JSON.stringify(value)); + const value = yield validator.claim.fetchValue( + input.userId, + input.recipeUserId, + input.userContext + ); + logger_1.logDebugMessage( + "updateClaimsInPayloadIfNeeded " + validator.id + " refetch result " + JSON.stringify(value) + ); if (value !== undefined) { - accessTokenPayload = validator.claim.addToPayload_internal(accessTokenPayload, value, input.userContext); + accessTokenPayload = validator.claim.addToPayload_internal( + accessTokenPayload, + value, + input.userContext + ); } } } if (JSON.stringify(accessTokenPayload) !== origSessionClaimPayloadJSON) { accessTokenPayloadUpdate = accessTokenPayload; } - const invalidClaims = yield utils_1.validateClaimsInPayload(input.claimValidators, accessTokenPayload, input.userContext); + const invalidClaims = yield utils_1.validateClaimsInPayload( + input.claimValidators, + accessTokenPayload, + input.userContext + ); return { invalidClaims, accessTokenPayloadUpdate, }; }); }, - getSessionInformation: function ({ sessionHandle, }) { + getSessionInformation: function ({ sessionHandle }) { return __awaiter(this, void 0, void 0, function* () { return SessionFunctions.getSessionInformation(helpers, sessionHandle); }); @@ -274,25 +434,38 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride logger_1.logDebugMessage("refreshSession: getTokenTransferMethod returned " + allowedTransferMethod); let requestTransferMethod; let refreshToken; - if ((allowedTransferMethod === "any" || allowedTransferMethod === "header") && - refreshTokens["header"] !== undefined) { + if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "header") && + refreshTokens["header"] !== undefined + ) { logger_1.logDebugMessage("refreshSession: using header transfer method"); requestTransferMethod = "header"; refreshToken = refreshTokens["header"]; - } - else if ((allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && - refreshTokens["cookie"]) { + } else if ( + (allowedTransferMethod === "any" || allowedTransferMethod === "cookie") && + refreshTokens["cookie"] + ) { logger_1.logDebugMessage("refreshSession: using cookie transfer method"); requestTransferMethod = "cookie"; refreshToken = refreshTokens["cookie"]; - } - else { + } else { // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { - logger_1.logDebugMessage("refreshSession: cleared legacy id refresh token because refresh token was not found"); - cookieAndHeaders_1.setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + logger_1.logDebugMessage( + "refreshSession: cleared legacy id refresh token because refresh token was not found" + ); + cookieAndHeaders_1.setCookie( + config, + res, + LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, + "", + 0, + "accessTokenPath" + ); } - logger_1.logDebugMessage("refreshSession: UNAUTHORISED because refresh token in request is undefined"); + logger_1.logDebugMessage( + "refreshSession: UNAUTHORISED because refresh token in request is undefined" + ); throw new error_1.default({ message: "Refresh token not found. Are you sending the refresh token in the request?", payload: { @@ -303,8 +476,16 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride } try { let antiCsrfToken = cookieAndHeaders_1.getAntiCsrfTokenFromHeaders(req); - let response = yield SessionFunctions.refreshSession(helpers, refreshToken, antiCsrfToken, utils_2.getRidFromHeader(req) !== undefined, requestTransferMethod); - logger_1.logDebugMessage("refreshSession: Attaching refreshed session info as " + requestTransferMethod); + let response = yield SessionFunctions.refreshSession( + helpers, + refreshToken, + antiCsrfToken, + utils_2.getRidFromHeader(req) !== undefined, + requestTransferMethod + ); + logger_1.logDebugMessage( + "refreshSession: Attaching refreshed session info as " + requestTransferMethod + ); // We clear the tokens in all token transfer methods we are not going to overwrite for (const transferMethod of constants_1.availableTokenTransferMethods) { if (transferMethod !== requestTransferMethod && refreshTokens[transferMethod] !== undefined) { @@ -315,17 +496,44 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride logger_1.logDebugMessage("refreshSession: Success!"); // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { - logger_1.logDebugMessage("refreshSession: cleared legacy id refresh token after successful refresh"); - cookieAndHeaders_1.setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + logger_1.logDebugMessage( + "refreshSession: cleared legacy id refresh token after successful refresh" + ); + cookieAndHeaders_1.setCookie( + config, + res, + LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, + "", + 0, + "accessTokenPath" + ); } - return new sessionClass_1.default(helpers, response.accessToken.token, response.session.handle, response.session.userId, response.session.recipeUserId, response.session.userDataInJWT, res, req, requestTransferMethod); - } - catch (err) { + return new sessionClass_1.default( + helpers, + response.accessToken.token, + response.session.handle, + response.session.userId, + response.session.recipeUserId, + response.session.userDataInJWT, + res, + req, + requestTransferMethod + ); + } catch (err) { if (err.type === error_1.default.TOKEN_THEFT_DETECTED || err.payload.clearTokens) { // This token isn't handled by getToken/setToken to limit the scope of this legacy/migration code if (req.getCookieValue(LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME) !== undefined) { - logger_1.logDebugMessage("refreshSession: cleared legacy id refresh token because refresh is clearing other tokens"); - cookieAndHeaders_1.setCookie(config, res, LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, "", 0, "accessTokenPath"); + logger_1.logDebugMessage( + "refreshSession: cleared legacy id refresh token because refresh is clearing other tokens" + ); + cookieAndHeaders_1.setCookie( + config, + res, + LEGACY_ID_REFRESH_TOKEN_COOKIE_NAME, + "", + 0, + "accessTokenPath" + ); } } throw err; @@ -334,13 +542,17 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride }, regenerateAccessToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - let newAccessTokenPayload = input.newAccessTokenPayload === null || input.newAccessTokenPayload === undefined - ? {} - : input.newAccessTokenPayload; - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/regenerate"), { - accessToken: input.accessToken, - userDataInJWT: newAccessTokenPayload, - }); + let newAccessTokenPayload = + input.newAccessTokenPayload === null || input.newAccessTokenPayload === undefined + ? {} + : input.newAccessTokenPayload; + let response = yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/session/regenerate"), + { + accessToken: input.accessToken, + userDataInJWT: newAccessTokenPayload, + } + ); if (response.status === "UNAUTHORISED") { return undefined; } @@ -359,19 +571,22 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride revokeMultipleSessions: function ({ sessionHandles }) { return SessionFunctions.revokeMultipleSessions(helpers, sessionHandles); }, - updateSessionData: function ({ sessionHandle, newSessionData, }) { + updateSessionData: function ({ sessionHandle, newSessionData }) { return SessionFunctions.updateSessionData(helpers, sessionHandle, newSessionData); }, - updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, }) { + updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload }) { return SessionFunctions.updateAccessTokenPayload(helpers, sessionHandle, newAccessTokenPayload); }, - mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext, }) { + mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext }) { return __awaiter(this, void 0, void 0, function* () { const sessionInfo = yield this.getSessionInformation({ sessionHandle, userContext }); if (sessionInfo === undefined) { return false; } - const newAccessTokenPayload = Object.assign(Object.assign({}, sessionInfo.accessTokenPayload), accessTokenPayloadUpdate); + const newAccessTokenPayload = Object.assign( + Object.assign({}, sessionInfo.accessTokenPayload), + accessTokenPayloadUpdate + ); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete newAccessTokenPayload[key]; @@ -399,7 +614,11 @@ function getRecipeInterface(querier, config, appInfo, getRecipeImplAfterOverride if (sessionInfo === undefined) { return false; } - const accessTokenPayloadUpdate = yield input.claim.build(sessionInfo.userId, sessionInfo.recipeUserId, input.userContext); + const accessTokenPayloadUpdate = yield input.claim.build( + sessionInfo.userId, + sessionInfo.recipeUserId, + input.userContext + ); return this.mergeIntoAccessTokenPayload({ sessionHandle: input.sessionHandle, accessTokenPayloadUpdate, diff --git a/lib/build/recipe/session/sessionClass.d.ts b/lib/build/recipe/session/sessionClass.d.ts index 5961a31fb..cf93574b3 100644 --- a/lib/build/recipe/session/sessionClass.d.ts +++ b/lib/build/recipe/session/sessionClass.d.ts @@ -11,7 +11,17 @@ export default class Session implements SessionContainerInterface { protected res: BaseResponse; protected readonly req: BaseRequest; protected readonly transferMethod: TokenTransferMethod; - constructor(helpers: Helpers, accessToken: string, sessionHandle: string, userId: string, recipeUserId: string, userDataInAccessToken: any, res: BaseResponse, req: BaseRequest, transferMethod: TokenTransferMethod); + constructor( + helpers: Helpers, + accessToken: string, + sessionHandle: string, + userId: string, + recipeUserId: string, + userDataInAccessToken: any, + res: BaseResponse, + req: BaseRequest, + transferMethod: TokenTransferMethod + ); getRecipeUserId(_userContext?: any): string; revokeSession(userContext?: any): Promise; getSessionData(userContext?: any): Promise; diff --git a/lib/build/recipe/session/sessionClass.js b/lib/build/recipe/session/sessionClass.js index 46ed8a70b..0b5182995 100644 --- a/lib/build/recipe/session/sessionClass.js +++ b/lib/build/recipe/session/sessionClass.js @@ -1,21 +1,55 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const cookieAndHeaders_1 = require("./cookieAndHeaders"); const error_1 = __importDefault(require("./error")); class Session { - constructor(helpers, accessToken, sessionHandle, userId, recipeUserId, userDataInAccessToken, res, req, transferMethod) { + constructor( + helpers, + accessToken, + sessionHandle, + userId, + recipeUserId, + userDataInAccessToken, + res, + req, + transferMethod + ) { this.helpers = helpers; this.accessToken = accessToken; this.sessionHandle = sessionHandle; @@ -61,11 +95,13 @@ class Session { } updateSessionData(newSessionData, userContext) { return __awaiter(this, void 0, void 0, function* () { - if (!(yield this.helpers.getRecipeImpl().updateSessionData({ - sessionHandle: this.sessionHandle, - newSessionData, - userContext: userContext === undefined ? {} : userContext, - }))) { + if ( + !(yield this.helpers.getRecipeImpl().updateSessionData({ + sessionHandle: this.sessionHandle, + newSessionData, + userContext: userContext === undefined ? {} : userContext, + })) + ) { throw new error_1.default({ message: "Session does not exist anymore", type: error_1.default.UNAUTHORISED, @@ -88,7 +124,10 @@ class Session { // Any update to this function should also be reflected in the respective JWT version mergeIntoAccessTokenPayload(accessTokenPayloadUpdate, userContext) { return __awaiter(this, void 0, void 0, function* () { - const updatedPayload = Object.assign(Object.assign({}, this.getAccessTokenPayload(userContext)), accessTokenPayloadUpdate); + const updatedPayload = Object.assign( + Object.assign({}, this.getAccessTokenPayload(userContext)), + accessTokenPayloadUpdate + ); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete updatedPayload[key]; @@ -152,7 +191,11 @@ class Session { // Any update to this function should also be reflected in the respective JWT version fetchAndSetClaim(claim, userContext) { return __awaiter(this, void 0, void 0, function* () { - const update = yield claim.build(this.getUserId(userContext), this.getRecipeUserId(userContext), userContext); + const update = yield claim.build( + this.getUserId(userContext), + this.getRecipeUserId(userContext), + userContext + ); return this.mergeIntoAccessTokenPayload(update, userContext); }); } @@ -191,13 +234,24 @@ class Session { this.userDataInAccessToken = response.session.userDataInJWT; if (response.accessToken !== undefined) { this.accessToken = response.accessToken.token; - cookieAndHeaders_1.setFrontTokenInHeaders(this.res, response.session.userId, response.accessToken.expiry, response.session.userDataInJWT); - cookieAndHeaders_1.setToken(this.helpers.config, this.res, "access", response.accessToken.token, - // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. - // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. - // Even if the token is expired the presence of the token indicates that the user could have a valid refresh - // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. - Date.now() + 3153600000000, this.transferMethod); + cookieAndHeaders_1.setFrontTokenInHeaders( + this.res, + response.session.userId, + response.accessToken.expiry, + response.session.userDataInJWT + ); + cookieAndHeaders_1.setToken( + this.helpers.config, + this.res, + "access", + response.accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, + this.transferMethod + ); } }); } diff --git a/lib/build/recipe/session/sessionFunctions.d.ts b/lib/build/recipe/session/sessionFunctions.d.ts index 25363ed0d..fef7d65bf 100644 --- a/lib/build/recipe/session/sessionFunctions.d.ts +++ b/lib/build/recipe/session/sessionFunctions.d.ts @@ -4,11 +4,24 @@ import { Helpers } from "./recipeImplementation"; /** * @description call this to "login" a user. */ -export declare function createNewSession(helpers: Helpers, userId: string, disableAntiCsrf: boolean, recipeUserId?: string, accessTokenPayload?: any, sessionData?: any): Promise; +export declare function createNewSession( + helpers: Helpers, + userId: string, + disableAntiCsrf: boolean, + recipeUserId?: string, + accessTokenPayload?: any, + sessionData?: any +): Promise; /** * @description authenticates a session. To be used in APIs that require authentication */ -export declare function getSession(helpers: Helpers, parsedAccessToken: ParsedJWTInfo, antiCsrfToken: string | undefined, doAntiCsrfCheck: boolean, containsCustomHeader: boolean): Promise<{ +export declare function getSession( + helpers: Helpers, + parsedAccessToken: ParsedJWTInfo, + antiCsrfToken: string | undefined, + doAntiCsrfCheck: boolean, + containsCustomHeader: boolean +): Promise<{ session: { handle: string; userId: string; @@ -25,12 +38,21 @@ export declare function getSession(helpers: Helpers, parsedAccessToken: ParsedJW * @description Retrieves session information from storage for a given session handle * @returns session data stored in the database, including userData and access token payload, or undefined if sessionHandle is invalid */ -export declare function getSessionInformation(helpers: Helpers, sessionHandle: string): Promise; +export declare function getSessionInformation( + helpers: Helpers, + sessionHandle: string +): Promise; /** * @description generates new access and refresh tokens for a given refresh token. Called when client's access token has expired. * @sideEffects calls onTokenTheftDetection if token theft is detected. */ -export declare function refreshSession(helpers: Helpers, refreshToken: string, antiCsrfToken: string | undefined, containsCustomHeader: boolean, transferMethod: TokenTransferMethod): Promise; +export declare function refreshSession( + helpers: Helpers, + refreshToken: string, + antiCsrfToken: string | undefined, + containsCustomHeader: boolean, + transferMethod: TokenTransferMethod +): Promise; /** * @description deletes session info of a user from db. This only invalidates the refresh token. Not the access token. * Access tokens cannot be immediately invalidated. Unless we add a blacklisting method. Or changed the private key to sign them. @@ -53,5 +75,13 @@ export declare function revokeMultipleSessions(helpers: Helpers, sessionHandles: /** * @description: It provides no locking mechanism in case other processes are updating session data for this session as well. */ -export declare function updateSessionData(helpers: Helpers, sessionHandle: string, newSessionData: any): Promise; -export declare function updateAccessTokenPayload(helpers: Helpers, sessionHandle: string, newAccessTokenPayload: any): Promise; +export declare function updateSessionData( + helpers: Helpers, + sessionHandle: string, + newSessionData: any +): Promise; +export declare function updateAccessTokenPayload( + helpers: Helpers, + sessionHandle: string, + newAccessTokenPayload: any +): Promise; diff --git a/lib/build/recipe/session/sessionFunctions.js b/lib/build/recipe/session/sessionFunctions.js index 6e8828867..7f272ba58 100644 --- a/lib/build/recipe/session/sessionFunctions.js +++ b/lib/build/recipe/session/sessionFunctions.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.updateAccessTokenPayload = exports.updateSessionData = exports.revokeMultipleSessions = exports.revokeSession = exports.getAllSessionHandlesForUser = exports.revokeAllSessionsForUser = exports.refreshSession = exports.getSessionInformation = exports.getSession = exports.createNewSession = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -48,8 +72,15 @@ function createNewSession(helpers, userId, disableAntiCsrf, recipeUserId, access }; let handShakeInfo = yield helpers.getHandshakeInfo(); requestBody.enableAntiCsrf = !disableAntiCsrf && handShakeInfo.antiCsrf === "VIA_TOKEN"; - let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session"), requestBody); - helpers.updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); + let response = yield helpers.querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/session"), + requestBody + ); + helpers.updateJwtSigningPublicKeyInfo( + response.jwtSigningPublicKeyList, + response.jwtSigningPublicKey, + response.jwtSigningPublicKeyExpiryTime + ); delete response.status; delete response.jwtSigningPublicKey; delete response.jwtSigningPublicKeyExpiryTime; @@ -72,10 +103,13 @@ function getSession(helpers, parsedAccessToken, antiCsrfToken, doAntiCsrfCheck, /** * get access token info using existing signingKey */ - accessTokenInfo = yield accessToken_1.getInfoFromAccessToken(parsedAccessToken, key.publicKey, handShakeInfo.antiCsrf === "VIA_TOKEN" && doAntiCsrfCheck); + accessTokenInfo = yield accessToken_1.getInfoFromAccessToken( + parsedAccessToken, + key.publicKey, + handShakeInfo.antiCsrf === "VIA_TOKEN" && doAntiCsrfCheck + ); foundASigningKeyThatIsOlderThanTheAccessToken = true; - } - catch (err) { + } catch (err) { /** * if error type is not TRY_REFRESH_TOKEN, we return the * error to the user @@ -137,14 +171,18 @@ function getSession(helpers, parsedAccessToken, antiCsrfToken, doAntiCsrfCheck, if (accessTokenInfo !== undefined) { if (antiCsrfToken === undefined || antiCsrfToken !== accessTokenInfo.antiCsrfToken) { if (antiCsrfToken === undefined) { - logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because antiCsrfToken is missing from request"); + logger_1.logDebugMessage( + "getSession: Returning TRY_REFRESH_TOKEN because antiCsrfToken is missing from request" + ); throw new error_1.default({ - message: "Provided antiCsrfToken is undefined. If you do not want anti-csrf check for this API, please set doAntiCsrfCheck to false for this API", + message: + "Provided antiCsrfToken is undefined. If you do not want anti-csrf check for this API, please set doAntiCsrfCheck to false for this API", type: error_1.default.TRY_REFRESH_TOKEN, }); - } - else { - logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because the passed antiCsrfToken is not the same as in the access token"); + } else { + logger_1.logDebugMessage( + "getSession: Returning TRY_REFRESH_TOKEN because the passed antiCsrfToken is not the same as in the access token" + ); throw new error_1.default({ message: "anti-csrf check failed", type: error_1.default.TRY_REFRESH_TOKEN, @@ -152,20 +190,24 @@ function getSession(helpers, parsedAccessToken, antiCsrfToken, doAntiCsrfCheck, } } } - } - else if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { + } else if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { if (!containsCustomHeader) { - logger_1.logDebugMessage("getSession: Returning TRY_REFRESH_TOKEN because custom header (rid) was not passed"); + logger_1.logDebugMessage( + "getSession: Returning TRY_REFRESH_TOKEN because custom header (rid) was not passed" + ); throw new error_1.default({ - message: "anti-csrf check failed. Please pass 'rid: \"session\"' header in the request, or set doAntiCsrfCheck to false for this API", + message: + "anti-csrf check failed. Please pass 'rid: \"session\"' header in the request, or set doAntiCsrfCheck to false for this API", type: error_1.default.TRY_REFRESH_TOKEN, }); } } } - if (accessTokenInfo !== undefined && + if ( + accessTokenInfo !== undefined && !handShakeInfo.accessTokenBlacklistingEnabled && - accessTokenInfo.parentRefreshTokenHash1 === undefined) { + accessTokenInfo.parentRefreshTokenHash1 === undefined + ) { return { session: { handle: accessTokenInfo.sessionHandle, @@ -182,29 +224,39 @@ function getSession(helpers, parsedAccessToken, antiCsrfToken, doAntiCsrfCheck, doAntiCsrfCheck, enableAntiCsrf: handShakeInfo.antiCsrf === "VIA_TOKEN", }; - let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/verify"), requestBody); + let response = yield helpers.querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/session/verify"), + requestBody + ); if (response.status === "OK") { - helpers.updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); + helpers.updateJwtSigningPublicKeyInfo( + response.jwtSigningPublicKeyList, + response.jwtSigningPublicKey, + response.jwtSigningPublicKeyExpiryTime + ); delete response.status; delete response.jwtSigningPublicKey; delete response.jwtSigningPublicKeyExpiryTime; delete response.jwtSigningPublicKeyList; return response; - } - else if (response.status === "UNAUTHORISED") { + } else if (response.status === "UNAUTHORISED") { logger_1.logDebugMessage("getSession: Returning UNAUTHORISED because of core response"); throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, }); - } - else { - if (response.jwtSigningPublicKeyList !== undefined || - (response.jwtSigningPublicKey !== undefined && response.jwtSigningPublicKeyExpiryTime !== undefined)) { + } else { + if ( + response.jwtSigningPublicKeyList !== undefined || + (response.jwtSigningPublicKey !== undefined && response.jwtSigningPublicKeyExpiryTime !== undefined) + ) { // after CDI 2.7.1, the API returns the new keys - helpers.updateJwtSigningPublicKeyInfo(response.jwtSigningPublicKeyList, response.jwtSigningPublicKey, response.jwtSigningPublicKeyExpiryTime); - } - else { + helpers.updateJwtSigningPublicKeyInfo( + response.jwtSigningPublicKeyList, + response.jwtSigningPublicKey, + response.jwtSigningPublicKeyExpiryTime + ); + } else { // we force update the signing keys... yield helpers.getHandshakeInfo(true); } @@ -237,8 +289,7 @@ function getSessionInformation(helpers, sessionHandle) { delete response.userDataInJWT; delete response.userDataInJWT; return response; - } - else { + } else { return undefined; } }); @@ -258,7 +309,9 @@ function refreshSession(helpers, refreshToken, antiCsrfToken, containsCustomHead }; if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER" && transferMethod === "cookie") { if (!containsCustomHeader) { - logger_1.logDebugMessage("refreshSession: Returning UNAUTHORISED because custom header (rid) was not passed"); + logger_1.logDebugMessage( + "refreshSession: Returning UNAUTHORISED because custom header (rid) was not passed" + ); throw new error_1.default({ message: "anti-csrf check failed. Please pass 'rid: \"session\"' header in the request.", type: error_1.default.UNAUTHORISED, @@ -268,19 +321,20 @@ function refreshSession(helpers, refreshToken, antiCsrfToken, containsCustomHead }); } } - let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/refresh"), requestBody); + let response = yield helpers.querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/session/refresh"), + requestBody + ); if (response.status === "OK") { delete response.status; return response; - } - else if (response.status === "UNAUTHORISED") { + } else if (response.status === "UNAUTHORISED") { logger_1.logDebugMessage("refreshSession: Returning UNAUTHORISED because of core response"); throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, }); - } - else { + } else { logger_1.logDebugMessage("refreshSession: Returning TOKEN_THEFT_DETECTED because of core response"); throw new error_1.default({ message: "Token theft detected", @@ -301,9 +355,12 @@ exports.refreshSession = refreshSession; */ function revokeAllSessionsForUser(helpers, userId) { return __awaiter(this, void 0, void 0, function* () { - let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/remove"), { - userId, - }); + let response = yield helpers.querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/session/remove"), + { + userId, + } + ); return response.sessionHandlesRevoked; }); } @@ -326,9 +383,12 @@ exports.getAllSessionHandlesForUser = getAllSessionHandlesForUser; */ function revokeSession(helpers, sessionHandle) { return __awaiter(this, void 0, void 0, function* () { - let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/remove"), { - sessionHandles: [sessionHandle], - }); + let response = yield helpers.querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/session/remove"), + { + sessionHandles: [sessionHandle], + } + ); return response.sessionHandlesRevoked.length === 1; }); } @@ -339,9 +399,12 @@ exports.revokeSession = revokeSession; */ function revokeMultipleSessions(helpers, sessionHandles) { return __awaiter(this, void 0, void 0, function* () { - let response = yield helpers.querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/session/remove"), { - sessionHandles, - }); + let response = yield helpers.querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/session/remove"), + { + sessionHandles, + } + ); return response.sessionHandlesRevoked; }); } diff --git a/lib/build/recipe/session/types.d.ts b/lib/build/recipe/session/types.d.ts index f26f541bd..618ff280b 100644 --- a/lib/build/recipe/session/types.d.ts +++ b/lib/build/recipe/session/types.d.ts @@ -16,13 +16,16 @@ export declare type StoredHandshakeInfo = { accessTokenBlacklistingEnabled: boolean; accessTokenValidity: number; refreshTokenValidity: number; -} & ({ - jwtSigningPublicKeyList: KeyInfo[]; -} | { - jwtSigningPublicKeyList: undefined; - jwtSigningPublicKey: string; - jwtSigningPublicKeyExpiryTime: number; -}); +} & ( + | { + jwtSigningPublicKeyList: KeyInfo[]; + } + | { + jwtSigningPublicKeyList: undefined; + jwtSigningPublicKey: string; + jwtSigningPublicKeyExpiryTime: number; + } +); export declare type CreateOrRefreshAPIResponse = { session: { handle: string; @@ -62,22 +65,39 @@ export declare type TypeInput = { }) => TokenTransferMethod | "any"; errorHandlers?: ErrorHandlers; antiCsrf?: "VIA_TOKEN" | "VIA_CUSTOM_HEADER" | "NONE"; - jwt?: { - enable: true; - propertyNameInAccessTokenPayload?: string; - issuer?: string; - } | { - enable: false; - }; + jwt?: + | { + enable: true; + propertyNameInAccessTokenPayload?: string; + issuer?: string; + } + | { + enable: false; + }; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; openIdFeature?: { - functions?: (originalImplementation: OpenIdRecipeInterface, builder?: OverrideableBuilder) => OpenIdRecipeInterface; - apis?: (originalImplementation: OpenIdAPIInterface, builder?: OverrideableBuilder) => OpenIdAPIInterface; + functions?: ( + originalImplementation: OpenIdRecipeInterface, + builder?: OverrideableBuilder + ) => OpenIdRecipeInterface; + apis?: ( + originalImplementation: OpenIdAPIInterface, + builder?: OverrideableBuilder + ) => OpenIdAPIInterface; jwtFeature?: { - functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; - apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; + functions?: ( + originalImplementation: JWTRecipeInterface, + builder?: OverrideableBuilder + ) => JWTRecipeInterface; + apis?: ( + originalImplementation: JWTAPIInterface, + builder?: OverrideableBuilder + ) => JWTAPIInterface; }; }; }; @@ -102,14 +122,29 @@ export declare type TypeNormalisedInput = { issuer?: string; }; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; openIdFeature?: { - functions?: (originalImplementation: OpenIdRecipeInterface, builder?: OverrideableBuilder) => OpenIdRecipeInterface; - apis?: (originalImplementation: OpenIdAPIInterface, builder?: OverrideableBuilder) => OpenIdAPIInterface; + functions?: ( + originalImplementation: OpenIdRecipeInterface, + builder?: OverrideableBuilder + ) => OpenIdRecipeInterface; + apis?: ( + originalImplementation: OpenIdAPIInterface, + builder?: OverrideableBuilder + ) => OpenIdAPIInterface; jwtFeature?: { - functions?: (originalImplementation: JWTRecipeInterface, builder?: OverrideableBuilder) => JWTRecipeInterface; - apis?: (originalImplementation: JWTAPIInterface, builder?: OverrideableBuilder) => JWTAPIInterface; + functions?: ( + originalImplementation: JWTRecipeInterface, + builder?: OverrideableBuilder + ) => JWTRecipeInterface; + apis?: ( + originalImplementation: JWTAPIInterface, + builder?: OverrideableBuilder + ) => JWTAPIInterface; }; }; }; @@ -121,7 +156,13 @@ export interface ErrorHandlerMiddleware { (message: string, request: BaseRequest, response: BaseResponse): Promise; } export interface TokenTheftErrorHandlerMiddleware { - (sessionHandle: string, userId: string, recipeUserId: string, request: BaseRequest, response: BaseResponse): Promise; + ( + sessionHandle: string, + userId: string, + recipeUserId: string, + request: BaseRequest, + response: BaseResponse + ): Promise; } export interface InvalidClaimErrorHandlerMiddleware { (validatorErrors: ClaimValidationError[], request: BaseRequest, response: BaseResponse): Promise; @@ -135,7 +176,11 @@ export interface NormalisedErrorHandlers { export interface VerifySessionOptions { antiCsrfCheck?: boolean; sessionRequired?: boolean; - overrideGlobalClaimValidators?: (globalClaimValidators: SessionClaimValidator[], session: SessionContainerInterface, userContext: any) => Promise | SessionClaimValidator[]; + overrideGlobalClaimValidators?: ( + globalClaimValidators: SessionClaimValidator[], + session: SessionContainerInterface, + userContext: any + ) => Promise | SessionClaimValidator[]; } export declare type RecipeInterface = { createNewSession(input: { @@ -171,31 +216,12 @@ export declare type RecipeInterface = { * * Returns undefined if the sessionHandle does not exist */ - getSessionInformation(input: { - sessionHandle: string; - userContext: any; - }): Promise; - revokeAllSessionsForUser(input: { - userId: string; - userContext: any; - }): Promise; - getAllSessionHandlesForUser(input: { - userId: string; - userContext: any; - }): Promise; - revokeSession(input: { - sessionHandle: string; - userContext: any; - }): Promise; - revokeMultipleSessions(input: { - sessionHandles: string[]; - userContext: any; - }): Promise; - updateSessionData(input: { - sessionHandle: string; - newSessionData: any; - userContext: any; - }): Promise; + getSessionInformation(input: { sessionHandle: string; userContext: any }): Promise; + revokeAllSessionsForUser(input: { userId: string; userContext: any }): Promise; + getAllSessionHandlesForUser(input: { userId: string; userContext: any }): Promise; + revokeSession(input: { sessionHandle: string; userContext: any }): Promise; + revokeMultipleSessions(input: { sessionHandles: string[]; userContext: any }): Promise; + updateSessionData(input: { sessionHandle: string; newSessionData: any; userContext: any }): Promise; /** * @deprecated Use mergeIntoAccessTokenPayload instead * @returns {Promise} Returns false if the sessionHandle does not exist @@ -217,26 +243,25 @@ export declare type RecipeInterface = { accessToken: string; newAccessTokenPayload?: any; userContext: any; - }): Promise<{ - status: "OK"; - session: { - handle: string; - userId: string; - recipeUserId: string; - userDataInJWT: any; - }; - accessToken?: { - token: string; - expiry: number; - createdTime: number; - }; - } | undefined>; - getAccessTokenLifeTimeMS(input: { - userContext: any; - }): Promise; - getRefreshTokenLifeTimeMS(input: { - userContext: any; - }): Promise; + }): Promise< + | { + status: "OK"; + session: { + handle: string; + userId: string; + recipeUserId: string; + userDataInJWT: any; + }; + accessToken?: { + token: string; + expiry: number; + createdTime: number; + }; + } + | undefined + >; + getAccessTokenLifeTimeMS(input: { userContext: any }): Promise; + getRefreshTokenLifeTimeMS(input: { userContext: any }): Promise; validateClaims(input: { userId: string; recipeUserId: string; @@ -247,11 +272,7 @@ export declare type RecipeInterface = { invalidClaims: ClaimValidationError[]; accessTokenPayloadUpdate?: any; }>; - fetchAndSetClaim(input: { - sessionHandle: string; - claim: SessionClaim; - userContext: any; - }): Promise; + fetchAndSetClaim(input: { sessionHandle: string; claim: SessionClaim; userContext: any }): Promise; setClaimValue(input: { sessionHandle: string; claim: SessionClaim; @@ -262,17 +283,16 @@ export declare type RecipeInterface = { sessionHandle: string; claim: SessionClaim; userContext: any; - }): Promise<{ - status: "SESSION_DOES_NOT_EXIST_ERROR"; - } | { - status: "OK"; - value: T | undefined; - }>; - removeClaim(input: { - sessionHandle: string; - claim: SessionClaim; - userContext: any; - }): Promise; + }): Promise< + | { + status: "SESSION_DOES_NOT_EXIST_ERROR"; + } + | { + status: "OK"; + value: T | undefined; + } + >; + removeClaim(input: { sessionHandle: string; claim: SessionClaim; userContext: any }): Promise; }; export interface SessionContainerInterface { revokeSession(userContext?: any): Promise; @@ -310,17 +330,19 @@ export declare type APIInterface = { * since it's not something that is directly called by the user on the * frontend anyway */ - refreshPOST: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise); - signOutPOST: undefined | ((input: { - options: APIOptions; - session: SessionContainerInterface | undefined; - userContext: any; - }) => Promise<{ - status: "OK"; - } | GeneralErrorResponse>); + refreshPOST: undefined | ((input: { options: APIOptions; userContext: any }) => Promise); + signOutPOST: + | undefined + | ((input: { + options: APIOptions; + session: SessionContainerInterface | undefined; + userContext: any; + }) => Promise< + | { + status: "OK"; + } + | GeneralErrorResponse + >); verifySession(input: { verifySessionOptions: VerifySessionOptions | undefined; options: APIOptions; @@ -336,25 +358,30 @@ export declare type SessionInformation = { accessTokenPayload: any; timeCreated: number; }; -export declare type ClaimValidationResult = { - isValid: true; -} | { - isValid: false; - reason?: JSONValue; -}; +export declare type ClaimValidationResult = + | { + isValid: true; + } + | { + isValid: false; + reason?: JSONValue; + }; export declare type ClaimValidationError = { id: string; reason?: JSONValue; }; -export declare type SessionClaimValidator = (// We split the type like this to express that either both claim and shouldRefetch is defined or neither. -{ - claim: SessionClaim; - /** - * Decides if we need to refetch the claim value before checking the payload with `isValid`. - * E.g.: if the information in the payload is expired, or is not sufficient for this check. - */ - shouldRefetch: (payload: any, userContext: any) => Promise | boolean; -} | {}) & { +export declare type SessionClaimValidator = ( + | // We split the type like this to express that either both claim and shouldRefetch is defined or neither. + { + claim: SessionClaim; + /** + * Decides if we need to refetch the claim value before checking the payload with `isValid`. + * E.g.: if the information in the payload is expired, or is not sufficient for this check. + */ + shouldRefetch: (payload: any, userContext: any) => Promise | boolean; + } + | {} +) & { id: string; /** * Decides if the claim is valid based on the payload (and not checking DB or anything else) diff --git a/lib/build/recipe/session/types.js b/lib/build/recipe/session/types.js index 1e23a6a70..d2b9feb27 100644 --- a/lib/build/recipe/session/types.js +++ b/lib/build/recipe/session/types.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SessionClaim = void 0; class SessionClaim { diff --git a/lib/build/recipe/session/utils.d.ts b/lib/build/recipe/session/utils.d.ts index 0bdb57d95..0ede4269f 100644 --- a/lib/build/recipe/session/utils.d.ts +++ b/lib/build/recipe/session/utils.d.ts @@ -1,18 +1,68 @@ -import { CreateOrRefreshAPIResponse, TypeInput, TypeNormalisedInput, ClaimValidationError, SessionClaimValidator, SessionContainerInterface, VerifySessionOptions, TokenTransferMethod } from "./types"; +import { + CreateOrRefreshAPIResponse, + TypeInput, + TypeNormalisedInput, + ClaimValidationError, + SessionClaimValidator, + SessionContainerInterface, + VerifySessionOptions, + TokenTransferMethod, +} from "./types"; import SessionRecipe from "./recipe"; import { NormalisedAppinfo } from "../../types"; import { BaseRequest, BaseResponse } from "../../framework"; -export declare function sendTryRefreshTokenResponse(recipeInstance: SessionRecipe, _: string, __: BaseRequest, response: BaseResponse): Promise; -export declare function sendUnauthorisedResponse(recipeInstance: SessionRecipe, _: string, __: BaseRequest, response: BaseResponse): Promise; -export declare function sendInvalidClaimResponse(recipeInstance: SessionRecipe, claimValidationErrors: ClaimValidationError[], __: BaseRequest, response: BaseResponse): Promise; -export declare function sendTokenTheftDetectedResponse(recipeInstance: SessionRecipe, sessionHandle: string, _: string, __: string, ___: BaseRequest, response: BaseResponse): Promise; +export declare function sendTryRefreshTokenResponse( + recipeInstance: SessionRecipe, + _: string, + __: BaseRequest, + response: BaseResponse +): Promise; +export declare function sendUnauthorisedResponse( + recipeInstance: SessionRecipe, + _: string, + __: BaseRequest, + response: BaseResponse +): Promise; +export declare function sendInvalidClaimResponse( + recipeInstance: SessionRecipe, + claimValidationErrors: ClaimValidationError[], + __: BaseRequest, + response: BaseResponse +): Promise; +export declare function sendTokenTheftDetectedResponse( + recipeInstance: SessionRecipe, + sessionHandle: string, + _: string, + __: string, + ___: BaseRequest, + response: BaseResponse +): Promise; export declare function normaliseSessionScopeOrThrowError(sessionScope: string): string; export declare function getURLProtocol(url: string): string; -export declare function validateAndNormaliseUserInput(recipeInstance: SessionRecipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + recipeInstance: SessionRecipe, + appInfo: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; export declare function normaliseSameSiteOrThrowError(sameSite: string): "strict" | "lax" | "none"; -export declare function attachTokensToResponse(config: TypeNormalisedInput, res: BaseResponse, response: CreateOrRefreshAPIResponse, transferMethod: TokenTransferMethod): void; -export declare function getRequiredClaimValidators(session: SessionContainerInterface, overrideGlobalClaimValidators: VerifySessionOptions["overrideGlobalClaimValidators"], userContext: any): Promise; -export declare function validateClaimsInPayload(claimValidators: SessionClaimValidator[], newAccessTokenPayload: any, userContext: any): Promise<{ - id: string; - reason: import("../../types").JSONValue; -}[]>; +export declare function attachTokensToResponse( + config: TypeNormalisedInput, + res: BaseResponse, + response: CreateOrRefreshAPIResponse, + transferMethod: TokenTransferMethod +): void; +export declare function getRequiredClaimValidators( + session: SessionContainerInterface, + overrideGlobalClaimValidators: VerifySessionOptions["overrideGlobalClaimValidators"], + userContext: any +): Promise; +export declare function validateClaimsInPayload( + claimValidators: SessionClaimValidator[], + newAccessTokenPayload: any, + userContext: any +): Promise< + { + id: string; + reason: import("../../types").JSONValue; + }[] +>; diff --git a/lib/build/recipe/session/utils.js b/lib/build/recipe/session/utils.js index 29e6b84eb..4b421d138 100644 --- a/lib/build/recipe/session/utils.js +++ b/lib/build/recipe/session/utils.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateClaimsInPayload = exports.getRequiredClaimValidators = exports.attachTokensToResponse = exports.normaliseSameSiteOrThrowError = exports.validateAndNormaliseUserInput = exports.getURLProtocol = exports.normaliseSessionScopeOrThrowError = exports.sendTokenTheftDetectedResponse = exports.sendInvalidClaimResponse = exports.sendUnauthorisedResponse = exports.sendTryRefreshTokenResponse = void 0; const cookieAndHeaders_1 = require("./cookieAndHeaders"); @@ -38,7 +62,11 @@ const constants_2 = require("./with-jwt/constants"); const logger_1 = require("../../logger"); function sendTryRefreshTokenResponse(recipeInstance, _, __, response) { return __awaiter(this, void 0, void 0, function* () { - utils_2.sendNon200ResponseWithMessage(response, "try refresh token", recipeInstance.config.sessionExpiredStatusCode); + utils_2.sendNon200ResponseWithMessage( + response, + "try refresh token", + recipeInstance.config.sessionExpiredStatusCode + ); }); } exports.sendTryRefreshTokenResponse = sendTryRefreshTokenResponse; @@ -60,7 +88,11 @@ exports.sendInvalidClaimResponse = sendInvalidClaimResponse; function sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, _, __, ___, response) { return __awaiter(this, void 0, void 0, function* () { yield recipeInstance.recipeInterfaceImpl.revokeSession({ sessionHandle, userContext: {} }); - utils_2.sendNon200ResponseWithMessage(response, "token theft detected", recipeInstance.config.sessionExpiredStatusCode); + utils_2.sendNon200ResponseWithMessage( + response, + "token theft detected", + recipeInstance.config.sessionExpiredStatusCode + ); }); } exports.sendTokenTheftDetectedResponse = sendTokenTheftDetectedResponse; @@ -82,8 +114,7 @@ function normaliseSessionScopeOrThrowError(sessionScope) { sessionScope = sessionScope.substr(1); } return sessionScope; - } - catch (err) { + } catch (err) { throw new Error("Please provide a valid sessionScope"); } } @@ -104,23 +135,30 @@ function getURLProtocol(url) { exports.getURLProtocol = getURLProtocol; function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { var _a; - let cookieDomain = config === undefined || config.cookieDomain === undefined - ? undefined - : normaliseSessionScopeOrThrowError(config.cookieDomain); + let cookieDomain = + config === undefined || config.cookieDomain === undefined + ? undefined + : normaliseSessionScopeOrThrowError(config.cookieDomain); let protocolOfAPIDomain = getURLProtocol(appInfo.apiDomain.getAsStringDangerous()); let protocolOfWebsiteDomain = getURLProtocol(appInfo.websiteDomain.getAsStringDangerous()); - let cookieSameSite = appInfo.topLevelAPIDomain !== appInfo.topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain - ? "none" - : "lax"; + let cookieSameSite = + appInfo.topLevelAPIDomain !== appInfo.topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain + ? "none" + : "lax"; cookieSameSite = config === undefined || config.cookieSameSite === undefined ? cookieSameSite : normaliseSameSiteOrThrowError(config.cookieSameSite); - let cookieSecure = config === undefined || config.cookieSecure === undefined - ? appInfo.apiDomain.getAsStringDangerous().startsWith("https") - : config.cookieSecure; - let sessionExpiredStatusCode = config === undefined || config.sessionExpiredStatusCode === undefined ? 401 : config.sessionExpiredStatusCode; - const invalidClaimStatusCode = (_a = config === null || config === void 0 ? void 0 : config.invalidClaimStatusCode) !== null && _a !== void 0 ? _a : 403; + let cookieSecure = + config === undefined || config.cookieSecure === undefined + ? appInfo.apiDomain.getAsStringDangerous().startsWith("https") + : config.cookieSecure; + let sessionExpiredStatusCode = + config === undefined || config.sessionExpiredStatusCode === undefined ? 401 : config.sessionExpiredStatusCode; + const invalidClaimStatusCode = + (_a = config === null || config === void 0 ? void 0 : config.invalidClaimStatusCode) !== null && _a !== void 0 + ? _a + : 403; if (sessionExpiredStatusCode === invalidClaimStatusCode) { throw new Error("sessionExpiredStatusCode and sessionExpiredStatusCode must be different"); } @@ -129,21 +167,32 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { throw new Error("antiCsrf config must be one of 'NONE' or 'VIA_CUSTOM_HEADER' or 'VIA_TOKEN'"); } } - let antiCsrf = config === undefined || config.antiCsrf === undefined - ? cookieSameSite === "none" - ? "VIA_CUSTOM_HEADER" - : "NONE" - : config.antiCsrf; + let antiCsrf = + config === undefined || config.antiCsrf === undefined + ? cookieSameSite === "none" + ? "VIA_CUSTOM_HEADER" + : "NONE" + : config.antiCsrf; let errorHandlers = { - onTokenTheftDetected: (sessionHandle, userId, recipeUserId, request, response) => __awaiter(this, void 0, void 0, function* () { - return yield sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, userId, recipeUserId, request, response); - }), - onTryRefreshToken: (message, request, response) => __awaiter(this, void 0, void 0, function* () { - return yield sendTryRefreshTokenResponse(recipeInstance, message, request, response); - }), - onUnauthorised: (message, request, response) => __awaiter(this, void 0, void 0, function* () { - return yield sendUnauthorisedResponse(recipeInstance, message, request, response); - }), + onTokenTheftDetected: (sessionHandle, userId, recipeUserId, request, response) => + __awaiter(this, void 0, void 0, function* () { + return yield sendTokenTheftDetectedResponse( + recipeInstance, + sessionHandle, + userId, + recipeUserId, + request, + response + ); + }), + onTryRefreshToken: (message, request, response) => + __awaiter(this, void 0, void 0, function* () { + return yield sendTryRefreshTokenResponse(recipeInstance, message, request, response); + }), + onUnauthorised: (message, request, response) => + __awaiter(this, void 0, void 0, function* () { + return yield sendUnauthorisedResponse(recipeInstance, message, request, response); + }), onInvalidClaim: (validationErrors, request, response) => { return sendInvalidClaimResponse(recipeInstance, validationErrors, request, response); }, @@ -173,12 +222,19 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { accessTokenPayloadJWTPropertyName = jwtPropertyName; } } - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); return { refreshTokenPath: appInfo.apiBasePath.appendPath(new normalisedURLPath_1.default(constants_1.REFRESH_API_PATH)), - getTokenTransferMethod: (config === null || config === void 0 ? void 0 : config.getTokenTransferMethod) === undefined - ? defaultGetTokenTransferMethod - : config.getTokenTransferMethod, + getTokenTransferMethod: + (config === null || config === void 0 ? void 0 : config.getTokenTransferMethod) === undefined + ? defaultGetTokenTransferMethod + : config.getTokenTransferMethod, cookieDomain, cookieSameSite, cookieSecure, @@ -207,13 +263,24 @@ exports.normaliseSameSiteOrThrowError = normaliseSameSiteOrThrowError; function attachTokensToResponse(config, res, response, transferMethod) { let accessToken = response.accessToken; let refreshToken = response.refreshToken; - cookieAndHeaders_1.setFrontTokenInHeaders(res, response.session.userId, response.accessToken.expiry, response.session.userDataInJWT); - cookieAndHeaders_1.setToken(config, res, "access", accessToken.token, - // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. - // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. - // Even if the token is expired the presence of the token indicates that the user could have a valid refresh - // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. - Date.now() + 3153600000000, transferMethod); + cookieAndHeaders_1.setFrontTokenInHeaders( + res, + response.session.userId, + response.accessToken.expiry, + response.session.userDataInJWT + ); + cookieAndHeaders_1.setToken( + config, + res, + "access", + accessToken.token, + // We set the expiration to 100 years, because we can't really access the expiration of the refresh token everywhere we are setting it. + // This should be safe to do, since this is only the validity of the cookie (set here or on the frontend) but we check the expiration of the JWT anyway. + // Even if the token is expired the presence of the token indicates that the user could have a valid refresh + // Setting them to infinity would require special case handling on the frontend and just adding 10 years seems enough. + Date.now() + 3153600000000, + transferMethod + ); cookieAndHeaders_1.setToken(config, res, "refresh", refreshToken.token, refreshToken.expiry, transferMethod); if (response.antiCsrfToken !== undefined) { cookieAndHeaders_1.setAntiCsrfTokenInHeaders(res, response.antiCsrfToken); @@ -222,13 +289,17 @@ function attachTokensToResponse(config, res, response, transferMethod) { exports.attachTokensToResponse = attachTokensToResponse; function getRequiredClaimValidators(session, overrideGlobalClaimValidators, userContext) { return __awaiter(this, void 0, void 0, function* () { - const claimValidatorsAddedByOtherRecipes = recipe_1.default.getInstanceOrThrowError().getClaimValidatorsAddedByOtherRecipes(); - const globalClaimValidators = yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getGlobalClaimValidators({ - userId: session.getUserId(), - recipeUserId: session.getRecipeUserId(), - claimValidatorsAddedByOtherRecipes, - userContext, - }); + const claimValidatorsAddedByOtherRecipes = recipe_1.default + .getInstanceOrThrowError() + .getClaimValidatorsAddedByOtherRecipes(); + const globalClaimValidators = yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getGlobalClaimValidators({ + userId: session.getUserId(), + recipeUserId: session.getRecipeUserId(), + claimValidatorsAddedByOtherRecipes, + userContext, + }); return overrideGlobalClaimValidators !== undefined ? yield overrideGlobalClaimValidators(globalClaimValidators, session, userContext) : globalClaimValidators; @@ -240,7 +311,9 @@ function validateClaimsInPayload(claimValidators, newAccessTokenPayload, userCon const validationErrors = []; for (const validator of claimValidators) { const claimValidationResult = yield validator.validate(newAccessTokenPayload, userContext); - logger_1.logDebugMessage("validateClaimsInPayload " + validator.id + " validation res " + JSON.stringify(claimValidationResult)); + logger_1.logDebugMessage( + "validateClaimsInPayload " + validator.id + " validation res " + JSON.stringify(claimValidationResult) + ); if (!claimValidationResult.isValid) { validationErrors.push({ id: validator.id, @@ -252,7 +325,7 @@ function validateClaimsInPayload(claimValidators, newAccessTokenPayload, userCon }); } exports.validateClaimsInPayload = validateClaimsInPayload; -function defaultGetTokenTransferMethod({ req, forCreateNewSession, }) { +function defaultGetTokenTransferMethod({ req, forCreateNewSession }) { // We allow fallback (checking headers then cookies) by default when validating if (!forCreateNewSession) { return "any"; diff --git a/lib/build/recipe/session/with-jwt/index.js b/lib/build/recipe/session/with-jwt/index.js index ce0d33e26..6b58cbc0b 100644 --- a/lib/build/recipe/session/with-jwt/index.js +++ b/lib/build/recipe/session/with-jwt/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * diff --git a/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts b/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts index 17547f84f..d089224ea 100644 --- a/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts +++ b/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts @@ -2,4 +2,8 @@ import { RecipeInterface } from "../"; import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; import { TypeNormalisedInput } from "../types"; export declare function setJWTExpiryOffsetSecondsForTesting(offset: number): void; -export default function (originalImplementation: RecipeInterface, openIdRecipeImplementation: OpenIdRecipeInterface, config: TypeNormalisedInput): RecipeInterface; +export default function ( + originalImplementation: RecipeInterface, + openIdRecipeImplementation: OpenIdRecipeInterface, + config: TypeNormalisedInput +): RecipeInterface; diff --git a/lib/build/recipe/session/with-jwt/recipeImplementation.js b/lib/build/recipe/session/with-jwt/recipeImplementation.js index 323c8ca59..b50a2991a 100644 --- a/lib/build/recipe/session/with-jwt/recipeImplementation.js +++ b/lib/build/recipe/session/with-jwt/recipeImplementation.js @@ -1,35 +1,76 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.setJWTExpiryOffsetSecondsForTesting = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -108,11 +149,14 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { }); }); } - return Object.assign(Object.assign({}, originalImplementation), { createNewSession: function ({ req, res, userId, recipeUserId, accessTokenPayload, sessionData, userContext, }) { + return Object.assign(Object.assign({}, originalImplementation), { + createNewSession: function ({ req, res, userId, recipeUserId, accessTokenPayload, sessionData, userContext }) { return __awaiter(this, void 0, void 0, function* () { accessTokenPayload = accessTokenPayload === null || accessTokenPayload === undefined ? {} : accessTokenPayload; - let accessTokenValidityInSeconds = Math.ceil((yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000); + let accessTokenValidityInSeconds = Math.ceil( + (yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000 + ); accessTokenPayload = yield utils_1.addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry: getJWTExpiry(accessTokenValidityInSeconds), @@ -132,7 +176,8 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { }); return new sessionClass_1.default(sessionContainer, openIdRecipeImplementation); }); - }, getSession: function ({ req, res, options, userContext, }) { + }, + getSession: function ({ req, res, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let sessionContainer = yield originalImplementation.getSession({ req, res, options, userContext }); if (sessionContainer === undefined) { @@ -140,9 +185,12 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { } return new sessionClass_1.default(sessionContainer, openIdRecipeImplementation); }); - }, refreshSession: function ({ req, res, userContext, }) { + }, + refreshSession: function ({ req, res, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let accessTokenValidityInSeconds = Math.ceil((yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000); + let accessTokenValidityInSeconds = Math.ceil( + (yield this.getAccessTokenLifeTimeMS({ userContext })) / 1000 + ); // Refresh session first because this will create a new access token let newSession = yield originalImplementation.refreshSession({ req, res, userContext }); let accessTokenPayload = newSession.getAccessTokenPayload(); @@ -157,13 +205,17 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { yield newSession.updateAccessTokenPayload(accessTokenPayload); return new sessionClass_1.default(newSession, openIdRecipeImplementation); }); - }, mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext, }) { + }, + mergeIntoAccessTokenPayload: function ({ sessionHandle, accessTokenPayloadUpdate, userContext }) { return __awaiter(this, void 0, void 0, function* () { let sessionInformation = yield this.getSessionInformation({ sessionHandle, userContext }); if (!sessionInformation) { return false; } - let newAccessTokenPayload = Object.assign(Object.assign({}, sessionInformation.accessTokenPayload), accessTokenPayloadUpdate); + let newAccessTokenPayload = Object.assign( + Object.assign({}, sessionInformation.accessTokenPayload), + accessTokenPayloadUpdate + ); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete newAccessTokenPayload[key]; @@ -171,11 +223,11 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { } return jwtAwareUpdateAccessTokenPayload(sessionInformation, newAccessTokenPayload, userContext); }); - }, + }, /** * @deprecated use mergeIntoAccessTokenPayload instead */ - updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext, }) { + updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext }) { return __awaiter(this, void 0, void 0, function* () { newAccessTokenPayload = newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; @@ -185,6 +237,7 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { } return jwtAwareUpdateAccessTokenPayload(sessionInformation, newAccessTokenPayload, userContext); }); - } }); + }, + }); } exports.default = default_1; diff --git a/lib/build/recipe/session/with-jwt/sessionClass.d.ts b/lib/build/recipe/session/with-jwt/sessionClass.d.ts index 3d33f3c4c..d7f4984fc 100644 --- a/lib/build/recipe/session/with-jwt/sessionClass.d.ts +++ b/lib/build/recipe/session/with-jwt/sessionClass.d.ts @@ -19,9 +19,17 @@ export default class SessionClassWithJWT implements SessionContainerInterface { setClaimValue(this: SessionClassWithJWT, claim: SessionClaim, value: T, userContext?: any): Promise; getClaimValue(this: SessionClassWithJWT, claim: SessionClaim, userContext?: any): Promise; removeClaim(this: SessionClassWithJWT, claim: SessionClaim, userContext?: any): Promise; - mergeIntoAccessTokenPayload(this: SessionClassWithJWT, accessTokenPayloadUpdate: any, userContext?: any): Promise; + mergeIntoAccessTokenPayload( + this: SessionClassWithJWT, + accessTokenPayloadUpdate: any, + userContext?: any + ): Promise; /** * @deprecated use mergeIntoAccessTokenPayload instead */ - updateAccessTokenPayload(this: SessionClassWithJWT, newAccessTokenPayload: any | undefined, userContext?: any): Promise; + updateAccessTokenPayload( + this: SessionClassWithJWT, + newAccessTokenPayload: any | undefined, + userContext?: any + ): Promise; } diff --git a/lib/build/recipe/session/with-jwt/sessionClass.js b/lib/build/recipe/session/with-jwt/sessionClass.js index bd26274eb..9e76cb8a8 100644 --- a/lib/build/recipe/session/with-jwt/sessionClass.js +++ b/lib/build/recipe/session/with-jwt/sessionClass.js @@ -1,35 +1,76 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -89,13 +130,15 @@ class SessionClassWithJWT { // We copy the implementation here, since we want to override updateAccessTokenPayload assertClaims(claimValidators, userContext) { return __awaiter(this, void 0, void 0, function* () { - let validateClaimResponse = yield recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.validateClaims({ - accessTokenPayload: this.getAccessTokenPayload(userContext), - userId: this.getUserId(userContext), - recipeUserId: this.getRecipeUserId(userContext), - claimValidators, - userContext, - }); + let validateClaimResponse = yield recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.validateClaims({ + accessTokenPayload: this.getAccessTokenPayload(userContext), + userId: this.getUserId(userContext), + recipeUserId: this.getRecipeUserId(userContext), + claimValidators, + userContext, + }); if (validateClaimResponse.accessTokenPayloadUpdate !== undefined) { yield this.mergeIntoAccessTokenPayload(validateClaimResponse.accessTokenPayloadUpdate, userContext); } @@ -111,7 +154,11 @@ class SessionClassWithJWT { // We copy the implementation here, since we want to override updateAccessTokenPayload fetchAndSetClaim(claim, userContext) { return __awaiter(this, void 0, void 0, function* () { - const update = yield claim.build(this.getUserId(userContext), this.getRecipeUserId(userContext), userContext); + const update = yield claim.build( + this.getUserId(userContext), + this.getRecipeUserId(userContext), + userContext + ); return this.mergeIntoAccessTokenPayload(update, userContext); }); } @@ -134,7 +181,10 @@ class SessionClassWithJWT { // We copy the implementation here, since we want to override updateAccessTokenPayload mergeIntoAccessTokenPayload(accessTokenPayloadUpdate, userContext) { return __awaiter(this, void 0, void 0, function* () { - const updatedPayload = Object.assign(Object.assign({}, this.getAccessTokenPayload(userContext)), accessTokenPayloadUpdate); + const updatedPayload = Object.assign( + Object.assign({}, this.getAccessTokenPayload(userContext)), + accessTokenPayloadUpdate + ); for (const key of Object.keys(accessTokenPayloadUpdate)) { if (accessTokenPayloadUpdate[key] === null) { delete updatedPayload[key]; diff --git a/lib/build/recipe/session/with-jwt/utils.d.ts b/lib/build/recipe/session/with-jwt/utils.d.ts index 772df0b99..7d716db8d 100644 --- a/lib/build/recipe/session/with-jwt/utils.d.ts +++ b/lib/build/recipe/session/with-jwt/utils.d.ts @@ -1,5 +1,12 @@ import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; -export declare function addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry, userId, jwtPropertyName, openIdRecipeImplementation, userContext, }: { +export declare function addJWTToAccessTokenPayload({ + accessTokenPayload, + jwtExpiry, + userId, + jwtPropertyName, + openIdRecipeImplementation, + userContext, +}: { accessTokenPayload: any; jwtExpiry: number; userId: string; diff --git a/lib/build/recipe/session/with-jwt/utils.js b/lib/build/recipe/session/with-jwt/utils.js index 4b5492e66..5597b5ca0 100644 --- a/lib/build/recipe/session/with-jwt/utils.js +++ b/lib/build/recipe/session/with-jwt/utils.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.addJWTToAccessTokenPayload = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. @@ -25,7 +47,14 @@ exports.addJWTToAccessTokenPayload = void 0; * under the License. */ const constants_1 = require("./constants"); -function addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry, userId, jwtPropertyName, openIdRecipeImplementation, userContext, }) { +function addJWTToAccessTokenPayload({ + accessTokenPayload, + jwtExpiry, + userId, + jwtPropertyName, + openIdRecipeImplementation, + userContext, +}) { return __awaiter(this, void 0, void 0, function* () { // If jwtPropertyName is not undefined it means that the JWT was added to the access token payload already let existingJwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; @@ -36,12 +65,16 @@ function addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry, userId, jwt } // Create the JWT let jwtResponse = yield openIdRecipeImplementation.createJWT({ - payload: Object.assign({ - /* + payload: Object.assign( + { + /* We add our claims before the user provided ones so that if they use the same claims then the final payload will use the values they provide */ - sub: userId }, accessTokenPayload), + sub: userId, + }, + accessTokenPayload + ), validitySeconds: jwtExpiry, userContext, }); @@ -50,7 +83,7 @@ function addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry, userId, jwt throw new Error("JWT Signing algorithm not supported"); } // Add the jwt and the property name to the access token payload - accessTokenPayload = Object.assign(Object.assign({}, accessTokenPayload), { + accessTokenPayload = Object.assign(Object.assign({}, accessTokenPayload), { /* We add the JWT after the user defined keys because we want to make sure that it never gets overwritten by a user defined key. Using the same key as the one configured (or defaulting) @@ -67,7 +100,9 @@ function addJWTToAccessTokenPayload({ accessTokenPayload, jwtExpiry, userId, jwt guaranteed that the right JWT is returned. This case is considered to be a rare requirement and we assume that users will not need multiple JWT representations of their access token payload. */ - [jwtPropertyName]: jwtResponse.jwt, [constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]: jwtPropertyName }); + [jwtPropertyName]: jwtResponse.jwt, + [constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]: jwtPropertyName, + }); return accessTokenPayload; }); } diff --git a/lib/build/recipe/thirdparty/api/appleRedirect.js b/lib/build/recipe/thirdparty/api/appleRedirect.js index 5e659d3bc..caf7cad15 100644 --- a/lib/build/recipe/thirdparty/api/appleRedirect.js +++ b/lib/build/recipe/thirdparty/api/appleRedirect.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); function appleRedirectHandler(apiImplementation, options) { diff --git a/lib/build/recipe/thirdparty/api/authorisationUrl.js b/lib/build/recipe/thirdparty/api/authorisationUrl.js index ff7125485..dc9c1d64d 100644 --- a/lib/build/recipe/thirdparty/api/authorisationUrl.js +++ b/lib/build/recipe/thirdparty/api/authorisationUrl.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const error_1 = __importDefault(require("../error")); diff --git a/lib/build/recipe/thirdparty/api/implementation.js b/lib/build/recipe/thirdparty/api/implementation.js index 380634353..82ec2395a 100644 --- a/lib/build/recipe/thirdparty/api/implementation.js +++ b/lib/build/recipe/thirdparty/api/implementation.js @@ -1,35 +1,76 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getActualClientIdFromDevelopmentClientId = void 0; const session_1 = __importDefault(require("../../session")); @@ -48,7 +89,7 @@ function getAPIInterface() { }; }); }, - authorisationUrlGET: function ({ provider, options, userContext, }) { + authorisationUrlGET: function ({ provider, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let providerInfo = provider.get(undefined, undefined, userContext); let params = {}; @@ -58,8 +99,10 @@ function getAPIInterface() { let value = providerInfo.authorisationRedirect.params[key]; params[key] = typeof value === "function" ? yield value(options.req.original) : value; } - if (providerInfo.getRedirectURI !== undefined && - !isUsingDevelopmentClientId(providerInfo.getClientId(userContext))) { + if ( + providerInfo.getRedirectURI !== undefined && + !isUsingDevelopmentClientId(providerInfo.getClientId(userContext)) + ) { // the backend wants to set the redirectURI - so we set that here. // we add the not development keys because the oauth provider will // redirect to supertokens.io's URL which will redirect the app @@ -72,7 +115,9 @@ function getAPIInterface() { params["actual_redirect_uri"] = providerInfo.authorisationRedirect.url; Object.keys(params).forEach((key) => { if (params[key] === providerInfo.getClientId(userContext)) { - params[key] = getActualClientIdFromDevelopmentClientId(providerInfo.getClientId(userContext)); + params[key] = getActualClientIdFromDevelopmentClientId( + providerInfo.getClientId(userContext) + ); } }); } @@ -87,7 +132,7 @@ function getAPIInterface() { }; }); }, - signInUpPOST: function ({ provider, code, redirectURI, authCodeResponse, options, userContext, }) { + signInUpPOST: function ({ provider, code, redirectURI, authCodeResponse, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let userInfo; let accessTokenAPIResponse; @@ -95,8 +140,7 @@ function getAPIInterface() { let providerInfo = provider.get(undefined, undefined, userContext); if (isUsingDevelopmentClientId(providerInfo.getClientId(userContext))) { redirectURI = DEV_OAUTH_REDIRECT_URL; - } - else if (providerInfo.getRedirectURI !== undefined) { + } else if (providerInfo.getRedirectURI !== undefined) { // we overwrite the redirectURI provided by the frontend // since the backend wants to take charge of setting this. redirectURI = providerInfo.getRedirectURI(userContext); @@ -107,13 +151,14 @@ function getAPIInterface() { accessTokenAPIResponse = { data: authCodeResponse, }; - } - else { + } else { // we should use code to get the authCodeResponse body if (isUsingDevelopmentClientId(providerInfo.getClientId(userContext))) { Object.keys(providerInfo.accessTokenAPI.params).forEach((key) => { if (providerInfo.accessTokenAPI.params[key] === providerInfo.getClientId(userContext)) { - providerInfo.accessTokenAPI.params[key] = getActualClientIdFromDevelopmentClientId(providerInfo.getClientId(userContext)); + providerInfo.accessTokenAPI.params[key] = getActualClientIdFromDevelopmentClientId( + providerInfo.getClientId(userContext) + ); } }); } @@ -145,11 +190,13 @@ function getAPIInterface() { if (emailInfo.isVerified) { const emailVerificationInstance = recipe_1.default.getInstance(); if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken({ - userId: response.user.id, - email: response.user.email, - userContext, - }); + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId: response.user.id, + email: response.user.email, + userContext, + } + ); if (tokenResponse.status === "OK") { yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ token: tokenResponse.token, @@ -158,7 +205,15 @@ function getAPIInterface() { } } } - let session = yield session_1.default.createNewSession(options.req, options.res, response.user.id, response.user.recipeUserId, {}, {}, userContext); + let session = yield session_1.default.createNewSession( + options.req, + options.res, + response.user.id, + response.user.recipeUserId, + {}, + {}, + userContext + ); return { status: "OK", createdNewUser: response.createdNewUser, @@ -171,13 +226,16 @@ function getAPIInterface() { }, appleRedirectHandlerPOST: function ({ code, state, options }) { return __awaiter(this, void 0, void 0, function* () { - const redirectURL = options.appInfo.websiteDomain.getAsStringDangerous() + + const redirectURL = + options.appInfo.websiteDomain.getAsStringDangerous() + options.appInfo.websiteBasePath.getAsStringDangerous() + "/callback/apple?state=" + state + "&code=" + code; - options.res.sendHTMLResponse(``); + options.res.sendHTMLResponse( + `` + ); }); }, }; diff --git a/lib/build/recipe/thirdparty/api/signinup.js b/lib/build/recipe/thirdparty/api/signinup.js index 8f2bde3ca..c9e1c7bf2 100644 --- a/lib/build/recipe/thirdparty/api/signinup.js +++ b/lib/build/recipe/thirdparty/api/signinup.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../error")); const utils_1 = require("../../../utils"); @@ -76,13 +100,14 @@ function signInUpAPI(apiImplementation, options) { if (clientId === undefined) { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, - message: "The third party provider " + thirdPartyId + ` seems to be missing from the backend configs.`, + message: + "The third party provider " + thirdPartyId + ` seems to be missing from the backend configs.`, }); - } - else { + } else { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, - message: "The third party provider " + + message: + "The third party provider " + thirdPartyId + ` seems to be missing from the backend configs. If it is configured, then please make sure that you are passing the correct clientId from the frontend.`, }); @@ -103,13 +128,11 @@ function signInUpAPI(apiImplementation, options) { user: result.user, createdNewUser: result.createdNewUser, }); - } - else if (result.status === "NO_EMAIL_GIVEN_BY_PROVIDER") { + } else if (result.status === "NO_EMAIL_GIVEN_BY_PROVIDER") { utils_1.send200Response(options.res, { status: "NO_EMAIL_GIVEN_BY_PROVIDER", }); - } - else { + } else { utils_1.send200Response(options.res, result); } return true; diff --git a/lib/build/recipe/thirdparty/error.d.ts b/lib/build/recipe/thirdparty/error.d.ts index d1e71e0b1..248cddbeb 100644 --- a/lib/build/recipe/thirdparty/error.d.ts +++ b/lib/build/recipe/thirdparty/error.d.ts @@ -1,7 +1,4 @@ import STError from "../../error"; export default class ThirdPartyError extends STError { - constructor(options: { - type: "BAD_INPUT_ERROR"; - message: string; - }); + constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); } diff --git a/lib/build/recipe/thirdparty/error.js b/lib/build/recipe/thirdparty/error.js index fd5075d93..49fa39f33 100644 --- a/lib/build/recipe/thirdparty/error.js +++ b/lib/build/recipe/thirdparty/error.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); class ThirdPartyError extends error_1.default { diff --git a/lib/build/recipe/thirdparty/index.d.ts b/lib/build/recipe/thirdparty/index.d.ts index e8d9582d5..f1dbcf15b 100644 --- a/lib/build/recipe/thirdparty/index.d.ts +++ b/lib/build/recipe/thirdparty/index.d.ts @@ -4,14 +4,23 @@ import { RecipeInterface, User, APIInterface, APIOptions, TypeProvider } from ". export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static signInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ + static signInUp( + thirdPartyId: string, + thirdPartyUserId: string, + email: string, + userContext?: any + ): Promise<{ status: "OK"; createdNewUser: boolean; user: User; }>; static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise; - static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; + static getUserByThirdPartyInfo( + thirdPartyId: string, + thirdPartyUserId: string, + userContext?: any + ): Promise; static Google: typeof import("./providers/google").default; static Github: typeof import("./providers/github").default; static Facebook: typeof import("./providers/facebook").default; diff --git a/lib/build/recipe/thirdparty/index.js b/lib/build/recipe/thirdparty/index.js index fa35009ae..f6a6ac49d 100644 --- a/lib/build/recipe/thirdparty/index.js +++ b/lib/build/recipe/thirdparty/index.js @@ -13,37 +13,78 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.getUserByThirdPartyInfo = exports.getUsersByEmail = exports.getUserById = exports.signInUp = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); diff --git a/lib/build/recipe/thirdparty/providers/apple.js b/lib/build/recipe/thirdparty/providers/apple.js index 12d4f5223..9ef569cc3 100644 --- a/lib/build/recipe/thirdparty/providers/apple.js +++ b/lib/build/recipe/thirdparty/providers/apple.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const jsonwebtoken_1 = require("jsonwebtoken"); const error_1 = __importDefault(require("../error")); @@ -21,19 +45,27 @@ const verify_apple_id_token_1 = __importDefault(require("verify-apple-id-token") function Apple(config) { const id = "apple"; function getClientSecret(clientId, keyId, teamId, privateKey) { - return jsonwebtoken_1.sign({ - iss: teamId, - iat: Math.floor(Date.now() / 1000), - exp: Math.floor(Date.now() / 1000) + 86400 * 180, - aud: "https://appleid.apple.com", - sub: implementation_1.getActualClientIdFromDevelopmentClientId(clientId), - }, privateKey.replace(/\\n/g, "\n"), { algorithm: "ES256", keyid: keyId }); + return jsonwebtoken_1.sign( + { + iss: teamId, + iat: Math.floor(Date.now() / 1000), + exp: Math.floor(Date.now() / 1000) + 86400 * 180, + aud: "https://appleid.apple.com", + sub: implementation_1.getActualClientIdFromDevelopmentClientId(clientId), + }, + privateKey.replace(/\\n/g, "\n"), + { algorithm: "ES256", keyid: keyId } + ); } try { // trying to generate a client secret, in case client has not passed the values correctly - getClientSecret(config.clientId, config.clientSecret.keyId, config.clientSecret.teamId, config.clientSecret.privateKey); - } - catch (error) { + getClientSecret( + config.clientId, + config.clientSecret.keyId, + config.clientSecret.teamId, + config.clientSecret.privateKey + ); + } catch (error) { throw new error_1.default({ type: error_1.default.BAD_INPUT_ERROR, message: error.message, @@ -41,7 +73,12 @@ function Apple(config) { } function get(redirectURI, authCodeFromRequest) { let accessTokenAPIURL = "https://appleid.apple.com/auth/token"; - let clientSecret = getClientSecret(config.clientId, config.clientSecret.keyId, config.clientSecret.teamId, config.clientSecret.privateKey); + let clientSecret = getClientSecret( + config.clientId, + config.clientSecret.keyId, + config.clientSecret.teamId, + config.clientSecret.privateKey + ); let accessTokenAPIParams = { client_id: config.clientId, client_secret: clientSecret, @@ -59,10 +96,14 @@ function Apple(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), response_mode: "form_post", response_type: "code", client_id: config.clientId }, additionalParams); + let additionalParams = + config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign( + { scope: scopes.join(" "), response_mode: "form_post", response_type: "code", client_id: config.clientId }, + additionalParams + ); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { /* @@ -95,9 +136,11 @@ function Apple(config) { } function getRedirectURI() { let supertokens = supertokens_1.default.getInstanceOrThrowError(); - return (supertokens.appInfo.apiDomain.getAsStringDangerous() + + return ( + supertokens.appInfo.apiDomain.getAsStringDangerous() + supertokens.appInfo.apiBasePath.getAsStringDangerous() + - constants_1.APPLE_REDIRECT_HANDLER); + constants_1.APPLE_REDIRECT_HANDLER + ); } return { accessTokenAPI: { diff --git a/lib/build/recipe/thirdparty/providers/discord.js b/lib/build/recipe/thirdparty/providers/discord.js index 1aaad3e18..ccb1f043e 100644 --- a/lib/build/recipe/thirdparty/providers/discord.js +++ b/lib/build/recipe/thirdparty/providers/discord.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); function Discord(config) { @@ -34,10 +58,14 @@ function Discord(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), client_id: config.clientId, response_type: "code" }, additionalParams); + let additionalParams = + config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign( + { scope: scopes.join(" "), client_id: config.clientId, response_type: "code" }, + additionalParams + ); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { let accessToken = accessTokenAPIResponse.access_token; @@ -52,12 +80,13 @@ function Discord(config) { let userInfo = response.data; return { id: userInfo.id, - email: userInfo.email === undefined - ? undefined - : { - id: userInfo.email, - isVerified: userInfo.verified, - }, + email: + userInfo.email === undefined + ? undefined + : { + id: userInfo.email, + isVerified: userInfo.verified, + }, }; }); } diff --git a/lib/build/recipe/thirdparty/providers/facebook.js b/lib/build/recipe/thirdparty/providers/facebook.js index 1b1559cbb..1b735a43f 100644 --- a/lib/build/recipe/thirdparty/providers/facebook.js +++ b/lib/build/recipe/thirdparty/providers/facebook.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); function Facebook(config) { diff --git a/lib/build/recipe/thirdparty/providers/github.js b/lib/build/recipe/thirdparty/providers/github.js index 30abe313f..c387c0f4d 100644 --- a/lib/build/recipe/thirdparty/providers/github.js +++ b/lib/build/recipe/thirdparty/providers/github.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); function Github(config) { @@ -33,10 +57,14 @@ function Github(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), client_id: config.clientId }, additionalParams); + let additionalParams = + config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign( + { scope: scopes.join(" "), client_id: config.clientId }, + additionalParams + ); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { let accessToken = accessTokenAPIResponse.access_token; @@ -83,12 +111,13 @@ function Github(config) { let isVerified = emailInfo !== undefined ? emailInfo.verified : false; return { id, - email: emailInfo.email === undefined - ? undefined - : { - id: emailInfo.email, - isVerified, - }, + email: + emailInfo.email === undefined + ? undefined + : { + id: emailInfo.email, + isVerified, + }, }; }); } diff --git a/lib/build/recipe/thirdparty/providers/google.js b/lib/build/recipe/thirdparty/providers/google.js index 75d09466a..a9a479c2f 100644 --- a/lib/build/recipe/thirdparty/providers/google.js +++ b/lib/build/recipe/thirdparty/providers/google.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); function Google(config) { @@ -34,10 +58,20 @@ function Google(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), access_type: "offline", include_granted_scopes: "true", response_type: "code", client_id: config.clientId }, additionalParams); + let additionalParams = + config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign( + { + scope: scopes.join(" "), + access_type: "offline", + include_granted_scopes: "true", + response_type: "code", + client_id: config.clientId, + }, + additionalParams + ); function getProfileInfo(accessTokenAPIResponse) { return __awaiter(this, void 0, void 0, function* () { let accessToken = accessTokenAPIResponse.access_token; diff --git a/lib/build/recipe/thirdparty/providers/googleWorkspaces.js b/lib/build/recipe/thirdparty/providers/googleWorkspaces.js index e616bbe26..8a1e526f6 100644 --- a/lib/build/recipe/thirdparty/providers/googleWorkspaces.js +++ b/lib/build/recipe/thirdparty/providers/googleWorkspaces.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("./utils"); const implementation_1 = require("../api/implementation"); @@ -33,16 +55,31 @@ function GW(config) { scopes = config.scope; scopes = Array.from(new Set(scopes)); } - let additionalParams = config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined - ? {} - : config.authorisationRedirect.params; - let authorizationRedirectParams = Object.assign({ scope: scopes.join(" "), access_type: "offline", include_granted_scopes: "true", response_type: "code", client_id: config.clientId, hd: domain }, additionalParams); + let additionalParams = + config.authorisationRedirect === undefined || config.authorisationRedirect.params === undefined + ? {} + : config.authorisationRedirect.params; + let authorizationRedirectParams = Object.assign( + { + scope: scopes.join(" "), + access_type: "offline", + include_granted_scopes: "true", + response_type: "code", + client_id: config.clientId, + hd: domain, + }, + additionalParams + ); function getProfileInfo(authCodeResponse) { return __awaiter(this, void 0, void 0, function* () { - let payload = yield utils_1.verifyIdTokenFromJWKSEndpoint(authCodeResponse.id_token, "https://www.googleapis.com/oauth2/v3/certs", { - audience: implementation_1.getActualClientIdFromDevelopmentClientId(config.clientId), - issuer: ["https://accounts.google.com", "accounts.google.com"], - }); + let payload = yield utils_1.verifyIdTokenFromJWKSEndpoint( + authCodeResponse.id_token, + "https://www.googleapis.com/oauth2/v3/certs", + { + audience: implementation_1.getActualClientIdFromDevelopmentClientId(config.clientId), + issuer: ["https://accounts.google.com", "accounts.google.com"], + } + ); if (payload.email === undefined) { throw new Error("Could not get email. Please use a different login method"); } diff --git a/lib/build/recipe/thirdparty/providers/index.js b/lib/build/recipe/thirdparty/providers/index.js index c862ddc8c..6c796b11c 100644 --- a/lib/build/recipe/thirdparty/providers/index.js +++ b/lib/build/recipe/thirdparty/providers/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Github = exports.Facebook = exports.Google = void 0; const google_1 = __importDefault(require("./google")); diff --git a/lib/build/recipe/thirdparty/providers/utils.d.ts b/lib/build/recipe/thirdparty/providers/utils.d.ts index a3297f944..7edad22c7 100644 --- a/lib/build/recipe/thirdparty/providers/utils.d.ts +++ b/lib/build/recipe/thirdparty/providers/utils.d.ts @@ -1,2 +1,6 @@ import { VerifyOptions } from "jsonwebtoken"; -export declare function verifyIdTokenFromJWKSEndpoint(idToken: string, jwksUri: string, otherOptions: VerifyOptions): Promise; +export declare function verifyIdTokenFromJWKSEndpoint( + idToken: string, + jwksUri: string, + otherOptions: VerifyOptions +): Promise; diff --git a/lib/build/recipe/thirdparty/providers/utils.js b/lib/build/recipe/thirdparty/providers/utils.js index 3b004a20b..fbbe76311 100644 --- a/lib/build/recipe/thirdparty/providers/utils.js +++ b/lib/build/recipe/thirdparty/providers/utils.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyIdTokenFromJWKSEndpoint = void 0; const jsonwebtoken_1 = require("jsonwebtoken"); @@ -30,8 +54,7 @@ function verifyIdTokenFromJWKSEndpoint(idToken, jwksUri, otherOptions) { jsonwebtoken_1.verify(idToken, getKey, otherOptions, function (err, decoded) { if (err) { reject(err); - } - else { + } else { resolve(decoded); } }); diff --git a/lib/build/recipe/thirdparty/recipe.d.ts b/lib/build/recipe/thirdparty/recipe.d.ts index f1e31112b..e7f99ff8d 100644 --- a/lib/build/recipe/thirdparty/recipe.d.ts +++ b/lib/build/recipe/thirdparty/recipe.d.ts @@ -13,12 +13,25 @@ export default class Recipe extends RecipeModule { recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; isInServerlessEnv: boolean; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, _recipes: {}, _ingredients: {}); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + _recipes: {}, + _ingredients: {} + ); static init(config: TypeInput): RecipeListFunction; static getInstanceOrThrowError(): Recipe; static reset(): void; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, _path: NormalisedURLPath, _method: HTTPMethod) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + _path: NormalisedURLPath, + _method: HTTPMethod + ) => Promise; handleError: (err: STError, _request: BaseRequest, _response: BaseResponse) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; diff --git a/lib/build/recipe/thirdparty/recipe.js b/lib/build/recipe/thirdparty/recipe.js index 4b50c6cc0..b60df47f8 100644 --- a/lib/build/recipe/thirdparty/recipe.js +++ b/lib/build/recipe/thirdparty/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeModule_1 = __importDefault(require("../../recipeModule")); const utils_1 = require("./utils"); @@ -65,31 +89,31 @@ class Recipe extends recipeModule_1.default { }, ]; }; - this.handleAPIRequest = (id, req, res, _path, _method) => __awaiter(this, void 0, void 0, function* () { - let options = { - config: this.config, - recipeId: this.getRecipeId(), - isInServerlessEnv: this.isInServerlessEnv, - recipeImplementation: this.recipeInterfaceImpl, - providers: this.providers, - req, - res, - appInfo: this.getAppInfo(), - }; - if (id === constants_1.SIGN_IN_UP_API) { - return yield signinup_1.default(this.apiImpl, options); - } - else if (id === constants_1.AUTHORISATION_API) { - return yield authorisationUrl_1.default(this.apiImpl, options); - } - else if (id === constants_1.APPLE_REDIRECT_HANDLER) { - return yield appleRedirect_1.default(this.apiImpl, options); - } - return false; - }); - this.handleError = (err, _request, _response) => __awaiter(this, void 0, void 0, function* () { - throw err; - }); + this.handleAPIRequest = (id, req, res, _path, _method) => + __awaiter(this, void 0, void 0, function* () { + let options = { + config: this.config, + recipeId: this.getRecipeId(), + isInServerlessEnv: this.isInServerlessEnv, + recipeImplementation: this.recipeInterfaceImpl, + providers: this.providers, + req, + res, + appInfo: this.getAppInfo(), + }; + if (id === constants_1.SIGN_IN_UP_API) { + return yield signinup_1.default(this.apiImpl, options); + } else if (id === constants_1.AUTHORISATION_API) { + return yield authorisationUrl_1.default(this.apiImpl, options); + } else if (id === constants_1.APPLE_REDIRECT_HANDLER) { + return yield appleRedirect_1.default(this.apiImpl, options); + } + return false; + }); + this.handleError = (err, _request, _response) => + __awaiter(this, void 0, void 0, function* () { + throw err; + }); this.getAllCORSHeaders = () => { return []; }; @@ -97,23 +121,26 @@ class Recipe extends recipeModule_1.default { return error_1.default.isErrorFromSuperTokens(err) && err.fromRecipe === Recipe.RECIPE_ID; }; // helper functions... - this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo !== undefined) { + this.getEmailForUserId = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo !== undefined) { + return { + status: "OK", + email: userInfo.email, + }; + } return { - status: "OK", - email: userInfo.email, + status: "UNKNOWN_USER_ID_ERROR", }; - } - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - }); + }); this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); this.isInServerlessEnv = isInServerlessEnv; this.providers = this.config.signInAndUpFeature.providers; { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -130,12 +157,18 @@ class Recipe extends recipeModule_1.default { static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config, {}, { - emailDelivery: undefined, - }); + Recipe.instance = new Recipe( + Recipe.RECIPE_ID, + appInfo, + isInServerlessEnv, + config, + {}, + { + emailDelivery: undefined, + } + ); return Recipe.instance; - } - else { + } else { throw new Error("ThirdParty recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/thirdparty/recipeImplementation.js b/lib/build/recipe/thirdparty/recipeImplementation.js index 9f9a6a247..5fe91ff97 100644 --- a/lib/build/recipe/thirdparty/recipeImplementation.js +++ b/lib/build/recipe/thirdparty/recipeImplementation.js @@ -1,21 +1,45 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); function getRecipeImplementation(querier) { return { - signInUp: function ({ thirdPartyId, thirdPartyUserId, email, }) { + signInUp: function ({ thirdPartyId, thirdPartyUserId, email }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signinup"), { thirdPartyId, @@ -36,21 +60,23 @@ function getRecipeImplementation(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } - else { + } else { return undefined; } }); }, getUsersByEmail: function ({ email }) { return __awaiter(this, void 0, void 0, function* () { - const { users } = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/users/by-email"), { - email, - }); + const { users } = yield querier.sendGetRequest( + new normalisedURLPath_1.default("/recipe/users/by-email"), + { + email, + } + ); return users; }); }, - getUserByThirdPartyInfo: function ({ thirdPartyId, thirdPartyUserId, }) { + getUserByThirdPartyInfo: function ({ thirdPartyId, thirdPartyUserId }) { return __awaiter(this, void 0, void 0, function* () { let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { thirdPartyId, @@ -58,8 +84,7 @@ function getRecipeImplementation(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } - else { + } else { return undefined; } }); diff --git a/lib/build/recipe/thirdparty/types.d.ts b/lib/build/recipe/thirdparty/types.d.ts index 4d74f1e62..b0b9b6f6b 100644 --- a/lib/build/recipe/thirdparty/types.d.ts +++ b/lib/build/recipe/thirdparty/types.d.ts @@ -29,7 +29,11 @@ export declare type TypeProviderGetResponse = { }; export declare type TypeProvider = { id: string; - get: (redirectURI: string | undefined, authCodeFromRequest: string | undefined, userContext: any) => TypeProviderGetResponse; + get: ( + redirectURI: string | undefined, + authCodeFromRequest: string | undefined, + userContext: any + ) => TypeProviderGetResponse; isDefault?: boolean; }; export declare type User = { @@ -51,26 +55,26 @@ export declare type TypeNormalisedInputSignInAndUp = { export declare type TypeInput = { signInAndUpFeature: TypeInputSignInAndUp; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { signInAndUpFeature: TypeNormalisedInputSignInAndUp; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getUserById(input: { - userId: string; - userContext: any; - }): Promise; - getUsersByEmail(input: { - email: string; - userContext: any; - }): Promise; + getUserById(input: { userId: string; userContext: any }): Promise; + getUsersByEmail(input: { email: string; userContext: any }): Promise; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -98,75 +102,94 @@ export declare type APIOptions = { appInfo: NormalisedAppinfo; }; export declare type APIInterface = { - authorisationUrlGET: undefined | ((input: { - provider: TypeProvider; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - url: string; - } | GeneralErrorResponse>); - signInUpPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } | { - status: "SIGNIN_NOT_ALLOWED"; - primaryUserId: string; - description: string; - } | GeneralErrorResponse>); - linkAccountToExistingAccountPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - authCodeResponse: any; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } | GeneralErrorResponse>); - appleRedirectHandlerPOST: undefined | ((input: { - code: string; - state: string; - options: APIOptions; - userContext: any; - }) => Promise); + authorisationUrlGET: + | undefined + | ((input: { + provider: TypeProvider; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + url: string; + } + | GeneralErrorResponse + >); + signInUpPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } + | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + | { + status: "SIGNIN_NOT_ALLOWED"; + primaryUserId: string; + description: string; + } + | GeneralErrorResponse + >); + linkAccountToExistingAccountPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + authCodeResponse: any; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } + | GeneralErrorResponse + >); + appleRedirectHandlerPOST: + | undefined + | ((input: { code: string; state: string; options: APIOptions; userContext: any }) => Promise); }; diff --git a/lib/build/recipe/thirdparty/utils.d.ts b/lib/build/recipe/thirdparty/utils.d.ts index 7e28d0a8c..c83bcea11 100644 --- a/lib/build/recipe/thirdparty/utils.d.ts +++ b/lib/build/recipe/thirdparty/utils.d.ts @@ -1,5 +1,12 @@ import { NormalisedAppinfo } from "../../types"; import { TypeProvider } from "./types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput(appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; -export declare function findRightProvider(providers: TypeProvider[], thirdPartyId: string, clientId?: string): TypeProvider | undefined; +export declare function validateAndNormaliseUserInput( + appInfo: NormalisedAppinfo, + config: TypeInput +): TypeNormalisedInput; +export declare function findRightProvider( + providers: TypeProvider[], + thirdPartyId: string, + clientId?: string +): TypeProvider | undefined; diff --git a/lib/build/recipe/thirdparty/utils.js b/lib/build/recipe/thirdparty/utils.js index 873ce97c8..ab88136b4 100644 --- a/lib/build/recipe/thirdparty/utils.js +++ b/lib/build/recipe/thirdparty/utils.js @@ -17,7 +17,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.findRightProvider = exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(appInfo, config) { let signInAndUpFeature = validateAndNormaliseSignInAndUpConfig(appInfo, config.signInAndUpFeature); - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config.override + ); return { signInAndUpFeature, override, @@ -48,7 +54,9 @@ exports.findRightProvider = findRightProvider; function validateAndNormaliseSignInAndUpConfig(_, config) { let providers = config.providers; if (providers === undefined || providers.length === 0) { - throw new Error("thirdparty recipe requires atleast 1 provider to be passed in signInAndUpFeature.providers config"); + throw new Error( + "thirdparty recipe requires atleast 1 provider to be passed in signInAndUpFeature.providers config" + ); } // we check if there are multiple providers with the same id that have isDefault as true. // In this case, we want to throw an error.. @@ -68,14 +76,18 @@ function validateAndNormaliseSignInAndUpConfig(_, config) { } if (isDefault) { if (isDefaultProvidersSet.has(id)) { - throw new Error(`You have provided multiple third party providers that have the id: "${id}" and are marked as "isDefault: true". Please only mark one of them as isDefault.`); + throw new Error( + `You have provided multiple third party providers that have the id: "${id}" and are marked as "isDefault: true". Please only mark one of them as isDefault.` + ); } isDefaultProvidersSet.add(id); } }); if (isDefaultProvidersSet.size !== allProvidersSet.size) { // this means that there is no provider marked as isDefault - throw new Error(`The providers array has multiple entries for the same third party provider. Please mark one of them as the default one by using "isDefault: true".`); + throw new Error( + `The providers array has multiple entries for the same third party provider. Please mark one of them as the default one by using "isDefault: true".` + ); } return { providers, diff --git a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js index 8e25733ae..ecdb8e01a 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js @@ -3,12 +3,28 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e, _f; return { - emailExistsGET: (_a = apiImplmentation.emailPasswordEmailExistsGET) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation), - generatePasswordResetTokenPOST: (_b = apiImplmentation.generatePasswordResetTokenPOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), - passwordResetPOST: (_c = apiImplmentation.passwordResetPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - signInPOST: (_d = apiImplmentation.emailPasswordSignInPOST) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), - signUpPOST: (_e = apiImplmentation.emailPasswordSignUpPOST) === null || _e === void 0 ? void 0 : _e.bind(apiImplmentation), - linkAccountToExistingAccountPOST: (_f = apiImplmentation.linkEmailPasswordAccountToExistingAccountPOST) === null || _f === void 0 ? void 0 : _f.bind(apiImplmentation), + emailExistsGET: + (_a = apiImplmentation.emailPasswordEmailExistsGET) === null || _a === void 0 + ? void 0 + : _a.bind(apiImplmentation), + generatePasswordResetTokenPOST: + (_b = apiImplmentation.generatePasswordResetTokenPOST) === null || _b === void 0 + ? void 0 + : _b.bind(apiImplmentation), + passwordResetPOST: + (_c = apiImplmentation.passwordResetPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + signInPOST: + (_d = apiImplmentation.emailPasswordSignInPOST) === null || _d === void 0 + ? void 0 + : _d.bind(apiImplmentation), + signUpPOST: + (_e = apiImplmentation.emailPasswordSignUpPOST) === null || _e === void 0 + ? void 0 + : _e.bind(apiImplmentation), + linkAccountToExistingAccountPOST: + (_f = apiImplmentation.linkEmailPasswordAccountToExistingAccountPOST) === null || _f === void 0 + ? void 0 + : _f.bind(apiImplmentation), }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/implementation.js b/lib/build/recipe/thirdpartyemailpassword/api/implementation.js index a1297f0f8..05d5a6332 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/implementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/implementation.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const implementation_1 = __importDefault(require("../../emailpassword/api/implementation")); const implementation_2 = __importDefault(require("../../thirdparty/api/implementation")); @@ -12,16 +14,46 @@ function getAPIImplementation() { let emailPasswordImplementation = implementation_1.default(); let thirdPartyImplementation = implementation_2.default(); return { - emailPasswordEmailExistsGET: (_a = emailPasswordImplementation.emailExistsGET) === null || _a === void 0 ? void 0 : _a.bind(emailPasswordAPIImplementation_1.default(this)), - authorisationUrlGET: (_b = thirdPartyImplementation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(thirdPartyAPIImplementation_1.default(this)), - emailPasswordSignInPOST: (_c = emailPasswordImplementation.signInPOST) === null || _c === void 0 ? void 0 : _c.bind(emailPasswordAPIImplementation_1.default(this)), - emailPasswordSignUpPOST: (_d = emailPasswordImplementation.signUpPOST) === null || _d === void 0 ? void 0 : _d.bind(emailPasswordAPIImplementation_1.default(this)), - generatePasswordResetTokenPOST: (_e = emailPasswordImplementation.generatePasswordResetTokenPOST) === null || _e === void 0 ? void 0 : _e.bind(emailPasswordAPIImplementation_1.default(this)), - linkEmailPasswordAccountToExistingAccountPOST: (_f = emailPasswordImplementation.linkAccountToExistingAccountPOST) === null || _f === void 0 ? void 0 : _f.bind(emailPasswordAPIImplementation_1.default(this)), - linkThirdPartyAccountToExistingAccountPOST: (_g = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), - passwordResetPOST: (_h = emailPasswordImplementation.passwordResetPOST) === null || _h === void 0 ? void 0 : _h.bind(emailPasswordAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: (_j = thirdPartyImplementation.signInUpPOST) === null || _j === void 0 ? void 0 : _j.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: (_k = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _k === void 0 ? void 0 : _k.bind(thirdPartyAPIImplementation_1.default(this)), + emailPasswordEmailExistsGET: + (_a = emailPasswordImplementation.emailExistsGET) === null || _a === void 0 + ? void 0 + : _a.bind(emailPasswordAPIImplementation_1.default(this)), + authorisationUrlGET: + (_b = thirdPartyImplementation.authorisationUrlGET) === null || _b === void 0 + ? void 0 + : _b.bind(thirdPartyAPIImplementation_1.default(this)), + emailPasswordSignInPOST: + (_c = emailPasswordImplementation.signInPOST) === null || _c === void 0 + ? void 0 + : _c.bind(emailPasswordAPIImplementation_1.default(this)), + emailPasswordSignUpPOST: + (_d = emailPasswordImplementation.signUpPOST) === null || _d === void 0 + ? void 0 + : _d.bind(emailPasswordAPIImplementation_1.default(this)), + generatePasswordResetTokenPOST: + (_e = emailPasswordImplementation.generatePasswordResetTokenPOST) === null || _e === void 0 + ? void 0 + : _e.bind(emailPasswordAPIImplementation_1.default(this)), + linkEmailPasswordAccountToExistingAccountPOST: + (_f = emailPasswordImplementation.linkAccountToExistingAccountPOST) === null || _f === void 0 + ? void 0 + : _f.bind(emailPasswordAPIImplementation_1.default(this)), + linkThirdPartyAccountToExistingAccountPOST: + (_g = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _g === void 0 + ? void 0 + : _g.bind(thirdPartyAPIImplementation_1.default(this)), + passwordResetPOST: + (_h = emailPasswordImplementation.passwordResetPOST) === null || _h === void 0 + ? void 0 + : _h.bind(emailPasswordAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: + (_j = thirdPartyImplementation.signInUpPOST) === null || _j === void 0 + ? void 0 + : _j.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: + (_k = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _k === void 0 + ? void 0 + : _k.bind(thirdPartyAPIImplementation_1.default(this)), }; } exports.default = getAPIImplementation; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js index 4e020209b..f440fdfb5 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js @@ -1,49 +1,89 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d; - const signInUpPOSTFromThirdPartyEmailPassword = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); - const linkThirdPartyAccountToExistingAccountPOST = (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyEmailPassword = + (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const linkThirdPartyAccountToExistingAccountPOST = + (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 + ? void 0 + : _b.bind(apiImplmentation); return { - authorisationUrlGET: (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - appleRedirectHandlerPOST: (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), - linkAccountToExistingAccountPOST: linkThirdPartyAccountToExistingAccountPOST === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield linkThirdPartyAccountToExistingAccountPOST(input); - if (result.status === "OK") { - if (result.user.thirdParty === undefined) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); - } - return result; - }); - }, - signInUpPOST: signInUpPOSTFromThirdPartyEmailPassword === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield signInUpPOSTFromThirdPartyEmailPassword(input); - if (result.status === "OK") { - if (result.user.thirdParty === undefined) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); - } - return result; - }); - }, + authorisationUrlGET: + (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + appleRedirectHandlerPOST: + (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 + ? void 0 + : _d.bind(apiImplmentation), + linkAccountToExistingAccountPOST: + linkThirdPartyAccountToExistingAccountPOST === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield linkThirdPartyAccountToExistingAccountPOST(input); + if (result.status === "OK") { + if (result.user.thirdParty === undefined) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { + user: Object.assign(Object.assign({}, result.user), { + thirdParty: Object.assign({}, result.user.thirdParty), + }), + }); + } + return result; + }); + }, + signInUpPOST: + signInUpPOSTFromThirdPartyEmailPassword === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield signInUpPOSTFromThirdPartyEmailPassword(input); + if (result.status === "OK") { + if (result.user.thirdParty === undefined) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { + user: Object.assign(Object.assign({}, result.user), { + thirdParty: Object.assign({}, result.user.thirdParty), + }), + }); + } + return result; + }); + }, }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 0d8f8bc11..68787c2e0 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -2,10 +2,17 @@ import { TypeThirdPartyEmailPasswordEmailDeliveryInput } from "../../../types"; import { RecipeInterface as EmailPasswordRecipeInterface } from "../../../../emailpassword"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService implements EmailDeliveryInterface { +export default class BackwardCompatibilityService + implements EmailDeliveryInterface { private emailPasswordBackwardCompatibilityService; - constructor(emailPasswordRecipeInterfaceImpl: EmailPasswordRecipeInterface, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean); - sendEmail: (input: TypeThirdPartyEmailPasswordEmailDeliveryInput & { - userContext: any; - }) => Promise; + constructor( + emailPasswordRecipeInterfaceImpl: EmailPasswordRecipeInterface, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean + ); + sendEmail: ( + input: TypeThirdPartyEmailPasswordEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js index 3f61cbbe2..ee09e5c75 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.js @@ -1,25 +1,56 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); -const backwardCompatibility_1 = __importDefault(require("../../../../emailpassword/emaildelivery/services/backwardCompatibility")); +const backwardCompatibility_1 = __importDefault( + require("../../../../emailpassword/emaildelivery/services/backwardCompatibility") +); class BackwardCompatibilityService { constructor(emailPasswordRecipeInterfaceImpl, appInfo, isInServerlessEnv) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.emailPasswordBackwardCompatibilityService.sendEmail(input); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.emailPasswordBackwardCompatibilityService.sendEmail(input); + }); { - this.emailPasswordBackwardCompatibilityService = new backwardCompatibility_1.default(emailPasswordRecipeInterfaceImpl, appInfo, isInServerlessEnv); + this.emailPasswordBackwardCompatibilityService = new backwardCompatibility_1.default( + emailPasswordRecipeInterfaceImpl, + appInfo, + isInServerlessEnv + ); } } } diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js index 3e4b76c1d..7e07f6706 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SMTPService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts index 9c7db38da..03dc8c577 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts @@ -4,7 +4,9 @@ import { TypeThirdPartyEmailPasswordEmailDeliveryInput } from "../../../types"; export default class SMTPService implements EmailDeliveryInterface { private emailPasswordSMTPService; constructor(config: TypeInput); - sendEmail: (input: TypeThirdPartyEmailPasswordEmailDeliveryInput & { - userContext: any; - }) => Promise; + sendEmail: ( + input: TypeThirdPartyEmailPasswordEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js index f2bd7086f..ab6aa1bf8 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.js @@ -1,23 +1,48 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const smtp_1 = __importDefault(require("../../../../emailpassword/emaildelivery/services/smtp")); class SMTPService { constructor(config) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.emailPasswordSMTPService.sendEmail(input); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.emailPasswordSMTPService.sendEmail(input); + }); this.emailPasswordSMTPService = new smtp_1.default(config); } } diff --git a/lib/build/recipe/thirdpartyemailpassword/error.d.ts b/lib/build/recipe/thirdpartyemailpassword/error.d.ts index 3dc8820ff..56d432191 100644 --- a/lib/build/recipe/thirdpartyemailpassword/error.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/error.d.ts @@ -1,7 +1,4 @@ import STError from "../../error"; export default class ThirdPartyEmailPasswordError extends STError { - constructor(options: { - type: "BAD_INPUT_ERROR"; - message: string; - }); + constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); } diff --git a/lib/build/recipe/thirdpartyemailpassword/error.js b/lib/build/recipe/thirdpartyemailpassword/error.js index 004372622..a16bebfe0 100644 --- a/lib/build/recipe/thirdpartyemailpassword/error.js +++ b/lib/build/recipe/thirdpartyemailpassword/error.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); class ThirdPartyEmailPasswordError extends error_1.default { diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index 19d6cbba1..cc1b4cf71 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -6,47 +6,89 @@ import { TypeEmailPasswordEmailDeliveryInput } from "../emailpassword/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ + static thirdPartySignInUp( + thirdPartyId: string, + thirdPartyUserId: string, + email: string, + userContext?: any + ): Promise<{ status: "OK"; createdNewUser: boolean; user: User; }>; - static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; - static emailPasswordSignUp(email: string, password: string, doAccountLinking?: boolean, userContext?: any): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: import("../emailpassword").User; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - }>; - static emailPasswordSignIn(email: string, password: string, userContext?: any): Promise<{ - status: "OK"; - user: import("../emailpassword").User; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - }>; + static getUserByThirdPartyInfo( + thirdPartyId: string, + thirdPartyUserId: string, + userContext?: any + ): Promise; + static emailPasswordSignUp( + email: string, + password: string, + doAccountLinking?: boolean, + userContext?: any + ): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: import("../emailpassword").User; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >; + static emailPasswordSignIn( + email: string, + password: string, + userContext?: any + ): Promise< + | { + status: "OK"; + user: import("../emailpassword").User; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + >; static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise<(import("../emailpassword").User | User)[]>; - static createResetPasswordToken(userId: string, email: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "UNKNOWN_USER_ID_ERROR"; - }>; - static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ - status: "OK"; - email: string; - userId: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + static createResetPasswordToken( + userId: string, + email: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "UNKNOWN_USER_ID_ERROR"; + } + >; + static resetPasswordUsingToken( + token: string, + newPassword: string, + userContext?: any + ): Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; static updateEmailOrPassword(input: { userId: string; email?: string; password?: string; userContext?: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; static Google: typeof import("../thirdparty/providers/google").default; static Github: typeof import("../thirdparty/providers/github").default; @@ -54,9 +96,11 @@ export default class Wrapper { static Apple: typeof import("../thirdparty/providers/apple").default; static Discord: typeof import("../thirdparty/providers/discord").default; static GoogleWorkspaces: typeof import("../thirdparty/providers/googleWorkspaces").default; - static sendEmail(input: TypeEmailPasswordEmailDeliveryInput & { - userContext?: any; - }): Promise; + static sendEmail( + input: TypeEmailPasswordEmailDeliveryInput & { + userContext?: any; + } + ): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/thirdpartyemailpassword/index.js b/lib/build/recipe/thirdpartyemailpassword/index.js index 8ca4e6941..281cbddf9 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/index.js @@ -13,37 +13,78 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sendEmail = exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.updateEmailOrPassword = exports.resetPasswordUsingToken = exports.createResetPasswordToken = exports.getUsersByEmail = exports.getUserByThirdPartyInfo = exports.getUserById = exports.thirdPartySignInUp = exports.emailPasswordSignIn = exports.emailPasswordSignUp = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); @@ -101,13 +142,17 @@ class Wrapper { }); } static updateEmailOrPassword(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.updateEmailOrPassword(Object.assign({ userContext: {} }, input)); } // static Okta = thirdPartyProviders.Okta; // static ActiveDirectory = thirdPartyProviders.ActiveDirectory; static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default + .getInstanceOrThrowError() + .emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } } diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts index 4b05b5419..0d27e198f 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts @@ -4,7 +4,13 @@ import EmailPasswordRecipe from "../emailpassword/recipe"; import ThirdPartyRecipe from "../thirdparty/recipe"; import { BaseRequest, BaseResponse } from "../../framework"; import STError from "./error"; -import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, TypeThirdPartyEmailPasswordEmailDeliveryInput } from "./types"; +import { + TypeInput, + TypeNormalisedInput, + RecipeInterface, + APIInterface, + TypeThirdPartyEmailPasswordEmailDeliveryInput, +} from "./types"; import STErrorEmailPassword from "../emailpassword/error"; import STErrorThirdParty from "../thirdparty/error"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -19,18 +25,35 @@ export default class Recipe extends RecipeModule { apiImpl: APIInterface; isInServerlessEnv: boolean; emailDelivery: EmailDeliveryIngredient; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { - thirdPartyInstance: ThirdPartyRecipe | undefined; - emailPasswordInstance: EmailPasswordRecipe | undefined; - }, ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + recipes: { + thirdPartyInstance: ThirdPartyRecipe | undefined; + emailPasswordInstance: EmailPasswordRecipe | undefined; + }, + ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + } + ); static init(config: TypeInput): RecipeListFunction; static reset(): void; static getInstanceOrThrowError(): Recipe; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; - handleError: (err: STErrorEmailPassword | STErrorThirdParty, request: BaseRequest, response: BaseResponse) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + path: NormalisedURLPath, + method: HTTPMethod + ) => Promise; + handleError: ( + err: STErrorEmailPassword | STErrorThirdParty, + request: BaseRequest, + response: BaseResponse + ) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; } diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.js b/lib/build/recipe/thirdpartyemailpassword/recipe.js index 9ceb2be89..37614c57f 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -32,8 +56,12 @@ const recipe_2 = __importDefault(require("../thirdparty/recipe")); const error_1 = __importDefault(require("./error")); const utils_1 = require("./utils"); const recipeImplementation_1 = __importDefault(require("./recipeImplementation")); -const emailPasswordRecipeImplementation_1 = __importDefault(require("./recipeImplementation/emailPasswordRecipeImplementation")); -const thirdPartyRecipeImplementation_1 = __importDefault(require("./recipeImplementation/thirdPartyRecipeImplementation")); +const emailPasswordRecipeImplementation_1 = __importDefault( + require("./recipeImplementation/emailPasswordRecipeImplementation") +); +const thirdPartyRecipeImplementation_1 = __importDefault( + require("./recipeImplementation/thirdPartyRecipeImplementation") +); const thirdPartyAPIImplementation_1 = __importDefault(require("./api/thirdPartyAPIImplementation")); const emailPasswordAPIImplementation_1 = __importDefault(require("./api/emailPasswordAPIImplementation")); const implementation_1 = __importDefault(require("./api/implementation")); @@ -50,30 +78,35 @@ class Recipe extends recipeModule_1.default { } return apisHandled; }; - this.handleAPIRequest = (id, req, res, path, method) => __awaiter(this, void 0, void 0, function* () { - if (this.emailPasswordRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { - return yield this.emailPasswordRecipe.handleAPIRequest(id, req, res, path, method); - } - if (this.thirdPartyRecipe !== undefined && - this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { - return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); - } - return false; - }); - this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - throw err; - } - else { - if (this.emailPasswordRecipe.isErrorFromThisRecipe(err)) { - return yield this.emailPasswordRecipe.handleError(err, request, response); + this.handleAPIRequest = (id, req, res, path, method) => + __awaiter(this, void 0, void 0, function* () { + if (this.emailPasswordRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { + return yield this.emailPasswordRecipe.handleAPIRequest(id, req, res, path, method); } - else if (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)) { - return yield this.thirdPartyRecipe.handleError(err, request, response); + if ( + this.thirdPartyRecipe !== undefined && + this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined + ) { + return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); } - throw err; - } - }); + return false; + }); + this.handleError = (err, request, response) => + __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + throw err; + } else { + if (this.emailPasswordRecipe.isErrorFromThisRecipe(err)) { + return yield this.emailPasswordRecipe.handleError(err, request, response); + } else if ( + this.thirdPartyRecipe !== undefined && + this.thirdPartyRecipe.isErrorFromThisRecipe(err) + ) { + return yield this.thirdPartyRecipe.handleError(err, request, response); + } + throw err; + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [...this.emailPasswordRecipe.getAllCORSHeaders()]; if (this.thirdPartyRecipe !== undefined) { @@ -82,15 +115,22 @@ class Recipe extends recipeModule_1.default { return corsHeaders; }; this.isErrorFromThisRecipe = (err) => { - return (error_1.default.isErrorFromSuperTokens(err) && + return ( + error_1.default.isErrorFromSuperTokens(err) && (err.fromRecipe === Recipe.RECIPE_ID || this.emailPasswordRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) + ); }; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default( + querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), + querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID) + ) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -104,60 +144,83 @@ class Recipe extends recipeModule_1.default { */ this.emailDelivery = ingredients.emailDelivery === undefined - ? new emaildelivery_1.default(this.config.getEmailDeliveryConfig(emailPasswordRecipeImplementation, this.isInServerlessEnv)) + ? new emaildelivery_1.default( + this.config.getEmailDeliveryConfig(emailPasswordRecipeImplementation, this.isInServerlessEnv) + ) : ingredients.emailDelivery; this.emailPasswordRecipe = recipes.emailPasswordInstance !== undefined ? recipes.emailPasswordInstance - : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, { - override: { - functions: (_) => { - return emailPasswordRecipeImplementation; - }, - apis: (_) => { - return emailPasswordAPIImplementation_1.default(this.apiImpl); - }, - }, - signUpFeature: { - formFields: this.config.signUpFeature.formFields, - }, - }, { - emailDelivery: this.emailDelivery, - }); + : new recipe_1.default( + recipeId, + appInfo, + isInServerlessEnv, + { + override: { + functions: (_) => { + return emailPasswordRecipeImplementation; + }, + apis: (_) => { + return emailPasswordAPIImplementation_1.default(this.apiImpl); + }, + }, + signUpFeature: { + formFields: this.config.signUpFeature.formFields, + }, + }, + { + emailDelivery: this.emailDelivery, + } + ); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_2.default(recipeId, appInfo, isInServerlessEnv, { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, {}, { - emailDelivery: this.emailDelivery, - }); + : new recipe_2.default( + recipeId, + appInfo, + isInServerlessEnv, + { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, + {}, + { + emailDelivery: this.emailDelivery, + } + ); } } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config, { - emailPasswordInstance: undefined, - thirdPartyInstance: undefined, - }, { - emailDelivery: undefined, - }); + Recipe.instance = new Recipe( + Recipe.RECIPE_ID, + appInfo, + isInServerlessEnv, + config, + { + emailPasswordInstance: undefined, + thirdPartyInstance: undefined, + }, + { + emailDelivery: undefined, + } + ); return Recipe.instance; - } - else { - throw new Error("ThirdPartyEmailPassword recipe has already been initialised. Please check your code for bugs."); + } else { + throw new Error( + "ThirdPartyEmailPassword recipe has already been initialised. Please check your code for bugs." + ); } }; } diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js index 2ce58f790..8d8772bdd 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js index adcfda326..333844ed6 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeImplementation_1 = __importDefault(require("../../emailpassword/recipeImplementation")); const recipeImplementation_2 = __importDefault(require("../../thirdparty/recipeImplementation")); @@ -25,12 +49,16 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { return { emailPasswordSignUp: function (input) { return __awaiter(this, void 0, void 0, function* () { - return yield originalEmailPasswordImplementation.signUp.bind(emailPasswordRecipeImplementation_1.default(this))(input); + return yield originalEmailPasswordImplementation.signUp.bind( + emailPasswordRecipeImplementation_1.default(this) + )(input); }); }, emailPasswordSignIn: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.signIn.bind(emailPasswordRecipeImplementation_1.default(this))(input); + return originalEmailPasswordImplementation.signIn.bind( + emailPasswordRecipeImplementation_1.default(this) + )(input); }); }, thirdPartySignInUp: function (input) { @@ -38,31 +66,41 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { throw new Error("No thirdparty provider configured"); } - return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))(input); + return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))( + input + ); }); }, getUserById: function (input) { return __awaiter(this, void 0, void 0, function* () { - let user = yield originalEmailPasswordImplementation.getUserById.bind(emailPasswordRecipeImplementation_1.default(this))(input); + let user = yield originalEmailPasswordImplementation.getUserById.bind( + emailPasswordRecipeImplementation_1.default(this) + )(input); if (user !== undefined) { return user; } if (originalThirdPartyImplementation === undefined) { return undefined; } - return yield originalThirdPartyImplementation.getUserById.bind(thirdPartyRecipeImplementation_1.default(this))(input); + return yield originalThirdPartyImplementation.getUserById.bind( + thirdPartyRecipeImplementation_1.default(this) + )(input); }); }, - getUsersByEmail: function ({ email, userContext, }) { + getUsersByEmail: function ({ email, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let userFromEmailPass = yield originalEmailPasswordImplementation.getUserByEmail.bind(emailPasswordRecipeImplementation_1.default(this))({ + let userFromEmailPass = yield originalEmailPasswordImplementation.getUserByEmail.bind( + emailPasswordRecipeImplementation_1.default(this) + )({ email, userContext, }); if (originalThirdPartyImplementation === undefined) { return userFromEmailPass === undefined ? [] : [userFromEmailPass]; } - let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind(thirdPartyRecipeImplementation_1.default(this))({ email, userContext }); + let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind( + thirdPartyRecipeImplementation_1.default(this) + )({ email, userContext }); if (userFromEmailPass !== undefined) { return [...usersFromThirdParty, userFromEmailPass]; } @@ -74,17 +112,23 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { return undefined; } - return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind(thirdPartyRecipeImplementation_1.default(this))(input); + return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind( + thirdPartyRecipeImplementation_1.default(this) + )(input); }); }, createResetPasswordToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.createResetPasswordToken.bind(emailPasswordRecipeImplementation_1.default(this))(input); + return originalEmailPasswordImplementation.createResetPasswordToken.bind( + emailPasswordRecipeImplementation_1.default(this) + )(input); }); }, resetPasswordUsingToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.resetPasswordUsingToken.bind(emailPasswordRecipeImplementation_1.default(this))(input); + return originalEmailPasswordImplementation.resetPasswordUsingToken.bind( + emailPasswordRecipeImplementation_1.default(this) + )(input); }); }, updateEmailOrPassword: function (input) { @@ -94,11 +138,12 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { return { status: "UNKNOWN_USER_ID_ERROR", }; - } - else if (user.thirdParty !== undefined) { + } else if (user.thirdParty !== undefined) { throw new Error("Cannot update email or password of a user who signed up using third party login."); } - return originalEmailPasswordImplementation.updateEmailOrPassword.bind(emailPasswordRecipeImplementation_1.default(this))(input); + return originalEmailPasswordImplementation.updateEmailOrPassword.bind( + emailPasswordRecipeImplementation_1.default(this) + )(input); }); }, }; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js index 9638c19cf..25f155ca3 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartyemailpassword/types.d.ts b/lib/build/recipe/thirdpartyemailpassword/types.d.ts index e100b05a4..1a46c9fa7 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -1,8 +1,18 @@ import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; -import { NormalisedFormField, TypeFormField, TypeInputFormField, APIOptions as EmailPasswordAPIOptionsOriginal, TypeEmailPasswordEmailDeliveryInput, RecipeInterface as EPRecipeInterface } from "../emailpassword/types"; +import { + NormalisedFormField, + TypeFormField, + TypeInputFormField, + APIOptions as EmailPasswordAPIOptionsOriginal, + TypeEmailPasswordEmailDeliveryInput, + RecipeInterface as EPRecipeInterface, +} from "../emailpassword/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; +import { + TypeInput as EmailDeliveryTypeInput, + TypeInputWithService as EmailDeliveryTypeInputWithService, +} from "../../ingredients/emaildelivery/types"; import { GeneralErrorResponse, User as GlobalUser } from "../../types"; export declare type User = { id: string; @@ -36,28 +46,31 @@ export declare type TypeInput = { providers?: TypeProvider[]; emailDelivery?: EmailDeliveryTypeInput; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { signUpFeature: TypeNormalisedInputSignUp; providers: TypeProvider[]; - getEmailDeliveryConfig: (emailPasswordRecipeImpl: EPRecipeInterface, isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; + getEmailDeliveryConfig: ( + emailPasswordRecipeImpl: EPRecipeInterface, + isInServerlessEnv: boolean + ) => EmailDeliveryTypeInputWithService; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getUserById(input: { - userId: string; - userContext: any; - }): Promise; - getUsersByEmail(input: { - email: string; - userContext: any; - }): Promise<(User | GlobalUser)[]>; + getUserById(input: { userId: string; userContext: any }): Promise; + getUsersByEmail(input: { email: string; userContext: any }): Promise<(User | GlobalUser)[]>; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -78,224 +91,298 @@ export declare type RecipeInterface = { password: string; doAccountLinking: boolean; userContext: any; - }): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: GlobalUser; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: GlobalUser; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >; emailPasswordSignIn(input: { email: string; password: string; userContext: any; - }): Promise<{ - status: "OK"; - user: GlobalUser; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + user: GlobalUser; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + >; createResetPasswordToken(input: { userId: string; email: string; userContext: any; - }): Promise<{ - status: "OK"; - token: string; - } | { - status: "UNKNOWN_USER_ID_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "UNKNOWN_USER_ID_ERROR"; + } + >; resetPasswordUsingToken(input: { token: string; newPassword: string; userContext: any; - }): Promise<{ - status: "OK"; - email: string; - userId: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; updateEmailOrPassword(input: { userId: string; email?: string; password?: string; userContext: any; }): Promise<{ - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; + status: + | "OK" + | "UNKNOWN_USER_ID_ERROR" + | "EMAIL_ALREADY_EXISTS_ERROR" + | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; }>; }; export declare type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; export declare type ThirdPartyAPIOptions = ThirdPartyAPIOptionsOriginal; export declare type APIInterface = { - linkThirdPartyAccountToExistingAccountPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - session: SessionContainerInterface; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - authCodeResponse: any; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } | GeneralErrorResponse>); - authorisationUrlGET: undefined | ((input: { - provider: TypeProvider; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - url: string; - } | GeneralErrorResponse>); - emailPasswordEmailExistsGET: undefined | ((input: { - email: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - } | GeneralErrorResponse>); - generatePasswordResetTokenPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - } | { - status: "PASSWORD_RESET_NOT_ALLOWED"; - reason: string; - } | GeneralErrorResponse>); - passwordResetPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - email: string; - userId: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } | GeneralErrorResponse>); - thirdPartySignInUpPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } | GeneralErrorResponse | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } | { - status: "SIGNIN_NOT_ALLOWED"; - primaryUserId: string; - description: string; - }>); - linkEmailPasswordAccountToExistingAccountPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - session: SessionContainerInterface; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: GlobalUser; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } | GeneralErrorResponse>); - emailPasswordSignInPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: GlobalUser; - session: SessionContainerInterface; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - } | GeneralErrorResponse>); - emailPasswordSignUpPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: GlobalUser; - createdNewUser: boolean; - session: SessionContainerInterface; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } | GeneralErrorResponse>); - appleRedirectHandlerPOST: undefined | ((input: { - code: string; - state: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise); + linkThirdPartyAccountToExistingAccountPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + session: SessionContainerInterface; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + authCodeResponse: any; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } + | GeneralErrorResponse + >); + authorisationUrlGET: + | undefined + | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + url: string; + } + | GeneralErrorResponse + >); + emailPasswordEmailExistsGET: + | undefined + | ((input: { + email: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >); + generatePasswordResetTokenPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + } + | { + status: "PASSWORD_RESET_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); + passwordResetPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + | GeneralErrorResponse + >); + thirdPartySignInUpPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } + | GeneralErrorResponse + | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + | { + status: "SIGNIN_NOT_ALLOWED"; + primaryUserId: string; + description: string; + } + >); + linkEmailPasswordAccountToExistingAccountPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + session: SessionContainerInterface; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: GlobalUser; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } + | GeneralErrorResponse + >); + emailPasswordSignInPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: GlobalUser; + session: SessionContainerInterface; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + | GeneralErrorResponse + >); + emailPasswordSignUpPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: GlobalUser; + createdNewUser: boolean; + session: SessionContainerInterface; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); + appleRedirectHandlerPOST: + | undefined + | ((input: { code: string; state: string; options: ThirdPartyAPIOptions; userContext: any }) => Promise); }; export declare type TypeThirdPartyEmailPasswordEmailDeliveryInput = TypeEmailPasswordEmailDeliveryInput; diff --git a/lib/build/recipe/thirdpartyemailpassword/utils.d.ts b/lib/build/recipe/thirdpartyemailpassword/utils.d.ts index ff87c17db..56c6f7b41 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/utils.d.ts @@ -1,4 +1,8 @@ import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; import Recipe from "./recipe"; -export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + recipeInstance: Recipe, + appInfo: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; diff --git a/lib/build/recipe/thirdpartyemailpassword/utils.js b/lib/build/recipe/thirdpartyemailpassword/utils.js index 5fbead775..9b36d7936 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.js +++ b/lib/build/recipe/thirdpartyemailpassword/utils.js @@ -13,20 +13,35 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAndNormaliseUserInput = void 0; const utils_1 = require("../emailpassword/utils"); const backwardCompatibility_1 = __importDefault(require("./emaildelivery/services/backwardCompatibility")); function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { - let signUpFeature = validateAndNormaliseSignUpConfig(recipeInstance, appInfo, config === undefined ? undefined : config.signUpFeature); + let signUpFeature = validateAndNormaliseSignUpConfig( + recipeInstance, + appInfo, + config === undefined ? undefined : config.signUpFeature + ); let providers = config === undefined || config.providers === undefined ? [] : config.providers; - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); function getEmailDeliveryConfig(emailPasswordRecipeImpl, isInServerlessEnv) { var _a; - let emailService = (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; + let emailService = + (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 + ? void 0 + : _a.service; /** * following code is for backward compatibility. * if user has not passed emailDelivery config, we @@ -37,7 +52,7 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { if (emailService === undefined) { emailService = new backwardCompatibility_1.default(emailPasswordRecipeImpl, appInfo, isInServerlessEnv); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -49,7 +64,8 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService }); + service: emailService, + }); } return { override, diff --git a/lib/build/recipe/thirdpartypasswordless/api/implementation.js b/lib/build/recipe/thirdpartypasswordless/api/implementation.js index 5bedcfafb..b4e31da01 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/implementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/implementation.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const implementation_1 = __importDefault(require("../../passwordless/api/implementation")); const implementation_2 = __importDefault(require("../../thirdparty/api/implementation")); @@ -12,16 +14,46 @@ function getAPIImplementation() { let passwordlessImplementation = implementation_1.default(); let thirdPartyImplementation = implementation_2.default(); return { - consumeCodePOST: (_a = passwordlessImplementation.consumeCodePOST) === null || _a === void 0 ? void 0 : _a.bind(passwordlessAPIImplementation_1.default(this)), - createCodePOST: (_b = passwordlessImplementation.createCodePOST) === null || _b === void 0 ? void 0 : _b.bind(passwordlessAPIImplementation_1.default(this)), - passwordlessUserEmailExistsGET: (_c = passwordlessImplementation.emailExistsGET) === null || _c === void 0 ? void 0 : _c.bind(passwordlessAPIImplementation_1.default(this)), - passwordlessUserPhoneNumberExistsGET: (_d = passwordlessImplementation.phoneNumberExistsGET) === null || _d === void 0 ? void 0 : _d.bind(passwordlessAPIImplementation_1.default(this)), - linkThirdPartyAccountToExistingAccountPOST: (_e = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _e === void 0 ? void 0 : _e.bind(thirdPartyAPIImplementation_1.default(this)), - resendCodePOST: (_f = passwordlessImplementation.resendCodePOST) === null || _f === void 0 ? void 0 : _f.bind(passwordlessAPIImplementation_1.default(this)), - authorisationUrlGET: (_g = thirdPartyImplementation.authorisationUrlGET) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: (_h = thirdPartyImplementation.signInUpPOST) === null || _h === void 0 ? void 0 : _h.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: (_j = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _j === void 0 ? void 0 : _j.bind(thirdPartyAPIImplementation_1.default(this)), - linkPasswordlessAccountToExistingAccountPOST: (_k = passwordlessImplementation.linkAccountToExistingAccountPOST) === null || _k === void 0 ? void 0 : _k.bind(passwordlessAPIImplementation_1.default(this)), + consumeCodePOST: + (_a = passwordlessImplementation.consumeCodePOST) === null || _a === void 0 + ? void 0 + : _a.bind(passwordlessAPIImplementation_1.default(this)), + createCodePOST: + (_b = passwordlessImplementation.createCodePOST) === null || _b === void 0 + ? void 0 + : _b.bind(passwordlessAPIImplementation_1.default(this)), + passwordlessUserEmailExistsGET: + (_c = passwordlessImplementation.emailExistsGET) === null || _c === void 0 + ? void 0 + : _c.bind(passwordlessAPIImplementation_1.default(this)), + passwordlessUserPhoneNumberExistsGET: + (_d = passwordlessImplementation.phoneNumberExistsGET) === null || _d === void 0 + ? void 0 + : _d.bind(passwordlessAPIImplementation_1.default(this)), + linkThirdPartyAccountToExistingAccountPOST: + (_e = thirdPartyImplementation.linkAccountToExistingAccountPOST) === null || _e === void 0 + ? void 0 + : _e.bind(thirdPartyAPIImplementation_1.default(this)), + resendCodePOST: + (_f = passwordlessImplementation.resendCodePOST) === null || _f === void 0 + ? void 0 + : _f.bind(passwordlessAPIImplementation_1.default(this)), + authorisationUrlGET: + (_g = thirdPartyImplementation.authorisationUrlGET) === null || _g === void 0 + ? void 0 + : _g.bind(thirdPartyAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: + (_h = thirdPartyImplementation.signInUpPOST) === null || _h === void 0 + ? void 0 + : _h.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: + (_j = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _j === void 0 + ? void 0 + : _j.bind(thirdPartyAPIImplementation_1.default(this)), + linkPasswordlessAccountToExistingAccountPOST: + (_k = passwordlessImplementation.linkAccountToExistingAccountPOST) === null || _k === void 0 + ? void 0 + : _k.bind(passwordlessAPIImplementation_1.default(this)), }; } exports.default = getAPIImplementation; diff --git a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js index e111bc8d9..321f35dd6 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js @@ -3,12 +3,24 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e, _f; return { - emailExistsGET: (_a = apiImplmentation.passwordlessUserEmailExistsGET) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation), - consumeCodePOST: (_b = apiImplmentation.consumeCodePOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), - createCodePOST: (_c = apiImplmentation.createCodePOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - phoneNumberExistsGET: (_d = apiImplmentation.passwordlessUserPhoneNumberExistsGET) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), - resendCodePOST: (_e = apiImplmentation.resendCodePOST) === null || _e === void 0 ? void 0 : _e.bind(apiImplmentation), - linkAccountToExistingAccountPOST: (_f = apiImplmentation.linkPasswordlessAccountToExistingAccountPOST) === null || _f === void 0 ? void 0 : _f.bind(apiImplmentation), + emailExistsGET: + (_a = apiImplmentation.passwordlessUserEmailExistsGET) === null || _a === void 0 + ? void 0 + : _a.bind(apiImplmentation), + consumeCodePOST: + (_b = apiImplmentation.consumeCodePOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), + createCodePOST: + (_c = apiImplmentation.createCodePOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + phoneNumberExistsGET: + (_d = apiImplmentation.passwordlessUserPhoneNumberExistsGET) === null || _d === void 0 + ? void 0 + : _d.bind(apiImplmentation), + resendCodePOST: + (_e = apiImplmentation.resendCodePOST) === null || _e === void 0 ? void 0 : _e.bind(apiImplmentation), + linkAccountToExistingAccountPOST: + (_f = apiImplmentation.linkPasswordlessAccountToExistingAccountPOST) === null || _f === void 0 + ? void 0 + : _f.bind(apiImplmentation), }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js index 71b87509c..83eca8723 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js @@ -1,49 +1,89 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d; - const signInUpPOSTFromThirdPartyPasswordless = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); - const linkThirdPartyAccountToExistingAccountPOST = (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyPasswordless = + (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const linkThirdPartyAccountToExistingAccountPOST = + (_b = apiImplmentation.linkThirdPartyAccountToExistingAccountPOST) === null || _b === void 0 + ? void 0 + : _b.bind(apiImplmentation); return { - authorisationUrlGET: (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - appleRedirectHandlerPOST: (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 ? void 0 : _d.bind(apiImplmentation), - linkAccountToExistingAccountPOST: linkThirdPartyAccountToExistingAccountPOST === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield linkThirdPartyAccountToExistingAccountPOST(input); - if (result.status === "OK") { - if (!("thirdParty" in result.user)) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); - } - return result; - }); - }, - signInUpPOST: signInUpPOSTFromThirdPartyPasswordless === undefined - ? undefined - : function (input) { - return __awaiter(this, void 0, void 0, function* () { - let result = yield signInUpPOSTFromThirdPartyPasswordless(input); - if (result.status === "OK") { - if (!("thirdParty" in result.user)) { - throw new Error("Should never come here"); - } - return Object.assign(Object.assign({}, result), { user: Object.assign(Object.assign({}, result.user), { thirdParty: Object.assign({}, result.user.thirdParty) }) }); - } - return result; - }); - }, + authorisationUrlGET: + (_c = apiImplmentation.authorisationUrlGET) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + appleRedirectHandlerPOST: + (_d = apiImplmentation.appleRedirectHandlerPOST) === null || _d === void 0 + ? void 0 + : _d.bind(apiImplmentation), + linkAccountToExistingAccountPOST: + linkThirdPartyAccountToExistingAccountPOST === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield linkThirdPartyAccountToExistingAccountPOST(input); + if (result.status === "OK") { + if (!("thirdParty" in result.user)) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { + user: Object.assign(Object.assign({}, result.user), { + thirdParty: Object.assign({}, result.user.thirdParty), + }), + }); + } + return result; + }); + }, + signInUpPOST: + signInUpPOSTFromThirdPartyPasswordless === undefined + ? undefined + : function (input) { + return __awaiter(this, void 0, void 0, function* () { + let result = yield signInUpPOSTFromThirdPartyPasswordless(input); + if (result.status === "OK") { + if (!("thirdParty" in result.user)) { + throw new Error("Should never come here"); + } + return Object.assign(Object.assign({}, result), { + user: Object.assign(Object.assign({}, result.user), { + thirdParty: Object.assign({}, result.user.thirdParty), + }), + }); + } + return result; + }); + }, }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts index e441c1824..4063bc85f 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,18 +1,27 @@ import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; -export default class BackwardCompatibilityService implements EmailDeliveryInterface { +export default class BackwardCompatibilityService + implements EmailDeliveryInterface { private passwordlessBackwardCompatibilityService; - constructor(appInfo: NormalisedAppinfo, passwordlessFeature?: { - createAndSendCustomEmail?: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - }); - sendEmail: (input: TypeThirdPartyPasswordlessEmailDeliveryInput & { - userContext: any; - }) => Promise; + constructor( + appInfo: NormalisedAppinfo, + passwordlessFeature?: { + createAndSendCustomEmail?: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + ); + sendEmail: ( + input: TypeThirdPartyPasswordlessEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js index ea00c6e59..d61010ab5 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.js @@ -1,25 +1,57 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); -const backwardCompatibility_1 = __importDefault(require("../../../../passwordless/emaildelivery/services/backwardCompatibility")); +const backwardCompatibility_1 = __importDefault( + require("../../../../passwordless/emaildelivery/services/backwardCompatibility") +); class BackwardCompatibilityService { constructor(appInfo, passwordlessFeature) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessBackwardCompatibilityService.sendEmail(input); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessBackwardCompatibilityService.sendEmail(input); + }); { - this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default(appInfo, passwordlessFeature === null || passwordlessFeature === void 0 ? void 0 : passwordlessFeature.createAndSendCustomEmail); + this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default( + appInfo, + passwordlessFeature === null || passwordlessFeature === void 0 + ? void 0 + : passwordlessFeature.createAndSendCustomEmail + ); } } } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js index 3e4b76c1d..7e07f6706 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SMTPService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts index c60364839..9d3626b2f 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts @@ -5,7 +5,9 @@ export default class SMTPService implements EmailDeliveryInterface; private passwordlessSMTPService; constructor(config: TypeInput); - sendEmail: (input: TypeThirdPartyPasswordlessEmailDeliveryInput & { - userContext: any; - }) => Promise; + sendEmail: ( + input: TypeThirdPartyPasswordlessEmailDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js index 020265e97..88e970f1c 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.js @@ -1,27 +1,54 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const nodemailer_1 = require("nodemailer"); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const serviceImplementation_1 = require("./serviceImplementation"); const smtp_1 = __importDefault(require("../../../../passwordless/emaildelivery/services/smtp")); -const passwordlessServiceImplementation_1 = __importDefault(require("./serviceImplementation/passwordlessServiceImplementation")); +const passwordlessServiceImplementation_1 = __importDefault( + require("./serviceImplementation/passwordlessServiceImplementation") +); class SMTPService { constructor(config) { - this.sendEmail = (input) => __awaiter(this, void 0, void 0, function* () { - return yield this.passwordlessSMTPService.sendEmail(input); - }); + this.sendEmail = (input) => + __awaiter(this, void 0, void 0, function* () { + return yield this.passwordlessSMTPService.sendEmail(input); + }); const transporter = nodemailer_1.createTransport({ host: config.smtpSettings.host, port: config.smtpSettings.port, @@ -31,7 +58,9 @@ class SMTPService { }, secure: config.smtpSettings.secure, }); - let builder = new supertokens_js_override_1.default(serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from)); + let builder = new supertokens_js_override_1.default( + serviceImplementation_1.getServiceImplementation(transporter, config.smtpSettings.from) + ); if (config.override !== undefined) { builder = builder.override(config.override); } diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts index 52077572f..a77545987 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts @@ -1,7 +1,10 @@ import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; -export declare function getServiceImplementation(transporter: Transporter, from: { - name: string; - email: string; -}): ServiceInterface; +export declare function getServiceImplementation( + transporter: Transporter, + from: { + name: string; + email: string; + } +): ServiceInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js index b876aafd7..61a874879 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getServiceImplementation = void 0; const serviceImplementation_1 = require("../../../../../passwordless/emaildelivery/services/smtp/serviceImplementation"); @@ -44,7 +68,9 @@ function getServiceImplementation(transporter, from) { }, getContent: function (input) { return __awaiter(this, void 0, void 0, function* () { - return yield passwordlessServiceImpl.getContent.bind(passwordlessServiceImplementation_1.default(this))(input); + return yield passwordlessServiceImpl.getContent.bind(passwordlessServiceImplementation_1.default(this))( + input + ); }); }, }; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts index 416506b0d..bce1d3c64 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts @@ -1,4 +1,6 @@ import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../../types"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; import { TypePasswordlessEmailDeliveryInput } from "../../../../../passwordless/types"; -export default function getServiceInterface(thirdpartyPasswordlessServiceImplementation: ServiceInterface): ServiceInterface; +export default function getServiceInterface( + thirdpartyPasswordlessServiceImplementation: ServiceInterface +): ServiceInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js index 248634b1f..9da544281 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.js @@ -13,15 +13,37 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getServiceInterface(thirdpartyPasswordlessServiceImplementation) { return { diff --git a/lib/build/recipe/thirdpartypasswordless/error.d.ts b/lib/build/recipe/thirdpartypasswordless/error.d.ts index 3dc8820ff..56d432191 100644 --- a/lib/build/recipe/thirdpartypasswordless/error.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/error.d.ts @@ -1,7 +1,4 @@ import STError from "../../error"; export default class ThirdPartyEmailPasswordError extends STError { - constructor(options: { - type: "BAD_INPUT_ERROR"; - message: string; - }); + constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); } diff --git a/lib/build/recipe/thirdpartypasswordless/error.js b/lib/build/recipe/thirdpartypasswordless/error.js index 4c8bc8799..0114fec0e 100644 --- a/lib/build/recipe/thirdpartypasswordless/error.js +++ b/lib/build/recipe/thirdpartypasswordless/error.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); class ThirdPartyEmailPasswordError extends error_1.default { diff --git a/lib/build/recipe/thirdpartypasswordless/index.d.ts b/lib/build/recipe/thirdpartypasswordless/index.d.ts index d0d4cc363..cfb5efe85 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/index.d.ts @@ -1,27 +1,48 @@ import Recipe from "./recipe"; import SuperTokensError from "./error"; -import { RecipeInterface, User, APIInterface, PasswordlessAPIOptions, ThirdPartyAPIOptions, TypeThirdPartyPasswordlessEmailDeliveryInput } from "./types"; +import { + RecipeInterface, + User, + APIInterface, + PasswordlessAPIOptions, + ThirdPartyAPIOptions, + TypeThirdPartyPasswordlessEmailDeliveryInput, +} from "./types"; import { TypeProvider } from "../thirdparty/types"; import { TypePasswordlessSmsDeliveryInput } from "../passwordless/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: string, userContext?: any): Promise<{ + static thirdPartySignInUp( + thirdPartyId: string, + thirdPartyUserId: string, + email: string, + userContext?: any + ): Promise<{ status: "OK"; createdNewUser: boolean; user: User; }>; - static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; + static getUserByThirdPartyInfo( + thirdPartyId: string, + thirdPartyUserId: string, + userContext?: any + ): Promise; static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise; - static createCode(input: ({ - email: string; - } | { - phoneNumber: string; - }) & { - userInputCode?: string; - userContext?: any; - }): Promise<{ + static createCode( + input: ( + | { + email: string; + } + | { + phoneNumber: string; + } + ) & { + userInputCode?: string; + userContext?: any; + } + ): Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -35,42 +56,50 @@ export default class Wrapper { deviceId: string; userInputCode?: string; userContext?: any; - }): Promise<{ - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - }>; - static consumeCode(input: { - preAuthSessionId: string; - userInputCode: string; - deviceId: string; - userContext?: any; - } | { - preAuthSessionId: string; - linkCode: string; - userContext?: any; - }): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | { - status: "RESTART_FLOW_ERROR"; - }>; - static getUserByPhoneNumber(input: { - phoneNumber: string; - userContext?: any; - }): Promise; + }): Promise< + | { + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } + | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + } + >; + static consumeCode( + input: + | { + preAuthSessionId: string; + userInputCode: string; + deviceId: string; + userContext?: any; + } + | { + preAuthSessionId: string; + linkCode: string; + userContext?: any; + } + ): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | { + status: "RESTART_FLOW_ERROR"; + } + >; + static getUserByPhoneNumber(input: { phoneNumber: string; userContext?: any }): Promise; static updatePasswordlessUser(input: { userId: string; email?: string | null; @@ -79,13 +108,17 @@ export default class Wrapper { }): Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - static revokeAllCodes(input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }): Promise<{ + static revokeAllCodes( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ): Promise<{ status: "OK"; }>; static revokeCode(input: { @@ -110,20 +143,28 @@ export default class Wrapper { preAuthSessionId: string; userContext?: any; }): Promise; - static createMagicLink(input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }): Promise; - static passwordlessSignInUp(input: { - email: string; - userContext?: any; - } | { - phoneNumber: string; - userContext?: any; - }): Promise<{ + static createMagicLink( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ): Promise; + static passwordlessSignInUp( + input: + | { + email: string; + userContext?: any; + } + | { + phoneNumber: string; + userContext?: any; + } + ): Promise<{ status: string; createdNewUser: boolean; user: import("../passwordless/types").User; @@ -134,12 +175,16 @@ export default class Wrapper { static Apple: typeof import("../thirdparty/providers/apple").default; static Discord: typeof import("../thirdparty/providers/discord").default; static GoogleWorkspaces: typeof import("../thirdparty/providers/googleWorkspaces").default; - static sendEmail(input: TypeThirdPartyPasswordlessEmailDeliveryInput & { - userContext?: any; - }): Promise; - static sendSms(input: TypePasswordlessSmsDeliveryInput & { - userContext?: any; - }): Promise; + static sendEmail( + input: TypeThirdPartyPasswordlessEmailDeliveryInput & { + userContext?: any; + } + ): Promise; + static sendSms( + input: TypePasswordlessSmsDeliveryInput & { + userContext?: any; + } + ): Promise; } export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; diff --git a/lib/build/recipe/thirdpartypasswordless/index.js b/lib/build/recipe/thirdpartypasswordless/index.js index f4aa3b3ca..94110718d 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.js +++ b/lib/build/recipe/thirdpartypasswordless/index.js @@ -13,37 +13,78 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sendSms = exports.sendEmail = exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.createMagicLink = exports.revokeCode = exports.revokeAllCodes = exports.updatePasswordlessUser = exports.createNewCodeForDevice = exports.listCodesByPreAuthSessionId = exports.listCodesByPhoneNumber = exports.listCodesByEmail = exports.listCodesByDeviceId = exports.getUserByPhoneNumber = exports.consumeCode = exports.createCode = exports.getUsersByEmail = exports.getUserByThirdPartyInfo = exports.getUserById = exports.passwordlessSignInUp = exports.thirdPartySignInUp = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); @@ -72,54 +113,84 @@ class Wrapper { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsersByEmail({ email, userContext }); } static createCode(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.createCode(Object.assign({ userContext: {} }, input)); } static createNewCodeForDevice(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.createNewCodeForDevice(Object.assign({ userContext: {} }, input)); } static consumeCode(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.consumeCode(Object.assign({ userContext: {} }, input)); } static getUserByPhoneNumber(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getUserByPhoneNumber(Object.assign({ userContext: {} }, input)); } static updatePasswordlessUser(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.updatePasswordlessUser(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.updatePasswordlessUser(Object.assign({ userContext: {} }, input)); } static revokeAllCodes(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.revokeAllCodes(Object.assign({ userContext: {} }, input)); } static revokeCode(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.revokeCode(Object.assign({ userContext: {} }, input)); } static listCodesByEmail(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByEmail(Object.assign({ userContext: {} }, input)); } static listCodesByPhoneNumber(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByPhoneNumber(Object.assign({ userContext: {} }, input)); } static listCodesByDeviceId(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByDeviceId(Object.assign({ userContext: {} }, input)); } static listCodesByPreAuthSessionId(input) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.listCodesByPreAuthSessionId(Object.assign({ userContext: {} }, input)); } static createMagicLink(input) { - return recipe_1.default.getInstanceOrThrowError().passwordlessRecipe.createMagicLink(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .passwordlessRecipe.createMagicLink(Object.assign({ userContext: {} }, input)); } static passwordlessSignInUp(input) { - return recipe_1.default.getInstanceOrThrowError().passwordlessRecipe.signInUp(Object.assign({ userContext: {} }, input)); + return recipe_1.default + .getInstanceOrThrowError() + .passwordlessRecipe.signInUp(Object.assign({ userContext: {} }, input)); } // static Okta = thirdPartyProviders.Okta; // static ActiveDirectory = thirdPartyProviders.ActiveDirectory; static sendEmail(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default + .getInstanceOrThrowError() + .emailDelivery.ingredientInterfaceImpl.sendEmail(Object.assign({ userContext: {} }, input)); }); } static sendSms(input) { return __awaiter(this, void 0, void 0, function* () { - return yield recipe_1.default.getInstanceOrThrowError().smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); + return yield recipe_1.default + .getInstanceOrThrowError() + .smsDelivery.ingredientInterfaceImpl.sendSms(Object.assign({ userContext: {} }, input)); }); } } diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts index 9e5128bd3..3a2aa624b 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts @@ -4,7 +4,14 @@ import PasswordlessRecipe from "../passwordless/recipe"; import ThirdPartyRecipe from "../thirdparty/recipe"; import { BaseRequest, BaseResponse } from "../../framework"; import STError from "./error"; -import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, TypeThirdPartyPasswordlessEmailDeliveryInput, TypeThirdPartyPasswordlessSmsDeliveryInput } from "./types"; +import { + TypeInput, + TypeNormalisedInput, + RecipeInterface, + APIInterface, + TypeThirdPartyPasswordlessEmailDeliveryInput, + TypeThirdPartyPasswordlessSmsDeliveryInput, +} from "./types"; import STErrorPasswordless from "../passwordless/error"; import STErrorThirdParty from "../thirdparty/error"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -21,19 +28,36 @@ export default class Recipe extends RecipeModule { emailDelivery: EmailDeliveryIngredient; smsDelivery: SmsDeliveryIngredient; isInServerlessEnv: boolean; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { - thirdPartyInstance: ThirdPartyRecipe | undefined; - passwordlessInstance: PasswordlessRecipe | undefined; - }, ingredients: { - emailDelivery: EmailDeliveryIngredient | undefined; - smsDelivery: SmsDeliveryIngredient | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + recipes: { + thirdPartyInstance: ThirdPartyRecipe | undefined; + passwordlessInstance: PasswordlessRecipe | undefined; + }, + ingredients: { + emailDelivery: EmailDeliveryIngredient | undefined; + smsDelivery: SmsDeliveryIngredient | undefined; + } + ); static init(config: TypeInput): RecipeListFunction; static reset(): void; static getInstanceOrThrowError(): Recipe; getAPIsHandled: () => APIHandled[]; - handleAPIRequest: (id: string, req: BaseRequest, res: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; - handleError: (err: STErrorPasswordless | STErrorThirdParty, request: BaseRequest, response: BaseResponse) => Promise; + handleAPIRequest: ( + id: string, + req: BaseRequest, + res: BaseResponse, + path: NormalisedURLPath, + method: HTTPMethod + ) => Promise; + handleError: ( + err: STErrorPasswordless | STErrorThirdParty, + request: BaseRequest, + response: BaseResponse + ) => Promise; getAllCORSHeaders: () => string[]; isErrorFromThisRecipe: (err: any) => err is STError; } diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.js b/lib/build/recipe/thirdpartypasswordless/recipe.js index 6cd358d39..4bd2883ad 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.js +++ b/lib/build/recipe/thirdpartypasswordless/recipe.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -32,8 +56,12 @@ const recipe_2 = __importDefault(require("../thirdparty/recipe")); const error_1 = __importDefault(require("./error")); const utils_1 = require("./utils"); const recipeImplementation_1 = __importDefault(require("./recipeImplementation")); -const passwordlessRecipeImplementation_1 = __importDefault(require("./recipeImplementation/passwordlessRecipeImplementation")); -const thirdPartyRecipeImplementation_1 = __importDefault(require("./recipeImplementation/thirdPartyRecipeImplementation")); +const passwordlessRecipeImplementation_1 = __importDefault( + require("./recipeImplementation/passwordlessRecipeImplementation") +); +const thirdPartyRecipeImplementation_1 = __importDefault( + require("./recipeImplementation/thirdPartyRecipeImplementation") +); const thirdPartyAPIImplementation_1 = __importDefault(require("./api/thirdPartyAPIImplementation")); const passwordlessAPIImplementation_1 = __importDefault(require("./api/passwordlessAPIImplementation")); const implementation_1 = __importDefault(require("./api/implementation")); @@ -51,30 +79,35 @@ class Recipe extends recipeModule_1.default { } return apisHandled; }; - this.handleAPIRequest = (id, req, res, path, method) => __awaiter(this, void 0, void 0, function* () { - if (this.passwordlessRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { - return yield this.passwordlessRecipe.handleAPIRequest(id, req, res, path, method); - } - if (this.thirdPartyRecipe !== undefined && - this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { - return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); - } - return false; - }); - this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - throw err; - } - else { - if (this.passwordlessRecipe.isErrorFromThisRecipe(err)) { - return yield this.passwordlessRecipe.handleError(err, request, response); + this.handleAPIRequest = (id, req, res, path, method) => + __awaiter(this, void 0, void 0, function* () { + if (this.passwordlessRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined) { + return yield this.passwordlessRecipe.handleAPIRequest(id, req, res, path, method); } - else if (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)) { - return yield this.thirdPartyRecipe.handleError(err, request, response); + if ( + this.thirdPartyRecipe !== undefined && + this.thirdPartyRecipe.returnAPIIdIfCanHandleRequest(path, method) !== undefined + ) { + return yield this.thirdPartyRecipe.handleAPIRequest(id, req, res, path, method); } - throw err; - } - }); + return false; + }); + this.handleError = (err, request, response) => + __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + throw err; + } else { + if (this.passwordlessRecipe.isErrorFromThisRecipe(err)) { + return yield this.passwordlessRecipe.handleError(err, request, response); + } else if ( + this.thirdPartyRecipe !== undefined && + this.thirdPartyRecipe.isErrorFromThisRecipe(err) + ) { + return yield this.thirdPartyRecipe.handleError(err, request, response); + } + throw err; + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [...this.passwordlessRecipe.getAllCORSHeaders()]; if (this.thirdPartyRecipe !== undefined) { @@ -83,15 +116,22 @@ class Recipe extends recipeModule_1.default { return corsHeaders; }; this.isErrorFromThisRecipe = (err) => { - return (error_1.default.isErrorFromSuperTokens(err) && + return ( + error_1.default.isErrorFromSuperTokens(err) && (err.fromRecipe === Recipe.RECIPE_ID || this.passwordlessRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) + ); }; this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(appInfo, config); { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default( + querier_1.Querier.getNewInstanceOrThrowError(recipe_1.default.RECIPE_ID), + querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID) + ) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -100,7 +140,9 @@ class Recipe extends recipeModule_1.default { } this.emailDelivery = ingredients.emailDelivery === undefined - ? new emaildelivery_1.default(this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv)) + ? new emaildelivery_1.default( + this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) + ) : ingredients.emailDelivery; this.smsDelivery = ingredients.smsDelivery === undefined @@ -109,52 +151,75 @@ class Recipe extends recipeModule_1.default { this.passwordlessRecipe = recipes.passwordlessInstance !== undefined ? recipes.passwordlessInstance - : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign(Object.assign({}, this.config), { override: { - functions: (_) => { - return passwordlessRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return passwordlessAPIImplementation_1.default(this.apiImpl); - }, - } }), { - emailDelivery: this.emailDelivery, - smsDelivery: this.smsDelivery, - }); + : new recipe_1.default( + recipeId, + appInfo, + isInServerlessEnv, + Object.assign(Object.assign({}, this.config), { + override: { + functions: (_) => { + return passwordlessRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return passwordlessAPIImplementation_1.default(this.apiImpl); + }, + }, + }), + { + emailDelivery: this.emailDelivery, + smsDelivery: this.smsDelivery, + } + ); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_2.default(recipeId, appInfo, isInServerlessEnv, { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, {}, { - emailDelivery: this.emailDelivery, - }); + : new recipe_2.default( + recipeId, + appInfo, + isInServerlessEnv, + { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, + {}, + { + emailDelivery: this.emailDelivery, + } + ); } } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { - Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config, { - passwordlessInstance: undefined, - thirdPartyInstance: undefined, - }, { - emailDelivery: undefined, - smsDelivery: undefined, - }); + Recipe.instance = new Recipe( + Recipe.RECIPE_ID, + appInfo, + isInServerlessEnv, + config, + { + passwordlessInstance: undefined, + thirdPartyInstance: undefined, + }, + { + emailDelivery: undefined, + smsDelivery: undefined, + } + ); return Recipe.instance; - } - else { - throw new Error("ThirdPartyPasswordless recipe has already been initialised. Please check your code for bugs."); + } else { + throw new Error( + "ThirdPartyPasswordless recipe has already been initialised. Please check your code for bugs." + ); } }; } diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js index f8d6988e7..0acca2fd6 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const recipeImplementation_1 = __importDefault(require("../../passwordless/recipeImplementation")); const recipeImplementation_2 = __importDefault(require("../../thirdparty/recipeImplementation")); @@ -25,52 +49,72 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { return { consumeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.consumeCode.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.consumeCode.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, createCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.createCode.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.createCode.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, createNewCodeForDevice: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.createNewCodeForDevice.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.createNewCodeForDevice.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, getUserByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.getUserByPhoneNumber.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.getUserByPhoneNumber.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, listCodesByDeviceId: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByDeviceId.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.listCodesByDeviceId.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, listCodesByEmail: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByEmail.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.listCodesByEmail.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, listCodesByPhoneNumber: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByPhoneNumber.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.listCodesByPhoneNumber.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, listCodesByPreAuthSessionId: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.listCodesByPreAuthSessionId.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.listCodesByPreAuthSessionId.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, revokeAllCodes: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.revokeAllCodes.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.revokeAllCodes.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, revokeCode: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalPasswordlessImplementation.revokeCode.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.revokeCode.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, updatePasswordlessUser: function (input) { @@ -80,11 +124,14 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { return { status: "UNKNOWN_USER_ID_ERROR", }; + } else if ("thirdParty" in user) { + throw new Error( + "Cannot update passwordless user info for those who signed up using third party login." + ); } - else if ("thirdParty" in user) { - throw new Error("Cannot update passwordless user info for those who signed up using third party login."); - } - return originalPasswordlessImplementation.updateUser.bind(passwordlessRecipeImplementation_1.default(this))(input); + return originalPasswordlessImplementation.updateUser.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); }); }, thirdPartySignInUp: function (input) { @@ -92,28 +139,38 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { throw new Error("No thirdparty provider configured"); } - return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))(input); + return originalThirdPartyImplementation.signInUp.bind(thirdPartyRecipeImplementation_1.default(this))( + input + ); }); }, getUserById: function (input) { return __awaiter(this, void 0, void 0, function* () { - let user = yield originalPasswordlessImplementation.getUserById.bind(passwordlessRecipeImplementation_1.default(this))(input); + let user = yield originalPasswordlessImplementation.getUserById.bind( + passwordlessRecipeImplementation_1.default(this) + )(input); if (user !== undefined) { return user; } if (originalThirdPartyImplementation === undefined) { return undefined; } - return yield originalThirdPartyImplementation.getUserById.bind(thirdPartyRecipeImplementation_1.default(this))(input); + return yield originalThirdPartyImplementation.getUserById.bind( + thirdPartyRecipeImplementation_1.default(this) + )(input); }); }, getUsersByEmail: function ({ email, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let userFromEmailPass = yield originalPasswordlessImplementation.getUserByEmail.bind(passwordlessRecipeImplementation_1.default(this))({ email, userContext }); + let userFromEmailPass = yield originalPasswordlessImplementation.getUserByEmail.bind( + passwordlessRecipeImplementation_1.default(this) + )({ email, userContext }); if (originalThirdPartyImplementation === undefined) { return userFromEmailPass === undefined ? [] : [userFromEmailPass]; } - let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind(thirdPartyRecipeImplementation_1.default(this))({ email, userContext }); + let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind( + thirdPartyRecipeImplementation_1.default(this) + )({ email, userContext }); if (userFromEmailPass !== undefined) { return [...usersFromThirdParty, userFromEmailPass]; } @@ -125,7 +182,9 @@ function getRecipeInterface(passwordlessQuerier, thirdPartyQuerier) { if (originalThirdPartyImplementation === undefined) { return undefined; } - return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind(thirdPartyRecipeImplementation_1.default(this))(input); + return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind( + thirdPartyRecipeImplementation_1.default(this) + )(input); }); }, }; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js index e4357e3f4..34cc8cf85 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js index 156808814..715a0171f 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.js @@ -1,13 +1,35 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; Object.defineProperty(exports, "__esModule", { value: true }); function getRecipeInterface(recipeInterface) { return { diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts index 746e6d8e1..5fd8e90a3 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts @@ -1,18 +1,27 @@ import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; -export default class BackwardCompatibilityService implements SmsDeliveryInterface { +export default class BackwardCompatibilityService + implements SmsDeliveryInterface { private passwordlessBackwardCompatibilityService; - constructor(appInfo: NormalisedAppinfo, passwordlessFeature?: { - createAndSendCustomTextMessage?: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - }); - sendSms: (input: TypeThirdPartyPasswordlessSmsDeliveryInput & { - userContext: any; - }) => Promise; + constructor( + appInfo: NormalisedAppinfo, + passwordlessFeature?: { + createAndSendCustomTextMessage?: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + ); + sendSms: ( + input: TypeThirdPartyPasswordlessSmsDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js index 843e5125e..6fb2a2e25 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.js @@ -1,24 +1,56 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); -const backwardCompatibility_1 = __importDefault(require("../../../../passwordless/smsdelivery/services/backwardCompatibility")); +const backwardCompatibility_1 = __importDefault( + require("../../../../passwordless/smsdelivery/services/backwardCompatibility") +); class BackwardCompatibilityService { constructor(appInfo, passwordlessFeature) { - this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessBackwardCompatibilityService.sendSms(input); - }); - this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default(appInfo, passwordlessFeature === null || passwordlessFeature === void 0 ? void 0 : passwordlessFeature.createAndSendCustomTextMessage); + this.sendSms = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessBackwardCompatibilityService.sendSms(input); + }); + this.passwordlessBackwardCompatibilityService = new backwardCompatibility_1.default( + appInfo, + passwordlessFeature === null || passwordlessFeature === void 0 + ? void 0 + : passwordlessFeature.createAndSendCustomTextMessage + ); } } exports.default = BackwardCompatibilityService; diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js index c4ba9a912..f85fb8900 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.js @@ -1,7 +1,9 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SupertokensService = exports.TwilioService = void 0; /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts index 01fd7e9c9..e3729cb71 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts @@ -3,7 +3,9 @@ import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; export default class SupertokensService implements SmsDeliveryInterface { private passwordlessSupertokensService; constructor(apiKey: string); - sendSms: (input: TypeThirdPartyPasswordlessSmsDeliveryInput & { - userContext: any; - }) => Promise; + sendSms: ( + input: TypeThirdPartyPasswordlessSmsDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js index 75955634a..4c764c79d 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.js @@ -1,23 +1,48 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const supertokens_1 = __importDefault(require("../../../../passwordless/smsdelivery/services/supertokens")); class SupertokensService { constructor(apiKey) { - this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessSupertokensService.sendSms(input); - }); + this.sendSms = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessSupertokensService.sendSms(input); + }); this.passwordlessSupertokensService = new supertokens_1.default(apiKey); } } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts index 5f6e15e73..8f19e409b 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts @@ -4,7 +4,9 @@ import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; export default class TwilioService implements SmsDeliveryInterface { private passwordlessTwilioService; constructor(config: TypeInput); - sendSms: (input: TypeThirdPartyPasswordlessSmsDeliveryInput & { - userContext: any; - }) => Promise; + sendSms: ( + input: TypeThirdPartyPasswordlessSmsDeliveryInput & { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js index cea433588..4dcafed68 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.js @@ -1,23 +1,48 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const index_1 = __importDefault(require("../../../../passwordless/smsdelivery/services/twilio/index")); class TwilioService { constructor(config) { - this.sendSms = (input) => __awaiter(this, void 0, void 0, function* () { - yield this.passwordlessTwilioService.sendSms(input); - }); + this.sendSms = (input) => + __awaiter(this, void 0, void 0, function* () { + yield this.passwordlessTwilioService.sendSms(input); + }); this.passwordlessTwilioService = new index_1.default(config); } } diff --git a/lib/build/recipe/thirdpartypasswordless/types.d.ts b/lib/build/recipe/thirdpartypasswordless/types.d.ts index d230ca51f..558bc68e6 100644 --- a/lib/build/recipe/thirdpartypasswordless/types.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/types.d.ts @@ -1,76 +1,106 @@ import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; -import { DeviceType as DeviceTypeOriginal, APIOptions as PasswordlessAPIOptionsOriginal, TypePasswordlessEmailDeliveryInput, TypePasswordlessSmsDeliveryInput } from "../passwordless/types"; +import { + DeviceType as DeviceTypeOriginal, + APIOptions as PasswordlessAPIOptionsOriginal, + TypePasswordlessEmailDeliveryInput, + TypePasswordlessSmsDeliveryInput, +} from "../passwordless/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; -import { TypeInput as EmailDeliveryTypeInput, TypeInputWithService as EmailDeliveryTypeInputWithService } from "../../ingredients/emaildelivery/types"; -import { TypeInput as SmsDeliveryTypeInput, TypeInputWithService as SmsDeliveryTypeInputWithService } from "../../ingredients/smsdelivery/types"; +import { + TypeInput as EmailDeliveryTypeInput, + TypeInputWithService as EmailDeliveryTypeInputWithService, +} from "../../ingredients/emaildelivery/types"; +import { + TypeInput as SmsDeliveryTypeInput, + TypeInputWithService as SmsDeliveryTypeInputWithService, +} from "../../ingredients/smsdelivery/types"; import { GeneralErrorResponse } from "../../types"; export declare type DeviceType = DeviceTypeOriginal; -export declare type User = ({ - email?: string; - phoneNumber?: string; -} | { - email: string; - thirdParty: { - id: string; - userId: string; - }; -}) & { +export declare type User = ( + | { + email?: string; + phoneNumber?: string; + } + | { + email: string; + thirdParty: { + id: string; + userId: string; + }; + } +) & { id: string; recipeUserId: string; timeJoined: number; }; -export declare type TypeInput = ({ - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - /** - * @deprecated Please use emailDelivery config instead - */ - createAndSendCustomEmail?: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - /** - * @deprecated Please use smsDelivery config instead - */ - createAndSendCustomTextMessage?: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -}) & { +export declare type TypeInput = ( + | { + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + /** + * @deprecated Please use emailDelivery config instead + */ + createAndSendCustomEmail?: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + /** + * @deprecated Please use smsDelivery config instead + */ + createAndSendCustomTextMessage?: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } +) & { /** * Unlike passwordless recipe, emailDelivery config is outside here because regardless * of `contactMethod` value, the config is required for email verification recipe @@ -81,44 +111,48 @@ export declare type TypeInput = ({ flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; getCustomUserInputCode?: (userContext: any) => Promise | string; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; -export declare type TypeNormalisedInput = ({ - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; -} | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; -} | { - contactMethod: "EMAIL_OR_PHONE"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; -}) & { +export declare type TypeNormalisedInput = ( + | { + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + } + | { + contactMethod: "EMAIL_OR_PHONE"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + } +) & { flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; getCustomUserInputCode?: (userContext: any) => Promise | string; providers: TypeProvider[]; - getEmailDeliveryConfig: (recipeImpl: RecipeInterface, isInServerlessEnv: boolean) => EmailDeliveryTypeInputWithService; + getEmailDeliveryConfig: ( + recipeImpl: RecipeInterface, + isInServerlessEnv: boolean + ) => EmailDeliveryTypeInputWithService; getSmsDeliveryConfig: () => SmsDeliveryTypeInputWithService; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type RecipeInterface = { - getUserById(input: { - userId: string; - userContext: any; - }): Promise; - getUsersByEmail(input: { - email: string; - userContext: any; - }): Promise; - getUserByPhoneNumber: (input: { - phoneNumber: string; - userContext: any; - }) => Promise; + getUserById(input: { userId: string; userContext: any }): Promise; + getUsersByEmail(input: { email: string; userContext: any }): Promise; + getUserByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -134,14 +168,19 @@ export declare type RecipeInterface = { createdNewUser: boolean; user: User; }>; - createCode: (input: ({ - email: string; - } | { - phoneNumber: string; - }) & { - userInputCode?: string; - userContext: any; - }) => Promise<{ + createCode: ( + input: ( + | { + email: string; + } + | { + phoneNumber: string; + } + ) & { + userInputCode?: string; + userContext: any; + } + ) => Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -155,38 +194,49 @@ export declare type RecipeInterface = { deviceId: string; userInputCode?: string; userContext: any; - }) => Promise<{ - status: "OK"; - preAuthSessionId: string; - codeId: string; - deviceId: string; - userInputCode: string; - linkCode: string; - codeLifetime: number; - timeCreated: number; - } | { - status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; - }>; - consumeCode: (input: { - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - userContext: any; - } | { - linkCode: string; - preAuthSessionId: string; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | { - status: "RESTART_FLOW_ERROR"; - }>; + }) => Promise< + | { + status: "OK"; + preAuthSessionId: string; + codeId: string; + deviceId: string; + userInputCode: string; + linkCode: string; + codeLifetime: number; + timeCreated: number; + } + | { + status: "RESTART_FLOW_ERROR" | "USER_INPUT_CODE_ALREADY_USED_ERROR"; + } + >; + consumeCode: ( + input: + | { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + userContext: any; + } + | { + linkCode: string; + preAuthSessionId: string; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | { + status: "RESTART_FLOW_ERROR"; + } + >; updatePasswordlessUser: (input: { userId: string; email?: string | null; @@ -195,13 +245,17 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR" | "PHONE_NUMBER_ALREADY_EXISTS_ERROR"; }>; - revokeAllCodes: (input: { - email: string; - userContext: any; - } | { - phoneNumber: string; - userContext: any; - }) => Promise<{ + revokeAllCodes: ( + input: + | { + email: string; + userContext: any; + } + | { + phoneNumber: string; + userContext: any; + } + ) => Promise<{ status: "OK"; }>; revokeCode: (input: { @@ -210,18 +264,9 @@ export declare type RecipeInterface = { }) => Promise<{ status: "OK"; }>; - listCodesByEmail: (input: { - email: string; - userContext: any; - }) => Promise; - listCodesByPhoneNumber: (input: { - phoneNumber: string; - userContext: any; - }) => Promise; - listCodesByDeviceId: (input: { - deviceId: string; - userContext: any; - }) => Promise; + listCodesByEmail: (input: { email: string; userContext: any }) => Promise; + listCodesByPhoneNumber: (input: { phoneNumber: string; userContext: any }) => Promise; + listCodesByDeviceId: (input: { deviceId: string; userContext: any }) => Promise; listCodesByPreAuthSessionId: (input: { preAuthSessionId: string; userContext: any; @@ -230,174 +275,247 @@ export declare type RecipeInterface = { export declare type PasswordlessAPIOptions = PasswordlessAPIOptionsOriginal; export declare type ThirdPartyAPIOptions = ThirdPartyAPIOptionsOriginal; export declare type APIInterface = { - authorisationUrlGET: undefined | ((input: { - provider: TypeProvider; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - url: string; - } | GeneralErrorResponse>); - linkThirdPartyAccountToExistingAccountPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - session: SessionContainerInterface; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - authCodeResponse: any; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } | GeneralErrorResponse>); - thirdPartySignInUpPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } | GeneralErrorResponse | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } | { - status: "SIGNIN_NOT_ALLOWED"; - primaryUserId: string; - description: string; - }>); - appleRedirectHandlerPOST: undefined | ((input: { - code: string; - state: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise); - createCodePOST: undefined | ((input: ({ - email: string; - } | { - phoneNumber: string; - }) & { - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - deviceId: string; - preAuthSessionId: string; - flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; - } | GeneralErrorResponse>); - resendCodePOST: undefined | ((input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise); - consumeCodePOST: undefined | ((input: ({ - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } | { - linkCode: string; - preAuthSessionId: string; - }) & { - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - createdNewRecipeUser: boolean; - user: User; - session: SessionContainerInterface; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | GeneralErrorResponse | { - status: "RESTART_FLOW_ERROR"; - } | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - }>); - passwordlessUserEmailExistsGET: undefined | ((input: { - email: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - } | GeneralErrorResponse>); - passwordlessUserPhoneNumberExistsGET: undefined | ((input: { - phoneNumber: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - } | GeneralErrorResponse>); - linkPasswordlessAccountToExistingAccountPOST: undefined | ((input: ({ - userInputCode: string; - deviceId: string; - preAuthSessionId: string; - } | { - linkCode: string; - preAuthSessionId: string; - }) & { - session: SessionContainerInterface; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; - } | GeneralErrorResponse>); + authorisationUrlGET: + | undefined + | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + url: string; + } + | GeneralErrorResponse + >); + linkThirdPartyAccountToExistingAccountPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + session: SessionContainerInterface; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + authCodeResponse: any; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } + | GeneralErrorResponse + >); + thirdPartySignInUpPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } + | GeneralErrorResponse + | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + | { + status: "SIGNIN_NOT_ALLOWED"; + primaryUserId: string; + description: string; + } + >); + appleRedirectHandlerPOST: + | undefined + | ((input: { code: string; state: string; options: ThirdPartyAPIOptions; userContext: any }) => Promise); + createCodePOST: + | undefined + | (( + input: ( + | { + email: string; + } + | { + phoneNumber: string; + } + ) & { + options: PasswordlessAPIOptions; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + deviceId: string; + preAuthSessionId: string; + flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; + } + | GeneralErrorResponse + >); + resendCodePOST: + | undefined + | (( + input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: PasswordlessAPIOptions; + userContext: any; + } + ) => Promise< + | GeneralErrorResponse + | { + status: "RESTART_FLOW_ERROR" | "OK"; + } + >); + consumeCodePOST: + | undefined + | (( + input: ( + | { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } + | { + linkCode: string; + preAuthSessionId: string; + } + ) & { + options: PasswordlessAPIOptions; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + createdNewRecipeUser: boolean; + user: User; + session: SessionContainerInterface; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | GeneralErrorResponse + | { + status: "RESTART_FLOW_ERROR"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + >); + passwordlessUserEmailExistsGET: + | undefined + | ((input: { + email: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >); + passwordlessUserPhoneNumberExistsGET: + | undefined + | ((input: { + phoneNumber: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >); + linkPasswordlessAccountToExistingAccountPOST: + | undefined + | (( + input: ( + | { + userInputCode: string; + deviceId: string; + preAuthSessionId: string; + } + | { + linkCode: string; + preAuthSessionId: string; + } + ) & { + session: SessionContainerInterface; + options: PasswordlessAPIOptions; + userContext: any; + } + ) => Promise< + | { + status: "OK"; + user: User; + createdNewRecipeUser: boolean; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } + | { + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } + | { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | { + status: "ACCOUNT_NOT_VERIFIED_ERROR"; + isNotVerifiedAccountFromInputSession: boolean; + description: string; + } + | GeneralErrorResponse + >); }; export declare type TypeThirdPartyPasswordlessEmailDeliveryInput = TypePasswordlessEmailDeliveryInput; export declare type TypeThirdPartyPasswordlessSmsDeliveryInput = TypePasswordlessSmsDeliveryInput; diff --git a/lib/build/recipe/thirdpartypasswordless/utils.d.ts b/lib/build/recipe/thirdpartypasswordless/utils.d.ts index 77d16fe02..4cae3a2f0 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/utils.d.ts @@ -1,3 +1,6 @@ import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput(appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + appInfo: NormalisedAppinfo, + config: TypeInput +): TypeNormalisedInput; diff --git a/lib/build/recipe/thirdpartypasswordless/utils.js b/lib/build/recipe/thirdpartypasswordless/utils.js index c8348c0f5..ffdfd159c 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.js +++ b/lib/build/recipe/thirdpartypasswordless/utils.js @@ -13,19 +13,30 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAndNormaliseUserInput = void 0; const backwardCompatibility_1 = __importDefault(require("./emaildelivery/services/backwardCompatibility")); const backwardCompatibility_2 = __importDefault(require("./smsdelivery/services/backwardCompatibility")); function validateAndNormaliseUserInput(appInfo, config) { let providers = config.providers === undefined ? [] : config.providers; - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); function getEmailDeliveryConfig() { var _a; - let emailService = (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 ? void 0 : _a.service; + let emailService = + (_a = config === null || config === void 0 ? void 0 : config.emailDelivery) === null || _a === void 0 + ? void 0 + : _a.service; /** * following code is for backward compatibility. * if user has not passed emailDelivery config, we @@ -35,10 +46,15 @@ function validateAndNormaliseUserInput(appInfo, config) { */ if (emailService === undefined) { emailService = new backwardCompatibility_1.default(appInfo, { - createAndSendCustomEmail: (config === null || config === void 0 ? void 0 : config.contactMethod) !== "PHONE" ? config === null || config === void 0 ? void 0 : config.createAndSendCustomEmail : undefined, + createAndSendCustomEmail: + (config === null || config === void 0 ? void 0 : config.contactMethod) !== "PHONE" + ? config === null || config === void 0 + ? void 0 + : config.createAndSendCustomEmail + : undefined, }); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.emailDelivery), { /** * if we do * let emailDelivery = { @@ -50,11 +66,15 @@ function validateAndNormaliseUserInput(appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: emailService }); + service: emailService, + }); } function getSmsDeliveryConfig() { var _a; - let smsService = (_a = config === null || config === void 0 ? void 0 : config.smsDelivery) === null || _a === void 0 ? void 0 : _a.service; + let smsService = + (_a = config === null || config === void 0 ? void 0 : config.smsDelivery) === null || _a === void 0 + ? void 0 + : _a.service; /** * following code is for backward compatibility. * if user has not passed smsDelivery config, we @@ -64,10 +84,15 @@ function validateAndNormaliseUserInput(appInfo, config) { */ if (smsService === undefined) { smsService = new backwardCompatibility_2.default(appInfo, { - createAndSendCustomTextMessage: (config === null || config === void 0 ? void 0 : config.contactMethod) !== "EMAIL" ? config === null || config === void 0 ? void 0 : config.createAndSendCustomTextMessage : undefined, + createAndSendCustomTextMessage: + (config === null || config === void 0 ? void 0 : config.contactMethod) !== "EMAIL" + ? config === null || config === void 0 + ? void 0 + : config.createAndSendCustomTextMessage + : undefined, }); } - return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.smsDelivery), { + return Object.assign(Object.assign({}, config === null || config === void 0 ? void 0 : config.smsDelivery), { /** * if we do * let smsDelivery = { @@ -79,11 +104,14 @@ function validateAndNormaliseUserInput(appInfo, config) { * it it again get set to undefined, so we * set service at the end */ - service: smsService }); + service: smsService, + }); } - return Object.assign(Object.assign({}, config), { providers, + return Object.assign(Object.assign({}, config), { + providers, override, getEmailDeliveryConfig, - getSmsDeliveryConfig }); + getSmsDeliveryConfig, + }); } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; diff --git a/lib/build/recipe/usermetadata/index.d.ts b/lib/build/recipe/usermetadata/index.d.ts index 99f4147d1..08475a87f 100644 --- a/lib/build/recipe/usermetadata/index.d.ts +++ b/lib/build/recipe/usermetadata/index.d.ts @@ -3,15 +3,25 @@ import Recipe from "./recipe"; import { RecipeInterface } from "./types"; export default class Wrapper { static init: typeof Recipe.init; - static getUserMetadata(userId: string, userContext?: any): Promise<{ + static getUserMetadata( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; metadata: any; }>; - static updateUserMetadata(userId: string, metadataUpdate: JSONObject, userContext?: any): Promise<{ + static updateUserMetadata( + userId: string, + metadataUpdate: JSONObject, + userContext?: any + ): Promise<{ status: "OK"; metadata: JSONObject; }>; - static clearUserMetadata(userId: string, userContext?: any): Promise<{ + static clearUserMetadata( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; } diff --git a/lib/build/recipe/usermetadata/index.js b/lib/build/recipe/usermetadata/index.js index d5cfcbe23..c5d267836 100644 --- a/lib/build/recipe/usermetadata/index.js +++ b/lib/build/recipe/usermetadata/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.clearUserMetadata = exports.updateUserMetadata = exports.getUserMetadata = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); diff --git a/lib/build/recipe/usermetadata/recipe.d.ts b/lib/build/recipe/usermetadata/recipe.d.ts index 8864bf2bb..3c8759b7e 100644 --- a/lib/build/recipe/usermetadata/recipe.d.ts +++ b/lib/build/recipe/usermetadata/recipe.d.ts @@ -15,7 +15,13 @@ export default class Recipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled(): APIHandled[]; - handleAPIRequest: (_: string, __: BaseRequest, ___: BaseResponse, ____: normalisedURLPath, _____: HTTPMethod) => Promise; + handleAPIRequest: ( + _: string, + __: BaseRequest, + ___: BaseResponse, + ____: normalisedURLPath, + _____: HTTPMethod + ) => Promise; handleError(error: error, _: BaseRequest, __: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; diff --git a/lib/build/recipe/usermetadata/recipe.js b/lib/build/recipe/usermetadata/recipe.js index 0b40b3b34..1b7ab148b 100644 --- a/lib/build/recipe/usermetadata/recipe.js +++ b/lib/build/recipe/usermetadata/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); const querier_1 = require("../../querier"); @@ -36,13 +60,16 @@ class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config) { super(recipeId, appInfo); // This stub is required to implement RecipeModule - this.handleAPIRequest = (_, __, ___, ____, _____) => __awaiter(this, void 0, void 0, function* () { - throw new Error("Should never come here"); - }); + this.handleAPIRequest = (_, __, ___, ____, _____) => + __awaiter(this, void 0, void 0, function* () { + throw new Error("Should never come here"); + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } } @@ -51,15 +78,16 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance !== undefined) { return Recipe.instance; } - throw new Error("Initialisation not done. Did you forget to call the UserMetadata.init or SuperTokens.init function?"); + throw new Error( + "Initialisation not done. Did you forget to call the UserMetadata.init or SuperTokens.init function?" + ); } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } - else { + } else { throw new Error("UserMetadata recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/usermetadata/recipeImplementation.js b/lib/build/recipe/usermetadata/recipeImplementation.js index 9247851d1..1f9653e83 100644 --- a/lib/build/recipe/usermetadata/recipeImplementation.js +++ b/lib/build/recipe/usermetadata/recipeImplementation.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); function getRecipeInterface(querier) { diff --git a/lib/build/recipe/usermetadata/types.d.ts b/lib/build/recipe/usermetadata/types.d.ts index f1211c840..9b1ef77a0 100644 --- a/lib/build/recipe/usermetadata/types.d.ts +++ b/lib/build/recipe/usermetadata/types.d.ts @@ -2,13 +2,19 @@ import OverrideableBuilder from "supertokens-js-override"; import { JSONObject } from "../../types"; export declare type TypeInput = { override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; export declare type TypeNormalisedInput = { override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; diff --git a/lib/build/recipe/usermetadata/utils.d.ts b/lib/build/recipe/usermetadata/utils.d.ts index 371d85a96..e368bc539 100644 --- a/lib/build/recipe/usermetadata/utils.d.ts +++ b/lib/build/recipe/usermetadata/utils.d.ts @@ -1,4 +1,8 @@ import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput(_: Recipe, __: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + _: Recipe, + __: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; diff --git a/lib/build/recipe/usermetadata/utils.js b/lib/build/recipe/usermetadata/utils.js index 9bdd116e1..74993e81f 100644 --- a/lib/build/recipe/usermetadata/utils.js +++ b/lib/build/recipe/usermetadata/utils.js @@ -16,7 +16,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(_, __, config) { - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); return { override, }; diff --git a/lib/build/recipe/userroles/index.d.ts b/lib/build/recipe/userroles/index.d.ts index cf7a97184..c0f832dfb 100644 --- a/lib/build/recipe/userroles/index.d.ts +++ b/lib/build/recipe/userroles/index.d.ts @@ -4,50 +4,95 @@ export default class Wrapper { static init: typeof Recipe.init; static PermissionClaim: import("./permissionClaim").PermissionClaimClass; static UserRoleClaim: import("./userRoleClaim").UserRoleClaimClass; - static addRoleToUser(userId: string, role: string, userContext?: any): Promise<{ - status: "OK"; - didUserAlreadyHaveRole: boolean; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; - static removeUserRole(userId: string, role: string, userContext?: any): Promise<{ - status: "OK"; - didUserHaveRole: boolean; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; - static getRolesForUser(userId: string, userContext?: any): Promise<{ + static addRoleToUser( + userId: string, + role: string, + userContext?: any + ): Promise< + | { + status: "OK"; + didUserAlreadyHaveRole: boolean; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; + static removeUserRole( + userId: string, + role: string, + userContext?: any + ): Promise< + | { + status: "OK"; + didUserHaveRole: boolean; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; + static getRolesForUser( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; roles: string[]; }>; - static getUsersThatHaveRole(role: string, userContext?: any): Promise<{ - status: "OK"; - users: string[]; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; - static createNewRoleOrAddPermissions(role: string, permissions: string[], userContext?: any): Promise<{ + static getUsersThatHaveRole( + role: string, + userContext?: any + ): Promise< + | { + status: "OK"; + users: string[]; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; + static createNewRoleOrAddPermissions( + role: string, + permissions: string[], + userContext?: any + ): Promise<{ status: "OK"; createdNewRole: boolean; }>; - static getPermissionsForRole(role: string, userContext?: any): Promise<{ - status: "OK"; - permissions: string[]; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; - static removePermissionsFromRole(role: string, permissions: string[], userContext?: any): Promise<{ + static getPermissionsForRole( + role: string, + userContext?: any + ): Promise< + | { + status: "OK"; + permissions: string[]; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; + static removePermissionsFromRole( + role: string, + permissions: string[], + userContext?: any + ): Promise<{ status: "OK" | "UNKNOWN_ROLE_ERROR"; }>; - static getRolesThatHavePermission(permission: string, userContext?: any): Promise<{ + static getRolesThatHavePermission( + permission: string, + userContext?: any + ): Promise<{ status: "OK"; roles: string[]; }>; - static deleteRole(role: string, userContext?: any): Promise<{ + static deleteRole( + role: string, + userContext?: any + ): Promise<{ status: "OK"; didRoleExist: boolean; }>; - static getAllRoles(userContext?: any): Promise<{ + static getAllRoles( + userContext?: any + ): Promise<{ status: "OK"; roles: string[]; }>; diff --git a/lib/build/recipe/userroles/index.js b/lib/build/recipe/userroles/index.js index 69db1e0f7..c01687051 100644 --- a/lib/build/recipe/userroles/index.js +++ b/lib/build/recipe/userroles/index.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PermissionClaim = exports.UserRoleClaim = exports.getAllRoles = exports.deleteRole = exports.getRolesThatHavePermission = exports.removePermissionsFromRole = exports.getPermissionsForRole = exports.createNewRoleOrAddPermissions = exports.getUsersThatHaveRole = exports.getRolesForUser = exports.removeUserRole = exports.addRoleToUser = exports.init = void 0; const permissionClaim_1 = require("./permissionClaim"); @@ -131,6 +155,16 @@ exports.getRolesThatHavePermission = Wrapper.getRolesThatHavePermission; exports.deleteRole = Wrapper.deleteRole; exports.getAllRoles = Wrapper.getAllRoles; var userRoleClaim_2 = require("./userRoleClaim"); -Object.defineProperty(exports, "UserRoleClaim", { enumerable: true, get: function () { return userRoleClaim_2.UserRoleClaim; } }); +Object.defineProperty(exports, "UserRoleClaim", { + enumerable: true, + get: function () { + return userRoleClaim_2.UserRoleClaim; + }, +}); var permissionClaim_2 = require("./permissionClaim"); -Object.defineProperty(exports, "PermissionClaim", { enumerable: true, get: function () { return permissionClaim_2.PermissionClaim; } }); +Object.defineProperty(exports, "PermissionClaim", { + enumerable: true, + get: function () { + return permissionClaim_2.PermissionClaim; + }, +}); diff --git a/lib/build/recipe/userroles/permissionClaim.js b/lib/build/recipe/userroles/permissionClaim.js index 9015e4e9c..8d68c2fb4 100644 --- a/lib/build/recipe/userroles/permissionClaim.js +++ b/lib/build/recipe/userroles/permissionClaim.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PermissionClaim = exports.PermissionClaimClass = void 0; const recipe_1 = __importDefault(require("./recipe")); diff --git a/lib/build/recipe/userroles/recipe.d.ts b/lib/build/recipe/userroles/recipe.d.ts index 8864bf2bb..3c8759b7e 100644 --- a/lib/build/recipe/userroles/recipe.d.ts +++ b/lib/build/recipe/userroles/recipe.d.ts @@ -15,7 +15,13 @@ export default class Recipe extends RecipeModule { static init(config?: TypeInput): RecipeListFunction; static reset(): void; getAPIsHandled(): APIHandled[]; - handleAPIRequest: (_: string, __: BaseRequest, ___: BaseResponse, ____: normalisedURLPath, _____: HTTPMethod) => Promise; + handleAPIRequest: ( + _: string, + __: BaseRequest, + ___: BaseResponse, + ____: normalisedURLPath, + _____: HTTPMethod + ) => Promise; handleError(error: error, _: BaseRequest, __: BaseResponse): Promise; getAllCORSHeaders(): string[]; isErrorFromThisRecipe(err: any): err is error; diff --git a/lib/build/recipe/userroles/recipe.js b/lib/build/recipe/userroles/recipe.js index 87d9cba52..92931f54f 100644 --- a/lib/build/recipe/userroles/recipe.js +++ b/lib/build/recipe/userroles/recipe.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = __importDefault(require("../../error")); const querier_1 = require("../../querier"); @@ -40,13 +64,16 @@ class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config) { super(recipeId, appInfo); // This stub is required to implement RecipeModule - this.handleAPIRequest = (_, __, ___, ____, _____) => __awaiter(this, void 0, void 0, function* () { - throw new Error("Should never come here"); - }); + this.handleAPIRequest = (_, __, ___, ____, _____) => + __awaiter(this, void 0, void 0, function* () { + throw new Error("Should never come here"); + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId)) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } postSuperTokensInitCallbacks_1.PostSuperTokensInitCallbacks.addPostInitCallback(() => { @@ -63,15 +90,16 @@ class Recipe extends recipeModule_1.default { if (Recipe.instance !== undefined) { return Recipe.instance; } - throw new Error("Initialisation not done. Did you forget to call the UserRoles.init or SuperTokens.init functions?"); + throw new Error( + "Initialisation not done. Did you forget to call the UserRoles.init or SuperTokens.init functions?" + ); } static init(config) { return (appInfo, isInServerlessEnv) => { if (Recipe.instance === undefined) { Recipe.instance = new Recipe(Recipe.RECIPE_ID, appInfo, isInServerlessEnv, config); return Recipe.instance; - } - else { + } else { throw new Error("UserRoles recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/userroles/recipeImplementation.js b/lib/build/recipe/userroles/recipeImplementation.js index 3db34f8bc..459e621f1 100644 --- a/lib/build/recipe/userroles/recipeImplementation.js +++ b/lib/build/recipe/userroles/recipeImplementation.js @@ -13,9 +13,11 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); function getRecipeInterface(querier) { @@ -24,7 +26,10 @@ function getRecipeInterface(querier) { return querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/user/role"), { userId, role }); }, removeUserRole: function ({ userId, role }) { - return querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/role/remove"), { userId, role }); + return querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/user/role/remove"), { + userId, + role, + }); }, getRolesForUser: function ({ userId }) { return querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user/roles"), { userId }); diff --git a/lib/build/recipe/userroles/types.d.ts b/lib/build/recipe/userroles/types.d.ts index c4c889911..af23a75a8 100644 --- a/lib/build/recipe/userroles/types.d.ts +++ b/lib/build/recipe/userroles/types.d.ts @@ -3,7 +3,10 @@ export declare type TypeInput = { skipAddingRolesToAccessToken?: boolean; skipAddingPermissionsToAccessToken?: boolean; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -11,7 +14,10 @@ export declare type TypeNormalisedInput = { skipAddingRolesToAccessToken: boolean; skipAddingPermissionsToAccessToken: boolean; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; }; }; @@ -21,22 +27,28 @@ export declare type RecipeInterface = { userId: string; role: string; userContext: any; - }) => Promise<{ - status: "OK"; - didUserAlreadyHaveRole: boolean; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; + }) => Promise< + | { + status: "OK"; + didUserAlreadyHaveRole: boolean; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; removeUserRole: (input: { userId: string; role: string; userContext: any; - }) => Promise<{ - status: "OK"; - didUserHaveRole: boolean; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; + }) => Promise< + | { + status: "OK"; + didUserHaveRole: boolean; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; getRolesForUser: (input: { userId: string; userContext: any; @@ -47,12 +59,15 @@ export declare type RecipeInterface = { getUsersThatHaveRole: (input: { role: string; userContext: any; - }) => Promise<{ - status: "OK"; - users: string[]; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; + }) => Promise< + | { + status: "OK"; + users: string[]; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; createNewRoleOrAddPermissions: (input: { role: string; permissions: string[]; @@ -64,12 +79,15 @@ export declare type RecipeInterface = { getPermissionsForRole: (input: { role: string; userContext: any; - }) => Promise<{ - status: "OK"; - permissions: string[]; - } | { - status: "UNKNOWN_ROLE_ERROR"; - }>; + }) => Promise< + | { + status: "OK"; + permissions: string[]; + } + | { + status: "UNKNOWN_ROLE_ERROR"; + } + >; removePermissionsFromRole: (input: { role: string; permissions: string[]; diff --git a/lib/build/recipe/userroles/userRoleClaim.js b/lib/build/recipe/userroles/userRoleClaim.js index b59bd5a6a..9f0a777aa 100644 --- a/lib/build/recipe/userroles/userRoleClaim.js +++ b/lib/build/recipe/userroles/userRoleClaim.js @@ -1,16 +1,40 @@ "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.UserRoleClaim = exports.UserRoleClaimClass = void 0; const recipe_1 = __importDefault(require("./recipe")); diff --git a/lib/build/recipe/userroles/utils.d.ts b/lib/build/recipe/userroles/utils.d.ts index 371d85a96..e368bc539 100644 --- a/lib/build/recipe/userroles/utils.d.ts +++ b/lib/build/recipe/userroles/utils.d.ts @@ -1,4 +1,8 @@ import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput(_: Recipe, __: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseUserInput( + _: Recipe, + __: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; diff --git a/lib/build/recipe/userroles/utils.js b/lib/build/recipe/userroles/utils.js index f392db6ee..7023b84d5 100644 --- a/lib/build/recipe/userroles/utils.js +++ b/lib/build/recipe/userroles/utils.js @@ -16,10 +16,18 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAndNormaliseUserInput = void 0; function validateAndNormaliseUserInput(_, __, config) { - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); return { - skipAddingRolesToAccessToken: (config === null || config === void 0 ? void 0 : config.skipAddingRolesToAccessToken) === true, - skipAddingPermissionsToAccessToken: (config === null || config === void 0 ? void 0 : config.skipAddingPermissionsToAccessToken) === true, + skipAddingRolesToAccessToken: + (config === null || config === void 0 ? void 0 : config.skipAddingRolesToAccessToken) === true, + skipAddingPermissionsToAccessToken: + (config === null || config === void 0 ? void 0 : config.skipAddingPermissionsToAccessToken) === true, override, }; } diff --git a/lib/build/recipeModule.d.ts b/lib/build/recipeModule.d.ts index 001dd5819..269a2eb18 100644 --- a/lib/build/recipeModule.d.ts +++ b/lib/build/recipeModule.d.ts @@ -10,7 +10,13 @@ export default abstract class RecipeModule { getAppInfo: () => NormalisedAppinfo; returnAPIIdIfCanHandleRequest: (path: NormalisedURLPath, method: HTTPMethod) => string | undefined; abstract getAPIsHandled(): APIHandled[]; - abstract handleAPIRequest(id: string, req: BaseRequest, response: BaseResponse, path: NormalisedURLPath, method: HTTPMethod): Promise; + abstract handleAPIRequest( + id: string, + req: BaseRequest, + response: BaseResponse, + path: NormalisedURLPath, + method: HTTPMethod + ): Promise; abstract handleError(error: STError, request: BaseRequest, response: BaseResponse): Promise; abstract getAllCORSHeaders(): string[]; abstract isErrorFromThisRecipe(err: any): err is STError; diff --git a/lib/build/recipeModule.js b/lib/build/recipeModule.js index 20473d2b2..efdd876f1 100644 --- a/lib/build/recipeModule.js +++ b/lib/build/recipeModule.js @@ -26,9 +26,11 @@ class RecipeModule { let apisHandled = this.getAPIsHandled(); for (let i = 0; i < apisHandled.length; i++) { let currAPI = apisHandled[i]; - if (!currAPI.disabled && + if ( + !currAPI.disabled && currAPI.method === method && - this.appInfo.apiBasePath.appendPath(currAPI.pathWithoutApiBasePath).equals(path)) { + this.appInfo.apiBasePath.appendPath(currAPI.pathWithoutApiBasePath).equals(path) + ) { return currAPI.id; } } diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 73f8caa1b..5a6621e46 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -15,7 +15,14 @@ export default class SuperTokens { static init(config: TypeInput): void; static reset(): void; static getInstanceOrThrowError(): SuperTokens; - handleAPI: (matchedRecipe: RecipeModule, id: string, request: BaseRequest, response: BaseResponse, path: NormalisedURLPath, method: HTTPMethod) => Promise; + handleAPI: ( + matchedRecipe: RecipeModule, + id: string, + request: BaseRequest, + response: BaseResponse, + path: NormalisedURLPath, + method: HTTPMethod + ) => Promise; getAllCORSHeaders: () => string[]; getUserCount: (includeRecipeIds?: string[] | undefined) => Promise; createUserIdMapping: (input: { @@ -23,24 +30,30 @@ export default class SuperTokens { externalUserId: string; externalUserIdInfo?: string; force?: boolean; - }) => Promise<{ - status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; - } | { - status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; - doesSuperTokensUserIdExist: boolean; - doesExternalUserIdExist: boolean; - }>; + }) => Promise< + | { + status: "OK" | "UNKNOWN_SUPERTOKENS_USER_ID_ERROR"; + } + | { + status: "USER_ID_MAPPING_ALREADY_EXISTS_ERROR"; + doesSuperTokensUserIdExist: boolean; + doesExternalUserIdExist: boolean; + } + >; getUserIdMapping: (input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; - }) => Promise<{ - status: "OK"; - superTokensUserId: string; - externalUserId: string; - externalUserIdInfo: string | undefined; - } | { - status: "UNKNOWN_MAPPING_ERROR"; - }>; + }) => Promise< + | { + status: "OK"; + superTokensUserId: string; + externalUserId: string; + externalUserIdInfo: string | undefined; + } + | { + status: "UNKNOWN_MAPPING_ERROR"; + } + >; deleteUserIdMapping: (input: { userId: string; userIdType?: "SUPERTOKENS" | "EXTERNAL" | "ANY"; diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index d5ae0c95a..8b7d1c904 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.js @@ -13,18 +13,42 @@ * License for the specific language governing permissions and limitations * under the License. */ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); const utils_1 = require("./utils"); @@ -39,32 +63,33 @@ const recipe_1 = __importDefault(require("./recipe/accountlinking/recipe")); class SuperTokens { constructor(config) { var _a, _b; - this.sendTelemetry = () => __awaiter(this, void 0, void 0, function* () { - try { - let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/telemetry"), {}); - let telemetryId; - if (response.exists) { - telemetryId = response.telemetryId; - } - yield axios_1.default({ - method: "POST", - url: "https://api.supertokens.com/0/st/telemetry", - data: { - appName: this.appInfo.appName, - websiteDomain: this.appInfo.websiteDomain.getAsStringDangerous(), - telemetryId, - }, - headers: { - "api-version": 2, - }, - }); - } - catch (ignored) { } - }); - this.handleAPI = (matchedRecipe, id, request, response, path, method) => __awaiter(this, void 0, void 0, function* () { - return yield matchedRecipe.handleAPIRequest(id, request, response, path, method); - }); + this.sendTelemetry = () => + __awaiter(this, void 0, void 0, function* () { + try { + let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/telemetry"), {}); + let telemetryId; + if (response.exists) { + telemetryId = response.telemetryId; + } + yield axios_1.default({ + method: "POST", + url: "https://api.supertokens.com/0/st/telemetry", + data: { + appName: this.appInfo.appName, + websiteDomain: this.appInfo.websiteDomain.getAsStringDangerous(), + telemetryId, + }, + headers: { + "api-version": 2, + }, + }); + } catch (ignored) {} + }); + this.handleAPI = (matchedRecipe, id, request, response, path, method) => + __awaiter(this, void 0, void 0, function* () { + return yield matchedRecipe.handleAPIRequest(id, request, response, path, method); + }); this.getAllCORSHeaders = () => { let headerSet = new Set(); headerSet.add(constants_1.HEADER_RID); @@ -77,21 +102,24 @@ class SuperTokens { }); return Array.from(headerSet); }; - this.getUserCount = (includeRecipeIds) => __awaiter(this, void 0, void 0, function* () { - let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); - let apiVersion = yield querier.getAPIVersion(); - if (utils_1.maxVersion(apiVersion, "2.7") === "2.7") { - throw new Error("Please use core version >= 3.5 to call this function. Otherwise, you can call .getUserCount() instead (for example, EmailPassword.getUserCount())"); - } - let includeRecipeIdsStr = undefined; - if (includeRecipeIds !== undefined) { - includeRecipeIdsStr = includeRecipeIds.join(","); - } - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users/count"), { - includeRecipeIds: includeRecipeIdsStr, + this.getUserCount = (includeRecipeIds) => + __awaiter(this, void 0, void 0, function* () { + let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); + let apiVersion = yield querier.getAPIVersion(); + if (utils_1.maxVersion(apiVersion, "2.7") === "2.7") { + throw new Error( + "Please use core version >= 3.5 to call this function. Otherwise, you can call .getUserCount() instead (for example, EmailPassword.getUserCount())" + ); + } + let includeRecipeIdsStr = undefined; + if (includeRecipeIds !== undefined) { + includeRecipeIdsStr = includeRecipeIds.join(","); + } + let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/users/count"), { + includeRecipeIds: includeRecipeIdsStr, + }); + return Number(response.count); }); - return Number(response.count); - }); this.createUserIdMapping = function (input) { return __awaiter(this, void 0, void 0, function* () { let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); @@ -104,8 +132,7 @@ class SuperTokens { externalUserIdInfo: input.externalUserIdInfo, force: input.force, }); - } - else { + } else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); @@ -121,8 +148,7 @@ class SuperTokens { userIdType: input.userIdType, }); return response; - } - else { + } else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); @@ -137,8 +163,7 @@ class SuperTokens { userIdType: input.userIdType, force: input.force, }); - } - else { + } else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); @@ -148,118 +173,153 @@ class SuperTokens { let querier = querier_1.Querier.getNewInstanceOrThrowError(undefined); let cdiVersion = yield querier.getAPIVersion(); if (utils_1.maxVersion("2.15", cdiVersion) === cdiVersion) { - return yield querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/userid/external-user-id-info"), { - userId: input.userId, - userIdType: input.userIdType, - externalUserIdInfo: input.externalUserIdInfo, - }); - } - else { + return yield querier.sendPutRequest( + new normalisedURLPath_1.default("/recipe/userid/external-user-id-info"), + { + userId: input.userId, + userIdType: input.userIdType, + externalUserIdInfo: input.externalUserIdInfo, + } + ); + } else { throw new global.Error("Please upgrade the SuperTokens core to >= 3.15.0"); } }); }; - this.middleware = (request, response) => __awaiter(this, void 0, void 0, function* () { - logger_1.logDebugMessage("middleware: Started"); - let path = this.appInfo.apiGatewayPath.appendPath(new normalisedURLPath_1.default(request.getOriginalURL())); - let method = utils_1.normaliseHttpMethod(request.getMethod()); - // if the prefix of the URL doesn't match the base path, we skip - if (!path.startsWith(this.appInfo.apiBasePath)) { - logger_1.logDebugMessage("middleware: Not handling because request path did not start with config path. Request path: " + - path.getAsStringDangerous()); - return false; - } - let requestRID = utils_1.getRidFromHeader(request); - logger_1.logDebugMessage("middleware: requestRID is: " + requestRID); - if (requestRID === "anti-csrf") { - // see https://github.com/supertokens/supertokens-node/issues/202 - requestRID = undefined; - } - if (requestRID !== undefined) { - let matchedRecipe = undefined; - // we loop through all recipe modules to find the one with the matching rId - for (let i = 0; i < this.recipeModules.length; i++) { - logger_1.logDebugMessage("middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId()); - if (this.recipeModules[i].getRecipeId() === requestRID) { - matchedRecipe = this.recipeModules[i]; - break; - } - } - if (matchedRecipe === undefined) { - logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); - // we could not find one, so we skip + this.middleware = (request, response) => + __awaiter(this, void 0, void 0, function* () { + logger_1.logDebugMessage("middleware: Started"); + let path = this.appInfo.apiGatewayPath.appendPath( + new normalisedURLPath_1.default(request.getOriginalURL()) + ); + let method = utils_1.normaliseHttpMethod(request.getMethod()); + // if the prefix of the URL doesn't match the base path, we skip + if (!path.startsWith(this.appInfo.apiBasePath)) { + logger_1.logDebugMessage( + "middleware: Not handling because request path did not start with config path. Request path: " + + path.getAsStringDangerous() + ); return false; } - logger_1.logDebugMessage("middleware: Matched with recipe ID: " + matchedRecipe.getRecipeId()); - let id = matchedRecipe.returnAPIIdIfCanHandleRequest(path, method); - if (id === undefined) { - logger_1.logDebugMessage("middleware: Not handling because recipe doesn't handle request path or method. Request path: " + - path.getAsStringDangerous() + - ", request method: " + - method); - // the matched recipe doesn't handle this path and http method - return false; - } - logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); - // give task to the matched recipe - let requestHandled = yield matchedRecipe.handleAPIRequest(id, request, response, path, method); - if (!requestHandled) { - logger_1.logDebugMessage("middleware: Not handled because API returned requestHandled as false"); - return false; + let requestRID = utils_1.getRidFromHeader(request); + logger_1.logDebugMessage("middleware: requestRID is: " + requestRID); + if (requestRID === "anti-csrf") { + // see https://github.com/supertokens/supertokens-node/issues/202 + requestRID = undefined; } - logger_1.logDebugMessage("middleware: Ended"); - return true; - } - else { - // we loop through all recipe modules to find the one with the matching path and method - for (let i = 0; i < this.recipeModules.length; i++) { - logger_1.logDebugMessage("middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId()); - let id = this.recipeModules[i].returnAPIIdIfCanHandleRequest(path, method); - if (id !== undefined) { - logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); - let requestHandled = yield this.recipeModules[i].handleAPIRequest(id, request, response, path, method); - if (!requestHandled) { - logger_1.logDebugMessage("middleware: Not handled because API returned requestHandled as false"); - return false; + if (requestRID !== undefined) { + let matchedRecipe = undefined; + // we loop through all recipe modules to find the one with the matching rId + for (let i = 0; i < this.recipeModules.length; i++) { + logger_1.logDebugMessage( + "middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId() + ); + if (this.recipeModules[i].getRecipeId() === requestRID) { + matchedRecipe = this.recipeModules[i]; + break; } - logger_1.logDebugMessage("middleware: Ended"); - return true; } + if (matchedRecipe === undefined) { + logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); + // we could not find one, so we skip + return false; + } + logger_1.logDebugMessage("middleware: Matched with recipe ID: " + matchedRecipe.getRecipeId()); + let id = matchedRecipe.returnAPIIdIfCanHandleRequest(path, method); + if (id === undefined) { + logger_1.logDebugMessage( + "middleware: Not handling because recipe doesn't handle request path or method. Request path: " + + path.getAsStringDangerous() + + ", request method: " + + method + ); + // the matched recipe doesn't handle this path and http method + return false; + } + logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); + // give task to the matched recipe + let requestHandled = yield matchedRecipe.handleAPIRequest(id, request, response, path, method); + if (!requestHandled) { + logger_1.logDebugMessage( + "middleware: Not handled because API returned requestHandled as false" + ); + return false; + } + logger_1.logDebugMessage("middleware: Ended"); + return true; + } else { + // we loop through all recipe modules to find the one with the matching path and method + for (let i = 0; i < this.recipeModules.length; i++) { + logger_1.logDebugMessage( + "middleware: Checking recipe ID for match: " + this.recipeModules[i].getRecipeId() + ); + let id = this.recipeModules[i].returnAPIIdIfCanHandleRequest(path, method); + if (id !== undefined) { + logger_1.logDebugMessage("middleware: Request being handled by recipe. ID is: " + id); + let requestHandled = yield this.recipeModules[i].handleAPIRequest( + id, + request, + response, + path, + method + ); + if (!requestHandled) { + logger_1.logDebugMessage( + "middleware: Not handled because API returned requestHandled as false" + ); + return false; + } + logger_1.logDebugMessage("middleware: Ended"); + return true; + } + } + logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); + return false; } - logger_1.logDebugMessage("middleware: Not handling because no recipe matched"); - return false; - } - }); - this.errorHandler = (err, request, response) => __awaiter(this, void 0, void 0, function* () { - logger_1.logDebugMessage("errorHandler: Started"); - if (error_1.default.isErrorFromSuperTokens(err)) { - logger_1.logDebugMessage("errorHandler: Error is from SuperTokens recipe. Message: " + err.message); - if (err.type === error_1.default.BAD_INPUT_ERROR) { - logger_1.logDebugMessage("errorHandler: Sending 400 status code response"); - return utils_1.sendNon200ResponseWithMessage(response, err.message, 400); - } - for (let i = 0; i < this.recipeModules.length; i++) { - logger_1.logDebugMessage("errorHandler: Checking recipe for match: " + this.recipeModules[i].getRecipeId()); - if (this.recipeModules[i].isErrorFromThisRecipe(err)) { - logger_1.logDebugMessage("errorHandler: Matched with recipeID: " + this.recipeModules[i].getRecipeId()); - return yield this.recipeModules[i].handleError(err, request, response); + }); + this.errorHandler = (err, request, response) => + __awaiter(this, void 0, void 0, function* () { + logger_1.logDebugMessage("errorHandler: Started"); + if (error_1.default.isErrorFromSuperTokens(err)) { + logger_1.logDebugMessage("errorHandler: Error is from SuperTokens recipe. Message: " + err.message); + if (err.type === error_1.default.BAD_INPUT_ERROR) { + logger_1.logDebugMessage("errorHandler: Sending 400 status code response"); + return utils_1.sendNon200ResponseWithMessage(response, err.message, 400); + } + for (let i = 0; i < this.recipeModules.length; i++) { + logger_1.logDebugMessage( + "errorHandler: Checking recipe for match: " + this.recipeModules[i].getRecipeId() + ); + if (this.recipeModules[i].isErrorFromThisRecipe(err)) { + logger_1.logDebugMessage( + "errorHandler: Matched with recipeID: " + this.recipeModules[i].getRecipeId() + ); + return yield this.recipeModules[i].handleError(err, request, response); + } } } - } - throw err; - }); + throw err; + }); logger_1.logDebugMessage("Started SuperTokens with debug logging (supertokens.init called)"); logger_1.logDebugMessage("appInfo: " + JSON.stringify(config.appInfo)); this.framework = config.framework !== undefined ? config.framework : "express"; logger_1.logDebugMessage("framework: " + this.framework); this.appInfo = utils_1.normaliseInputAppInfoOrThrowError(config.appInfo); this.supertokens = config.supertokens; - querier_1.Querier.init((_a = config.supertokens) === null || _a === void 0 ? void 0 : _a.connectionURI.split(";").filter((h) => h !== "").map((h) => { - return { - domain: new normalisedURLDomain_1.default(h.trim()), - basePath: new normalisedURLPath_1.default(h.trim()), - }; - }), (_b = config.supertokens) === null || _b === void 0 ? void 0 : _b.apiKey); + querier_1.Querier.init( + (_a = config.supertokens) === null || _a === void 0 + ? void 0 + : _a.connectionURI + .split(";") + .filter((h) => h !== "") + .map((h) => { + return { + domain: new normalisedURLDomain_1.default(h.trim()), + basePath: new normalisedURLPath_1.default(h.trim()), + }; + }), + (_b = config.supertokens) === null || _b === void 0 ? void 0 : _b.apiKey + ); if (config.recipeList === undefined || config.recipeList.length === 0) { throw new Error("Please provide at least one recipe to the supertokens.init function call"); } @@ -272,7 +332,9 @@ class SuperTokens { this.recipeModules = config.recipeList.map((func) => { return func(this.appInfo, this.isInServerlessEnv); }); - let isAccountLinkingInitialised = this.recipeModules.find((r) => r.getRecipeId() === recipe_1.default.RECIPE_ID); + let isAccountLinkingInitialised = this.recipeModules.find( + (r) => r.getRecipeId() === recipe_1.default.RECIPE_ID + ); if (!isAccountLinkingInitialised) { this.recipeModules.push(recipe_1.default.init({})(this.appInfo, this.isInServerlessEnv)); } @@ -284,8 +346,7 @@ class SuperTokens { if (randomNum > 7) { this.sendTelemetry(); } - } - else { + } else { this.sendTelemetry(); } } diff --git a/lib/build/utils.js b/lib/build/utils.js index c3abc4160..a35e7fb98 100644 --- a/lib/build/utils.js +++ b/lib/build/utils.js @@ -1,26 +1,45 @@ "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = + (this && this.__createBinding) || + (Object.create + ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { + enumerable: true, + get: function () { + return m[k]; + }, + }); + } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create + ? function (o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } + : function (o, v) { + o["default"] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getTopLevelDomainForSameSiteResolution = exports.makeDefaultUserContextFromAPI = exports.humaniseMilliseconds = exports.frontendHasInterceptor = exports.getRidFromHeader = exports.isAnIpAddress = exports.send200Response = exports.sendNon200Response = exports.sendNon200ResponseWithMessage = exports.normaliseHttpMethod = exports.normaliseInputAppInfoOrThrowError = exports.maxVersion = exports.getLargestVersionFromIntersection = void 0; const psl = __importStar(require("psl")); @@ -49,8 +68,7 @@ function maxVersion(version1, version2) { let v2 = Number(splittedv2[i]); if (v1 > v2) { return version1; - } - else if (v2 > v1) { + } else if (v2 > v1) { return version2; } } @@ -73,9 +91,10 @@ function normaliseInputAppInfoOrThrowError(appInfo) { if (appInfo.websiteDomain === undefined) { throw new Error("Please provide your websiteDomain inside the appInfo object when calling supertokens.init"); } - let apiGatewayPath = appInfo.apiGatewayPath !== undefined - ? new normalisedURLPath_1.default(appInfo.apiGatewayPath) - : new normalisedURLPath_1.default(""); + let apiGatewayPath = + appInfo.apiGatewayPath !== undefined + ? new normalisedURLPath_1.default(appInfo.apiGatewayPath) + : new normalisedURLPath_1.default(""); const websiteDomain = new normalisedURLDomain_1.default(appInfo.websiteDomain); const apiDomain = new normalisedURLDomain_1.default(appInfo.apiDomain); const topLevelAPIDomain = getTopLevelDomainForSameSiteResolution(apiDomain.getAsStringDangerous()); @@ -84,12 +103,15 @@ function normaliseInputAppInfoOrThrowError(appInfo) { appName: appInfo.appName, websiteDomain, apiDomain, - apiBasePath: apiGatewayPath.appendPath(appInfo.apiBasePath === undefined - ? new normalisedURLPath_1.default("/auth") - : new normalisedURLPath_1.default(appInfo.apiBasePath)), - websiteBasePath: appInfo.websiteBasePath === undefined - ? new normalisedURLPath_1.default("/auth") - : new normalisedURLPath_1.default(appInfo.websiteBasePath), + apiBasePath: apiGatewayPath.appendPath( + appInfo.apiBasePath === undefined + ? new normalisedURLPath_1.default("/auth") + : new normalisedURLPath_1.default(appInfo.apiBasePath) + ), + websiteBasePath: + appInfo.websiteBasePath === undefined + ? new normalisedURLPath_1.default("/auth") + : new normalisedURLPath_1.default(appInfo.websiteBasePath), apiGatewayPath, topLevelAPIDomain, topLevelWebsiteDomain, @@ -120,7 +142,9 @@ function send200Response(res, responseJson) { } exports.send200Response = send200Response; function isAnIpAddress(ipaddress) { - return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress); + return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test( + ipaddress + ); } exports.isAnIpAddress = isAnIpAddress; function getRidFromHeader(req) { @@ -135,20 +159,15 @@ function humaniseMilliseconds(ms) { let t = Math.floor(ms / 1000); let suffix = ""; if (t < 60) { - if (t > 1) - suffix = "s"; + if (t > 1) suffix = "s"; return `${t} second${suffix}`; - } - else if (t < 3600) { + } else if (t < 3600) { const m = Math.floor(t / 60); - if (m > 1) - suffix = "s"; + if (m > 1) suffix = "s"; return `${m} minute${suffix}`; - } - else { + } else { const h = Math.floor(t / 360) / 10; - if (h > 1) - suffix = "s"; + if (h > 1) suffix = "s"; return `${h} hour${suffix}`; } } diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index e5511a21d..cf5dddddc 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -392,12 +392,12 @@ export default class Recipe extends RecipeModule { userContext: any; }): Promise< | { - status: "OK" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; - } + status: "OK" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } > => { // In order to link the newUser to the session user, // we need to first make sure that the session user diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 6249719a7..0c9268ac8 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -36,6 +36,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }); return result.userIdMapping; }, + getPrimaryUserIdsForRecipeUserIds: async function ( this: RecipeInterface, { @@ -51,6 +52,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }); return result.userIdMapping; }, + getUsers: async function ( this: RecipeInterface, { @@ -83,6 +85,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo nextPaginationToken: response.nextPaginationToken, }; }, + canCreatePrimaryUserId: async function ( this: RecipeInterface, { @@ -92,25 +95,25 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - wasAlreadyAPrimaryUser: boolean; - } + status: "OK"; + wasAlreadyAPrimaryUser: boolean; + } | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { - let result = await querier.sendGetRequest( + return await querier.sendGetRequest( new NormalisedURLPath("/recipe/accountlinking/user/primary/check"), { recipeUserId, } ); - return result; }, + createPrimaryUser: async function ( this: RecipeInterface, { @@ -120,24 +123,23 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - user: User; - wasAlreadyAPrimaryUser: boolean; - } + status: "OK"; + user: User; + wasAlreadyAPrimaryUser: boolean; + } | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { - let result = await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/primary"), { + return await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/primary"), { recipeUserId, }); - - return result; }, + canLinkAccounts: async function ( this: RecipeInterface, { @@ -149,19 +151,19 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - accountsAlreadyLinked: boolean; - } + status: "OK"; + accountsAlreadyLinked: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user/link/check"), { recipeUserId, @@ -170,6 +172,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo return result; }, + linkAccounts: async function ( this: RecipeInterface, { @@ -183,19 +186,19 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - accountsAlreadyLinked: boolean; - } + status: "OK"; + accountsAlreadyLinked: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { let accountsLinkingResult = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/link"), @@ -223,6 +226,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo return accountsLinkingResult; }, + unlinkAccounts: async function ( this: RecipeInterface, { @@ -234,75 +238,35 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - wasRecipeUserDeleted: boolean; - } - | { - status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; - description: string; - } - > { - let recipeUserIdToPrimaryUserIdMapping = await this.getPrimaryUserIdsForRecipeUserIds({ - recipeUserIds: [recipeUserId], - userContext, - }); - let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId === undefined) { - return { - status: "RECIPE_USER_NOT_FOUND_ERROR", - description: "No user exists with the provided recipeUserId", - }; - } - if (primaryUserId === null) { - return { - status: "PRIMARY_USER_NOT_FOUND_ERROR", - description: - "The input recipeUserId is not linked to any primary user, or is not a primary user itself", - }; + status: "OK"; + wasRecipeUserDeleted: boolean; } - - if (primaryUserId === recipeUserId) { - let user = await this.getUser({ - userId: primaryUserId, - userContext, - }); - - if (user === undefined) { - // this can happen cause of some race condition.. - return this.unlinkAccounts({ - recipeUserId, - userContext, - }); - } - if (user.loginMethods.length > 1) { - // we delete the user here cause if we didn't - // do that, then it would result in the primary user ID having the same - // user ID as the recipe user ID, but they are not linked. So this is not allowed. - await this.deleteUser({ - userId: recipeUserId, - removeAllLinkedAccounts: false, - userContext, - }); - - return { - status: "OK", - wasRecipeUserDeleted: true, - }; - } + | { + status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; + description: string; } + > { let accountsUnlinkingResult = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/unlink"), { recipeUserId, - primaryUserId, } ); - if (accountsUnlinkingResult.status === "OK") { + if (accountsUnlinkingResult.status === "OK" && !accountsUnlinkingResult.wasRecipeUserDeleted) { + // we have the !accountsUnlinkingResult.wasRecipeUserDeleted check + // cause if the user was deleted, it means that it's user ID was the + // same as the primary user ID, AND that the primary user ID has more + // than one login method - so if we revoke the session in this case, + // it will revoke the session for all login methods as well (since recipeUserId == primaryUserID). + + // The reason we don't do this in the core is that if the user has overriden + // session recipe, it goes through their logic. await Session.revokeAllSessionsForUser(recipeUserId, userContext); } return accountsUnlinkingResult; }, + getUser: async function (this: RecipeInterface, { userId }: { userId: string }): Promise { let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user"), { userId, @@ -312,6 +276,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } return undefined; }, + listUsersByAccountInfo: async function ( this: RecipeInterface, { accountInfo }: { accountInfo: AccountInfo } @@ -321,6 +286,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }); return result.users; }, + deleteUser: async function ( this: RecipeInterface, { @@ -333,12 +299,12 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo ): Promise<{ status: "OK"; }> { - let result = await querier.sendPostRequest(new NormalisedURLPath("/user/remove"), { + return await querier.sendPostRequest(new NormalisedURLPath("/user/remove"), { userId, removeAllLinkedAccounts, }); - return result; }, + fetchFromAccountToLinkTable: async function ({ recipeUserId, }: { @@ -349,6 +315,7 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo }); return result.user; }, + storeIntoAccountToLinkTable: async function ({ recipeUserId, primaryUserId, @@ -357,13 +324,13 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo primaryUserId: string; }): Promise< | { - status: "OK"; - didInsertNewRow: boolean; - } + status: "OK"; + didInsertNewRow: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + } > { let result = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/link/table"), @@ -374,5 +341,6 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo ); return result; }, + }; } diff --git a/lib/ts/recipe/accountlinking/types.ts b/lib/ts/recipe/accountlinking/types.ts index 05fa4b279..57e460ac9 100644 --- a/lib/ts/recipe/accountlinking/types.ts +++ b/lib/ts/recipe/accountlinking/types.ts @@ -26,12 +26,12 @@ export type TypeInput = { userContext: any ) => Promise< | { - shouldAutomaticallyLink: false; - } + shouldAutomaticallyLink: false; + } | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - } + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + } >; override?: { functions?: ( @@ -50,12 +50,12 @@ export type TypeNormalisedInput = { userContext: any ) => Promise< | { - shouldAutomaticallyLink: false; - } + shouldAutomaticallyLink: false; + } | { - shouldAutomaticallyLink: true; - shouldRequireVerification: boolean; - } + shouldAutomaticallyLink: true; + shouldRequireVerification: boolean; + } >; override: { functions: ( @@ -93,33 +93,33 @@ export type RecipeInterface = { userContext: any; }) => Promise< | { - status: "OK"; - wasAlreadyAPrimaryUser: boolean; - } + status: "OK"; + wasAlreadyAPrimaryUser: boolean; + } | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } >; createPrimaryUser: (input: { recipeUserId: string; userContext: any; }) => Promise< | { - status: "OK"; - user: User; - wasAlreadyAPrimaryUser: boolean; - } - | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "OK"; + user: User; + wasAlreadyAPrimaryUser: boolean; + } + | { + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } >; canLinkAccounts: (input: { recipeUserId: string; @@ -127,19 +127,19 @@ export type RecipeInterface = { userContext: any; }) => Promise< | { - status: "OK"; - accountsAlreadyLinked: boolean; - } + status: "OK"; + accountsAlreadyLinked: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } >; linkAccounts: (input: { recipeUserId: string; @@ -147,32 +147,32 @@ export type RecipeInterface = { userContext: any; }) => Promise< | { - status: "OK"; - accountsAlreadyLinked: boolean; - } + status: "OK"; + accountsAlreadyLinked: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } >; unlinkAccounts: (input: { recipeUserId: string; userContext: any; }) => Promise< | { - status: "OK"; - wasRecipeUserDeleted: boolean; - } + status: "OK"; + wasRecipeUserDeleted: boolean; + } | { - status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; - description: string; - } + status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; + description: string; + } >; getUser: (input: { userId: string; userContext: any }) => Promise; listUsersByAccountInfo: (input: { accountInfo: AccountInfo; userContext: any }) => Promise; diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index 5ccf9b81c..ccce72e43 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -7,22 +7,27 @@ import { User } from "../../types"; export default function getRecipeInterface(querier: Querier): RecipeInterface { return { - signUp: async function (this: RecipeInterface, { - email, - password, - userContext, - }: { - email: string; - password: string; - userContext: any; - }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + signUp: async function ( + this: RecipeInterface, + { + email, + password, + userContext, + }: { + email: string; + password: string; + userContext: any; + } + ): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { // this function does not check if there is some primary user where the email // of that primary user is unverified (isSignUpAllowed function logic) cause // that is checked in the API layer before calling this function. // This is the recipe function layer which can be // called by the user manually as well if they want to. So we allow them to do that. let response = await this.createNewRecipeUser({ - email, password, userContext + email, + password, + userContext, }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; @@ -38,7 +43,7 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { return { status: "OK", - user: (await getUser(userId, userContext))! + user: (await getUser(userId, userContext))!, }; }, @@ -46,9 +51,13 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { email: string; password: string; userContext: any; - }): Promise<{ - status: "OK"; user: User - } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise< + | { + status: "OK"; + user: User; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + > { return await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { email: input.email, password: input.password, @@ -62,17 +71,10 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { email: string; password: string; }): Promise<{ status: "OK"; user: User } | { status: "WRONG_CREDENTIALS_ERROR" }> { - let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/signin"), { + return await querier.sendPostRequest(new NormalisedURLPath("/recipe/signin"), { email, password, }); - if (response.status === "OK") { - return response; - } else { - return { - status: "WRONG_CREDENTIALS_ERROR", - }; - } }, createResetPasswordToken: async function ({ @@ -83,20 +85,10 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { email: string; }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }> { // the input user ID can be a recipe or a primary user ID. - let response = await querier.sendPostRequest(new NormalisedURLPath("/recipe/user/password/reset/token"), { + return await querier.sendPostRequest(new NormalisedURLPath("/recipe/user/password/reset/token"), { userId, email, }); - if (response.status === "OK") { - return { - status: "OK", - token: response.token, - }; - } else { - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - } }, consumePasswordResetToken: async function ({ @@ -120,15 +112,15 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { userId: string; email?: string; password?: string; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR"; - } | { - status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR", - reason: string - }> { + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + > { // the input can be primary or recipe level user id. return await querier.sendPutRequest(new NormalisedURLPath("/recipe/user"), { userId: input.userId, diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index 4fa1aa8f7..b8c71cd36 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -88,19 +88,26 @@ export type RecipeInterface = { email: string; password: string; userContext: any; - }): Promise<{ - status: "OK"; - user: User - } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise< + | { + status: "OK"; + user: User; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + >; // this function is meant only for creating the recipe in the core and nothing else. createNewRecipeUser(input: { email: string; password: string; userContext: any; - }): Promise<{ - status: "OK"; user: User - } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise< + | { + status: "OK"; + user: User; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + >; signIn(input: { email: string; @@ -124,10 +131,10 @@ export type RecipeInterface = { userContext: any; }): Promise< | { - status: "OK"; - email: string; - userId: string; - } + status: "OK"; + email: string; + userId: string; + } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } >; @@ -136,15 +143,15 @@ export type RecipeInterface = { email?: string; password?: string; userContext: any; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - } | { - status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR", - reason: string - }>; + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + >; }; export type APIOptions = { @@ -160,130 +167,130 @@ export type APIOptions = { export type APIInterface = { emailExistsGET: - | undefined - | ((input: { - email: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - exists: boolean; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + email: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + exists: boolean; + } + | GeneralErrorResponse + >); generatePasswordResetTokenPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - } - | { - status: "PASSWORD_RESET_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + } + | { + status: "PASSWORD_RESET_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); passwordResetPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - email: string; - userId: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + email: string; + userId: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + | GeneralErrorResponse + >); signInPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + | GeneralErrorResponse + >); signUpPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - | { - status: "SIGNUP_NOT_ALLOWED"; - reason: string; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "SIGNUP_NOT_ALLOWED"; + reason: string; + } + | GeneralErrorResponse + >); linkAccountToExistingAccountPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - session: SessionContainerInterface; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - wereAccountsAlreadyLinked: boolean; - } - | { - status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | GeneralErrorResponse - >); + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + session: SessionContainerInterface; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + wereAccountsAlreadyLinked: boolean; + } + | { + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; + description: string; + } + | GeneralErrorResponse + >); }; export type TypeEmailPasswordPasswordResetEmailDeliveryInput = { From cc9ea9a586b4cca2610a62c2b57f7d0fa64210e2 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 19:16:10 +0530 Subject: [PATCH 68/82] more fixes - ts still not compiling --- .../emailpassword/api/linkAccountToExistingAccount.ts | 1 - lib/ts/recipe/emailpassword/constants.ts | 2 +- .../emaildelivery/services/backwardCompatibility/index.ts | 5 ++--- lib/ts/recipe/emailpassword/passwordResetFunctions.ts | 1 - lib/ts/recipe/emailpassword/recipe.ts | 8 +++++--- 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts index 43b20ac31..904f3b287 100644 --- a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts +++ b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts @@ -24,7 +24,6 @@ export default async function linkAccountToExistingAccountAPI( apiImplementation: APIInterface, options: APIOptions ): Promise { - // Logic as per https://github.com/supertokens/supertokens-node/issues/21#issuecomment-710423536 if (apiImplementation.linkAccountToExistingAccountPOST === undefined) { return false; diff --git a/lib/ts/recipe/emailpassword/constants.ts b/lib/ts/recipe/emailpassword/constants.ts index a152f0da8..98573f240 100644 --- a/lib/ts/recipe/emailpassword/constants.ts +++ b/lib/ts/recipe/emailpassword/constants.ts @@ -27,4 +27,4 @@ export const PASSWORD_RESET_API = "/user/password/reset"; export const SIGNUP_EMAIL_EXISTS_API = "/signup/email/exists"; -export const LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/link-account/signup"; +export const LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/signup/link-account"; diff --git a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts index 74a0b3d22..2a46e4321 100644 --- a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts +++ b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts @@ -25,7 +25,6 @@ export default class BackwardCompatibilityService createAndSendCustomEmail: ( user: { id: string; - recipeUserId: string; email: string; }, passwordResetURLWithToken: string, @@ -51,7 +50,7 @@ export default class BackwardCompatibilityService if (!this.isInServerlessEnv) { this.resetPasswordUsingTokenFeature .createAndSendCustomEmail(input.user, input.passwordResetLink, input.userContext) - .catch((_) => {}); + .catch((_) => { }); } else { // see https://github.com/supertokens/supertokens-node/pull/135 await this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( @@ -60,6 +59,6 @@ export default class BackwardCompatibilityService input.userContext ); } - } catch (_) {} + } catch (_) { } }; } diff --git a/lib/ts/recipe/emailpassword/passwordResetFunctions.ts b/lib/ts/recipe/emailpassword/passwordResetFunctions.ts index 195d82732..3f8d2d2d8 100644 --- a/lib/ts/recipe/emailpassword/passwordResetFunctions.ts +++ b/lib/ts/recipe/emailpassword/passwordResetFunctions.ts @@ -21,7 +21,6 @@ export function createAndSendCustomEmail(appInfo: NormalisedAppinfo) { return async ( user: { id: string; - recipeUserId?: string; email: string; }, passwordResetURLWithToken: string diff --git a/lib/ts/recipe/emailpassword/recipe.ts b/lib/ts/recipe/emailpassword/recipe.ts index 802680b7e..8197646e5 100644 --- a/lib/ts/recipe/emailpassword/recipe.ts +++ b/lib/ts/recipe/emailpassword/recipe.ts @@ -43,6 +43,7 @@ import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; import { TypeEmailPasswordEmailDeliveryInput } from "./types"; import { PostSuperTokensInitCallbacks } from "../../postSuperTokensInitCallbacks"; import { GetEmailForUserIdFunc } from "../emailverification/types"; +import { getUser } from "../../" export default class Recipe extends RecipeModule { private static instance: Recipe | undefined = undefined; @@ -86,8 +87,8 @@ export default class Recipe extends RecipeModule { this.emailDelivery = ingredients.emailDelivery === undefined ? new EmailDeliveryIngredient( - this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) - ) + this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) + ) : ingredients.emailDelivery; PostSuperTokensInitCallbacks.addPostInitCallback(() => { @@ -224,13 +225,14 @@ export default class Recipe extends RecipeModule { // extra instance functions below............... getEmailForUserId: GetEmailForUserIdFunc = async (userId, userContext) => { - let user = await this.recipeInterfaceImpl.getUserById({ userId, userContext }); + let user = await getUser(userId, userContext); if (user !== undefined) { let recipeLevelUser = user.loginMethods.find( (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId ); if (recipeLevelUser !== undefined) { if (recipeLevelUser.email === undefined) { + // this check if only for types purposes. throw new Error("Should never come here"); } return { From e3f8f63bd3686b39ca0f76edcec4f48f842bf6f4 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 19:30:23 +0530 Subject: [PATCH 69/82] more fixes - ts still not compiling --- .../api/linkAccountToExistingAccount.ts | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts index 904f3b287..fca5d6766 100644 --- a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts +++ b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts @@ -29,7 +29,6 @@ export default async function linkAccountToExistingAccountAPI( return false; } - // step 1 let formFields: { id: string; value: string; @@ -59,16 +58,8 @@ export default async function linkAccountToExistingAccountAPI( } else if (result.status === "GENERAL_ERROR") { send200Response(options.res, result); } else { - throw new STError({ - type: STError.FIELD_ERROR, - payload: [ - { - id: "email", - error: "This email already exists. Please sign in instead.", - }, - ], - message: "Error in input formFields", - }); + // status: NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR | ACCOUNT_LINKING_NOT_ALLOWED_ERROR + send200Response(options.res, result); } return true; } From d354bfb1ea7f33660e4a39a5bf7d772a54265e66 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 19:30:43 +0530 Subject: [PATCH 70/82] more fixes - ts still not compiling --- .../accountlinking/recipeImplementation.ts | 116 +++++++++--------- .../api/linkAccountToExistingAccount.ts | 1 - .../services/backwardCompatibility/index.ts | 4 +- lib/ts/recipe/emailpassword/recipe.ts | 6 +- .../emailpassword/recipeImplementation.ts | 24 ++-- 5 files changed, 73 insertions(+), 78 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipeImplementation.ts b/lib/ts/recipe/accountlinking/recipeImplementation.ts index 0c9268ac8..6ad5fc7c5 100644 --- a/lib/ts/recipe/accountlinking/recipeImplementation.ts +++ b/lib/ts/recipe/accountlinking/recipeImplementation.ts @@ -95,23 +95,20 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - wasAlreadyAPrimaryUser: boolean; - } + status: "OK"; + wasAlreadyAPrimaryUser: boolean; + } | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { - return await querier.sendGetRequest( - new NormalisedURLPath("/recipe/accountlinking/user/primary/check"), - { - recipeUserId, - } - ); + return await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user/primary/check"), { + recipeUserId, + }); }, createPrimaryUser: async function ( @@ -123,17 +120,17 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - user: User; - wasAlreadyAPrimaryUser: boolean; - } + status: "OK"; + user: User; + wasAlreadyAPrimaryUser: boolean; + } | { - status: - | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" - | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: + | "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR" + | "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { return await querier.sendPostRequest(new NormalisedURLPath("/recipe/accountlinking/user/primary"), { recipeUserId, @@ -151,19 +148,19 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - accountsAlreadyLinked: boolean; - } + status: "OK"; + accountsAlreadyLinked: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - description: string; - primaryUserId: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + description: string; + primaryUserId: string; + } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { let result = await querier.sendGetRequest(new NormalisedURLPath("/recipe/accountlinking/user/link/check"), { recipeUserId, @@ -186,19 +183,19 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - accountsAlreadyLinked: boolean; - } + status: "OK"; + accountsAlreadyLinked: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } + status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + description: string; + } > { let accountsLinkingResult = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/link"), @@ -238,13 +235,13 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo } ): Promise< | { - status: "OK"; - wasRecipeUserDeleted: boolean; - } + status: "OK"; + wasRecipeUserDeleted: boolean; + } | { - status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; - description: string; - } + status: "PRIMARY_USER_NOT_FOUND_ERROR" | "RECIPE_USER_NOT_FOUND_ERROR"; + description: string; + } > { let accountsUnlinkingResult = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/unlink"), @@ -324,13 +321,13 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo primaryUserId: string; }): Promise< | { - status: "OK"; - didInsertNewRow: boolean; - } + status: "OK"; + didInsertNewRow: boolean; + } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - } + status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR"; + primaryUserId: string; + } > { let result = await querier.sendPostRequest( new NormalisedURLPath("/recipe/accountlinking/user/link/table"), @@ -341,6 +338,5 @@ export default function getRecipeImplementation(querier: Querier, config: TypeNo ); return result; }, - }; } diff --git a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts index fca5d6766..9e5c8013d 100644 --- a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts +++ b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts @@ -24,7 +24,6 @@ export default async function linkAccountToExistingAccountAPI( apiImplementation: APIInterface, options: APIOptions ): Promise { - if (apiImplementation.linkAccountToExistingAccountPOST === undefined) { return false; } diff --git a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts index 2a46e4321..89e822288 100644 --- a/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts +++ b/lib/ts/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.ts @@ -50,7 +50,7 @@ export default class BackwardCompatibilityService if (!this.isInServerlessEnv) { this.resetPasswordUsingTokenFeature .createAndSendCustomEmail(input.user, input.passwordResetLink, input.userContext) - .catch((_) => { }); + .catch((_) => {}); } else { // see https://github.com/supertokens/supertokens-node/pull/135 await this.resetPasswordUsingTokenFeature.createAndSendCustomEmail( @@ -59,6 +59,6 @@ export default class BackwardCompatibilityService input.userContext ); } - } catch (_) { } + } catch (_) {} }; } diff --git a/lib/ts/recipe/emailpassword/recipe.ts b/lib/ts/recipe/emailpassword/recipe.ts index 8197646e5..13ded1267 100644 --- a/lib/ts/recipe/emailpassword/recipe.ts +++ b/lib/ts/recipe/emailpassword/recipe.ts @@ -43,7 +43,7 @@ import EmailDeliveryIngredient from "../../ingredients/emaildelivery"; import { TypeEmailPasswordEmailDeliveryInput } from "./types"; import { PostSuperTokensInitCallbacks } from "../../postSuperTokensInitCallbacks"; import { GetEmailForUserIdFunc } from "../emailverification/types"; -import { getUser } from "../../" +import { getUser } from "../../"; export default class Recipe extends RecipeModule { private static instance: Recipe | undefined = undefined; @@ -87,8 +87,8 @@ export default class Recipe extends RecipeModule { this.emailDelivery = ingredients.emailDelivery === undefined ? new EmailDeliveryIngredient( - this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) - ) + this.config.getEmailDeliveryConfig(this.recipeInterfaceImpl, this.isInServerlessEnv) + ) : ingredients.emailDelivery; PostSuperTokensInitCallbacks.addPostInitCallback(() => { diff --git a/lib/ts/recipe/emailpassword/recipeImplementation.ts b/lib/ts/recipe/emailpassword/recipeImplementation.ts index ccce72e43..fbb4a74c0 100644 --- a/lib/ts/recipe/emailpassword/recipeImplementation.ts +++ b/lib/ts/recipe/emailpassword/recipeImplementation.ts @@ -53,9 +53,9 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { userContext: any; }): Promise< | { - status: "OK"; - user: User; - } + status: "OK"; + user: User; + } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } > { return await querier.sendPostRequest(new NormalisedURLPath("/recipe/signup"), { @@ -97,10 +97,10 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { token: string; }): Promise< | { - status: "OK"; - userId: string; - email: string; - } + status: "OK"; + userId: string; + email: string; + } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } > { return await querier.sendPostRequest(new NormalisedURLPath("/recipe/user/password/reset/token/consume"), { @@ -114,12 +114,12 @@ export default function getRecipeInterface(querier: Querier): RecipeInterface { password?: string; }): Promise< | { - status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; - } + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } | { - status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; - reason: string; - } + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } > { // the input can be primary or recipe level user id. return await querier.sendPutRequest(new NormalisedURLPath("/recipe/user"), { From 883eabf0b74c6df20bef08dc099df4a0e1e850f0 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 20:26:08 +0530 Subject: [PATCH 71/82] more fixes - ts still not compiling --- lib/ts/recipe/accountlinking/recipe.ts | 22 +- .../emailpassword/api/implementation.ts | 198 ++++-------------- .../api/linkAccountToExistingAccount.ts | 3 +- lib/ts/recipe/emailpassword/types.ts | 2 - 4 files changed, 64 insertions(+), 161 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index cf5dddddc..c8112e917 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -388,16 +388,22 @@ export default class Recipe extends RecipeModule { }: { session: SessionContainer; newUser: AccountInfoWithRecipeId; - createRecipeUserFunc: (newUser: AccountInfoWithRecipeId) => Promise; + createRecipeUserFunc: () => Promise; userContext: any; }): Promise< | { - status: "OK" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + status: "OK"; + wereAccountsAlreadyLinked: boolean; } | { status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } + | { + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + primaryUserId: string; + recipeUserId: string; + } > => { // In order to link the newUser to the session user, // we need to first make sure that the session user @@ -586,7 +592,7 @@ export default class Recipe extends RecipeModule { } // we create the new recipe user - await createRecipeUserFunc(newUser); + await createRecipeUserFunc(); // now when we recurse, the new recipe user will be found and we can try linking again. return await this.linkAccountsWithUserFromSession({ @@ -605,9 +611,18 @@ export default class Recipe extends RecipeModule { // in terms of account info. So we check for email verification status.. if (!newUserIsVerified && shouldDoAccountLinking.shouldRequireVerification) { + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.isPrimaryUser) { + // TODO: investigate if this can ever happen and eliminate it. + // If this happens, it means that somehow, the new user to be linked is already linked, + // and is not verified. The part of it being already linked is possible, + // but that part of it not being verified and being linked is weird. + throw new Error("Should never come here."); + } // we stop the flow and ask the user to verify this email first. return { status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + primaryUserId: existingUser.id, + recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, }; } } @@ -621,6 +636,7 @@ export default class Recipe extends RecipeModule { if (linkAccountResponse.status === "OK") { return { status: "OK", + wereAccountsAlreadyLinked: linkAccountResponse.accountsAlreadyLinked, }; } else if (linkAccountResponse.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR") { // this means that the the new user is already linked to some other primary user ID, diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index fb56022fe..96db167c8 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -7,9 +7,7 @@ import { listUsersByAccountInfo, getUser } from "../../../"; import AccountLinking from "../../accountlinking/recipe"; import EmailVerification from "../../emailverification/recipe"; import { AccountLinkingClaim } from "../../accountlinking/accountLinkingClaim"; -import { linkAccounts } from "../../accountlinking"; -import { EmailVerificationClaim } from "../../emailverification/emailVerificationClaim"; -import { getEmailVerifyLink } from "../../emailverification/utils"; +import { linkAccounts, storeIntoAccountToLinkTable } from "../../accountlinking"; export default function getAPIImplementation(): APIInterface { return { @@ -29,178 +27,70 @@ export default function getAPIImplementation(): APIInterface { }): Promise< | { status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; wereAccountsAlreadyLinked: boolean; } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } | GeneralErrorResponse > { - let email = formFields.filter((f) => f.id === "email")[0].value; - let result = await AccountLinking.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + const email = formFields.filter((f) => f.id === "email")[0].value; + const password = formFields.filter((f) => f.id === "password")[0].value; + const createRecipeUserFunc = async () => { + await options.recipeImplementation.createNewRecipeUser({ + email, + password, + userContext, + }); + // we ignore the error from the above function call cause it's either successful. + // or it says that the email already exists. In either case, the linkAccountsWithUserFromSession + // function will recurse and things will be fine anyway. + }; + let accountLinkingInstance = await AccountLinking.getInstanceOrThrowError(); + let result = await accountLinkingInstance.linkAccountsWithUserFromSession({ session, newUser: { email, recipeId: "emailpassword", }, - newUserVerified: false, + createRecipeUserFunc, userContext, }); - let createdNewRecipeUser = false; - if (result.createRecipeUser) { - let password = formFields.filter((f) => f.id === "password")[0].value; - let response = await options.recipeImplementation.signUp({ - email, - password, - doAccountLinking: false, - userContext, - }); - if (response.status !== "OK") { - throw Error( - `this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}` - ); - } - createdNewRecipeUser = true; - if (result.updateAccountLinkingClaim === "ADD_CLAIM") { - const emailVerificationInstance = EmailVerification.getInstance(); - if (emailVerificationInstance !== undefined) { - let emailVerificationResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: response.user.id, - email, - userContext, - } - ); - if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { - await session.fetchAndSetClaim(EmailVerificationClaim, userContext); - let emailVerifyLink = getEmailVerifyLink({ - appInfo: options.appInfo, - token: emailVerificationResponse.token, - recipeId: options.recipeId, - }); - await emailVerificationInstance.emailDelivery.ingredientInterfaceImpl.sendEmail({ - type: "EMAIL_VERIFICATION", - user: { - id: response.user.id, - email, - }, - emailVerifyLink, - userContext, - }); - } - } - await session.setClaimValue(AccountLinkingClaim, response.user.id, userContext); - return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: false, - description: "", - }; - } else { - result = await AccountLinking.getInstanceOrThrowError().accountLinkPostSignInViaSession({ - session, - newUser: { - email, - recipeId: "emailpassword", - }, - newUserVerified: false, - userContext, - }); - } - } - if (result.createRecipeUser) { - throw Error( - `this error should never be thrown after creating a new user during accountLinkPostSignInViaSession flow` + if (result.status === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + // this will store in the db that these need to be linked, + // and after verification, it will link these accounts. + let toLinkResult = await storeIntoAccountToLinkTable( + result.recipeUserId, + result.primaryUserId, + userContext ); - } - if (!result.accountsLinked && "reason" in result) { - if (result.reason === "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { - const emailVerificationInstance = EmailVerification.getInstance(); - if (emailVerificationInstance !== undefined) { - let emailVerificationResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: result.userId, - email, - userContext, - } - ); - if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { - await session.fetchAndSetClaim(EmailVerificationClaim, userContext); - let emailVerifyLink = getEmailVerifyLink({ - appInfo: options.appInfo, - token: emailVerificationResponse.token, - recipeId: options.recipeId, - }); - await emailVerificationInstance.emailDelivery.ingredientInterfaceImpl.sendEmail({ - type: "EMAIL_VERIFICATION", - user: { - id: result.userId, - email, - }, - emailVerifyLink, - userContext, - }); - } + if (toLinkResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { + if (toLinkResult.primaryUserId === result.primaryUserId) { + // this is some sort of a race condition issue, so we just ignore it + // since we already linked to the session's account anyway... + return { + status: "OK", + wereAccountsAlreadyLinked: true, + }; + } else { + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: + "Input user is already linked to another account. Please try again or contact support.", + }; } - return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: true, - description: "", - }; - } - if ( - result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || - result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - ) { - return { - status: result.reason, - description: "", - primaryUserId: result.primaryUserId, - }; } + // status: "OK" + await session.fetchAndSetClaim(AccountLinkingClaim, userContext); return { - status: result.reason, - description: "", + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + description: "Before accounts can be linked, the new account must be verified", }; } - let wereAccountsAlreadyLinked = false; - if (result.updateAccountLinkingClaim === "REMOVE_CLAIM") { - await session.removeClaim(AccountLinkingClaim, userContext); - } else { - wereAccountsAlreadyLinked = true; - } - let user = await getUser(session.getUserId()); - if (user === undefined) { - throw Error( - "this error should never be thrown. Can't find primary user with userId: " + session.getUserId() - ); - } - return { - status: "OK", - user, - createdNewRecipeUser, - wereAccountsAlreadyLinked, - session, - }; + // status: "OK" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" + return result; }, emailExistsGET: async function ({ email, diff --git a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts index 9e5c8013d..4efd19684 100644 --- a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts +++ b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts @@ -16,7 +16,6 @@ import { send200Response } from "../../../utils"; import { validateFormFieldsOrThrowError } from "./utils"; import { APIInterface, APIOptions } from ".."; -import STError from "../error"; import { makeDefaultUserContextFromAPI } from "../../../utils"; import Session from "../../session"; @@ -52,7 +51,7 @@ export default async function linkAccountToExistingAccountAPI( if (result.status === "OK") { send200Response(options.res, { status: "OK", - user: result.user, + wereAccountsAlreadyLinked: result.wereAccountsAlreadyLinked, }); } else if (result.status === "GENERAL_ERROR") { send200Response(options.res, result); diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index b8c71cd36..905d8c65b 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -281,8 +281,6 @@ export type APIInterface = { }) => Promise< | { status: "OK"; - user: User; - session: SessionContainerInterface; wereAccountsAlreadyLinked: boolean; } | { From 226215df2f48bbc28b8fd2d5b1d33d62171af872 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 21:06:46 +0530 Subject: [PATCH 72/82] more fixes - ts still not compiling --- lib/ts/recipe/accountlinking/recipe.ts | 28 +++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index c8112e917..fc374e5ac 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -603,6 +603,25 @@ export default class Recipe extends RecipeModule { }); } + // we check if the userObjThatHasSameAccountInfoAndRecipeIdAsNewUser is + // a primary user or not, and if it is, then it means that our newUser + // is already linked so we can return early. + + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.isPrimaryUser) { + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id === existingUser.id) { + // this means that the accounts we want to link are already linked. + return { + status: "OK", + wereAccountsAlreadyLinked: true, + }; + } else { + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: "New user is already linked to another account", + }; + } + } + // now we check about the email verification of the new user. If it's verified, we proceed // to try and link the accounts, and if not, we send email verification error ONLY if the email // or phone number of the new account is different compared to the existing account. @@ -611,14 +630,9 @@ export default class Recipe extends RecipeModule { // in terms of account info. So we check for email verification status.. if (!newUserIsVerified && shouldDoAccountLinking.shouldRequireVerification) { - if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.isPrimaryUser) { - // TODO: investigate if this can ever happen and eliminate it. - // If this happens, it means that somehow, the new user to be linked is already linked, - // and is not verified. The part of it being already linked is possible, - // but that part of it not being verified and being linked is weird. - throw new Error("Should never come here."); - } // we stop the flow and ask the user to verify this email first. + // the recipe ID is the userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id + // cause above we checked that userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.isPrimaryUser is false. return { status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", primaryUserId: existingUser.id, From 225ae466e2377b8648023eb96ea0fe98b0af928c Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 2 May 2023 21:40:01 +0530 Subject: [PATCH 73/82] more fixes - ts still not compiling --- lib/ts/recipe/accountlinking/recipe.ts | 42 +++++++++---------- .../emailpassword/api/implementation.ts | 19 +++++++-- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index fc374e5ac..f4abfaa9a 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -549,29 +549,24 @@ export default class Recipe extends RecipeModule { userContext, }); - let newUserIsVerified = false; - const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => - u.loginMethods.find((lU) => { - let found = false; - if (lU.recipeId !== newUser.recipeId) { - return false; - } - if (newUser.recipeId === "thirdparty") { - if (lU.thirdParty === undefined) { + const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find( + (u) => + u.loginMethods.find((lU) => { + if (lU.recipeId !== newUser.recipeId) { return false; } - found = - lU.thirdParty.id === newUser.thirdParty!.id && - lU.thirdParty.userId === newUser.thirdParty!.userId; - } else { - found = lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; - } - if (!found) { - return false; - } - newUserIsVerified = lU.verified; - return true; - }) + if (newUser.recipeId === "thirdparty") { + if (lU.thirdParty === undefined) { + return false; + } + return ( + lU.thirdParty.id === newUser.thirdParty!.id && + lU.thirdParty.userId === newUser.thirdParty!.userId + ); + } else { + return lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; + } + }) !== undefined ); if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser === undefined) { @@ -629,7 +624,10 @@ export default class Recipe extends RecipeModule { // this means that the existing user does not share anything in common with the new user // in terms of account info. So we check for email verification status.. - if (!newUserIsVerified && shouldDoAccountLinking.shouldRequireVerification) { + if ( + !userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.loginMethods[0].verified && + shouldDoAccountLinking.shouldRequireVerification + ) { // we stop the flow and ask the user to verify this email first. // the recipe ID is the userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id // cause above we checked that userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.isPrimaryUser is false. diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 96db167c8..6444a8c85 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -94,7 +94,6 @@ export default function getAPIImplementation(): APIInterface { }, emailExistsGET: async function ({ email, - options, userContext, }: { email: string; @@ -107,11 +106,25 @@ export default function getAPIImplementation(): APIInterface { } | GeneralErrorResponse > { - let user = await options.recipeImplementation.getUserByEmail({ email, userContext }); + let usersWithSameEmail = await listUsersByAccountInfo( + { + email, + }, + userContext + ); + + let exists = + usersWithSameEmail.find((user) => { + return ( + user.loginMethods.find((lM) => { + return lM.recipeId === "emailpassword" && lM.email === email; + }) !== undefined + ); + }) !== undefined; return { status: "OK", - exists: user !== undefined, + exists, }; }, generatePasswordResetTokenPOST: async function ({ From 98c6532f53904141dc002c5e7386ba4514e75043 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 3 May 2023 00:13:44 +0530 Subject: [PATCH 74/82] more fixes - ts still not compiling --- lib/ts/recipe/accountlinking/recipe.ts | 20 ++++- .../emailpassword/api/implementation.ts | 73 +++++++++++++++++-- 2 files changed, 82 insertions(+), 11 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index f4abfaa9a..ea0fd6607 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -380,7 +380,7 @@ export default class Recipe extends RecipeModule { return false; }; - linkAccountsWithUserFromSession = async ({ + linkAccountsWithUserFromSession = async ({ session, newUser, createRecipeUserFunc, @@ -388,7 +388,13 @@ export default class Recipe extends RecipeModule { }: { session: SessionContainer; newUser: AccountInfoWithRecipeId; - createRecipeUserFunc: () => Promise; + createRecipeUserFunc: () => Promise< + | { status: "OK" } + | { + status: "CUSTOM_RESPONSE_FROM_CREATE_USER"; + resp: T; + } + >; userContext: any; }): Promise< | { @@ -404,6 +410,10 @@ export default class Recipe extends RecipeModule { primaryUserId: string; recipeUserId: string; } + | { + status: "CUSTOM_RESPONSE_FROM_CREATE_USER"; + resp: T; + } > => { // In order to link the newUser to the session user, // we need to first make sure that the session user @@ -587,7 +597,11 @@ export default class Recipe extends RecipeModule { } // we create the new recipe user - await createRecipeUserFunc(); + let respFromCreateRecipeUserFunc = await createRecipeUserFunc(); + if (respFromCreateRecipeUserFunc.status === "CUSTOM_RESPONSE_FROM_CREATE_USER") { + // this means that we could not create a recipe user for some reason.. + return respFromCreateRecipeUserFunc; + } // now when we recurse, the new recipe user will be found and we can try linking again. return await this.linkAccountsWithUserFromSession({ diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 6444a8c85..378f044c2 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -33,22 +33,78 @@ export default function getAPIImplementation(): APIInterface { status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } | GeneralErrorResponse > { const email = formFields.filter((f) => f.id === "email")[0].value; const password = formFields.filter((f) => f.id === "password")[0].value; - const createRecipeUserFunc = async () => { - await options.recipeImplementation.createNewRecipeUser({ + + // if a user already exists with the input email, we first + // verify the credentials. + const usersWithSameEmail = await listUsersByAccountInfo( + { + email, + }, + userContext + ); + + const newUser = usersWithSameEmail.find((user) => { + return ( + user.loginMethods.find((lM) => { + return lM.recipeId === "emailpassword" && lM.email === email; + }) !== undefined + ); + }); + + if (newUser !== undefined) { + let signInResult = await options.recipeImplementation.signIn({ email, password, userContext, }); - // we ignore the error from the above function call cause it's either successful. - // or it says that the email already exists. In either case, the linkAccountsWithUserFromSession - // function will recurse and things will be fine anyway. + if (signInResult.status === "WRONG_CREDENTIALS_ERROR") { + return signInResult; + } + } + + const createRecipeUserFunc = async (): Promise< + | { status: "OK" } + | { + status: "CUSTOM_RESPONSE_FROM_CREATE_USER"; + resp: { status: "WRONG_CREDENTIALS_ERROR" }; + } + > => { + let result = await options.recipeImplementation.createNewRecipeUser({ + email, + password, + userContext, + }); + if (result.status === "EMAIL_ALREADY_EXISTS_ERROR") { + // this can happen in a race condition wherein the user is already created + // by the time it reaches here in the function call for linkAccountsWithUserFromSession + let signInResult = await options.recipeImplementation.signIn({ + email, + password, + userContext, + }); + if (signInResult.status === "WRONG_CREDENTIALS_ERROR") { + return { + status: "CUSTOM_RESPONSE_FROM_CREATE_USER", + resp: signInResult, + }; + } + } + return { + status: "OK", + }; }; + let accountLinkingInstance = await AccountLinking.getInstanceOrThrowError(); - let result = await accountLinkingInstance.linkAccountsWithUserFromSession({ + let result = await accountLinkingInstance.linkAccountsWithUserFromSession<{ + status: "WRONG_CREDENTIALS_ERROR"; + }>({ session, newUser: { email, @@ -57,8 +113,9 @@ export default function getAPIImplementation(): APIInterface { createRecipeUserFunc, userContext, }); - - if (result.status === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + if (result.status === "CUSTOM_RESPONSE_FROM_CREATE_USER") { + return result.resp; + } else if (result.status === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { // this will store in the db that these need to be linked, // and after verification, it will link these accounts. let toLinkResult = await storeIntoAccountToLinkTable( From 21ec9632ae91c6081b176cbc52a1021d6fb31379 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 3 May 2023 00:15:42 +0530 Subject: [PATCH 75/82] more fixes - ts still not compiling --- .../api/linkAccountToExistingAccount.ts | 13 ++----------- lib/ts/recipe/emailpassword/types.ts | 3 +++ 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts index 4efd19684..9967c1cd1 100644 --- a/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts +++ b/lib/ts/recipe/emailpassword/api/linkAccountToExistingAccount.ts @@ -48,16 +48,7 @@ export default async function linkAccountToExistingAccountAPI( options, userContext, }); - if (result.status === "OK") { - send200Response(options.res, { - status: "OK", - wereAccountsAlreadyLinked: result.wereAccountsAlreadyLinked, - }); - } else if (result.status === "GENERAL_ERROR") { - send200Response(options.res, result); - } else { - // status: NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR | ACCOUNT_LINKING_NOT_ALLOWED_ERROR - send200Response(options.res, result); - } + // status: NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR | ACCOUNT_LINKING_NOT_ALLOWED_ERROR | WRONG_CREDENTIALS_ERROR | GENERAL_ERROR | "OK" + send200Response(options.res, result); return true; } diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index 905d8c65b..276b5d601 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -287,6 +287,9 @@ export type APIInterface = { status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } | GeneralErrorResponse >); }; From 686fb309a0068ffe5117b60c056b9f2476ade664 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 3 May 2023 00:17:28 +0530 Subject: [PATCH 76/82] more fixes - ts still not compiling --- lib/ts/recipe/emailpassword/api/implementation.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 378f044c2..716813d2e 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -42,7 +42,11 @@ export default function getAPIImplementation(): APIInterface { const password = formFields.filter((f) => f.id === "password")[0].value; // if a user already exists with the input email, we first - // verify the credentials. + // verify the credentials. We do this instead of relying just on + // createRecipeUserFunc below cause createRecipeUserFunc is only called + // when the user does not exist. This is to prevent a user from + // passing in wrong credentials for an existing user and getting their + // account linked const usersWithSameEmail = await listUsersByAccountInfo( { email, From 9c704deb4d134de049469579db25b00d9e3b705e Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Wed, 3 May 2023 00:34:13 +0530 Subject: [PATCH 77/82] more fixes - ts still not compiling --- lib/ts/recipe/accountlinking/recipe.ts | 24 ++++--- .../emailpassword/api/implementation.ts | 70 ++++++------------- 2 files changed, 37 insertions(+), 57 deletions(-) diff --git a/lib/ts/recipe/accountlinking/recipe.ts b/lib/ts/recipe/accountlinking/recipe.ts index ea0fd6607..7aa5d1175 100644 --- a/lib/ts/recipe/accountlinking/recipe.ts +++ b/lib/ts/recipe/accountlinking/recipe.ts @@ -384,14 +384,16 @@ export default class Recipe extends RecipeModule { session, newUser, createRecipeUserFunc, + verifyCredentialsFunc, userContext, }: { session: SessionContainer; newUser: AccountInfoWithRecipeId; - createRecipeUserFunc: () => Promise< + createRecipeUserFunc: () => Promise; + verifyCredentialsFunc: () => Promise< | { status: "OK" } | { - status: "CUSTOM_RESPONSE_FROM_CREATE_USER"; + status: "CUSTOM_RESPONSE"; resp: T; } >; @@ -411,7 +413,7 @@ export default class Recipe extends RecipeModule { recipeUserId: string; } | { - status: "CUSTOM_RESPONSE_FROM_CREATE_USER"; + status: "CUSTOM_RESPONSE"; resp: T; } > => { @@ -513,6 +515,7 @@ export default class Recipe extends RecipeModule { session, newUser, createRecipeUserFunc, + verifyCredentialsFunc, userContext, }); } else if ( @@ -597,19 +600,24 @@ export default class Recipe extends RecipeModule { } // we create the new recipe user - let respFromCreateRecipeUserFunc = await createRecipeUserFunc(); - if (respFromCreateRecipeUserFunc.status === "CUSTOM_RESPONSE_FROM_CREATE_USER") { - // this means that we could not create a recipe user for some reason.. - return respFromCreateRecipeUserFunc; - } + await createRecipeUserFunc(); // now when we recurse, the new recipe user will be found and we can try linking again. return await this.linkAccountsWithUserFromSession({ session, newUser, createRecipeUserFunc, + verifyCredentialsFunc, userContext, }); + } else { + // since the user already exists, we should first verify the credentials + // before continuing to link the accounts. + let verifyResult = await verifyCredentialsFunc(); + if (verifyResult.status === "CUSTOM_RESPONSE") { + return verifyResult; + } + // this means that the verification was fine and we can continue.. } // we check if the userObjThatHasSameAccountInfoAndRecipeIdAsNewUser is diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 716813d2e..1e96032f9 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -41,68 +41,39 @@ export default function getAPIImplementation(): APIInterface { const email = formFields.filter((f) => f.id === "email")[0].value; const password = formFields.filter((f) => f.id === "password")[0].value; - // if a user already exists with the input email, we first - // verify the credentials. We do this instead of relying just on - // createRecipeUserFunc below cause createRecipeUserFunc is only called - // when the user does not exist. This is to prevent a user from - // passing in wrong credentials for an existing user and getting their - // account linked - const usersWithSameEmail = await listUsersByAccountInfo( - { - email, - }, - userContext - ); - - const newUser = usersWithSameEmail.find((user) => { - return ( - user.loginMethods.find((lM) => { - return lM.recipeId === "emailpassword" && lM.email === email; - }) !== undefined - ); - }); - - if (newUser !== undefined) { - let signInResult = await options.recipeImplementation.signIn({ + const createRecipeUserFunc = async (): Promise => { + await options.recipeImplementation.createNewRecipeUser({ email, password, userContext, }); - if (signInResult.status === "WRONG_CREDENTIALS_ERROR") { - return signInResult; - } - } + // we ignore the result from the above cause after this, function returns, + // the linkAccountsWithUserFromSession anyway does recursion.. + }; - const createRecipeUserFunc = async (): Promise< + const verifyCredentialsFunc = async (): Promise< | { status: "OK" } | { - status: "CUSTOM_RESPONSE_FROM_CREATE_USER"; - resp: { status: "WRONG_CREDENTIALS_ERROR" }; + status: "CUSTOM_RESPONSE"; + resp: { + status: "WRONG_CREDENTIALS_ERROR"; + }; } > => { - let result = await options.recipeImplementation.createNewRecipeUser({ + const signInResult = await options.recipeImplementation.signIn({ email, password, userContext, }); - if (result.status === "EMAIL_ALREADY_EXISTS_ERROR") { - // this can happen in a race condition wherein the user is already created - // by the time it reaches here in the function call for linkAccountsWithUserFromSession - let signInResult = await options.recipeImplementation.signIn({ - email, - password, - userContext, - }); - if (signInResult.status === "WRONG_CREDENTIALS_ERROR") { - return { - status: "CUSTOM_RESPONSE_FROM_CREATE_USER", - resp: signInResult, - }; - } + + if (signInResult.status === "OK") { + return { status: "OK" }; + } else { + return { + status: "CUSTOM_RESPONSE", + resp: signInResult, + }; } - return { - status: "OK", - }; }; let accountLinkingInstance = await AccountLinking.getInstanceOrThrowError(); @@ -115,9 +86,10 @@ export default function getAPIImplementation(): APIInterface { recipeId: "emailpassword", }, createRecipeUserFunc, + verifyCredentialsFunc, userContext, }); - if (result.status === "CUSTOM_RESPONSE_FROM_CREATE_USER") { + if (result.status === "CUSTOM_RESPONSE") { return result.resp; } else if (result.status === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { // this will store in the db that these need to be linked, From 5212cc4f11f4e3b1a1c5a2f348cfdf389e70b493 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Sun, 7 May 2023 12:33:41 +0530 Subject: [PATCH 78/82] more fixes - ts still not compiling --- .../emailpassword/api/implementation.ts | 363 +++++++++--------- 1 file changed, 188 insertions(+), 175 deletions(-) diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 1e96032f9..159c5e408 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -8,6 +8,7 @@ import AccountLinking from "../../accountlinking/recipe"; import EmailVerification from "../../emailverification/recipe"; import { AccountLinkingClaim } from "../../accountlinking/accountLinkingClaim"; import { linkAccounts, storeIntoAccountToLinkTable } from "../../accountlinking"; +import { RecipeLevelUser } from "../../accountlinking/types"; export default function getAPIImplementation(): APIInterface { return { @@ -178,9 +179,54 @@ export default function getAPIImplementation(): APIInterface { | { status: "PASSWORD_RESET_NOT_ALLOWED"; reason: string } | GeneralErrorResponse > { - let email = formFields.filter((f) => f.id === "email")[0].value; - let userIdForPasswordReset: string | undefined = undefined; - let recipeUserId: string; + const email = formFields.filter((f) => f.id === "email")[0].value; + + // this function will be reused in different parts of the flow below.. + async function generateAndSendPasswordResetToken( + userId: string + ): Promise< + | { + status: "OK"; + } + | { status: "PASSWORD_RESET_NOT_ALLOWED"; reason: string } + | GeneralErrorResponse + > { + // the user ID here can be primary or recipe level. + let response = await options.recipeImplementation.createResetPasswordToken({ + userId, + email, + userContext, + }); + if (response.status === "UNKNOWN_USER_ID_ERROR") { + logDebugMessage(`Password reset email not sent, unknown user id: ${userId}`); + return { + status: "OK", + }; + } + + let passwordResetLink = + options.appInfo.websiteDomain.getAsStringDangerous() + + options.appInfo.websiteBasePath.getAsStringDangerous() + + "/reset-password?token=" + + response.token + + "&rid=" + + options.recipeId; + + logDebugMessage(`Sending password reset email to ${email}`); + await options.emailDelivery.ingredientInterfaceImpl.sendEmail({ + type: "PASSWORD_RESET", + user: { + id: userId, + email, + }, + passwordResetLink, + userContext, + }); + + return { + status: "OK", + }; + } /** * check if primaryUserId is linked with this email @@ -188,186 +234,153 @@ export default function getAPIImplementation(): APIInterface { let users = await listUsersByAccountInfo({ email, }); - if (users !== undefined) { - let primaryUser = users.find((u) => u.isPrimaryUser); - if (primaryUser !== undefined) { - /** - * checking if emailpassword user exists for the input email and associated with the primaryUserId - */ - let epUser = primaryUser.loginMethods.find((l) => l.recipeId === "emailpassword"); - if (epUser === undefined) { - /** - * this means no emailpassword user is associated with the primaryUserId which - * has the input email as identifying info - * now checking if emailpassword user exists for the input email - */ - let epRecipeUser = users.find( - (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined - ); - if (epRecipeUser === undefined) { - /** - * this means that there is no emailpassword recipe user for the input email - * so we check is account linking is enabled for the given email and primaryUserId - */ - let shouldDoAccountLinking = await AccountLinking.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( - { - email, - recipeId: "emailpassword", - }, - primaryUser, - undefined, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - /** - * here, reset password token generation is not allowed - * and we have decided to return "OK" status - */ - return { - status: "OK", - }; - } - let identitiesForPrimaryUser = AccountLinking.getInstanceOrThrowError().transformUserInfoIntoVerifiedAndUnverifiedBucket( - primaryUser - ); - /** - * if input email doens't belong to the verified indentity for the primaryUser, - * we need to check shouldRequireVerification boolean - */ - if (!identitiesForPrimaryUser.verified.emails.includes(email)) { - if (shouldDoAccountLinking.shouldRequireVerification) { - /** - * here, reset password token generation is not allowed - * an - */ - return { - status: "OK", - }; - } - } - userIdForPasswordReset = primaryUser.id; - recipeUserId = primaryUser.id; - } else { - /** - * this means emailpassword user associated with the input email exists but it - * is currently not associated with the primaryUserId we found in the - * previous step. We simply generate password reset token for such user - */ - userIdForPasswordReset = epRecipeUser.id; - recipeUserId = epRecipeUser.id; - } - } else { - /** - * the primaryUserId associated with the email has a linked - * emailpassword recipe user with same email - */ - recipeUserId = epUser.recipeUserId; - /** - * checking for shouldDoAccountLinking - */ - let shouldDoAccountLinking = await AccountLinking.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( - { - email, - recipeId: "emailpassword", - }, - primaryUser, - undefined, - userContext - ); - let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink - ? shouldDoAccountLinking.shouldRequireVerification - : false; - if (shouldRequireVerification) { - /** - * if verification is required, we check if this is EP user is - * the only user associated with the primaryUserId. - */ - if (primaryUser.loginMethods.length > 1) { - /** - * checking if the email belongs to the verified identities for the - * primary user - */ - let identitiesForPrimaryUser = AccountLinking.getInstanceOrThrowError().transformUserInfoIntoVerifiedAndUnverifiedBucket( - primaryUser - ); - if (!identitiesForPrimaryUser.verified.emails.includes(email)) { - /** - * the email is not verified for any account linked to the primary user. - * so we check if there exists any account linked with the primary user - * which doesn't have this email as identifying info - */ - let differentIdentityUser = primaryUser.loginMethods.find((u) => u.email !== email); - if (differentIdentityUser !== undefined) { - /** - * if any such user found, we return status to contact support - */ - return { - status: "GENERAL_ERROR", - message: "Password Reset Not Allowed. Please contact support.", - }; - } - } - } - } - userIdForPasswordReset = primaryUser.id; - } + + // we find the recipe user ID of the email password account from the user's list + // for later use. + let emailPasswordAccount: RecipeLevelUser | undefined = undefined; + for (let i = 0; i < users.length; i++) { + let emailPasswordAccountTmp = users[i].loginMethods.find( + (l) => l.recipeId === "emailpassword" && l.email === email + ); + if (emailPasswordAccount !== undefined) { + emailPasswordAccount = emailPasswordAccountTmp; + break; + } + } + + // we find the primary user ID from the user's list for later use. + let primaryUserAssociatedWithEmail = users.find((u) => u.isPrimaryUser); + + // first we check if there even exists a primary user that has the input email + // if not, then we do the regular flow for password reset. + if (primaryUserAssociatedWithEmail === undefined) { + if (emailPasswordAccount === undefined) { + logDebugMessage(`Password reset email not sent, unknown user email: ${email}`); + return { + status: "OK", + }; + } + return await generateAndSendPasswordResetToken(emailPasswordAccount.recipeUserId); + } + + // Now we need to check that if there exists any email password user at all + // for the input email. If not, then it implies that when the token is consumed, + // then we will create a new user - so we should only generate the token if + // the criteria for the new user is met. + if (emailPasswordAccount === undefined) { + // this means that there is no email password user that exists for the input email. + // So we check for the sign up condition and only go ahead if that condition is + // met. + let isSignUpAllowed = await AccountLinking.getInstanceOrThrowError().isSignUpAllowed({ + newUser: { + recipeId: "emailpassword", + email, + }, + userContext, + }); + if (isSignUpAllowed) { + // notice that we pass in the primary user ID here. This means that + // we will be creating a new email password account with the token + // is consumed and linking it to this primary user. + return await generateAndSendPasswordResetToken(primaryUserAssociatedWithEmail.id); } else { - /** - * no primaryUser exists for the given email. So we just find the - * associated emailpasword user, if exists - */ - let epRecipeUser = users.find( - (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + logDebugMessage( + `Password reset email not sent, isSignUpAllowed returned false for email: ${email}` ); - if (epRecipeUser === undefined) { - return { - status: "OK", - }; - } - userIdForPasswordReset = epRecipeUser.id; - recipeUserId = epRecipeUser.id; + return { + status: "OK", + }; } - } else { - return { - status: "OK", - }; } - let response = await options.recipeImplementation.createResetPasswordToken({ - userId: userIdForPasswordReset, - email, - userContext, - }); - if (response.status === "UNKNOWN_USER_ID_ERROR") { - logDebugMessage(`Password reset email not sent, unknown user id: ${userIdForPasswordReset}`); - return { - status: "OK", - }; + // At this point, we know that some email password user exists with this email + // and also some primary user ID exist. We now need to find out if they are linked + // together or not. If they are linked together, then we can just generate the token + // else we check for more security conditions (since we will be linking them post token generation) + + let areTheTwoAccountsLinked = + primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + return lm.recipeUserId === emailPasswordAccount!.recipeUserId; + }) !== undefined; + + if (areTheTwoAccountsLinked) { + return await generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); } - let passwordResetLink = - options.appInfo.websiteDomain.getAsStringDangerous() + - options.appInfo.websiteBasePath.getAsStringDangerous() + - "/reset-password?token=" + - response.token + - "&rid=" + - options.recipeId; - - logDebugMessage(`Sending password reset email to ${email}`); - await options.emailDelivery.ingredientInterfaceImpl.sendEmail({ - type: "PASSWORD_RESET", - user: { - id: userIdForPasswordReset, - recipeUserId, - email, - }, - passwordResetLink, - userContext, - }); + // Here we know that the two accounts are NOT linked. We now need to check for an + // extra security measure here to make sure that the input email in the primary user + // is verified, and if not, we need to make sure that there is no other email / phone number + // associated with the primary user account. If there is, then we do not proceed. - return { - status: "OK", - }; + /* + This security measure helps prevent the following attack: + An attacker has email A and they create an account using TP and it doesn't matter if A is verified or not. Now they create another account using EP with email A and verifies it. Both these accounts are linked. Now the attacker changes the email for EP recipe to B which makes the EP account unverified, but it's still linked. + + If the real owner of B tries to signup using EP, it will say that the account already exists so they may try to reset password which should be denied because then they will end up getting access to attacker's account and verify the EP account. + + The problem with this situation is if the EP account is verified, it will allow further sign-ups with email B which will also be linked to this primary account (that the attacker had created with email A). + + It is important to realise that the attacker had created another account with A because if they hadn't done that, then they wouldn't have access to this account after the real user resets the password which is why it is important to check there is another non-EP account linked to the primary such that the email is not the same as B. + + Exception to the above is that, if there is a third recipe account linked to the above two accounts and has B as verified, then we should allow reset password token generation because user has already proven that the owns the email B + */ + + // But first, this only matters it the user cares about checking for email verification status.. + + let shouldDoAccountLinkingResponse = await AccountLinking.getInstanceOrThrowError().config.shouldDoAutomaticAccountLinking( + emailPasswordAccount, + primaryUserAssociatedWithEmail, + undefined, + userContext + ); + + if (!shouldDoAccountLinkingResponse.shouldAutomaticallyLink) { + // here we will go ahead with the token generation cause + // even when the token is consumed, we will not be linking the accounts + // so no need to check for anything + return await generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + + if (!shouldDoAccountLinkingResponse.shouldRequireVerification) { + // the checks below are related to email verification, and if the user + // does not care about that, then we should just continue with token generation + return await generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + + // Now we start the required security checks. First we check if the primary user + // it has just one linked account. And if that's true, then we continue + // cause then there is no scope for account takeover + if (primaryUserAssociatedWithEmail.loginMethods.length === 1) { + return await generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + + // Next we check if there is any login method in which the input email is verified. + // If that is the case, then it's proven that the user owns the email and we can + // trust linking of the email password account. + let emailVerified = + primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + return lm.email === email && lm.verified; + }) !== undefined; + + if (emailVerified) { + return await generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + + // finally, we check if the primary user has any other email / phone number + // associated with this account - and if it does, then it means that + // there is a risk of account takeover, so we do not allow the token to be generated + let hasOtherEmailOrPhone = + primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + return lm.email !== email || lm.phoneNumber !== undefined; + }) !== undefined; + if (hasOtherEmailOrPhone) { + return { + status: "PASSWORD_RESET_NOT_ALLOWED", + reason: "Token generation was not done because of account take over risk. Please contact support.", + }; + } else { + return await generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } }, passwordResetPOST: async function ({ formFields, From 27eddc393018a1995f3dabe26e9e2a8a87857157 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Sun, 7 May 2023 16:07:36 +0530 Subject: [PATCH 79/82] more fixes - ts still not compiling --- .../emailpassword/api/implementation.ts | 281 +++++++++++------- .../recipe/emailpassword/api/passwordReset.ts | 5 +- lib/ts/recipe/emailpassword/types.ts | 2 +- 3 files changed, 180 insertions(+), 108 deletions(-) diff --git a/lib/ts/recipe/emailpassword/api/implementation.ts b/lib/ts/recipe/emailpassword/api/implementation.ts index 159c5e408..404c70b06 100644 --- a/lib/ts/recipe/emailpassword/api/implementation.ts +++ b/lib/ts/recipe/emailpassword/api/implementation.ts @@ -1,13 +1,13 @@ import { APIInterface, APIOptions, User } from "../"; import { logDebugMessage } from "../../../logger"; -import Session, { createNewSession } from "../../session"; +import Session from "../../session"; import { SessionContainerInterface } from "../../session/types"; import { GeneralErrorResponse } from "../../../types"; import { listUsersByAccountInfo, getUser } from "../../../"; import AccountLinking from "../../accountlinking/recipe"; import EmailVerification from "../../emailverification/recipe"; import { AccountLinkingClaim } from "../../accountlinking/accountLinkingClaim"; -import { linkAccounts, storeIntoAccountToLinkTable } from "../../accountlinking"; +import { storeIntoAccountToLinkTable } from "../../accountlinking"; import { RecipeLevelUser } from "../../accountlinking/types"; export default function getAPIImplementation(): APIInterface { @@ -320,7 +320,7 @@ export default function getAPIImplementation(): APIInterface { The problem with this situation is if the EP account is verified, it will allow further sign-ups with email B which will also be linked to this primary account (that the attacker had created with email A). - It is important to realise that the attacker had created another account with A because if they hadn't done that, then they wouldn't have access to this account after the real user resets the password which is why it is important to check there is another non-EP account linked to the primary such that the email is not the same as B. + It is important to realize that the attacker had created another account with A because if they hadn't done that, then they wouldn't have access to this account after the real user resets the password which is why it is important to check there is another non-EP account linked to the primary such that the email is not the same as B. Exception to the above is that, if there is a third recipe account linked to the above two accounts and has B as verified, then we should allow reset password token generation because user has already proven that the owns the email B */ @@ -398,109 +398,177 @@ export default function getAPIImplementation(): APIInterface { }): Promise< | { status: "OK"; - userId: string; + user: User; email: string; } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } | GeneralErrorResponse > { + async function markEmailAsVerified(userId: string, email: string) { + const emailVerificationInstance = EmailVerification.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId, + email, + userContext, + } + ); + + if (tokenResponse.status === "OK") { + await emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext, + }); + } + } + } + + async function doUpdatePassword(): Promise< + | { + status: "OK"; + user: User; + email: string; + } + | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR" } + | GeneralErrorResponse + > { + let updateResponse = await options.recipeImplementation.updateEmailOrPassword({ + userId: recipeUserIdForWhomTokenWasGenerated, + password: newPassword, + userContext, + }); + if ( + updateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR" || + updateResponse.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR" + ) { + throw new Error("This should never come here because we are not updating the email"); + } else if (updateResponse.status === "UNKNOWN_USER_ID_ERROR") { + // This should happen only cause of a race condition where the user + // might be deleted before token creation and consumption. + return { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + }; + } else { + // status: "OK" + return { + status: "OK", + user: existingUser!, + email: emailForWhomTokenWasGenerated, + }; + } + // TODO: we need to also handle password policy error. Note that this needs + // to happen in the api file (before this function is called) as well + // cause we don't want to consume the token unnecessarily. + } + let newPassword = formFields.filter((f) => f.id === "password")[0].value; - let response = await options.recipeImplementation.resetPasswordUsingToken({ + let tokenConsumptionResponse = await options.recipeImplementation.consumePasswordResetToken({ token, - newPassword, userContext, }); - if (response.status === "OK") { - let userId = response.userId; - let email = response.email; - async function verifyUser(rUserId: string) { - const emailVerificationInstance = EmailVerification.getInstance(); - if (emailVerificationInstance) { - const tokenResponse = await emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + if (tokenConsumptionResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { + return tokenConsumptionResponse; + } + + let recipeUserIdForWhomTokenWasGenerated = tokenConsumptionResponse.userId; + let emailForWhomTokenWasGenerated = tokenConsumptionResponse.email; + + let existingUser = await getUser(tokenConsumptionResponse.userId, userContext); + + if (existingUser === undefined) { + // This should happen only cause of a race condition where the user + // might be deleted before token creation and consumption. + // Also note that this being undefined doesn't mean that the email password + // user does not exist, but it means that there is no reicpe or primary user + // for whom the token was generated. + return { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + }; + } + + // We start by checking if the existingUser is a primary user or not. If it is, + // then we will try and create a new email password user and link it to the primary user (if required) + + if (existingUser.isPrimaryUser) { + // If this user contains an email password account for whom the token was generated, + // then we update that user's password. + let emailPasswordUserIsLinkedToExistingUser = + existingUser.loginMethods.find((lm) => { + // we check based on user ID and not email because the only time + // the primary user ID is used for token generation is if the email password + // user did not exist - in which case the value of emailPasswordUserExists will + // resolve to false anyway, and that's what we want. + return lm.recipeUserId === recipeUserIdForWhomTokenWasGenerated; + }) !== undefined; + + if (emailPasswordUserIsLinkedToExistingUser) { + return doUpdatePassword(); + } else { + // this means that the existingUser does not have an emailpassword user associated + // with it. It could now mean that no emailpassword user exists, or it could mean that + // the the ep user exists, but it's not linked to the current account. + // If no ep user doesn't exists, we will create one, and link it to the existing account. + // If ep user exists, then it means there is some race condition cause + // then the token should have been generated for that user instead of the primary user, + // and it shouldn't have come into this branch. So we can simply send a password reset + // invalid error and the user can try again. + + // NOTE: We do not ask the dev if we should do account linking or not here + // cause we already have asked them this when generating an password reset token. + + let createUserResponse = await options.recipeImplementation.createNewRecipeUser({ + email: tokenConsumptionResponse.email, + password: newPassword, + userContext, + }); + if (createUserResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { + // this means that the user already existed and we can just return an invalid + // token (see the above comment) + return { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + }; + } else { + // we mark the email as verified because password reset also requires + // access to the email to work.. This has a good side effect that + // any other login method with the same email in existingAccount will also get marked + // as verified. + await markEmailAsVerified(createUserResponse.user.id, tokenConsumptionResponse.email); + + // Now we try and link the accounts. The function below will try and also + // create a primary user of the new account, and if it does that, it's OK.. + // But in most cases, it will end up linking to existing account since the + // email is shared. + let linkedToUserId = await AccountLinking.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts( { - userId: rUserId, - email, + recipeUserId: createUserResponse.user.id, + isVerified: true, + checkAccountsToLinkTableAsWell: true, userContext, } ); - - if (tokenResponse.status === "OK") { - await emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ - token: tokenResponse.token, - userContext, - }); + if (linkedToUserId !== existingUser.id) { + // this means that the account we just linked to + // was not the one we had expected to link it to. This can happen + // due to some race condition or the other.. Either way, this + // is not an issue and we can just return OK } + return { + status: "OK", + email: tokenConsumptionResponse.email, + user: (await getUser(linkedToUserId, userContext))!, // we refetch cause we want to return the user object with the updated login methods. + }; } } - let user = await getUser(userId); - if (user === undefined) { - throw Error("this error should never be thrown"); - } - /** - * check if the user is a primaryUser - */ - if (user.isPrimaryUser) { - /** - * check if there exists an emailpassword recipe user - * associated with the primary user with the same email - * which is returned by core in the response - */ - let epUser = user.loginMethods.find((u) => u.email === email && u.recipeId === "emailpassword"); - if (epUser === undefined) { - /** - * create a new emailpassword recipe user - */ - let response = await options.recipeImplementation.signUp({ - email, - password: newPassword, - userContext, - doAccountLinking: false, - }); - if (response.status !== "OK") { - throw Error("this error should not be thrown. EP user already for email: " + email); - } - let recipeUser = response.user; - await verifyUser(response.user.id); - await linkAccounts(recipeUser.id, user.id, userContext); - } else if (!epUser.verified) { - await verifyUser(epUser.recipeUserId); - } - } else { - /** - * it's a recipe user - */ - if (!user.loginMethods[0].verified) { - await verifyUser(user.loginMethods[0].recipeUserId); - } - const session = await Session.getSession( - options.req, - options.res, - { overrideGlobalClaimValidators: () => [], sessionRequired: false }, - userContext - ); - let result = await AccountLinking.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccountsAfterEmailVerification( - { - recipeUserId: user.id, - session, - userContext, - } - ); - if (result.createNewSession) { - await createNewSession( - options.req, - options.res, - result.primaryUserId, - result.recipeUserId, - {}, - {}, - userContext - ); - } - } + } else { + // This means that the existing user is not a primary account, which implies that + // it must be a non linked email password account. In this case, we simply update the password. + // Linking to an existing account will be done after the user goes through the email + // verification flow once they log in (if applicable). + return doUpdatePassword(); } - return response; }, signInPOST: async function ({ formFields, @@ -531,19 +599,21 @@ export default function getAPIImplementation(): APIInterface { if (response.status === "WRONG_CREDENTIALS_ERROR") { return response; } - let user = response.user; - let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + let emailPasswordRecipeUser = response.user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.email === email + ); - if (recipeUser === undefined) { - throw new Error("Should never come here"); + if (emailPasswordRecipeUser === undefined) { + // this can happen cause of some race condition, but it's not a big deal. + throw new Error("Race condition error - please call this API again"); } let session = await Session.createNewSession( options.req, options.res, - user.id, - recipeUser.recipeUserId, + response.user.id, + emailPasswordRecipeUser.recipeUserId, {}, {}, userContext @@ -551,7 +621,7 @@ export default function getAPIImplementation(): APIInterface { return { status: "OK", session, - user, + user: response.user, }; }, signUpPOST: async function ({ @@ -570,8 +640,6 @@ export default function getAPIImplementation(): APIInterface { status: "OK"; session: SessionContainerInterface; user: User; - createdNewUser: boolean; - createdNewRecipeUser: boolean; } | { status: "EMAIL_ALREADY_EXISTS_ERROR"; @@ -597,30 +665,33 @@ export default function getAPIImplementation(): APIInterface { return { status: "SIGNUP_NOT_ALLOWED", reason: - "The input email is already associated with another account where it is not verified. Please disable automatic account linking, or verify the other account before trying again.", + "The input email is already associated with another account where it is not verified. Please verify the other account before trying again.", }; } + + // this function also does account linking let response = await options.recipeImplementation.signUp({ email, password, - doAccountLinking: true, userContext, }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; } - let user = response.user; - let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); + let emailPasswordRecipeUser = response.user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.email === email + ); - if (recipeUser === undefined) { + if (emailPasswordRecipeUser === undefined) { + // this can happen cause of some race condition, but it's not a big deal. throw new Error("Race condition error - please call this API again"); } let session = await Session.createNewSession( options.req, options.res, - user.id, - recipeUser.recipeUserId, + response.user.id, + emailPasswordRecipeUser.recipeUserId, {}, {}, userContext @@ -628,9 +699,7 @@ export default function getAPIImplementation(): APIInterface { return { status: "OK", session, - user, - createdNewUser: response.createdNewUser, - createdNewRecipeUser: true, + user: response.user, }; }, }; diff --git a/lib/ts/recipe/emailpassword/api/passwordReset.ts b/lib/ts/recipe/emailpassword/api/passwordReset.ts index f0ad8ca5b..70f5c6dd6 100644 --- a/lib/ts/recipe/emailpassword/api/passwordReset.ts +++ b/lib/ts/recipe/emailpassword/api/passwordReset.ts @@ -26,7 +26,10 @@ export default async function passwordReset(apiImplementation: APIInterface, opt return false; } - // step 1 + // step 1: We need to do this here even though the update emailpassword recipe function would do this cause: + // - we want to throw this error before consuming the token, so that the user can try again + // - there is a case in the api impl where we create a new user, and we want to assign + // a password that meets the password policy. let formFields: { id: string; value: string; diff --git a/lib/ts/recipe/emailpassword/types.ts b/lib/ts/recipe/emailpassword/types.ts index 276b5d601..0fcba1e68 100644 --- a/lib/ts/recipe/emailpassword/types.ts +++ b/lib/ts/recipe/emailpassword/types.ts @@ -214,7 +214,7 @@ export type APIInterface = { | { status: "OK"; email: string; - userId: string; + user: User; } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; From adb8732ab47da9e32d67e559518390a183b7f291 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Sun, 7 May 2023 16:10:40 +0530 Subject: [PATCH 80/82] more fixes - ts still not compiling --- lib/build/recipe/accountlinking/recipe.d.ts | 26 +- lib/build/recipe/accountlinking/recipe.js | 63 +- .../accountlinking/recipeImplementation.js | 64 +- .../emailpassword/api/implementation.js | 865 ++++++++---------- .../api/linkAccountToExistingAccount.js | 24 +- .../recipe/emailpassword/api/passwordReset.js | 5 +- lib/build/recipe/emailpassword/constants.d.ts | 2 +- lib/build/recipe/emailpassword/constants.js | 2 +- lib/build/recipe/emailpassword/index.d.ts | 27 +- lib/build/recipe/emailpassword/index.js | 26 +- .../emailpassword/passwordResetFunctions.d.ts | 1 - lib/build/recipe/emailpassword/recipe.js | 4 +- .../emailpassword/recipeImplementation.js | 159 +--- lib/build/recipe/emailpassword/types.d.ts | 82 +- lib/ts/recipe/emailpassword/index.ts | 28 +- 15 files changed, 575 insertions(+), 803 deletions(-) diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index 324845e3f..c1d2f7de8 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -63,23 +63,43 @@ export default class Recipe extends RecipeModule { newUser: AccountInfoWithRecipeId; userContext: any; }) => Promise; - linkAccountsWithUserFromSession: ({ + linkAccountsWithUserFromSession: ({ session, newUser, createRecipeUserFunc, + verifyCredentialsFunc, userContext, }: { session: SessionContainer; newUser: AccountInfoWithRecipeId; - createRecipeUserFunc: (newUser: AccountInfoWithRecipeId) => Promise; + createRecipeUserFunc: () => Promise; + verifyCredentialsFunc: () => Promise< + | { + status: "OK"; + } + | { + status: "CUSTOM_RESPONSE"; + resp: T; + } + >; userContext: any; }) => Promise< | { - status: "OK" | "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + status: "OK"; + wereAccountsAlreadyLinked: boolean; } | { status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } + | { + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR"; + primaryUserId: string; + recipeUserId: string; + } + | { + status: "CUSTOM_RESPONSE"; + resp: T; + } >; } diff --git a/lib/build/recipe/accountlinking/recipe.js b/lib/build/recipe/accountlinking/recipe.js index da58201a4..3dc9e8d69 100644 --- a/lib/build/recipe/accountlinking/recipe.js +++ b/lib/build/recipe/accountlinking/recipe.js @@ -295,7 +295,13 @@ class Recipe extends recipeModule_1.default { } return false; }); - this.linkAccountsWithUserFromSession = ({ session, newUser, createRecipeUserFunc, userContext }) => + this.linkAccountsWithUserFromSession = ({ + session, + newUser, + createRecipeUserFunc, + verifyCredentialsFunc, + userContext, + }) => __awaiter(this, void 0, void 0, function* () { // In order to link the newUser to the session user, // we need to first make sure that the session user @@ -384,6 +390,7 @@ class Recipe extends recipeModule_1.default { session, newUser, createRecipeUserFunc, + verifyCredentialsFunc, userContext, }); } else if ( @@ -426,11 +433,9 @@ class Recipe extends recipeModule_1.default { accountInfo: newUser, userContext, }); - let newUserIsVerified = false; const userObjThatHasSameAccountInfoAndRecipeIdAsNewUser = usersArrayThatHaveSameAccountInfoAsNewUser.find( (u) => u.loginMethods.find((lU) => { - let found = false; if (lU.recipeId !== newUser.recipeId) { return false; } @@ -438,18 +443,14 @@ class Recipe extends recipeModule_1.default { if (lU.thirdParty === undefined) { return false; } - found = + return ( lU.thirdParty.id === newUser.thirdParty.id && - lU.thirdParty.userId === newUser.thirdParty.userId; + lU.thirdParty.userId === newUser.thirdParty.userId + ); } else { - found = lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; - } - if (!found) { - return false; + return lU.email === newUser.email || newUser.phoneNumber === newUser.phoneNumber; } - newUserIsVerified = lU.verified; - return true; - }) + }) !== undefined ); if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser === undefined) { /* @@ -468,14 +469,40 @@ class Recipe extends recipeModule_1.default { }; } // we create the new recipe user - yield createRecipeUserFunc(newUser); + yield createRecipeUserFunc(); // now when we recurse, the new recipe user will be found and we can try linking again. return yield this.linkAccountsWithUserFromSession({ session, newUser, createRecipeUserFunc, + verifyCredentialsFunc, userContext, }); + } else { + // since the user already exists, we should first verify the credentials + // before continuing to link the accounts. + let verifyResult = yield verifyCredentialsFunc(); + if (verifyResult.status === "CUSTOM_RESPONSE") { + return verifyResult; + } + // this means that the verification was fine and we can continue.. + } + // we check if the userObjThatHasSameAccountInfoAndRecipeIdAsNewUser is + // a primary user or not, and if it is, then it means that our newUser + // is already linked so we can return early. + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.isPrimaryUser) { + if (userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id === existingUser.id) { + // this means that the accounts we want to link are already linked. + return { + status: "OK", + wereAccountsAlreadyLinked: true, + }; + } else { + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: "New user is already linked to another account", + }; + } } // now we check about the email verification of the new user. If it's verified, we proceed // to try and link the accounts, and if not, we send email verification error ONLY if the email @@ -483,10 +510,17 @@ class Recipe extends recipeModule_1.default { if (usersArrayThatHaveSameAccountInfoAsNewUser.find((u) => u.id === existingUser.id) === undefined) { // this means that the existing user does not share anything in common with the new user // in terms of account info. So we check for email verification status.. - if (!newUserIsVerified && shouldDoAccountLinking.shouldRequireVerification) { + if ( + !userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.loginMethods[0].verified && + shouldDoAccountLinking.shouldRequireVerification + ) { // we stop the flow and ask the user to verify this email first. + // the recipe ID is the userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id + // cause above we checked that userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.isPrimaryUser is false. return { status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + primaryUserId: existingUser.id, + recipeUserId: userObjThatHasSameAccountInfoAndRecipeIdAsNewUser.id, }; } } @@ -498,6 +532,7 @@ class Recipe extends recipeModule_1.default { if (linkAccountResponse.status === "OK") { return { status: "OK", + wereAccountsAlreadyLinked: linkAccountResponse.accountsAlreadyLinked, }; } else if ( linkAccountResponse.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" diff --git a/lib/build/recipe/accountlinking/recipeImplementation.js b/lib/build/recipe/accountlinking/recipeImplementation.js index a52e7f3c0..ca9628ee7 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.js +++ b/lib/build/recipe/accountlinking/recipeImplementation.js @@ -96,24 +96,22 @@ function getRecipeImplementation(querier, config) { }, canCreatePrimaryUserId: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendGetRequest( + return yield querier.sendGetRequest( new normalisedURLPath_1.default("/recipe/accountlinking/user/primary/check"), { recipeUserId, } ); - return result; }); }, createPrimaryUser: function ({ recipeUserId }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendPostRequest( + return yield querier.sendPostRequest( new normalisedURLPath_1.default("/recipe/accountlinking/user/primary"), { recipeUserId, } ); - return result; }); }, canLinkAccounts: function ({ recipeUserId, primaryUserId }) { @@ -157,59 +155,20 @@ function getRecipeImplementation(querier, config) { }, unlinkAccounts: function ({ recipeUserId, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let recipeUserIdToPrimaryUserIdMapping = yield this.getPrimaryUserIdsForRecipeUserIds({ - recipeUserIds: [recipeUserId], - userContext, - }); - let primaryUserId = recipeUserIdToPrimaryUserIdMapping[recipeUserId]; - if (primaryUserId === undefined) { - return { - status: "RECIPE_USER_NOT_FOUND_ERROR", - description: "No user exists with the provided recipeUserId", - }; - } - if (primaryUserId === null) { - return { - status: "PRIMARY_USER_NOT_FOUND_ERROR", - description: - "The input recipeUserId is not linked to any primary user, or is not a primary user itself", - }; - } - if (primaryUserId === recipeUserId) { - let user = yield this.getUser({ - userId: primaryUserId, - userContext, - }); - if (user === undefined) { - // this can happen cause of some race condition.. - return this.unlinkAccounts({ - recipeUserId, - userContext, - }); - } - if (user.loginMethods.length > 1) { - // we delete the user here cause if we didn't - // do that, then it would result in the primary user ID having the same - // user ID as the recipe user ID, but they are not linked. So this is not allowed. - yield this.deleteUser({ - userId: recipeUserId, - removeAllLinkedAccounts: false, - userContext, - }); - return { - status: "OK", - wasRecipeUserDeleted: true, - }; - } - } let accountsUnlinkingResult = yield querier.sendPostRequest( new normalisedURLPath_1.default("/recipe/accountlinking/user/unlink"), { recipeUserId, - primaryUserId, } ); - if (accountsUnlinkingResult.status === "OK") { + if (accountsUnlinkingResult.status === "OK" && !accountsUnlinkingResult.wasRecipeUserDeleted) { + // we have the !accountsUnlinkingResult.wasRecipeUserDeleted check + // cause if the user was deleted, it means that it's user ID was the + // same as the primary user ID, AND that the primary user ID has more + // than one login method - so if we revoke the session in this case, + // it will revoke the session for all login methods as well (since recipeUserId == primaryUserID). + // The reason we don't do this in the core is that if the user has overriden + // session recipe, it goes through their logic. yield session_1.default.revokeAllSessionsForUser(recipeUserId, userContext); } return accountsUnlinkingResult; @@ -240,11 +199,10 @@ function getRecipeImplementation(querier, config) { }, deleteUser: function ({ userId, removeAllLinkedAccounts }) { return __awaiter(this, void 0, void 0, function* () { - let result = yield querier.sendPostRequest(new normalisedURLPath_1.default("/user/remove"), { + return yield querier.sendPostRequest(new normalisedURLPath_1.default("/user/remove"), { userId, removeAllLinkedAccounts, }); - return result; }); }, fetchFromAccountToLinkTable: function ({ recipeUserId }) { diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index b57843e3c..ec58b94e9 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -1,40 +1,4 @@ "use strict"; -var __createBinding = - (this && this.__createBinding) || - (Object.create - ? function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { - enumerable: true, - get: function () { - return m[k]; - }, - }); - } - : function (o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); -var __setModuleDefault = - (this && this.__setModuleDefault) || - (Object.create - ? function (o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } - : function (o, v) { - o["default"] = v; - }); -var __importStar = - (this && this.__importStar) || - function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) - for (var k in mod) - if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -73,479 +37,444 @@ var __importDefault = }; Object.defineProperty(exports, "__esModule", { value: true }); const logger_1 = require("../../../logger"); -const session_1 = __importStar(require("../../session")); +const session_1 = __importDefault(require("../../session")); const __1 = require("../../../"); const recipe_1 = __importDefault(require("../../accountlinking/recipe")); const recipe_2 = __importDefault(require("../../emailverification/recipe")); const accountLinkingClaim_1 = require("../../accountlinking/accountLinkingClaim"); const accountlinking_1 = require("../../accountlinking"); -const emailVerificationClaim_1 = require("../../emailverification/emailVerificationClaim"); -const utils_1 = require("../../emailverification/utils"); function getAPIImplementation() { return { linkAccountToExistingAccountPOST: function ({ formFields, session, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let email = formFields.filter((f) => f.id === "email")[0].value; - let result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ + const email = formFields.filter((f) => f.id === "email")[0].value; + const password = formFields.filter((f) => f.id === "password")[0].value; + const createRecipeUserFunc = () => + __awaiter(this, void 0, void 0, function* () { + yield options.recipeImplementation.createNewRecipeUser({ + email, + password, + userContext, + }); + // we ignore the result from the above cause after this, function returns, + // the linkAccountsWithUserFromSession anyway does recursion.. + }); + const verifyCredentialsFunc = () => + __awaiter(this, void 0, void 0, function* () { + const signInResult = yield options.recipeImplementation.signIn({ + email, + password, + userContext, + }); + if (signInResult.status === "OK") { + return { status: "OK" }; + } else { + return { + status: "CUSTOM_RESPONSE", + resp: signInResult, + }; + } + }); + let accountLinkingInstance = yield recipe_1.default.getInstanceOrThrowError(); + let result = yield accountLinkingInstance.linkAccountsWithUserFromSession({ session, newUser: { email, recipeId: "emailpassword", }, - newUserVerified: false, + createRecipeUserFunc, + verifyCredentialsFunc, userContext, }); - let createdNewRecipeUser = false; - if (result.createRecipeUser) { - let password = formFields.filter((f) => f.id === "password")[0].value; - let response = yield options.recipeImplementation.signUp({ - email, - password, - doAccountLinking: false, - userContext, - }); - if (response.status !== "OK") { - throw Error( - `this error should never be thrown while creating a new user during accountLinkPostSignInViaSession flow: ${response.status}` - ); - } - createdNewRecipeUser = true; - if (result.updateAccountLinkingClaim === "ADD_CLAIM") { - const emailVerificationInstance = recipe_2.default.getInstance(); - if (emailVerificationInstance !== undefined) { - let emailVerificationResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: response.user.id, - email, - userContext, - } - ); - if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { - yield session.fetchAndSetClaim( - emailVerificationClaim_1.EmailVerificationClaim, - userContext - ); - let emailVerifyLink = utils_1.getEmailVerifyLink({ - appInfo: options.appInfo, - token: emailVerificationResponse.token, - recipeId: options.recipeId, - }); - yield emailVerificationInstance.emailDelivery.ingredientInterfaceImpl.sendEmail({ - type: "EMAIL_VERIFICATION", - user: { - id: response.user.id, - email, - }, - emailVerifyLink, - userContext, - }); - } - } - yield session.setClaimValue( - accountLinkingClaim_1.AccountLinkingClaim, - response.user.id, - userContext - ); - return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: false, - description: "", - }; - } else { - result = yield recipe_1.default.getInstanceOrThrowError().accountLinkPostSignInViaSession({ - session, - newUser: { - email, - recipeId: "emailpassword", - }, - newUserVerified: false, - userContext, - }); - } - } - if (result.createRecipeUser) { - throw Error( - `this error should never be thrown after creating a new user during accountLinkPostSignInViaSession flow` + if (result.status === "CUSTOM_RESPONSE") { + return result.resp; + } else if (result.status === "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { + // this will store in the db that these need to be linked, + // and after verification, it will link these accounts. + let toLinkResult = yield accountlinking_1.storeIntoAccountToLinkTable( + result.recipeUserId, + result.primaryUserId, + userContext ); - } - if (!result.accountsLinked && "reason" in result) { - if (result.reason === "EXISTING_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR") { - const emailVerificationInstance = recipe_2.default.getInstance(); - if (emailVerificationInstance !== undefined) { - let emailVerificationResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: result.userId, - email, - userContext, - } - ); - if (emailVerificationResponse.status !== "EMAIL_ALREADY_VERIFIED_ERROR") { - yield session.fetchAndSetClaim( - emailVerificationClaim_1.EmailVerificationClaim, - userContext - ); - let emailVerifyLink = utils_1.getEmailVerifyLink({ - appInfo: options.appInfo, - token: emailVerificationResponse.token, - recipeId: options.recipeId, - }); - yield emailVerificationInstance.emailDelivery.ingredientInterfaceImpl.sendEmail({ - type: "EMAIL_VERIFICATION", - user: { - id: result.userId, - email, - }, - emailVerifyLink, - userContext, - }); - } + if (toLinkResult.status === "RECIPE_USER_ID_ALREADY_LINKED_WITH_PRIMARY_USER_ID_ERROR") { + if (toLinkResult.primaryUserId === result.primaryUserId) { + // this is some sort of a race condition issue, so we just ignore it + // since we already linked to the session's account anyway... + return { + status: "OK", + wereAccountsAlreadyLinked: true, + }; + } else { + return { + status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR", + description: + "Input user is already linked to another account. Please try again or contact support.", + }; } - return { - status: "ACCOUNT_NOT_VERIFIED_ERROR", - isNotVerifiedAccountFromInputSession: true, - description: "", - }; - } - if ( - result.reason === "ACCOUNT_INFO_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" || - result.reason === "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR" - ) { - return { - status: result.reason, - description: "", - primaryUserId: result.primaryUserId, - }; } + // status: "OK" + yield session.fetchAndSetClaim(accountLinkingClaim_1.AccountLinkingClaim, userContext); return { - status: result.reason, - description: "", + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR", + description: "Before accounts can be linked, the new account must be verified", }; } - let wereAccountsAlreadyLinked = false; - if (result.updateAccountLinkingClaim === "REMOVE_CLAIM") { - yield session.removeClaim(accountLinkingClaim_1.AccountLinkingClaim, userContext); - } else { - wereAccountsAlreadyLinked = true; - } - let user = yield __1.getUser(session.getUserId()); - if (user === undefined) { - throw Error( - "this error should never be thrown. Can't find primary user with userId: " + session.getUserId() - ); - } - return { - status: "OK", - user, - createdNewRecipeUser, - wereAccountsAlreadyLinked, - session, - }; + // status: "OK" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR" + return result; }); }, - emailExistsGET: function ({ email, options, userContext }) { + emailExistsGET: function ({ email, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let user = yield options.recipeImplementation.getUserByEmail({ email, userContext }); + let usersWithSameEmail = yield __1.listUsersByAccountInfo( + { + email, + }, + userContext + ); + let exists = + usersWithSameEmail.find((user) => { + return ( + user.loginMethods.find((lM) => { + return lM.recipeId === "emailpassword" && lM.email === email; + }) !== undefined + ); + }) !== undefined; return { status: "OK", - exists: user !== undefined, + exists, }; }); }, generatePasswordResetTokenPOST: function ({ formFields, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let email = formFields.filter((f) => f.id === "email")[0].value; - let userIdForPasswordReset = undefined; - let recipeUserId; + const email = formFields.filter((f) => f.id === "email")[0].value; + // this function will be reused in different parts of the flow below.. + function generateAndSendPasswordResetToken(userId) { + return __awaiter(this, void 0, void 0, function* () { + // the user ID here can be primary or recipe level. + let response = yield options.recipeImplementation.createResetPasswordToken({ + userId, + email, + userContext, + }); + if (response.status === "UNKNOWN_USER_ID_ERROR") { + logger_1.logDebugMessage(`Password reset email not sent, unknown user id: ${userId}`); + return { + status: "OK", + }; + } + let passwordResetLink = + options.appInfo.websiteDomain.getAsStringDangerous() + + options.appInfo.websiteBasePath.getAsStringDangerous() + + "/reset-password?token=" + + response.token + + "&rid=" + + options.recipeId; + logger_1.logDebugMessage(`Sending password reset email to ${email}`); + yield options.emailDelivery.ingredientInterfaceImpl.sendEmail({ + type: "PASSWORD_RESET", + user: { + id: userId, + email, + }, + passwordResetLink, + userContext, + }); + return { + status: "OK", + }; + }); + } /** * check if primaryUserId is linked with this email */ let users = yield __1.listUsersByAccountInfo({ email, }); - if (users !== undefined) { - let primaryUser = users.find((u) => u.isPrimaryUser); - if (primaryUser !== undefined) { - /** - * checking if emailpassword user exists for the input email and associated with the primaryUserId - */ - let epUser = primaryUser.loginMethods.find((l) => l.recipeId === "emailpassword"); - if (epUser === undefined) { - /** - * this means no emailpassword user is associated with the primaryUserId which - * has the input email as identifying info - * now checking if emailpassword user exists for the input email - */ - let epRecipeUser = users.find( - (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined - ); - if (epRecipeUser === undefined) { - /** - * this means that there is no emailpassword recipe user for the input email - * so we check is account linking is enabled for the given email and primaryUserId - */ - let shouldDoAccountLinking = yield recipe_1.default - .getInstanceOrThrowError() - .config.shouldDoAutomaticAccountLinking( - { - email, - recipeId: "emailpassword", - }, - primaryUser, - undefined, - userContext - ); - if (!shouldDoAccountLinking.shouldAutomaticallyLink) { - /** - * here, reset password token generation is not allowed - * and we have decided to return "OK" status - */ - return { - status: "OK", - }; - } - let identitiesForPrimaryUser = recipe_1.default - .getInstanceOrThrowError() - .transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); - /** - * if input email doens't belong to the verified indentity for the primaryUser, - * we need to check shouldRequireVerification boolean - */ - if (!identitiesForPrimaryUser.verified.emails.includes(email)) { - if (shouldDoAccountLinking.shouldRequireVerification) { - /** - * here, reset password token generation is not allowed - * an - */ - return { - status: "OK", - }; - } - } - userIdForPasswordReset = primaryUser.id; - recipeUserId = primaryUser.id; - } else { - /** - * this means emailpassword user associated with the input email exists but it - * is currently not associated with the primaryUserId we found in the - * previous step. We simply generate password reset token for such user - */ - userIdForPasswordReset = epRecipeUser.id; - recipeUserId = epRecipeUser.id; - } - } else { - /** - * the primaryUserId associated with the email has a linked - * emailpassword recipe user with same email - */ - recipeUserId = epUser.recipeUserId; - /** - * checking for shouldDoAccountLinking - */ - let shouldDoAccountLinking = yield recipe_1.default - .getInstanceOrThrowError() - .config.shouldDoAutomaticAccountLinking( - { - email, - recipeId: "emailpassword", - }, - primaryUser, - undefined, - userContext - ); - let shouldRequireVerification = shouldDoAccountLinking.shouldAutomaticallyLink - ? shouldDoAccountLinking.shouldRequireVerification - : false; - if (shouldRequireVerification) { - /** - * if verification is required, we check if this is EP user is - * the only user associated with the primaryUserId. - */ - if (primaryUser.loginMethods.length > 1) { - /** - * checking if the email belongs to the verified identities for the - * primary user - */ - let identitiesForPrimaryUser = recipe_1.default - .getInstanceOrThrowError() - .transformUserInfoIntoVerifiedAndUnverifiedBucket(primaryUser); - if (!identitiesForPrimaryUser.verified.emails.includes(email)) { - /** - * the email is not verified for any account linked to the primary user. - * so we check if there exists any account linked with the primary user - * which doesn't have this email as identifying info - */ - let differentIdentityUser = primaryUser.loginMethods.find( - (u) => u.email !== email - ); - if (differentIdentityUser !== undefined) { - /** - * if any such user found, we return status to contact support - */ - return { - status: "GENERAL_ERROR", - message: "Password Reset Not Allowed. Please contact support.", - }; - } - } - } - } - userIdForPasswordReset = primaryUser.id; - } + // we find the recipe user ID of the email password account from the user's list + // for later use. + let emailPasswordAccount = undefined; + for (let i = 0; i < users.length; i++) { + let emailPasswordAccountTmp = users[i].loginMethods.find( + (l) => l.recipeId === "emailpassword" && l.email === email + ); + if (emailPasswordAccount !== undefined) { + emailPasswordAccount = emailPasswordAccountTmp; + break; + } + } + // we find the primary user ID from the user's list for later use. + let primaryUserAssociatedWithEmail = users.find((u) => u.isPrimaryUser); + // first we check if there even exists a primary user that has the input email + // if not, then we do the regular flow for password reset. + if (primaryUserAssociatedWithEmail === undefined) { + if (emailPasswordAccount === undefined) { + logger_1.logDebugMessage(`Password reset email not sent, unknown user email: ${email}`); + return { + status: "OK", + }; + } + return yield generateAndSendPasswordResetToken(emailPasswordAccount.recipeUserId); + } + // Now we need to check that if there exists any email password user at all + // for the input email. If not, then it implies that when the token is consumed, + // then we will create a new user - so we should only generate the token if + // the criteria for the new user is met. + if (emailPasswordAccount === undefined) { + // this means that there is no email password user that exists for the input email. + // So we check for the sign up condition and only go ahead if that condition is + // met. + let isSignUpAllowed = yield recipe_1.default.getInstanceOrThrowError().isSignUpAllowed({ + newUser: { + recipeId: "emailpassword", + email, + }, + userContext, + }); + if (isSignUpAllowed) { + // notice that we pass in the primary user ID here. This means that + // we will be creating a new email password account with the token + // is consumed and linking it to this primary user. + return yield generateAndSendPasswordResetToken(primaryUserAssociatedWithEmail.id); } else { - /** - * no primaryUser exists for the given email. So we just find the - * associated emailpasword user, if exists - */ - let epRecipeUser = users.find( - (u) => u.loginMethods.find((l) => l.recipeId === "emailpassword") !== undefined + logger_1.logDebugMessage( + `Password reset email not sent, isSignUpAllowed returned false for email: ${email}` ); - if (epRecipeUser === undefined) { - return { - status: "OK", - }; - } - userIdForPasswordReset = epRecipeUser.id; - recipeUserId = epRecipeUser.id; + return { + status: "OK", + }; } - } else { - return { - status: "OK", - }; } - let response = yield options.recipeImplementation.createResetPasswordToken({ - userId: userIdForPasswordReset, - email, - userContext, - }); - if (response.status === "UNKNOWN_USER_ID_ERROR") { - logger_1.logDebugMessage( - `Password reset email not sent, unknown user id: ${userIdForPasswordReset}` + // At this point, we know that some email password user exists with this email + // and also some primary user ID exist. We now need to find out if they are linked + // together or not. If they are linked together, then we can just generate the token + // else we check for more security conditions (since we will be linking them post token generation) + let areTheTwoAccountsLinked = + primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + return lm.recipeUserId === emailPasswordAccount.recipeUserId; + }) !== undefined; + if (areTheTwoAccountsLinked) { + return yield generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + // Here we know that the two accounts are NOT linked. We now need to check for an + // extra security measure here to make sure that the input email in the primary user + // is verified, and if not, we need to make sure that there is no other email / phone number + // associated with the primary user account. If there is, then we do not proceed. + /* + This security measure helps prevent the following attack: + An attacker has email A and they create an account using TP and it doesn't matter if A is verified or not. Now they create another account using EP with email A and verifies it. Both these accounts are linked. Now the attacker changes the email for EP recipe to B which makes the EP account unverified, but it's still linked. + + If the real owner of B tries to signup using EP, it will say that the account already exists so they may try to reset password which should be denied because then they will end up getting access to attacker's account and verify the EP account. + + The problem with this situation is if the EP account is verified, it will allow further sign-ups with email B which will also be linked to this primary account (that the attacker had created with email A). + + It is important to realize that the attacker had created another account with A because if they hadn't done that, then they wouldn't have access to this account after the real user resets the password which is why it is important to check there is another non-EP account linked to the primary such that the email is not the same as B. + + Exception to the above is that, if there is a third recipe account linked to the above two accounts and has B as verified, then we should allow reset password token generation because user has already proven that the owns the email B + */ + // But first, this only matters it the user cares about checking for email verification status.. + let shouldDoAccountLinkingResponse = yield recipe_1.default + .getInstanceOrThrowError() + .config.shouldDoAutomaticAccountLinking( + emailPasswordAccount, + primaryUserAssociatedWithEmail, + undefined, + userContext ); + if (!shouldDoAccountLinkingResponse.shouldAutomaticallyLink) { + // here we will go ahead with the token generation cause + // even when the token is consumed, we will not be linking the accounts + // so no need to check for anything + return yield generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + if (!shouldDoAccountLinkingResponse.shouldRequireVerification) { + // the checks below are related to email verification, and if the user + // does not care about that, then we should just continue with token generation + return yield generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + // Now we start the required security checks. First we check if the primary user + // it has just one linked account. And if that's true, then we continue + // cause then there is no scope for account takeover + if (primaryUserAssociatedWithEmail.loginMethods.length === 1) { + return yield generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + // Next we check if there is any login method in which the input email is verified. + // If that is the case, then it's proven that the user owns the email and we can + // trust linking of the email password account. + let emailVerified = + primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + return lm.email === email && lm.verified; + }) !== undefined; + if (emailVerified) { + return yield generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); + } + // finally, we check if the primary user has any other email / phone number + // associated with this account - and if it does, then it means that + // there is a risk of account takeover, so we do not allow the token to be generated + let hasOtherEmailOrPhone = + primaryUserAssociatedWithEmail.loginMethods.find((lm) => { + return lm.email !== email || lm.phoneNumber !== undefined; + }) !== undefined; + if (hasOtherEmailOrPhone) { return { - status: "OK", + status: "PASSWORD_RESET_NOT_ALLOWED", + reason: + "Token generation was not done because of account take over risk. Please contact support.", }; + } else { + return yield generateAndSendPasswordResetToken(emailPasswordAccount.recipeId); } - let passwordResetLink = - options.appInfo.websiteDomain.getAsStringDangerous() + - options.appInfo.websiteBasePath.getAsStringDangerous() + - "/reset-password?token=" + - response.token + - "&rid=" + - options.recipeId; - logger_1.logDebugMessage(`Sending password reset email to ${email}`); - yield options.emailDelivery.ingredientInterfaceImpl.sendEmail({ - type: "PASSWORD_RESET", - user: { - id: userIdForPasswordReset, - recipeUserId, - email, - }, - passwordResetLink, - userContext, - }); - return { - status: "OK", - }; }); }, passwordResetPOST: function ({ formFields, token, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { + function markEmailAsVerified(userId, email) { + return __awaiter(this, void 0, void 0, function* () { + const emailVerificationInstance = recipe_2.default.getInstance(); + if (emailVerificationInstance) { + const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( + { + userId, + email, + userContext, + } + ); + if (tokenResponse.status === "OK") { + yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ + token: tokenResponse.token, + userContext, + }); + } + } + }); + } + function doUpdatePassword() { + return __awaiter(this, void 0, void 0, function* () { + let updateResponse = yield options.recipeImplementation.updateEmailOrPassword({ + userId: recipeUserIdForWhomTokenWasGenerated, + password: newPassword, + userContext, + }); + if ( + updateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR" || + updateResponse.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR" + ) { + throw new Error("This should never come here because we are not updating the email"); + } else if (updateResponse.status === "UNKNOWN_USER_ID_ERROR") { + // This should happen only cause of a race condition where the user + // might be deleted before token creation and consumption. + return { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + }; + } else { + // status: "OK" + return { + status: "OK", + user: existingUser, + email: emailForWhomTokenWasGenerated, + }; + } + // TODO: we need to also handle password policy error. Note that this needs + // to happen in the api file (before this function is called) as well + // cause we don't want to consume the token unnecessarily. + }); + } let newPassword = formFields.filter((f) => f.id === "password")[0].value; - let response = yield options.recipeImplementation.resetPasswordUsingToken({ + let tokenConsumptionResponse = yield options.recipeImplementation.consumePasswordResetToken({ token, - newPassword, userContext, }); - if (response.status === "OK") { - let userId = response.userId; - let email = response.email; - function verifyUser(rUserId) { - return __awaiter(this, void 0, void 0, function* () { - const emailVerificationInstance = recipe_2.default.getInstance(); - if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: rUserId, - email, - userContext, - } - ); - if (tokenResponse.status === "OK") { - yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ - token: tokenResponse.token, - userContext, - }); - } - } + if (tokenConsumptionResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { + return tokenConsumptionResponse; + } + let recipeUserIdForWhomTokenWasGenerated = tokenConsumptionResponse.userId; + let emailForWhomTokenWasGenerated = tokenConsumptionResponse.email; + let existingUser = yield __1.getUser(tokenConsumptionResponse.userId, userContext); + if (existingUser === undefined) { + // This should happen only cause of a race condition where the user + // might be deleted before token creation and consumption. + // Also note that this being undefined doesn't mean that the email password + // user does not exist, but it means that there is no reicpe or primary user + // for whom the token was generated. + return { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + }; + } + // We start by checking if the existingUser is a primary user or not. If it is, + // then we will try and create a new email password user and link it to the primary user (if required) + if (existingUser.isPrimaryUser) { + // If this user contains an email password account for whom the token was generated, + // then we update that user's password. + let emailPasswordUserIsLinkedToExistingUser = + existingUser.loginMethods.find((lm) => { + // we check based on user ID and not email because the only time + // the primary user ID is used for token generation is if the email password + // user did not exist - in which case the value of emailPasswordUserExists will + // resolve to false anyway, and that's what we want. + return lm.recipeUserId === recipeUserIdForWhomTokenWasGenerated; + }) !== undefined; + if (emailPasswordUserIsLinkedToExistingUser) { + return doUpdatePassword(); + } else { + // this means that the existingUser does not have an emailpassword user associated + // with it. It could now mean that no emailpassword user exists, or it could mean that + // the the ep user exists, but it's not linked to the current account. + // If no ep user doesn't exists, we will create one, and link it to the existing account. + // If ep user exists, then it means there is some race condition cause + // then the token should have been generated for that user instead of the primary user, + // and it shouldn't have come into this branch. So we can simply send a password reset + // invalid error and the user can try again. + // NOTE: We do not ask the dev if we should do account linking or not here + // cause we already have asked them this when generating an password reset token. + let createUserResponse = yield options.recipeImplementation.createNewRecipeUser({ + email: tokenConsumptionResponse.email, + password: newPassword, + userContext, }); - } - let user = yield __1.getUser(userId); - if (user === undefined) { - throw Error("this error should never be thrown"); - } - /** - * check if the user is a primaryUser - */ - if (user.isPrimaryUser) { - /** - * check if there exists an emailpassword recipe user - * associated with the primary user with the same email - * which is returned by core in the response - */ - let epUser = user.loginMethods.find((u) => u.email === email && u.recipeId === "emailpassword"); - if (epUser === undefined) { - /** - * create a new emailpassword recipe user - */ - let response = yield options.recipeImplementation.signUp({ - email, - password: newPassword, - userContext, - doAccountLinking: false, - }); - if (response.status !== "OK") { - throw Error("this error should not be thrown. EP user already for email: " + email); + if (createUserResponse.status === "EMAIL_ALREADY_EXISTS_ERROR") { + // this means that the user already existed and we can just return an invalid + // token (see the above comment) + return { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR", + }; + } else { + // we mark the email as verified because password reset also requires + // access to the email to work.. This has a good side effect that + // any other login method with the same email in existingAccount will also get marked + // as verified. + yield markEmailAsVerified(createUserResponse.user.id, tokenConsumptionResponse.email); + // Now we try and link the accounts. The function below will try and also + // create a primary user of the new account, and if it does that, it's OK.. + // But in most cases, it will end up linking to existing account since the + // email is shared. + let linkedToUserId = yield recipe_1.default + .getInstanceOrThrowError() + .createPrimaryUserIdOrLinkAccounts({ + recipeUserId: createUserResponse.user.id, + isVerified: true, + checkAccountsToLinkTableAsWell: true, + userContext, + }); + if (linkedToUserId !== existingUser.id) { + // this means that the account we just linked to + // was not the one we had expected to link it to. This can happen + // due to some race condition or the other.. Either way, this + // is not an issue and we can just return OK } - let recipeUser = response.user; - yield verifyUser(response.user.id); - yield accountlinking_1.linkAccounts(recipeUser.id, user.id, userContext); - } else if (!epUser.verified) { - yield verifyUser(epUser.recipeUserId); - } - } else { - /** - * it's a recipe user - */ - if (!user.loginMethods[0].verified) { - yield verifyUser(user.loginMethods[0].recipeUserId); - } - const session = yield session_1.default.getSession( - options.req, - options.res, - { overrideGlobalClaimValidators: () => [], sessionRequired: false }, - userContext - ); - let result = yield recipe_1.default - .getInstanceOrThrowError() - .createPrimaryUserIdOrLinkAccountsAfterEmailVerification({ - recipeUserId: user.id, - session, - userContext, - }); - if (result.createNewSession) { - yield session_1.createNewSession( - options.req, - options.res, - result.primaryUserId, - result.recipeUserId, - {}, - {}, - userContext - ); + return { + status: "OK", + email: tokenConsumptionResponse.email, + user: yield __1.getUser(linkedToUserId, userContext), // we refetch cause we want to return the user object with the updated login methods. + }; } } + } else { + // This means that the existing user is not a primary account, which implies that + // it must be a non linked email password account. In this case, we simply update the password. + // Linking to an existing account will be done after the user goes through the email + // verification flow once they log in (if applicable). + return doUpdatePassword(); } - return response; }); }, signInPOST: function ({ formFields, options, userContext }) { @@ -556,16 +485,18 @@ function getAPIImplementation() { if (response.status === "WRONG_CREDENTIALS_ERROR") { return response; } - let user = response.user; - let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); - if (recipeUser === undefined) { - throw new Error("Should never come here"); + let emailPasswordRecipeUser = response.user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.email === email + ); + if (emailPasswordRecipeUser === undefined) { + // this can happen cause of some race condition, but it's not a big deal. + throw new Error("Race condition error - please call this API again"); } let session = yield session_1.default.createNewSession( options.req, options.res, - user.id, - recipeUser.recipeUserId, + response.user.id, + emailPasswordRecipeUser.recipeUserId, {}, {}, userContext @@ -573,7 +504,7 @@ function getAPIImplementation() { return { status: "OK", session, - user, + user: response.user, }; }); }, @@ -592,28 +523,30 @@ function getAPIImplementation() { return { status: "SIGNUP_NOT_ALLOWED", reason: - "The input email is already associated with another account where it is not verified. Please disable automatic account linking, or verify the other account before trying again.", + "The input email is already associated with another account where it is not verified. Please verify the other account before trying again.", }; } + // this function also does account linking let response = yield options.recipeImplementation.signUp({ email, password, - doAccountLinking: true, userContext, }); if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; } - let user = response.user; - let recipeUser = user.loginMethods.find((u) => u.recipeId === "emailpassword" && u.email === email); - if (recipeUser === undefined) { + let emailPasswordRecipeUser = response.user.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.email === email + ); + if (emailPasswordRecipeUser === undefined) { + // this can happen cause of some race condition, but it's not a big deal. throw new Error("Race condition error - please call this API again"); } let session = yield session_1.default.createNewSession( options.req, options.res, - user.id, - recipeUser.recipeUserId, + response.user.id, + emailPasswordRecipeUser.recipeUserId, {}, {}, userContext @@ -621,9 +554,7 @@ function getAPIImplementation() { return { status: "OK", session, - user, - createdNewUser: response.createdNewUser, - createdNewRecipeUser: true, + user: response.user, }; }); }, diff --git a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js index 84e6de768..643a21819 100644 --- a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js +++ b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.js @@ -52,16 +52,13 @@ var __importDefault = Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../../../utils"); const utils_2 = require("./utils"); -const error_1 = __importDefault(require("../error")); const utils_3 = require("../../../utils"); const session_1 = __importDefault(require("../../session")); function linkAccountToExistingAccountAPI(apiImplementation, options) { return __awaiter(this, void 0, void 0, function* () { - // Logic as per https://github.com/supertokens/supertokens-node/issues/21#issuecomment-710423536 if (apiImplementation.linkAccountToExistingAccountPOST === undefined) { return false; } - // step 1 let formFields = yield utils_2.validateFormFieldsOrThrowError( options.config.signUpFeature.formFields, (yield options.req.getJSONBody()).formFields @@ -79,25 +76,8 @@ function linkAccountToExistingAccountAPI(apiImplementation, options) { options, userContext, }); - if (result.status === "OK") { - utils_1.send200Response(options.res, { - status: "OK", - user: result.user, - }); - } else if (result.status === "GENERAL_ERROR") { - utils_1.send200Response(options.res, result); - } else { - throw new error_1.default({ - type: error_1.default.FIELD_ERROR, - payload: [ - { - id: "email", - error: "This email already exists. Please sign in instead.", - }, - ], - message: "Error in input formFields", - }); - } + // status: NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR | ACCOUNT_LINKING_NOT_ALLOWED_ERROR | WRONG_CREDENTIALS_ERROR | GENERAL_ERROR | "OK" + utils_1.send200Response(options.res, result); return true; }); } diff --git a/lib/build/recipe/emailpassword/api/passwordReset.js b/lib/build/recipe/emailpassword/api/passwordReset.js index dc8c29d4f..305462d75 100644 --- a/lib/build/recipe/emailpassword/api/passwordReset.js +++ b/lib/build/recipe/emailpassword/api/passwordReset.js @@ -60,7 +60,10 @@ function passwordReset(apiImplementation, options) { if (apiImplementation.passwordResetPOST === undefined) { return false; } - // step 1 + // step 1: We need to do this here even though the update emailpassword recipe function would do this cause: + // - we want to throw this error before consuming the token, so that the user can try again + // - there is a case in the api impl where we create a new user, and we want to assign + // a password that meets the password policy. let formFields = yield utils_2.validateFormFieldsOrThrowError( options.config.resetPasswordUsingTokenFeature.formFieldsForPasswordResetForm, (yield options.req.getJSONBody()).formFields diff --git a/lib/build/recipe/emailpassword/constants.d.ts b/lib/build/recipe/emailpassword/constants.d.ts index 69dc7508d..03c215a60 100644 --- a/lib/build/recipe/emailpassword/constants.d.ts +++ b/lib/build/recipe/emailpassword/constants.d.ts @@ -5,4 +5,4 @@ export declare const SIGN_IN_API = "/signin"; export declare const GENERATE_PASSWORD_RESET_TOKEN_API = "/user/password/reset/token"; export declare const PASSWORD_RESET_API = "/user/password/reset"; export declare const SIGNUP_EMAIL_EXISTS_API = "/signup/email/exists"; -export declare const LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/link-account/signup"; +export declare const LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/signup/link-account"; diff --git a/lib/build/recipe/emailpassword/constants.js b/lib/build/recipe/emailpassword/constants.js index 73f605b2f..a9f779e46 100644 --- a/lib/build/recipe/emailpassword/constants.js +++ b/lib/build/recipe/emailpassword/constants.js @@ -22,4 +22,4 @@ exports.SIGN_IN_API = "/signin"; exports.GENERATE_PASSWORD_RESET_TOKEN_API = "/user/password/reset/token"; exports.PASSWORD_RESET_API = "/user/password/reset"; exports.SIGNUP_EMAIL_EXISTS_API = "/signup/email/exists"; -exports.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/link-account/signup"; +exports.LINK_ACCOUNT_TO_EXISTING_ACCOUNT_API = "/signup/link-account"; diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index 867460d1d..eb238a28f 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -8,12 +8,10 @@ export default class Wrapper { static signUp( email: string, password: string, - doAccountLinking?: boolean, userContext?: any ): Promise< | { status: "OK"; - createdNewUser: boolean; user: User; } | { @@ -33,8 +31,6 @@ export default class Wrapper { status: "WRONG_CREDENTIALS_ERROR"; } >; - static getUserById(userId: string, userContext?: any): Promise; - static getUserByEmail(email: string, userContext?: any): Promise; /** * We do not make email optional here cause we want to * allow passing in primaryUserId. If we make email optional, @@ -59,9 +55,8 @@ export default class Wrapper { status: "UNKNOWN_USER_ID_ERROR"; } >; - static resetPasswordUsingToken( + static consumePasswordResetToken( token: string, - newPassword: string, userContext?: any ): Promise< | { @@ -78,13 +73,15 @@ export default class Wrapper { email?: string; password?: string; userContext?: any; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; - }>; + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + >; static sendEmail( input: TypeEmailPasswordEmailDeliveryInput & { userContext?: any; @@ -95,10 +92,8 @@ export declare let init: typeof Recipe.init; export declare let Error: typeof SuperTokensError; export declare let signUp: typeof Wrapper.signUp; export declare let signIn: typeof Wrapper.signIn; -export declare let getUserById: typeof Wrapper.getUserById; -export declare let getUserByEmail: typeof Wrapper.getUserByEmail; export declare let createResetPasswordToken: typeof Wrapper.createResetPasswordToken; -export declare let resetPasswordUsingToken: typeof Wrapper.resetPasswordUsingToken; +export declare let consumePasswordResetToken: typeof Wrapper.consumePasswordResetToken; export declare let updateEmailOrPassword: typeof Wrapper.updateEmailOrPassword; export type { RecipeInterface, User, APIOptions, APIInterface }; export declare let sendEmail: typeof Wrapper.sendEmail; diff --git a/lib/build/recipe/emailpassword/index.js b/lib/build/recipe/emailpassword/index.js index 0e31a7b7a..cf1da42f2 100644 --- a/lib/build/recipe/emailpassword/index.js +++ b/lib/build/recipe/emailpassword/index.js @@ -50,15 +50,14 @@ var __importDefault = return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.sendEmail = exports.updateEmailOrPassword = exports.resetPasswordUsingToken = exports.createResetPasswordToken = exports.getUserByEmail = exports.getUserById = exports.signIn = exports.signUp = exports.Error = exports.init = void 0; +exports.sendEmail = exports.updateEmailOrPassword = exports.consumePasswordResetToken = exports.createResetPasswordToken = exports.signIn = exports.signUp = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); const error_1 = __importDefault(require("./error")); class Wrapper { - static signUp(email, password, doAccountLinking = false, userContext) { + static signUp(email, password, userContext) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.signUp({ email, password, - doAccountLinking, userContext: userContext === undefined ? {} : userContext, }); } @@ -69,18 +68,6 @@ class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } - static getUserById(userId, userContext) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserById({ - userId, - userContext: userContext === undefined ? {} : userContext, - }); - } - static getUserByEmail(email, userContext) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserByEmail({ - email, - userContext: userContext === undefined ? {} : userContext, - }); - } /** * We do not make email optional here cause we want to * allow passing in primaryUserId. If we make email optional, @@ -99,10 +86,9 @@ class Wrapper { userContext: userContext === undefined ? {} : userContext, }); } - static resetPasswordUsingToken(token, newPassword, userContext) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.resetPasswordUsingToken({ + static consumePasswordResetToken(token, userContext) { + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.consumePasswordResetToken({ token, - newPassword, userContext: userContext === undefined ? {} : userContext, }); } @@ -127,9 +113,7 @@ exports.init = Wrapper.init; exports.Error = Wrapper.Error; exports.signUp = Wrapper.signUp; exports.signIn = Wrapper.signIn; -exports.getUserById = Wrapper.getUserById; -exports.getUserByEmail = Wrapper.getUserByEmail; exports.createResetPasswordToken = Wrapper.createResetPasswordToken; -exports.resetPasswordUsingToken = Wrapper.resetPasswordUsingToken; +exports.consumePasswordResetToken = Wrapper.consumePasswordResetToken; exports.updateEmailOrPassword = Wrapper.updateEmailOrPassword; exports.sendEmail = Wrapper.sendEmail; diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index a1c21861b..4713b3789 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -4,7 +4,6 @@ export declare function createAndSendCustomEmail( ): ( user: { id: string; - recipeUserId?: string; email: string; }, passwordResetURLWithToken: string diff --git a/lib/build/recipe/emailpassword/recipe.js b/lib/build/recipe/emailpassword/recipe.js index 4fdf2a02c..fb106bbce 100644 --- a/lib/build/recipe/emailpassword/recipe.js +++ b/lib/build/recipe/emailpassword/recipe.js @@ -68,6 +68,7 @@ const querier_1 = require("../../querier"); const supertokens_js_override_1 = __importDefault(require("supertokens-js-override")); const emaildelivery_1 = __importDefault(require("../../ingredients/emaildelivery")); const postSuperTokensInitCallbacks_1 = require("../../postSuperTokensInitCallbacks"); +const __1 = require("../../"); class Recipe extends recipeModule_1.default { constructor(recipeId, appInfo, isInServerlessEnv, config, ingredients) { super(recipeId, appInfo); @@ -165,13 +166,14 @@ class Recipe extends recipeModule_1.default { // extra instance functions below............... this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let user = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + let user = yield __1.getUser(userId, userContext); if (user !== undefined) { let recipeLevelUser = user.loginMethods.find( (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId ); if (recipeLevelUser !== undefined) { if (recipeLevelUser.email === undefined) { + // this check if only for types purposes. throw new Error("Should never come here"); } return { diff --git a/lib/build/recipe/emailpassword/recipeImplementation.js b/lib/build/recipe/emailpassword/recipeImplementation.js index cf74baef7..bb55e005e 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -39,173 +39,82 @@ Object.defineProperty(exports, "__esModule", { value: true }); const recipe_1 = __importDefault(require("../accountlinking/recipe")); const normalisedURLPath_1 = __importDefault(require("../../normalisedURLPath")); const __1 = require("../.."); -const recipe_2 = __importDefault(require("../emailverification/recipe")); function getRecipeInterface(querier) { return { - signUp: function ({ email, password, doAccountLinking, userContext }) { + signUp: function ({ email, password, userContext }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signup"), { + // this function does not check if there is some primary user where the email + // of that primary user is unverified (isSignUpAllowed function logic) cause + // that is checked in the API layer before calling this function. + // This is the recipe function layer which can be + // called by the user manually as well if they want to. So we allow them to do that. + let response = yield this.createNewRecipeUser({ email, password, + userContext, }); - if (response.status === "OK") { - let createdNewUser = true; - if (doAccountLinking) { - let primaryUserId = yield recipe_1.default - .getInstanceOrThrowError() - .doPostSignUpAccountLinkingOperations({ - newUser: { - email, - recipeId: "emailpassword", - }, - newUserVerified: false, - recipeUserId: response.user.id, - userContext, - }); - if (response.user.id !== primaryUserId) { - createdNewUser = false; - } - response.user.id = primaryUserId; - } - return Object.assign(Object.assign({}, response), { createdNewUser }); - } else { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } - }); - }, - signIn: function ({ email, password }) { - return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signin"), { - email, - password, - }); - if (response.status === "OK") { + if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { return response; - } else { - return { - status: "WRONG_CREDENTIALS_ERROR", - }; } + let userId = yield recipe_1.default.getInstanceOrThrowError().createPrimaryUserIdOrLinkAccounts({ + // we can use index 0 cause this is a new recipe user + recipeUserId: response.user.loginMethods[0].recipeUserId, + checkAccountsToLinkTableAsWell: true, + isVerified: false, + userContext, + }); + return { + status: "OK", + user: yield __1.getUser(userId, userContext), + }; }); }, - getUserById: function ({ userId }) { + createNewRecipeUser: function (input) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { - userId, + return yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signup"), { + email: input.email, + password: input.password, }); - if (response.status === "OK") { - return Object.assign({}, response.user); - } else { - return undefined; - } }); }, - getUserByEmail: function ({ email }) { + signIn: function ({ email, password }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendGetRequest(new normalisedURLPath_1.default("/recipe/user"), { + return yield querier.sendPostRequest(new normalisedURLPath_1.default("/recipe/signin"), { email, + password, }); - if (response.status === "OK") { - return Object.assign({}, response.user); - } else { - return undefined; - } }); }, createResetPasswordToken: function ({ userId, email }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( + // the input user ID can be a recipe or a primary user ID. + return yield querier.sendPostRequest( new normalisedURLPath_1.default("/recipe/user/password/reset/token"), { userId, email, } ); - if (response.status === "OK") { - return { - status: "OK", - token: response.token, - }; - } else { - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - } }); }, - resetPasswordUsingToken: function ({ token, newPassword }) { + consumePasswordResetToken: function ({ token }) { return __awaiter(this, void 0, void 0, function* () { - let response = yield querier.sendPostRequest( - new normalisedURLPath_1.default("/recipe/user/password/reset"), + return yield querier.sendPostRequest( + new normalisedURLPath_1.default("/recipe/user/password/reset/token/consume"), { - method: "token", token, - newPassword, } ); - return response; }); }, updateEmailOrPassword: function (input) { return __awaiter(this, void 0, void 0, function* () { - let markEmailAsVerified = false; - if (input.email !== undefined) { - let userForUserId = yield __1.getUser(input.userId); - if (userForUserId !== undefined && userForUserId.isPrimaryUser) { - let usersForEmail = yield __1.listUsersByAccountInfo({ - email: input.email, - }); - if (usersForEmail !== undefined) { - let primaryUserFromEmailUsers = usersForEmail.find((u) => u.isPrimaryUser); - if (primaryUserFromEmailUsers !== undefined) { - if (primaryUserFromEmailUsers.id !== userForUserId.id) { - return { - status: "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING", - }; - } - markEmailAsVerified = true; - } - } - } - } - let response = yield querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/user"), { + // the input can be primary or recipe level user id. + return yield querier.sendPutRequest(new normalisedURLPath_1.default("/recipe/user"), { userId: input.userId, email: input.email, password: input.password, }); - if (response.status === "OK") { - if (markEmailAsVerified && input.email !== undefined) { - const emailVerificationInstance = recipe_2.default.getInstance(); - if (emailVerificationInstance) { - const tokenResponse = yield emailVerificationInstance.recipeInterfaceImpl.createEmailVerificationToken( - { - userId: input.userId, - email: input.email, - userContext: undefined, - } - ); - if (tokenResponse.status === "OK") { - yield emailVerificationInstance.recipeInterfaceImpl.verifyEmailUsingToken({ - token: tokenResponse.token, - userContext: undefined, - }); - } - } - } - return { - status: "OK", - }; - } else if (response.status === "EMAIL_ALREADY_EXISTS_ERROR") { - return { - status: "EMAIL_ALREADY_EXISTS_ERROR", - }; - } else { - return { - status: "UNKNOWN_USER_ID_ERROR", - }; - } }); }, }; diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index a5080bbbc..baa428425 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -65,23 +65,23 @@ export declare type RecipeInterface = { signUp(input: { email: string; password: string; - /** - * we now do account-linking in the recipe implementation of - * this function. If someone wants to call this function - * manually and wants the any other account with the same email - * to be linked automatically, all they need to do is pass this - * boolean. If the user doesn't want to do automatic account linking - * while calling this function, they can pass false. Default value - * of the parameter would be false. So if we are moving the account - * linking part to be part of this function, ideally we should keep - * this boolean parameter - */ - doAccountLinking: boolean; userContext: any; }): Promise< | { status: "OK"; - createdNewUser: boolean; + user: User; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >; + createNewRecipeUser(input: { + email: string; + password: string; + userContext: any; + }): Promise< + | { + status: "OK"; user: User; } | { @@ -101,18 +101,10 @@ export declare type RecipeInterface = { status: "WRONG_CREDENTIALS_ERROR"; } >; - getUserById(input: { userId: string; userContext: any }): Promise; - getUserByEmail(input: { email: string; userContext: any }): Promise; /** - * We do not make email optional here cause we want to - * allow passing in primaryUserId. If we make email optional, - * and if the user provides a primaryUserId, then it may result in two problems: - * - there is no recipeUserId = input primaryUserId, in this case, - * this function will throw an error - * - There is a recipe userId = input primaryUserId, but that recipe has no email, - * or has wrong email compared to what the user wanted to generate a reset token for. - * - * And we want to allow primaryUserId being passed in. + * We pass in the email as well to this function cause the input userId + * may not be associated with an emailpassword account. In this case, we + * need to know which email to use to create an emailpassword account later on. */ createResetPasswordToken(input: { userId: string; @@ -127,9 +119,8 @@ export declare type RecipeInterface = { status: "UNKNOWN_USER_ID_ERROR"; } >; - resetPasswordUsingToken(input: { + consumePasswordResetToken(input: { token: string; - newPassword: string; userContext: any; }): Promise< | { @@ -146,13 +137,15 @@ export declare type RecipeInterface = { email?: string; password?: string; userContext: any; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; - }>; + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + >; }; export declare type APIOptions = { recipeImplementation: RecipeInterface; @@ -211,7 +204,7 @@ export declare type APIInterface = { | { status: "OK"; email: string; - userId: string; + user: User; } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; @@ -251,7 +244,6 @@ export declare type APIInterface = { | { status: "OK"; user: User; - createdNewUser: boolean; session: SessionContainerInterface; } | { @@ -276,29 +268,14 @@ export declare type APIInterface = { }) => Promise< | { status: "OK"; - user: User; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; wereAccountsAlreadyLinked: boolean; } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; + status: "WRONG_CREDENTIALS_ERROR"; } | GeneralErrorResponse >); @@ -307,7 +284,6 @@ export declare type TypeEmailPasswordPasswordResetEmailDeliveryInput = { type: "PASSWORD_RESET"; user: { id: string; - recipeUserId: string; email: string; }; passwordResetLink: string; diff --git a/lib/ts/recipe/emailpassword/index.ts b/lib/ts/recipe/emailpassword/index.ts index 4c6026eb3..89c98a471 100644 --- a/lib/ts/recipe/emailpassword/index.ts +++ b/lib/ts/recipe/emailpassword/index.ts @@ -23,11 +23,10 @@ export default class Wrapper { static Error = SuperTokensError; - static signUp(email: string, password: string, doAccountLinking = false, userContext?: any) { + static signUp(email: string, password: string, userContext?: any) { return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.signUp({ email, password, - doAccountLinking, userContext: userContext === undefined ? {} : userContext, }); } @@ -40,20 +39,6 @@ export default class Wrapper { }); } - static getUserById(userId: string, userContext?: any) { - return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUserById({ - userId, - userContext: userContext === undefined ? {} : userContext, - }); - } - - static getUserByEmail(email: string, userContext?: any) { - return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUserByEmail({ - email, - userContext: userContext === undefined ? {} : userContext, - }); - } - /** * We do not make email optional here cause we want to * allow passing in primaryUserId. If we make email optional, @@ -73,10 +58,9 @@ export default class Wrapper { }); } - static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any) { - return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.resetPasswordUsingToken({ + static consumePasswordResetToken(token: string, userContext?: any) { + return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.consumePasswordResetToken({ token, - newPassword, userContext: userContext === undefined ? {} : userContext, }); } @@ -105,13 +89,9 @@ export let signUp = Wrapper.signUp; export let signIn = Wrapper.signIn; -export let getUserById = Wrapper.getUserById; - -export let getUserByEmail = Wrapper.getUserByEmail; - export let createResetPasswordToken = Wrapper.createResetPasswordToken; -export let resetPasswordUsingToken = Wrapper.resetPasswordUsingToken; +export let consumePasswordResetToken = Wrapper.consumePasswordResetToken; export let updateEmailOrPassword = Wrapper.updateEmailOrPassword; From 31ed54a7e4c7fb66316f0ff69dac332ea40215d9 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Sun, 7 May 2023 16:15:00 +0530 Subject: [PATCH 81/82] more fixes - ts still not compiling --- .../api/userdetails/userPasswordPut.ts | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts b/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts index 6c263a26e..c68952cc4 100644 --- a/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts +++ b/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts @@ -71,21 +71,20 @@ export const userPasswordPut = async (_: APIInterface, options: APIOptions): Pro }; } - const passwordResetToken = await EmailPassword.createResetPasswordToken(userId, email); + const updateResponse = await EmailPassword.updateEmailOrPassword({ + userId, + password: newPassword, + }); - if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { + if ( + updateResponse.status === "UNKNOWN_USER_ID_ERROR" || + updateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR" || + updateResponse.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR" + ) { // Techincally it can but its an edge case so we assume that it wont throw new Error("Should never come here"); } - - const passwordResetResponse = await EmailPassword.resetPasswordUsingToken( - passwordResetToken.token, - newPassword - ); - - if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { - throw new Error("Should never come here"); - } + // TODO: check for password policy error has well. return { status: "OK", From 2f943f4723f3f993ddb0eb01187679167b5b446a Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Sun, 7 May 2023 16:45:01 +0530 Subject: [PATCH 82/82] fixes all ts issues --- lib/build/constants.d.ts | 1 + lib/build/error.d.ts | 1 + lib/build/framework/awsLambda/framework.d.ts | 1 + lib/build/framework/awsLambda/index.d.ts | 1 + lib/build/framework/constants.d.ts | 1 + lib/build/framework/express/framework.d.ts | 1 + lib/build/framework/express/index.d.ts | 2 +- lib/build/framework/fastify/framework.d.ts | 1 + lib/build/framework/fastify/index.d.ts | 1 + lib/build/framework/hapi/framework.d.ts | 1 + lib/build/framework/hapi/index.d.ts | 1 + lib/build/framework/index.d.ts | 1 + lib/build/framework/koa/framework.d.ts | 1 + lib/build/framework/koa/index.d.ts | 2 +- lib/build/framework/loopback/framework.d.ts | 1 + lib/build/framework/loopback/index.d.ts | 1 + lib/build/framework/request.d.ts | 1 + lib/build/framework/response.d.ts | 1 + lib/build/framework/types.d.ts | 1 + lib/build/framework/utils.d.ts | 1 + lib/build/index.d.ts | 1 + .../ingredients/emaildelivery/index.d.ts | 1 + .../emaildelivery/services/smtp.d.ts | 1 + .../ingredients/emaildelivery/types.d.ts | 1 + lib/build/ingredients/smsdelivery/index.d.ts | 1 + .../smsdelivery/services/supertokens.d.ts | 1 + .../smsdelivery/services/twilio.d.ts | 1 + lib/build/ingredients/smsdelivery/types.d.ts | 1 + lib/build/logger.d.ts | 1 + lib/build/nextjs.d.ts | 1 + lib/build/normalisedURLDomain.d.ts | 1 + lib/build/normalisedURLPath.d.ts | 1 + lib/build/postSuperTokensInitCallbacks.d.ts | 1 + lib/build/processState.d.ts | 1 + lib/build/querier.d.ts | 1 + .../accountlinking/accountLinkingClaim.d.ts | 1 + lib/build/recipe/accountlinking/index.d.ts | 1 + lib/build/recipe/accountlinking/recipe.d.ts | 1 + .../accountlinking/recipeImplementation.d.ts | 1 + lib/build/recipe/accountlinking/types.d.ts | 1 + lib/build/recipe/accountlinking/utils.d.ts | 1 + .../recipe/dashboard/api/apiKeyProtector.d.ts | 1 + lib/build/recipe/dashboard/api/dashboard.d.ts | 1 + .../recipe/dashboard/api/implementation.d.ts | 1 + .../dashboard/api/userdetails/userDelete.d.ts | 1 + .../api/userdetails/userEmailVerifyGet.d.ts | 1 + .../api/userdetails/userEmailVerifyPut.d.ts | 1 + .../userdetails/userEmailVerifyTokenPost.d.ts | 1 + .../dashboard/api/userdetails/userGet.d.ts | 1 + .../api/userdetails/userMetadataGet.d.ts | 1 + .../api/userdetails/userMetadataPut.d.ts | 1 + .../api/userdetails/userPasswordPut.d.ts | 1 + .../api/userdetails/userPasswordPut.js | 74 +++++++-------- .../dashboard/api/userdetails/userPut.d.ts | 1 + .../api/userdetails/userSessionsGet.d.ts | 1 + .../api/userdetails/userSessionsPost.d.ts | 1 + .../recipe/dashboard/api/usersCountGet.d.ts | 1 + lib/build/recipe/dashboard/api/usersGet.d.ts | 1 + .../recipe/dashboard/api/validateKey.d.ts | 1 + lib/build/recipe/dashboard/constants.d.ts | 1 + lib/build/recipe/dashboard/index.d.ts | 1 + lib/build/recipe/dashboard/recipe.d.ts | 1 + .../dashboard/recipeImplementation.d.ts | 1 + lib/build/recipe/dashboard/types.d.ts | 1 + lib/build/recipe/dashboard/utils.d.ts | 1 + lib/build/recipe/dashboard/utils.js | 38 ++++---- .../recipe/emailpassword/api/emailExists.d.ts | 1 + .../api/generatePasswordResetToken.d.ts | 1 + .../emailpassword/api/implementation.d.ts | 1 + .../api/linkAccountToExistingAccount.d.ts | 1 + .../emailpassword/api/passwordReset.d.ts | 1 + .../recipe/emailpassword/api/signin.d.ts | 1 + .../recipe/emailpassword/api/signup.d.ts | 1 + lib/build/recipe/emailpassword/api/utils.d.ts | 1 + lib/build/recipe/emailpassword/constants.d.ts | 1 + .../services/backwardCompatibility/index.d.ts | 1 + .../emaildelivery/services/index.d.ts | 1 + .../emaildelivery/services/smtp/index.d.ts | 1 + .../services/smtp/passwordReset.d.ts | 1 + .../smtp/serviceImplementation/index.d.ts | 1 + lib/build/recipe/emailpassword/error.d.ts | 1 + lib/build/recipe/emailpassword/index.d.ts | 1 + .../emailpassword/passwordResetFunctions.d.ts | 1 + lib/build/recipe/emailpassword/recipe.d.ts | 1 + .../emailpassword/recipeImplementation.d.ts | 1 + lib/build/recipe/emailpassword/types.d.ts | 1 + lib/build/recipe/emailpassword/utils.d.ts | 1 + .../emailverification/api/emailVerify.d.ts | 1 + .../api/generateEmailVerifyToken.d.ts | 1 + .../emailverification/api/implementation.d.ts | 1 + .../recipe/emailverification/constants.d.ts | 1 + .../emailVerificationClaim.d.ts | 1 + .../emailVerificationFunctions.d.ts | 1 + .../services/backwardCompatibility/index.d.ts | 1 + .../emaildelivery/services/index.d.ts | 1 + .../services/smtp/emailVerify.d.ts | 1 + .../emaildelivery/services/smtp/index.d.ts | 1 + .../services/smtp/serviceImplementation.d.ts | 1 + lib/build/recipe/emailverification/error.d.ts | 1 + lib/build/recipe/emailverification/index.d.ts | 1 + .../recipe/emailverification/recipe.d.ts | 1 + .../recipeImplementation.d.ts | 1 + lib/build/recipe/emailverification/types.d.ts | 1 + lib/build/recipe/emailverification/utils.d.ts | 1 + lib/build/recipe/jwt/api/getJWKS.d.ts | 1 + lib/build/recipe/jwt/api/implementation.d.ts | 1 + lib/build/recipe/jwt/constants.d.ts | 1 + lib/build/recipe/jwt/index.d.ts | 1 + lib/build/recipe/jwt/recipe.d.ts | 1 + .../recipe/jwt/recipeImplementation.d.ts | 1 + lib/build/recipe/jwt/types.d.ts | 1 + lib/build/recipe/jwt/utils.d.ts | 1 + .../api/getOpenIdDiscoveryConfiguration.d.ts | 1 + .../recipe/openid/api/implementation.d.ts | 1 + lib/build/recipe/openid/constants.d.ts | 1 + lib/build/recipe/openid/index.d.ts | 1 + lib/build/recipe/openid/recipe.d.ts | 1 + .../recipe/openid/recipeImplementation.d.ts | 1 + lib/build/recipe/openid/types.d.ts | 1 + lib/build/recipe/openid/utils.d.ts | 1 + .../recipe/passwordless/api/consumeCode.d.ts | 1 + .../recipe/passwordless/api/createCode.d.ts | 1 + .../recipe/passwordless/api/emailExists.d.ts | 1 + .../passwordless/api/implementation.d.ts | 1 + .../passwordless/api/phoneNumberExists.d.ts | 1 + .../recipe/passwordless/api/resendCode.d.ts | 1 + lib/build/recipe/passwordless/constants.d.ts | 1 + .../services/backwardCompatibility/index.d.ts | 1 + .../emaildelivery/services/index.d.ts | 1 + .../emaildelivery/services/smtp/index.d.ts | 1 + .../services/smtp/passwordlessLogin.d.ts | 1 + .../services/smtp/serviceImplementation.d.ts | 1 + lib/build/recipe/passwordless/error.d.ts | 1 + lib/build/recipe/passwordless/index.d.ts | 1 + lib/build/recipe/passwordless/recipe.d.ts | 1 + .../passwordless/recipeImplementation.d.ts | 1 + .../services/backwardCompatibility/index.d.ts | 1 + .../smsdelivery/services/index.d.ts | 1 + .../services/supertokens/index.d.ts | 1 + .../smsdelivery/services/twilio/index.d.ts | 1 + .../services/twilio/passwordlessLogin.d.ts | 1 + .../twilio/serviceImplementation.d.ts | 1 + lib/build/recipe/passwordless/types.d.ts | 1 + lib/build/recipe/passwordless/utils.d.ts | 1 + lib/build/recipe/session/accessToken.d.ts | 1 + .../recipe/session/api/implementation.d.ts | 1 + lib/build/recipe/session/api/refresh.d.ts | 1 + lib/build/recipe/session/api/signout.d.ts | 1 + .../claimBaseClasses/booleanClaim.d.ts | 1 + .../claimBaseClasses/primitiveArrayClaim.d.ts | 1 + .../claimBaseClasses/primitiveClaim.d.ts | 1 + lib/build/recipe/session/claims.d.ts | 1 + lib/build/recipe/session/constants.d.ts | 1 + .../recipe/session/cookieAndHeaders.d.ts | 1 + lib/build/recipe/session/error.d.ts | 1 + .../recipe/session/framework/awsLambda.d.ts | 1 + .../recipe/session/framework/express.d.ts | 1 + .../recipe/session/framework/fastify.d.ts | 1 + lib/build/recipe/session/framework/hapi.d.ts | 1 + lib/build/recipe/session/framework/index.d.ts | 1 + lib/build/recipe/session/framework/koa.d.ts | 1 + .../recipe/session/framework/loopback.d.ts | 1 + lib/build/recipe/session/index.d.ts | 1 + lib/build/recipe/session/jwt.d.ts | 1 + lib/build/recipe/session/recipe.d.ts | 1 + .../recipe/session/recipeImplementation.d.ts | 1 + lib/build/recipe/session/sessionClass.d.ts | 1 + .../recipe/session/sessionFunctions.d.ts | 1 + lib/build/recipe/session/types.d.ts | 1 + lib/build/recipe/session/utils.d.ts | 1 + .../recipe/session/with-jwt/constants.d.ts | 1 + lib/build/recipe/session/with-jwt/index.d.ts | 1 + .../with-jwt/recipeImplementation.d.ts | 1 + .../recipe/session/with-jwt/sessionClass.d.ts | 1 + lib/build/recipe/session/with-jwt/utils.d.ts | 1 + .../recipe/thirdparty/api/appleRedirect.d.ts | 1 + .../thirdparty/api/authorisationUrl.d.ts | 1 + .../recipe/thirdparty/api/implementation.d.ts | 1 + lib/build/recipe/thirdparty/api/signinup.d.ts | 1 + lib/build/recipe/thirdparty/constants.d.ts | 1 + lib/build/recipe/thirdparty/error.d.ts | 1 + lib/build/recipe/thirdparty/index.d.ts | 1 + .../thirdparty/providers/activeDirectory.d.ts | 1 + .../recipe/thirdparty/providers/apple.d.ts | 1 + .../recipe/thirdparty/providers/discord.d.ts | 1 + .../recipe/thirdparty/providers/facebook.d.ts | 1 + .../recipe/thirdparty/providers/github.d.ts | 1 + .../recipe/thirdparty/providers/google.d.ts | 1 + .../providers/googleWorkspaces.d.ts | 1 + .../recipe/thirdparty/providers/index.d.ts | 1 + .../recipe/thirdparty/providers/okta.d.ts | 1 + .../recipe/thirdparty/providers/utils.d.ts | 1 + lib/build/recipe/thirdparty/recipe.d.ts | 1 + .../thirdparty/recipeImplementation.d.ts | 1 + lib/build/recipe/thirdparty/types.d.ts | 1 + lib/build/recipe/thirdparty/utils.d.ts | 1 + .../api/emailPasswordAPIImplementation.d.ts | 1 + .../api/implementation.d.ts | 1 + .../api/thirdPartyAPIImplementation.d.ts | 1 + .../services/backwardCompatibility/index.d.ts | 1 + .../emaildelivery/services/index.d.ts | 1 + .../emaildelivery/services/smtp/index.d.ts | 1 + .../recipe/thirdpartyemailpassword/error.d.ts | 1 + .../recipe/thirdpartyemailpassword/index.d.ts | 28 +++--- .../recipe/thirdpartyemailpassword/index.js | 20 +--- .../thirdpartyemailpassword/recipe.d.ts | 1 + .../emailPasswordRecipeImplementation.d.ts | 1 + .../emailPasswordRecipeImplementation.js | 28 ++---- .../recipeImplementation/index.d.ts | 1 + .../recipeImplementation/index.js | 55 ++++------- .../thirdPartyRecipeImplementation.d.ts | 1 + .../thirdPartyRecipeImplementation.js | 17 +--- .../recipe/thirdpartyemailpassword/types.d.ts | 71 ++++++-------- .../recipe/thirdpartyemailpassword/utils.d.ts | 1 + .../api/implementation.d.ts | 1 + .../api/passwordlessAPIImplementation.d.ts | 1 + .../api/thirdPartyAPIImplementation.d.ts | 1 + .../services/backwardCompatibility/index.d.ts | 1 + .../emaildelivery/services/index.d.ts | 1 + .../emaildelivery/services/smtp/index.d.ts | 1 + .../smtp/serviceImplementation/index.d.ts | 1 + .../passwordlessServiceImplementation.d.ts | 1 + .../recipe/thirdpartypasswordless/error.d.ts | 1 + .../recipe/thirdpartypasswordless/index.d.ts | 1 + .../recipe/thirdpartypasswordless/recipe.d.ts | 1 + .../recipeImplementation/index.d.ts | 1 + .../passwordlessRecipeImplementation.d.ts | 1 + .../thirdPartyRecipeImplementation.d.ts | 1 + .../services/backwardCompatibility/index.d.ts | 1 + .../smsdelivery/services/index.d.ts | 1 + .../services/supertokens/index.d.ts | 1 + .../smsdelivery/services/twilio/index.d.ts | 1 + .../recipe/thirdpartypasswordless/types.d.ts | 1 + .../recipe/thirdpartypasswordless/utils.d.ts | 1 + lib/build/recipe/usermetadata/index.d.ts | 1 + lib/build/recipe/usermetadata/recipe.d.ts | 1 + .../usermetadata/recipeImplementation.d.ts | 1 + lib/build/recipe/usermetadata/types.d.ts | 1 + lib/build/recipe/usermetadata/utils.d.ts | 1 + lib/build/recipe/userroles/index.d.ts | 1 + .../recipe/userroles/permissionClaim.d.ts | 1 + lib/build/recipe/userroles/recipe.d.ts | 1 + .../userroles/recipeImplementation.d.ts | 1 + lib/build/recipe/userroles/types.d.ts | 1 + lib/build/recipe/userroles/userRoleClaim.d.ts | 1 + lib/build/recipe/userroles/utils.d.ts | 1 + lib/build/recipeModule.d.ts | 1 + lib/build/supertokens.d.ts | 1 + lib/build/types.d.ts | 1 + lib/build/utils.d.ts | 1 + lib/build/version.d.ts | 1 + .../api/userdetails/userPasswordPut.ts | 63 +++++-------- lib/ts/recipe/dashboard/utils.ts | 45 ++++----- .../recipe/thirdpartyemailpassword/index.ts | 22 +---- .../emailPasswordRecipeImplementation.ts | 56 +++++------ .../recipeImplementation/index.ts | 94 +++++++------------ .../thirdPartyRecipeImplementation.ts | 18 +--- .../recipe/thirdpartyemailpassword/types.ts | 75 +++++---------- test/with-typescript/index.ts | 32 ++----- 259 files changed, 511 insertions(+), 470 deletions(-) diff --git a/lib/build/constants.d.ts b/lib/build/constants.d.ts index e961ba82d..112aa652a 100644 --- a/lib/build/constants.d.ts +++ b/lib/build/constants.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck export declare const HEADER_RID = "rid"; export declare const HEADER_FDI = "fdi-version"; diff --git a/lib/build/error.d.ts b/lib/build/error.d.ts index 127b873e9..41083aef0 100644 --- a/lib/build/error.d.ts +++ b/lib/build/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export default class SuperTokensError extends Error { private static errMagic; static BAD_INPUT_ERROR: "BAD_INPUT_ERROR"; diff --git a/lib/build/framework/awsLambda/framework.d.ts b/lib/build/framework/awsLambda/framework.d.ts index efd8915cd..44d3f7e39 100644 --- a/lib/build/framework/awsLambda/framework.d.ts +++ b/lib/build/framework/awsLambda/framework.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { APIGatewayProxyEventV2, APIGatewayProxyEvent, diff --git a/lib/build/framework/awsLambda/index.d.ts b/lib/build/framework/awsLambda/index.d.ts index 2cd01ebff..1028174f0 100644 --- a/lib/build/framework/awsLambda/index.d.ts +++ b/lib/build/framework/awsLambda/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export type { SessionEvent, SessionEventV2 } from "./framework"; export declare const middleware: ( handler?: import("aws-lambda").Handler | undefined diff --git a/lib/build/framework/constants.d.ts b/lib/build/framework/constants.d.ts index 831d39575..eb751247f 100644 --- a/lib/build/framework/constants.d.ts +++ b/lib/build/framework/constants.d.ts @@ -1 +1,2 @@ +// @ts-nocheck export declare const COOKIE_HEADER = "Set-Cookie"; diff --git a/lib/build/framework/express/framework.d.ts b/lib/build/framework/express/framework.d.ts index 7b1c67feb..864a3cc92 100644 --- a/lib/build/framework/express/framework.d.ts +++ b/lib/build/framework/express/framework.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { Request, Response, NextFunction } from "express"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; diff --git a/lib/build/framework/express/index.d.ts b/lib/build/framework/express/index.d.ts index d4dc8eb85..9bf873aa2 100644 --- a/lib/build/framework/express/index.d.ts +++ b/lib/build/framework/express/index.d.ts @@ -1,4 +1,4 @@ -/// +// @ts-nocheck export type { SessionRequest } from "./framework"; export declare const middleware: () => ( req: import("express").Request, diff --git a/lib/build/framework/fastify/framework.d.ts b/lib/build/framework/fastify/framework.d.ts index 7f0411283..0af7536ea 100644 --- a/lib/build/framework/fastify/framework.d.ts +++ b/lib/build/framework/fastify/framework.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { FastifyRequest as OriginalFastifyRequest, FastifyReply, FastifyPluginCallback } from "fastify"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; diff --git a/lib/build/framework/fastify/index.d.ts b/lib/build/framework/fastify/index.d.ts index fd681c6cf..3cca3a1a2 100644 --- a/lib/build/framework/fastify/index.d.ts +++ b/lib/build/framework/fastify/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck /// export type { SessionRequest } from "./framework"; export declare const plugin: import("fastify").FastifyPluginCallback, import("http").Server>; diff --git a/lib/build/framework/hapi/framework.d.ts b/lib/build/framework/hapi/framework.d.ts index cfa5a2c16..5771d86e8 100644 --- a/lib/build/framework/hapi/framework.d.ts +++ b/lib/build/framework/hapi/framework.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { Request, ResponseToolkit, Plugin, ResponseObject } from "@hapi/hapi"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; diff --git a/lib/build/framework/hapi/index.d.ts b/lib/build/framework/hapi/index.d.ts index fb09d5b15..ea293f69b 100644 --- a/lib/build/framework/hapi/index.d.ts +++ b/lib/build/framework/hapi/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export type { SessionRequest } from "./framework"; export declare const plugin: import("@hapi/hapi").Plugin<{}>; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; diff --git a/lib/build/framework/index.d.ts b/lib/build/framework/index.d.ts index cd0ab5dcd..8fd8891ce 100644 --- a/lib/build/framework/index.d.ts +++ b/lib/build/framework/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export { BaseRequest } from "./request"; export { BaseResponse } from "./response"; import * as expressFramework from "./express"; diff --git a/lib/build/framework/koa/framework.d.ts b/lib/build/framework/koa/framework.d.ts index 814a94b73..96514a08d 100644 --- a/lib/build/framework/koa/framework.d.ts +++ b/lib/build/framework/koa/framework.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { Context, Next } from "koa"; import type { HTTPMethod } from "../../types"; import { BaseRequest } from "../request"; diff --git a/lib/build/framework/koa/index.d.ts b/lib/build/framework/koa/index.d.ts index 928863a7e..1d6395964 100644 --- a/lib/build/framework/koa/index.d.ts +++ b/lib/build/framework/koa/index.d.ts @@ -1,4 +1,4 @@ -/// +// @ts-nocheck export type { SessionContext } from "./framework"; export declare const middleware: () => (ctx: import("koa").Context, next: import("koa").Next) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; diff --git a/lib/build/framework/loopback/framework.d.ts b/lib/build/framework/loopback/framework.d.ts index 51b969742..51907ee8f 100644 --- a/lib/build/framework/loopback/framework.d.ts +++ b/lib/build/framework/loopback/framework.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { MiddlewareContext, Response, Middleware } from "@loopback/rest"; import { SessionContainerInterface } from "../../recipe/session/types"; import { HTTPMethod } from "../../types"; diff --git a/lib/build/framework/loopback/index.d.ts b/lib/build/framework/loopback/index.d.ts index 89ccde4f4..4074a2fd5 100644 --- a/lib/build/framework/loopback/index.d.ts +++ b/lib/build/framework/loopback/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export type { SessionContext } from "./framework"; export declare const middleware: import("@loopback/rest").Middleware; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; diff --git a/lib/build/framework/request.d.ts b/lib/build/framework/request.d.ts index a79bc1471..17513cb35 100644 --- a/lib/build/framework/request.d.ts +++ b/lib/build/framework/request.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { HTTPMethod } from "../types"; export declare abstract class BaseRequest { wrapperUsed: boolean; diff --git a/lib/build/framework/response.d.ts b/lib/build/framework/response.d.ts index 27f79761f..8cf7a67d3 100644 --- a/lib/build/framework/response.d.ts +++ b/lib/build/framework/response.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare abstract class BaseResponse { wrapperUsed: boolean; original: any; diff --git a/lib/build/framework/types.d.ts b/lib/build/framework/types.d.ts index 392cc0142..f685b5e0a 100644 --- a/lib/build/framework/types.d.ts +++ b/lib/build/framework/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda"; import { BaseRequest, BaseResponse } from "."; export declare let SchemaFramework: { diff --git a/lib/build/framework/utils.d.ts b/lib/build/framework/utils.d.ts index 68452dff1..c9e1a80c1 100644 --- a/lib/build/framework/utils.d.ts +++ b/lib/build/framework/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck /// import type { Request, Response } from "express"; import type { IncomingMessage } from "http"; diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index eb7fc8cb9..a20f04e90 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import SuperTokens from "./supertokens"; import SuperTokensError from "./error"; import { User } from "./types"; diff --git a/lib/build/ingredients/emaildelivery/index.d.ts b/lib/build/ingredients/emaildelivery/index.d.ts index d5e16f685..bfa1e8fd9 100644 --- a/lib/build/ingredients/emaildelivery/index.d.ts +++ b/lib/build/ingredients/emaildelivery/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeInputWithService, EmailDeliveryInterface } from "./types"; export default class EmailDelivery { ingredientInterfaceImpl: EmailDeliveryInterface; diff --git a/lib/build/ingredients/emaildelivery/services/smtp.d.ts b/lib/build/ingredients/emaildelivery/services/smtp.d.ts index 865c81541..43a3c5437 100644 --- a/lib/build/ingredients/emaildelivery/services/smtp.d.ts +++ b/lib/build/ingredients/emaildelivery/services/smtp.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export interface SMTPServiceConfig { host: string; diff --git a/lib/build/ingredients/emaildelivery/types.d.ts b/lib/build/ingredients/emaildelivery/types.d.ts index 34cf181ab..494e9f4cd 100644 --- a/lib/build/ingredients/emaildelivery/types.d.ts +++ b/lib/build/ingredients/emaildelivery/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export declare type EmailDeliveryInterface = { sendEmail: ( diff --git a/lib/build/ingredients/smsdelivery/index.d.ts b/lib/build/ingredients/smsdelivery/index.d.ts index e04656804..80e9f60a6 100644 --- a/lib/build/ingredients/smsdelivery/index.d.ts +++ b/lib/build/ingredients/smsdelivery/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeInputWithService, SmsDeliveryInterface } from "./types"; export default class SmsDelivery { ingredientInterfaceImpl: SmsDeliveryInterface; diff --git a/lib/build/ingredients/smsdelivery/services/supertokens.d.ts b/lib/build/ingredients/smsdelivery/services/supertokens.d.ts index 16a0f1990..1196903bb 100644 --- a/lib/build/ingredients/smsdelivery/services/supertokens.d.ts +++ b/lib/build/ingredients/smsdelivery/services/supertokens.d.ts @@ -1 +1,2 @@ +// @ts-nocheck export declare const SUPERTOKENS_SMS_SERVICE_URL = "https://api.supertokens.com/0/services/sms"; diff --git a/lib/build/ingredients/smsdelivery/services/twilio.d.ts b/lib/build/ingredients/smsdelivery/services/twilio.d.ts index 03853fd32..d2d0dabae 100644 --- a/lib/build/ingredients/smsdelivery/services/twilio.d.ts +++ b/lib/build/ingredients/smsdelivery/services/twilio.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import { ClientOpts } from "twilio/lib/base/BaseTwilio"; /** diff --git a/lib/build/ingredients/smsdelivery/types.d.ts b/lib/build/ingredients/smsdelivery/types.d.ts index 654a42746..f45dc8f2a 100644 --- a/lib/build/ingredients/smsdelivery/types.d.ts +++ b/lib/build/ingredients/smsdelivery/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export declare type SmsDeliveryInterface = { sendSms: ( diff --git a/lib/build/logger.d.ts b/lib/build/logger.d.ts index 3edf34fdc..1a3a6aef6 100644 --- a/lib/build/logger.d.ts +++ b/lib/build/logger.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck declare function logDebugMessage(message: string): void; export { logDebugMessage }; diff --git a/lib/build/nextjs.d.ts b/lib/build/nextjs.d.ts index e04d3c068..195a81422 100644 --- a/lib/build/nextjs.d.ts +++ b/lib/build/nextjs.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export default class NextJS { static superTokensNextWrapper( middleware: (next: (middlewareError?: any) => void) => Promise, diff --git a/lib/build/normalisedURLDomain.d.ts b/lib/build/normalisedURLDomain.d.ts index a5ad011c6..b75c15d4b 100644 --- a/lib/build/normalisedURLDomain.d.ts +++ b/lib/build/normalisedURLDomain.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export default class NormalisedURLDomain { private value; constructor(url: string); diff --git a/lib/build/normalisedURLPath.d.ts b/lib/build/normalisedURLPath.d.ts index 41e4ee331..db7787bb4 100644 --- a/lib/build/normalisedURLPath.d.ts +++ b/lib/build/normalisedURLPath.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export default class NormalisedURLPath { private value; constructor(url: string); diff --git a/lib/build/postSuperTokensInitCallbacks.d.ts b/lib/build/postSuperTokensInitCallbacks.d.ts index 7a16d1e20..6eef30adb 100644 --- a/lib/build/postSuperTokensInitCallbacks.d.ts +++ b/lib/build/postSuperTokensInitCallbacks.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare class PostSuperTokensInitCallbacks { static postInitCallbacks: (() => void)[]; static addPostInitCallback(cb: () => void): void; diff --git a/lib/build/processState.d.ts b/lib/build/processState.d.ts index 1a226f8c5..aa2d9a2a8 100644 --- a/lib/build/processState.d.ts +++ b/lib/build/processState.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare enum PROCESS_STATE { CALLING_SERVICE_IN_VERIFY = 0, CALLING_SERVICE_IN_GET_HANDSHAKE_INFO = 1, diff --git a/lib/build/querier.d.ts b/lib/build/querier.d.ts index 0a211ea06..791b32e0a 100644 --- a/lib/build/querier.d.ts +++ b/lib/build/querier.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import NormalisedURLDomain from "./normalisedURLDomain"; import NormalisedURLPath from "./normalisedURLPath"; export declare class Querier { diff --git a/lib/build/recipe/accountlinking/accountLinkingClaim.d.ts b/lib/build/recipe/accountlinking/accountLinkingClaim.d.ts index 5253d4c6a..f7141ffb6 100644 --- a/lib/build/recipe/accountlinking/accountLinkingClaim.d.ts +++ b/lib/build/recipe/accountlinking/accountLinkingClaim.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { PrimitiveClaim } from "../session/claims"; /** * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. diff --git a/lib/build/recipe/accountlinking/index.d.ts b/lib/build/recipe/accountlinking/index.d.ts index f509a3701..5918abe8a 100644 --- a/lib/build/recipe/accountlinking/index.d.ts +++ b/lib/build/recipe/accountlinking/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import type { RecipeInterface } from "./types"; export default class Wrapper { diff --git a/lib/build/recipe/accountlinking/recipe.d.ts b/lib/build/recipe/accountlinking/recipe.d.ts index c1d2f7de8..91a4acd71 100644 --- a/lib/build/recipe/accountlinking/recipe.d.ts +++ b/lib/build/recipe/accountlinking/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; diff --git a/lib/build/recipe/accountlinking/recipeImplementation.d.ts b/lib/build/recipe/accountlinking/recipeImplementation.d.ts index 9b5e6e73e..7e4369ba3 100644 --- a/lib/build/recipe/accountlinking/recipeImplementation.d.ts +++ b/lib/build/recipe/accountlinking/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface, TypeNormalisedInput } from "./types"; import { Querier } from "../../querier"; export default function getRecipeImplementation(querier: Querier, config: TypeNormalisedInput): RecipeInterface; diff --git a/lib/build/recipe/accountlinking/types.d.ts b/lib/build/recipe/accountlinking/types.d.ts index 18f4c891b..a0f9f1d1f 100644 --- a/lib/build/recipe/accountlinking/types.d.ts +++ b/lib/build/recipe/accountlinking/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import type { User } from "../../types"; import { SessionContainer } from "../session"; diff --git a/lib/build/recipe/accountlinking/utils.d.ts b/lib/build/recipe/accountlinking/utils.d.ts index 2ab72230d..687c0db39 100644 --- a/lib/build/recipe/accountlinking/utils.d.ts +++ b/lib/build/recipe/accountlinking/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { NormalisedAppinfo } from "../../types"; import type { TypeInput, TypeNormalisedInput } from "./types"; export declare function validateAndNormaliseUserInput(_: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; diff --git a/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts b/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts index 81d2cd778..ccb15887b 100644 --- a/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts +++ b/lib/build/recipe/dashboard/api/apiKeyProtector.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIFunction, APIInterface, APIOptions } from "../types"; export default function apiKeyProtector( apiImplementation: APIInterface, diff --git a/lib/build/recipe/dashboard/api/dashboard.d.ts b/lib/build/recipe/dashboard/api/dashboard.d.ts index 3d609d83f..f6bd1a1bf 100644 --- a/lib/build/recipe/dashboard/api/dashboard.d.ts +++ b/lib/build/recipe/dashboard/api/dashboard.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export default function dashboard(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/dashboard/api/implementation.d.ts b/lib/build/recipe/dashboard/api/implementation.d.ts index 75c1214f2..0218549fa 100644 --- a/lib/build/recipe/dashboard/api/implementation.d.ts +++ b/lib/build/recipe/dashboard/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts b/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts index 11588ff0e..c184332e6 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userDelete.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts index d996548af..ba6da64a6 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyGet.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIFunction } from "../../types"; export declare const userEmailverifyGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts index a5df12097..055c3cb89 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyPut.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts index 5d114cb61..50b925c62 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userEmailVerifyTokenPost.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK" | "EMAIL_ALREADY_VERIFIED_ERROR"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts index 95e0ac4b8..dd04c1ee3 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userGet.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIFunction } from "../../types"; export declare const userGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts index d5f6f5c8d..f2ba7687d 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataGet.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIFunction } from "../../types"; export declare const userMetaDataGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts index 84c9ada1b..0bbbe8a65 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userMetadataPut.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts index d44974d2b..83b8371fe 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = | { diff --git a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js index 43b63e871..4159bd21c 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js +++ b/lib/build/recipe/dashboard/api/userdetails/userPasswordPut.js @@ -42,12 +42,10 @@ const recipe_1 = __importDefault(require("../../../emailpassword/recipe")); const emailpassword_1 = __importDefault(require("../../../emailpassword")); const recipe_2 = __importDefault(require("../../../thirdpartyemailpassword/recipe")); const thirdpartyemailpassword_1 = __importDefault(require("../../../thirdpartyemailpassword")); -const constants_1 = require("../../../emailpassword/constants"); const userPasswordPut = (_, options) => __awaiter(void 0, void 0, void 0, function* () { const requestBody = yield options.req.getJSONBody(); const userId = requestBody.userId; - const email = requestBody.email; const newPassword = requestBody.newPassword; if (userId === undefined || typeof userId !== "string") { throw new error_1.default({ @@ -77,54 +75,50 @@ const userPasswordPut = (_, options) => throw new Error("Should never come here"); } if (recipeToUse === "emailpassword") { - let passwordFormFields = recipe_1.default - .getInstanceOrThrowError() - .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); - let passwordValidationError = yield passwordFormFields[0].validate(newPassword); - if (passwordValidationError !== undefined) { - return { - status: "INVALID_PASSWORD_ERROR", - error: passwordValidationError, - }; - } - const passwordResetToken = yield emailpassword_1.default.createResetPasswordToken(userId, email); - if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { + const updateResponse = yield emailpassword_1.default.updateEmailOrPassword({ + userId, + password: newPassword, + }); + if ( + updateResponse.status === "UNKNOWN_USER_ID_ERROR" || + updateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR" || + updateResponse.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR" + ) { // Techincally it can but its an edge case so we assume that it wont throw new Error("Should never come here"); } - const passwordResetResponse = yield emailpassword_1.default.resetPasswordUsingToken( - passwordResetToken.token, - newPassword - ); - if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { - throw new Error("Should never come here"); - } - return { - status: "OK", - }; - } - let passwordFormFields = recipe_2.default - .getInstanceOrThrowError() - .config.signUpFeature.formFields.filter((field) => field.id === constants_1.FORM_FIELD_PASSWORD_ID); - let passwordValidationError = yield passwordFormFields[0].validate(newPassword); - if (passwordValidationError !== undefined) { - return { + // TODO: check for password policy error has well. + /** + * + * return { status: "INVALID_PASSWORD_ERROR", error: passwordValidationError, }; + */ + return { + status: "OK", + }; } - const passwordResetToken = yield thirdpartyemailpassword_1.default.createResetPasswordToken(userId, email); - if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { + const updateResponse = yield thirdpartyemailpassword_1.default.updateEmailOrPassword({ + userId, + password: newPassword, + }); + if ( + updateResponse.status === "UNKNOWN_USER_ID_ERROR" || + updateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR" || + updateResponse.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR" + ) { // Techincally it can but its an edge case so we assume that it wont throw new Error("Should never come here"); } - const passwordResetResponse = yield thirdpartyemailpassword_1.default.resetPasswordUsingToken( - passwordResetToken.token, - newPassword - ); - if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { - throw new Error("Should never come here"); - } + // TODO: check for password policy error has well. + /** + * + * return { + status: "INVALID_PASSWORD_ERROR", + error: passwordValidationError, + }; + */ return { status: "OK", }; diff --git a/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts b/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts index 1a8a475e9..ba250bb3d 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userPut.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = | { diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts index 535a23b27..34a18f080 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsGet.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIFunction } from "../../types"; export declare const userSessionsGet: APIFunction; diff --git a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts index 68aa2a281..2a5a7eeb7 100644 --- a/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts +++ b/lib/build/recipe/dashboard/api/userdetails/userSessionsPost.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../../types"; declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/usersCountGet.d.ts b/lib/build/recipe/dashboard/api/usersCountGet.d.ts index 9546bd205..9291de948 100644 --- a/lib/build/recipe/dashboard/api/usersCountGet.d.ts +++ b/lib/build/recipe/dashboard/api/usersCountGet.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export declare type Response = { status: "OK"; diff --git a/lib/build/recipe/dashboard/api/usersGet.d.ts b/lib/build/recipe/dashboard/api/usersGet.d.ts index 0f1a16c6a..788cec3eb 100644 --- a/lib/build/recipe/dashboard/api/usersGet.d.ts +++ b/lib/build/recipe/dashboard/api/usersGet.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../types"; import { RecipeLevelUser } from "../../accountlinking/types"; declare type User = { diff --git a/lib/build/recipe/dashboard/api/validateKey.d.ts b/lib/build/recipe/dashboard/api/validateKey.d.ts index 7e393f9e4..39fa8c2a0 100644 --- a/lib/build/recipe/dashboard/api/validateKey.d.ts +++ b/lib/build/recipe/dashboard/api/validateKey.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export default function validateKey(_: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/dashboard/constants.d.ts b/lib/build/recipe/dashboard/constants.d.ts index 147eeee45..5862ffc64 100644 --- a/lib/build/recipe/dashboard/constants.d.ts +++ b/lib/build/recipe/dashboard/constants.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare const DASHBOARD_API = "/dashboard"; export declare const VALIDATE_KEY_API = "/api/key/validate"; export declare const USERS_LIST_GET_API = "/api/users"; diff --git a/lib/build/recipe/dashboard/index.d.ts b/lib/build/recipe/dashboard/index.d.ts index 8a3e59113..3fc17a34f 100644 --- a/lib/build/recipe/dashboard/index.d.ts +++ b/lib/build/recipe/dashboard/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import { RecipeInterface, APIOptions, APIInterface } from "./types"; export default class Wrapper { diff --git a/lib/build/recipe/dashboard/recipe.d.ts b/lib/build/recipe/dashboard/recipe.d.ts index 8ef5265fd..6e29b8d50 100644 --- a/lib/build/recipe/dashboard/recipe.d.ts +++ b/lib/build/recipe/dashboard/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { APIHandled, HTTPMethod, NormalisedAppinfo, RecipeListFunction } from "../../types"; import { APIInterface, RecipeInterface, TypeInput, TypeNormalisedInput } from "./types"; diff --git a/lib/build/recipe/dashboard/recipeImplementation.d.ts b/lib/build/recipe/dashboard/recipeImplementation.d.ts index e18ef71f4..881866f94 100644 --- a/lib/build/recipe/dashboard/recipeImplementation.d.ts +++ b/lib/build/recipe/dashboard/recipeImplementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { RecipeInterface } from "./types"; export default function getRecipeImplementation(): RecipeInterface; diff --git a/lib/build/recipe/dashboard/types.d.ts b/lib/build/recipe/dashboard/types.d.ts index 8dc459baf..be7b06b28 100644 --- a/lib/build/recipe/dashboard/types.d.ts +++ b/lib/build/recipe/dashboard/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import { BaseRequest, BaseResponse } from "../../framework"; import { NormalisedAppinfo } from "../../types"; diff --git a/lib/build/recipe/dashboard/utils.d.ts b/lib/build/recipe/dashboard/utils.d.ts index 5431adffe..61864bada 100644 --- a/lib/build/recipe/dashboard/utils.d.ts +++ b/lib/build/recipe/dashboard/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseResponse } from "../../framework"; import NormalisedURLPath from "../../normalisedURLPath"; import { HTTPMethod, NormalisedAppinfo } from "../../types"; diff --git a/lib/build/recipe/dashboard/utils.js b/lib/build/recipe/dashboard/utils.js index 5e574f3d7..60dff2aee 100644 --- a/lib/build/recipe/dashboard/utils.js +++ b/lib/build/recipe/dashboard/utils.js @@ -62,7 +62,6 @@ const recipe_5 = __importDefault(require("../thirdpartyemailpassword/recipe")); const recipe_6 = __importDefault(require("../thirdpartypasswordless/recipe")); const thirdparty_1 = __importDefault(require("../thirdparty")); const passwordless_1 = __importDefault(require("../passwordless")); -const thirdpartyemailpassword_1 = __importDefault(require("../thirdpartyemailpassword")); const thirdpartypasswordless_1 = __importDefault(require("../thirdpartypasswordless")); function validateAndNormaliseUserInput(config) { if (config.apiKey.trim().length === 0) { @@ -179,7 +178,7 @@ function _getUserForRecipeId(userId, recipeId) { (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId ); if (loginMethod !== undefined) { - user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); + user = Object.assign({}, loginMethod); recipe = "emailpassword"; } } @@ -188,18 +187,15 @@ function _getUserForRecipeId(userId, recipeId) { } if (user === undefined) { try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = Object.assign(Object.assign({}, loginMethod), { recipeId: "emailpassword" }); - recipe = "thirdpartyemailpassword"; - } - } else { - throw new Error("Should never come here. TODO remove me"); + // we detect if this recipe has been init or not.. + recipe_5.default.getInstanceOrThrowError(); + if (globalUser !== undefined) { + let loginMethod = globalUser.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = Object.assign({}, loginMethod); + recipe = "thirdpartyemailpassword"; } } } catch (e) { @@ -218,12 +214,14 @@ function _getUserForRecipeId(userId, recipeId) { } if (user === undefined) { try { - const userResponse = yield thirdpartyemailpassword_1.default.getUserById(userId); - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - throw new Error("Should never come here. TODO remove me"); - } else { - user = Object.assign(Object.assign({}, userResponse), { recipeId: "thirdparty" }); + // we detect if this recipe has been init or not.. + recipe_5.default.getInstanceOrThrowError(); + if (globalUser !== undefined) { + let loginMethod = globalUser.loginMethods.find( + (u) => u.recipeId === "thirdparty" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = Object.assign({}, loginMethod); recipe = "thirdpartyemailpassword"; } } diff --git a/lib/build/recipe/emailpassword/api/emailExists.d.ts b/lib/build/recipe/emailpassword/api/emailExists.d.ts index e0f0ae4d8..74f301a87 100644 --- a/lib/build/recipe/emailpassword/api/emailExists.d.ts +++ b/lib/build/recipe/emailpassword/api/emailExists.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function emailExists(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts index 3e0bfbb08..866cf3c64 100644 --- a/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts +++ b/lib/build/recipe/emailpassword/api/generatePasswordResetToken.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function generatePasswordResetToken( apiImplementation: APIInterface, diff --git a/lib/build/recipe/emailpassword/api/implementation.d.ts b/lib/build/recipe/emailpassword/api/implementation.d.ts index a1619b2fd..402db9918 100644 --- a/lib/build/recipe/emailpassword/api/implementation.d.ts +++ b/lib/build/recipe/emailpassword/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts index a7439fe8c..5588e7dd1 100644 --- a/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts +++ b/lib/build/recipe/emailpassword/api/linkAccountToExistingAccount.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function linkAccountToExistingAccountAPI( apiImplementation: APIInterface, diff --git a/lib/build/recipe/emailpassword/api/passwordReset.d.ts b/lib/build/recipe/emailpassword/api/passwordReset.d.ts index b3eff0ec7..4b5e6641c 100644 --- a/lib/build/recipe/emailpassword/api/passwordReset.d.ts +++ b/lib/build/recipe/emailpassword/api/passwordReset.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function passwordReset(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/signin.d.ts b/lib/build/recipe/emailpassword/api/signin.d.ts index 73c69f7c8..6ca49c1fc 100644 --- a/lib/build/recipe/emailpassword/api/signin.d.ts +++ b/lib/build/recipe/emailpassword/api/signin.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signInAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/signup.d.ts b/lib/build/recipe/emailpassword/api/signup.d.ts index 939be43a2..bd1fa2e88 100644 --- a/lib/build/recipe/emailpassword/api/signup.d.ts +++ b/lib/build/recipe/emailpassword/api/signup.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signUpAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailpassword/api/utils.d.ts b/lib/build/recipe/emailpassword/api/utils.d.ts index 055c33ac0..5579f71cc 100644 --- a/lib/build/recipe/emailpassword/api/utils.d.ts +++ b/lib/build/recipe/emailpassword/api/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedFormField } from "../types"; export declare function validateFormFieldsOrThrowError( configFormFields: NormalisedFormField[], diff --git a/lib/build/recipe/emailpassword/constants.d.ts b/lib/build/recipe/emailpassword/constants.d.ts index 03c215a60..d0dbede02 100644 --- a/lib/build/recipe/emailpassword/constants.d.ts +++ b/lib/build/recipe/emailpassword/constants.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare const FORM_FIELD_PASSWORD_ID = "password"; export declare const FORM_FIELD_EMAIL_ID = "email"; export declare const SIGN_UP_API = "/signup"; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 866c74e34..9844769ff 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeEmailPasswordEmailDeliveryInput, RecipeInterface } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts index dd2ef062c..4de04d983 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/index.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts index 01e4dcb3f..e17ccea3d 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { TypeEmailPasswordEmailDeliveryInput } from "../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts index f551ad8f5..34240509a 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/passwordReset.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeEmailPasswordPasswordResetEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; export default function getPasswordResetEmailContent( diff --git a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts index c80e6ba57..95fdbda32 100644 --- a/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts +++ b/lib/build/recipe/emailpassword/emaildelivery/services/smtp/serviceImplementation/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeEmailPasswordEmailDeliveryInput } from "../../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; diff --git a/lib/build/recipe/emailpassword/error.d.ts b/lib/build/recipe/emailpassword/error.d.ts index e55ae7b3f..d4dc2cf9b 100644 --- a/lib/build/recipe/emailpassword/error.d.ts +++ b/lib/build/recipe/emailpassword/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; export default class SessionError extends STError { static FIELD_ERROR: "FIELD_ERROR"; diff --git a/lib/build/recipe/emailpassword/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index eb238a28f..1e8837b73 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, APIOptions, APIInterface, TypeEmailPasswordEmailDeliveryInput } from "./types"; diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index 4713b3789..008e7d923 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; export declare function createAndSendCustomEmail( appInfo: NormalisedAppinfo diff --git a/lib/build/recipe/emailpassword/recipe.d.ts b/lib/build/recipe/emailpassword/recipe.d.ts index fb78464d3..f2bd86c2c 100644 --- a/lib/build/recipe/emailpassword/recipe.d.ts +++ b/lib/build/recipe/emailpassword/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface } from "./types"; import { NormalisedAppinfo, APIHandled, HTTPMethod, RecipeListFunction } from "../../types"; diff --git a/lib/build/recipe/emailpassword/recipeImplementation.d.ts b/lib/build/recipe/emailpassword/recipeImplementation.d.ts index 8a3a26d7c..86bf78a27 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.d.ts +++ b/lib/build/recipe/emailpassword/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/emailpassword/types.d.ts b/lib/build/recipe/emailpassword/types.d.ts index baa428425..97451c8a0 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; diff --git a/lib/build/recipe/emailpassword/utils.d.ts b/lib/build/recipe/emailpassword/utils.d.ts index 3440d4251..c48cdc96d 100644 --- a/lib/build/recipe/emailpassword/utils.d.ts +++ b/lib/build/recipe/emailpassword/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput, NormalisedFormField, TypeInputFormField } from "./types"; import { NormalisedAppinfo } from "../../types"; diff --git a/lib/build/recipe/emailverification/api/emailVerify.d.ts b/lib/build/recipe/emailverification/api/emailVerify.d.ts index 3504f8e34..bd6b5b6c4 100644 --- a/lib/build/recipe/emailverification/api/emailVerify.d.ts +++ b/lib/build/recipe/emailverification/api/emailVerify.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function emailVerify(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts index fb90e6d31..0bea1d2c2 100644 --- a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts +++ b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function generateEmailVerifyToken( apiImplementation: APIInterface, diff --git a/lib/build/recipe/emailverification/api/implementation.d.ts b/lib/build/recipe/emailverification/api/implementation.d.ts index b3c21a436..dd40e7025 100644 --- a/lib/build/recipe/emailverification/api/implementation.d.ts +++ b/lib/build/recipe/emailverification/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../"; export default function getAPIInterface(): APIInterface; diff --git a/lib/build/recipe/emailverification/constants.d.ts b/lib/build/recipe/emailverification/constants.d.ts index ebc1e0937..7d50fa860 100644 --- a/lib/build/recipe/emailverification/constants.d.ts +++ b/lib/build/recipe/emailverification/constants.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck export declare const GENERATE_EMAIL_VERIFY_TOKEN_API = "/user/email/verify/token"; export declare const EMAIL_VERIFY_API = "/user/email/verify"; diff --git a/lib/build/recipe/emailverification/emailVerificationClaim.d.ts b/lib/build/recipe/emailverification/emailVerificationClaim.d.ts index 87d3bf0b7..d29302506 100644 --- a/lib/build/recipe/emailverification/emailVerificationClaim.d.ts +++ b/lib/build/recipe/emailverification/emailVerificationClaim.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BooleanClaim } from "../session/claims"; import { SessionClaimValidator } from "../session"; /** diff --git a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts index 8f13c4e0a..f09fbc85b 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; export declare function createAndSendCustomEmail( diff --git a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts index 6a608cfe0..6a681f11d 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeEmailVerificationEmailDeliveryInput, User } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts index dd2ef062c..4de04d983 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/index.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts index 521c97ea6..c28581ed2 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/emailVerify.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; export default function getEmailVerifyEmailContent(input: TypeEmailVerificationEmailDeliveryInput): GetContentResult; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts index cffcbda91..c3030da4e 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; diff --git a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts index 162505801..3f668725f 100644 --- a/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts +++ b/lib/build/recipe/emailverification/emaildelivery/services/smtp/serviceImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeEmailVerificationEmailDeliveryInput } from "../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../ingredients/emaildelivery/services/smtp"; diff --git a/lib/build/recipe/emailverification/error.d.ts b/lib/build/recipe/emailverification/error.d.ts index 2eab0a85f..486758b61 100644 --- a/lib/build/recipe/emailverification/error.d.ts +++ b/lib/build/recipe/emailverification/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; export default class SessionError extends STError { constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); diff --git a/lib/build/recipe/emailverification/index.d.ts b/lib/build/recipe/emailverification/index.d.ts index a29e6affb..9262ec6ec 100644 --- a/lib/build/recipe/emailverification/index.d.ts +++ b/lib/build/recipe/emailverification/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, APIOptions, APIInterface, User, TypeEmailVerificationEmailDeliveryInput } from "./types"; diff --git a/lib/build/recipe/emailverification/recipe.d.ts b/lib/build/recipe/emailverification/recipe.d.ts index e8eb36583..6cb431f31 100644 --- a/lib/build/recipe/emailverification/recipe.d.ts +++ b/lib/build/recipe/emailverification/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, GetEmailForUserIdFunc } from "./types"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; diff --git a/lib/build/recipe/emailverification/recipeImplementation.d.ts b/lib/build/recipe/emailverification/recipeImplementation.d.ts index d6ed6101f..6a2182ed3 100644 --- a/lib/build/recipe/emailverification/recipeImplementation.d.ts +++ b/lib/build/recipe/emailverification/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "./"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/emailverification/types.d.ts b/lib/build/recipe/emailverification/types.d.ts index afcefff4e..27bb17bd3 100644 --- a/lib/build/recipe/emailverification/types.d.ts +++ b/lib/build/recipe/emailverification/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { diff --git a/lib/build/recipe/emailverification/utils.d.ts b/lib/build/recipe/emailverification/utils.d.ts index 9f8e73229..627176f4a 100644 --- a/lib/build/recipe/emailverification/utils.d.ts +++ b/lib/build/recipe/emailverification/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; import { NormalisedAppinfo } from "../../types"; diff --git a/lib/build/recipe/jwt/api/getJWKS.d.ts b/lib/build/recipe/jwt/api/getJWKS.d.ts index ac9271746..7b983911b 100644 --- a/lib/build/recipe/jwt/api/getJWKS.d.ts +++ b/lib/build/recipe/jwt/api/getJWKS.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export default function getJWKS(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/jwt/api/implementation.d.ts b/lib/build/recipe/jwt/api/implementation.d.ts index 75c1214f2..0218549fa 100644 --- a/lib/build/recipe/jwt/api/implementation.d.ts +++ b/lib/build/recipe/jwt/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/jwt/constants.d.ts b/lib/build/recipe/jwt/constants.d.ts index 298c59b58..719f84e81 100644 --- a/lib/build/recipe/jwt/constants.d.ts +++ b/lib/build/recipe/jwt/constants.d.ts @@ -1 +1,2 @@ +// @ts-nocheck export declare const GET_JWKS_API = "/jwt/jwks.json"; diff --git a/lib/build/recipe/jwt/index.d.ts b/lib/build/recipe/jwt/index.d.ts index 7bc4880c9..274bd280b 100644 --- a/lib/build/recipe/jwt/index.d.ts +++ b/lib/build/recipe/jwt/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import { APIInterface, RecipeInterface, APIOptions, JsonWebKey } from "./types"; export default class Wrapper { diff --git a/lib/build/recipe/jwt/recipe.d.ts b/lib/build/recipe/jwt/recipe.d.ts index 4bdb2f164..59cd100e9 100644 --- a/lib/build/recipe/jwt/recipe.d.ts +++ b/lib/build/recipe/jwt/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; diff --git a/lib/build/recipe/jwt/recipeImplementation.d.ts b/lib/build/recipe/jwt/recipeImplementation.d.ts index 198e4d95f..5109fbcb1 100644 --- a/lib/build/recipe/jwt/recipeImplementation.d.ts +++ b/lib/build/recipe/jwt/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { Querier } from "../../querier"; import { NormalisedAppinfo } from "../../types"; import { RecipeInterface, TypeNormalisedInput } from "./types"; diff --git a/lib/build/recipe/jwt/types.d.ts b/lib/build/recipe/jwt/types.d.ts index 96e29ea20..fc400eff6 100644 --- a/lib/build/recipe/jwt/types.d.ts +++ b/lib/build/recipe/jwt/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { GeneralErrorResponse } from "../../types"; diff --git a/lib/build/recipe/jwt/utils.d.ts b/lib/build/recipe/jwt/utils.d.ts index e368bc539..4025b1b44 100644 --- a/lib/build/recipe/jwt/utils.d.ts +++ b/lib/build/recipe/jwt/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; diff --git a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts index 1bdb0fcdb..e1cd1cd3b 100644 --- a/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts +++ b/lib/build/recipe/openid/api/getOpenIdDiscoveryConfiguration.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../types"; export default function getOpenIdDiscoveryConfiguration( apiImplementation: APIInterface, diff --git a/lib/build/recipe/openid/api/implementation.d.ts b/lib/build/recipe/openid/api/implementation.d.ts index 75c1214f2..0218549fa 100644 --- a/lib/build/recipe/openid/api/implementation.d.ts +++ b/lib/build/recipe/openid/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/openid/constants.d.ts b/lib/build/recipe/openid/constants.d.ts index 410727137..241a857f7 100644 --- a/lib/build/recipe/openid/constants.d.ts +++ b/lib/build/recipe/openid/constants.d.ts @@ -1 +1,2 @@ +// @ts-nocheck export declare const GET_DISCOVERY_CONFIG_URL = "/.well-known/openid-configuration"; diff --git a/lib/build/recipe/openid/index.d.ts b/lib/build/recipe/openid/index.d.ts index 5eddbb0ef..c84226a59 100644 --- a/lib/build/recipe/openid/index.d.ts +++ b/lib/build/recipe/openid/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OpenIdRecipe from "./recipe"; export default class OpenIdRecipeWrapper { static init: typeof OpenIdRecipe.init; diff --git a/lib/build/recipe/openid/recipe.d.ts b/lib/build/recipe/openid/recipe.d.ts index e6431dc5e..0de7ecdc7 100644 --- a/lib/build/recipe/openid/recipe.d.ts +++ b/lib/build/recipe/openid/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; diff --git a/lib/build/recipe/openid/recipeImplementation.d.ts b/lib/build/recipe/openid/recipeImplementation.d.ts index 4136ac535..d4698099c 100644 --- a/lib/build/recipe/openid/recipeImplementation.d.ts +++ b/lib/build/recipe/openid/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface, TypeNormalisedInput } from "./types"; import { RecipeInterface as JWTRecipeInterface } from "../jwt/types"; export default function getRecipeInterface( diff --git a/lib/build/recipe/openid/types.d.ts b/lib/build/recipe/openid/types.d.ts index d3105193b..a480f4b98 100644 --- a/lib/build/recipe/openid/types.d.ts +++ b/lib/build/recipe/openid/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import { BaseRequest, BaseResponse } from "../../framework"; import NormalisedURLDomain from "../../normalisedURLDomain"; diff --git a/lib/build/recipe/openid/utils.d.ts b/lib/build/recipe/openid/utils.d.ts index 79c8d178d..6b5abd280 100644 --- a/lib/build/recipe/openid/utils.d.ts +++ b/lib/build/recipe/openid/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; export declare function validateAndNormaliseUserInput( diff --git a/lib/build/recipe/passwordless/api/consumeCode.d.ts b/lib/build/recipe/passwordless/api/consumeCode.d.ts index 9163dc48d..0f21b8d73 100644 --- a/lib/build/recipe/passwordless/api/consumeCode.d.ts +++ b/lib/build/recipe/passwordless/api/consumeCode.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function consumeCode(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/createCode.d.ts b/lib/build/recipe/passwordless/api/createCode.d.ts index 45f20a34f..d72ea96e0 100644 --- a/lib/build/recipe/passwordless/api/createCode.d.ts +++ b/lib/build/recipe/passwordless/api/createCode.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function createCode(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/emailExists.d.ts b/lib/build/recipe/passwordless/api/emailExists.d.ts index e0f0ae4d8..74f301a87 100644 --- a/lib/build/recipe/passwordless/api/emailExists.d.ts +++ b/lib/build/recipe/passwordless/api/emailExists.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function emailExists(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/implementation.d.ts b/lib/build/recipe/passwordless/api/implementation.d.ts index a1619b2fd..402db9918 100644 --- a/lib/build/recipe/passwordless/api/implementation.d.ts +++ b/lib/build/recipe/passwordless/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts b/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts index 45f1a72ff..9416f0cda 100644 --- a/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts +++ b/lib/build/recipe/passwordless/api/phoneNumberExists.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function phoneNumberExists(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/api/resendCode.d.ts b/lib/build/recipe/passwordless/api/resendCode.d.ts index 80b411dd8..ad4629bb6 100644 --- a/lib/build/recipe/passwordless/api/resendCode.d.ts +++ b/lib/build/recipe/passwordless/api/resendCode.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from ".."; export default function resendCode(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/passwordless/constants.d.ts b/lib/build/recipe/passwordless/constants.d.ts index 02bb019f4..f7438a00e 100644 --- a/lib/build/recipe/passwordless/constants.d.ts +++ b/lib/build/recipe/passwordless/constants.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare const CREATE_CODE_API = "/signinup/code"; export declare const RESEND_CODE_API = "/signinup/code/resend"; export declare const CONSUME_CODE_API = "/signinup/code/consume"; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts index 76bfdb50f..2f0015dda 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts index dd2ef062c..4de04d983 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/index.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts index 726501ec8..3cda03b71 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { TypePasswordlessEmailDeliveryInput } from "../../../types"; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts index 4007a0589..e3ae65d56 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/passwordlessLogin.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/emaildelivery/services/smtp"; export default function getPasswordlessLoginEmailContent(input: TypePasswordlessEmailDeliveryInput): GetContentResult; diff --git a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts index dc22e6060..7a58ac4e4 100644 --- a/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts +++ b/lib/build/recipe/passwordless/emaildelivery/services/smtp/serviceImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypePasswordlessEmailDeliveryInput } from "../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../ingredients/emaildelivery/services/smtp"; diff --git a/lib/build/recipe/passwordless/error.d.ts b/lib/build/recipe/passwordless/error.d.ts index 2eab0a85f..486758b61 100644 --- a/lib/build/recipe/passwordless/error.d.ts +++ b/lib/build/recipe/passwordless/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; export default class SessionError extends STError { constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); diff --git a/lib/build/recipe/passwordless/index.d.ts b/lib/build/recipe/passwordless/index.d.ts index 01affcbe9..080d1a770 100644 --- a/lib/build/recipe/passwordless/index.d.ts +++ b/lib/build/recipe/passwordless/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { diff --git a/lib/build/recipe/passwordless/recipe.d.ts b/lib/build/recipe/passwordless/recipe.d.ts index ce7fedcb1..42b76df0a 100644 --- a/lib/build/recipe/passwordless/recipe.d.ts +++ b/lib/build/recipe/passwordless/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface } from "./types"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; diff --git a/lib/build/recipe/passwordless/recipeImplementation.d.ts b/lib/build/recipe/passwordless/recipeImplementation.d.ts index 8a3a26d7c..86bf78a27 100644 --- a/lib/build/recipe/passwordless/recipeImplementation.d.ts +++ b/lib/build/recipe/passwordless/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts index df93bfd39..d1477c878 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/backwardCompatibility/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypePasswordlessSmsDeliveryInput } from "../../../types"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts index 4e73dbb4d..f14aacf83 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Twilio from "./twilio"; import Supertokens from "./supertokens"; export declare let TwilioService: typeof Twilio; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts index 0326d42c0..501ecbce0 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/supertokens/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypePasswordlessSmsDeliveryInput } from "../../../types"; export default class SupertokensService implements SmsDeliveryInterface { diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts index 00262c904..ef7c09e1d 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/smsdelivery/services/twilio"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypePasswordlessSmsDeliveryInput } from "../../../types"; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts index a39956f9d..16af07d5e 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/passwordlessLogin.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypePasswordlessSmsDeliveryInput } from "../../../types"; import { GetContentResult } from "../../../../../ingredients/smsdelivery/services/twilio"; export default function getPasswordlessLoginSmsContent(input: TypePasswordlessSmsDeliveryInput): GetContentResult; diff --git a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts index 70b3c34d3..6aa22d4d2 100644 --- a/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts +++ b/lib/build/recipe/passwordless/smsdelivery/services/twilio/serviceImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypePasswordlessSmsDeliveryInput } from "../../../types"; import Twilio from "twilio/lib/rest/Twilio"; import { ServiceInterface } from "../../../../../ingredients/smsdelivery/services/twilio"; diff --git a/lib/build/recipe/passwordless/types.d.ts b/lib/build/recipe/passwordless/types.d.ts index e478f625c..4139dbc6d 100644 --- a/lib/build/recipe/passwordless/types.d.ts +++ b/lib/build/recipe/passwordless/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; diff --git a/lib/build/recipe/passwordless/utils.d.ts b/lib/build/recipe/passwordless/utils.d.ts index 9a19050d3..f00fc5184 100644 --- a/lib/build/recipe/passwordless/utils.d.ts +++ b/lib/build/recipe/passwordless/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; import { NormalisedAppinfo } from "../../types"; diff --git a/lib/build/recipe/session/accessToken.d.ts b/lib/build/recipe/session/accessToken.d.ts index 236137ec2..c7a0b9757 100644 --- a/lib/build/recipe/session/accessToken.d.ts +++ b/lib/build/recipe/session/accessToken.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ParsedJWTInfo } from "./jwt"; export declare function getInfoFromAccessToken( jwtInfo: ParsedJWTInfo, diff --git a/lib/build/recipe/session/api/implementation.d.ts b/lib/build/recipe/session/api/implementation.d.ts index b3c21a436..dd40e7025 100644 --- a/lib/build/recipe/session/api/implementation.d.ts +++ b/lib/build/recipe/session/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../"; export default function getAPIInterface(): APIInterface; diff --git a/lib/build/recipe/session/api/refresh.d.ts b/lib/build/recipe/session/api/refresh.d.ts index a24161ed0..6b4746e67 100644 --- a/lib/build/recipe/session/api/refresh.d.ts +++ b/lib/build/recipe/session/api/refresh.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function handleRefreshAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/session/api/signout.d.ts b/lib/build/recipe/session/api/signout.d.ts index 93bd2141e..0e1d985d3 100644 --- a/lib/build/recipe/session/api/signout.d.ts +++ b/lib/build/recipe/session/api/signout.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signOutAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts index f5085c633..ba5736f3f 100644 --- a/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/booleanClaim.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { SessionClaim, SessionClaimValidator } from "../types"; import { PrimitiveClaim } from "./primitiveClaim"; export declare class BooleanClaim extends PrimitiveClaim { diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts index 5c70b4785..9593151f1 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/primitiveArrayClaim.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { JSONPrimitive } from "../../../types"; import { SessionClaim, SessionClaimValidator } from "../types"; export declare class PrimitiveArrayClaim extends SessionClaim { diff --git a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts index ff14b35ca..dbc3f5355 100644 --- a/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts +++ b/lib/build/recipe/session/claimBaseClasses/primitiveClaim.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { JSONPrimitive } from "../../../types"; import { SessionClaim, SessionClaimValidator } from "../types"; export declare class PrimitiveClaim extends SessionClaim { diff --git a/lib/build/recipe/session/claims.d.ts b/lib/build/recipe/session/claims.d.ts index 03561b33f..ae6b132bd 100644 --- a/lib/build/recipe/session/claims.d.ts +++ b/lib/build/recipe/session/claims.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export { SessionClaim } from "./types"; export { PrimitiveClaim } from "./claimBaseClasses/primitiveClaim"; export { PrimitiveArrayClaim } from "./claimBaseClasses/primitiveArrayClaim"; diff --git a/lib/build/recipe/session/constants.d.ts b/lib/build/recipe/session/constants.d.ts index 51bf0ed63..4f1b5bd68 100644 --- a/lib/build/recipe/session/constants.d.ts +++ b/lib/build/recipe/session/constants.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TokenTransferMethod } from "./types"; export declare const REFRESH_API_PATH = "/session/refresh"; export declare const SIGNOUT_API_PATH = "/signout"; diff --git a/lib/build/recipe/session/cookieAndHeaders.d.ts b/lib/build/recipe/session/cookieAndHeaders.d.ts index 80d115180..40cd2f2bf 100644 --- a/lib/build/recipe/session/cookieAndHeaders.d.ts +++ b/lib/build/recipe/session/cookieAndHeaders.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import { TokenTransferMethod, TokenType, TypeNormalisedInput } from "./types"; export declare function clearSessionFromAllTokenTransferMethods(config: TypeNormalisedInput, res: BaseResponse): void; diff --git a/lib/build/recipe/session/error.d.ts b/lib/build/recipe/session/error.d.ts index 8daee8eab..e53df19f6 100644 --- a/lib/build/recipe/session/error.d.ts +++ b/lib/build/recipe/session/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; import { ClaimValidationError } from "./types"; export default class SessionError extends STError { diff --git a/lib/build/recipe/session/framework/awsLambda.d.ts b/lib/build/recipe/session/framework/awsLambda.d.ts index 90ed03730..2b5f88975 100644 --- a/lib/build/recipe/session/framework/awsLambda.d.ts +++ b/lib/build/recipe/session/framework/awsLambda.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { Handler } from "aws-lambda"; import { VerifySessionOptions } from ".."; export declare function verifySession(handler: Handler, verifySessionOptions?: VerifySessionOptions): Handler; diff --git a/lib/build/recipe/session/framework/express.d.ts b/lib/build/recipe/session/framework/express.d.ts index b8623860f..bcb0bf234 100644 --- a/lib/build/recipe/session/framework/express.d.ts +++ b/lib/build/recipe/session/framework/express.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { VerifySessionOptions } from ".."; import type { SessionRequest } from "../../../framework/express/framework"; import type { NextFunction, Response } from "express"; diff --git a/lib/build/recipe/session/framework/fastify.d.ts b/lib/build/recipe/session/framework/fastify.d.ts index be858806b..a097f307a 100644 --- a/lib/build/recipe/session/framework/fastify.d.ts +++ b/lib/build/recipe/session/framework/fastify.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { VerifySessionOptions } from ".."; import { SessionRequest } from "../../../framework/fastify/framework"; import { FastifyReply } from "fastify"; diff --git a/lib/build/recipe/session/framework/hapi.d.ts b/lib/build/recipe/session/framework/hapi.d.ts index 8f00dad02..0181a9012 100644 --- a/lib/build/recipe/session/framework/hapi.d.ts +++ b/lib/build/recipe/session/framework/hapi.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { VerifySessionOptions } from ".."; import { ResponseToolkit } from "@hapi/hapi"; import { SessionRequest } from "../../../framework/hapi/framework"; diff --git a/lib/build/recipe/session/framework/index.d.ts b/lib/build/recipe/session/framework/index.d.ts index b71f31cb4..dfba9d1f7 100644 --- a/lib/build/recipe/session/framework/index.d.ts +++ b/lib/build/recipe/session/framework/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import * as expressFramework from "./express"; import * as fastifyFramework from "./fastify"; import * as hapiFramework from "./hapi"; diff --git a/lib/build/recipe/session/framework/koa.d.ts b/lib/build/recipe/session/framework/koa.d.ts index e961a524b..9e23ae80b 100644 --- a/lib/build/recipe/session/framework/koa.d.ts +++ b/lib/build/recipe/session/framework/koa.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { VerifySessionOptions } from ".."; import type { Next } from "koa"; import type { SessionContext } from "../../../framework/koa/framework"; diff --git a/lib/build/recipe/session/framework/loopback.d.ts b/lib/build/recipe/session/framework/loopback.d.ts index 32a45a77f..ee251753d 100644 --- a/lib/build/recipe/session/framework/loopback.d.ts +++ b/lib/build/recipe/session/framework/loopback.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { VerifySessionOptions } from ".."; import { InterceptorOrKey } from "@loopback/core"; export declare function verifySession(options?: VerifySessionOptions): InterceptorOrKey; diff --git a/lib/build/recipe/session/index.d.ts b/lib/build/recipe/session/index.d.ts index 4705fd7c3..11885a9a2 100644 --- a/lib/build/recipe/session/index.d.ts +++ b/lib/build/recipe/session/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import SuperTokensError from "./error"; import { VerifySessionOptions, diff --git a/lib/build/recipe/session/jwt.d.ts b/lib/build/recipe/session/jwt.d.ts index e4ab56b66..4dda635b3 100644 --- a/lib/build/recipe/session/jwt.d.ts +++ b/lib/build/recipe/session/jwt.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare type ParsedJWTInfo = { rawTokenString: string; rawPayload: string; diff --git a/lib/build/recipe/session/recipe.d.ts b/lib/build/recipe/session/recipe.d.ts index bc06fe050..a7d920c95 100644 --- a/lib/build/recipe/session/recipe.d.ts +++ b/lib/build/recipe/session/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, diff --git a/lib/build/recipe/session/recipeImplementation.d.ts b/lib/build/recipe/session/recipeImplementation.d.ts index e15f04fd6..bbca23737 100644 --- a/lib/build/recipe/session/recipeImplementation.d.ts +++ b/lib/build/recipe/session/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface, TypeNormalisedInput, KeyInfo, AntiCsrfType } from "./types"; import { Querier } from "../../querier"; import { NormalisedAppinfo } from "../../types"; diff --git a/lib/build/recipe/session/sessionClass.d.ts b/lib/build/recipe/session/sessionClass.d.ts index cf93574b3..65b95bab5 100644 --- a/lib/build/recipe/session/sessionClass.d.ts +++ b/lib/build/recipe/session/sessionClass.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import { SessionClaim, SessionClaimValidator, SessionContainerInterface, TokenTransferMethod } from "./types"; import { Helpers } from "./recipeImplementation"; diff --git a/lib/build/recipe/session/sessionFunctions.d.ts b/lib/build/recipe/session/sessionFunctions.d.ts index fef7d65bf..70264f63e 100644 --- a/lib/build/recipe/session/sessionFunctions.d.ts +++ b/lib/build/recipe/session/sessionFunctions.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ParsedJWTInfo } from "./jwt"; import { CreateOrRefreshAPIResponse, SessionInformation, TokenTransferMethod } from "./types"; import { Helpers } from "./recipeImplementation"; diff --git a/lib/build/recipe/session/types.d.ts b/lib/build/recipe/session/types.d.ts index 618ff280b..030737476 100644 --- a/lib/build/recipe/session/types.d.ts +++ b/lib/build/recipe/session/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import NormalisedURLPath from "../../normalisedURLPath"; import { RecipeInterface as JWTRecipeInterface, APIInterface as JWTAPIInterface } from "../jwt/types"; diff --git a/lib/build/recipe/session/utils.d.ts b/lib/build/recipe/session/utils.d.ts index 0ede4269f..e5694ce6d 100644 --- a/lib/build/recipe/session/utils.d.ts +++ b/lib/build/recipe/session/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { CreateOrRefreshAPIResponse, TypeInput, diff --git a/lib/build/recipe/session/with-jwt/constants.d.ts b/lib/build/recipe/session/with-jwt/constants.d.ts index 5260dd27a..324030f7b 100644 --- a/lib/build/recipe/session/with-jwt/constants.d.ts +++ b/lib/build/recipe/session/with-jwt/constants.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck export declare const ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY = "_jwtPName"; export declare const JWT_RESERVED_KEY_USE_ERROR_MESSAGE: string; diff --git a/lib/build/recipe/session/with-jwt/index.d.ts b/lib/build/recipe/session/with-jwt/index.d.ts index 3e972865f..f8ccc90af 100644 --- a/lib/build/recipe/session/with-jwt/index.d.ts +++ b/lib/build/recipe/session/with-jwt/index.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import OriginalImplementation from "./recipeImplementation"; export default OriginalImplementation; diff --git a/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts b/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts index d089224ea..debe5ce4b 100644 --- a/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts +++ b/lib/build/recipe/session/with-jwt/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "../"; import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; import { TypeNormalisedInput } from "../types"; diff --git a/lib/build/recipe/session/with-jwt/sessionClass.d.ts b/lib/build/recipe/session/with-jwt/sessionClass.d.ts index d7f4984fc..a354342c4 100644 --- a/lib/build/recipe/session/with-jwt/sessionClass.d.ts +++ b/lib/build/recipe/session/with-jwt/sessionClass.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; import { SessionClaim, SessionClaimValidator, SessionContainerInterface } from "../types"; export default class SessionClassWithJWT implements SessionContainerInterface { diff --git a/lib/build/recipe/session/with-jwt/utils.d.ts b/lib/build/recipe/session/with-jwt/utils.d.ts index 7d716db8d..3a4b54185 100644 --- a/lib/build/recipe/session/with-jwt/utils.d.ts +++ b/lib/build/recipe/session/with-jwt/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface as OpenIdRecipeInterface } from "../../openid/types"; export declare function addJWTToAccessTokenPayload({ accessTokenPayload, diff --git a/lib/build/recipe/thirdparty/api/appleRedirect.d.ts b/lib/build/recipe/thirdparty/api/appleRedirect.d.ts index 177615549..df930a9a1 100644 --- a/lib/build/recipe/thirdparty/api/appleRedirect.d.ts +++ b/lib/build/recipe/thirdparty/api/appleRedirect.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function appleRedirectHandler(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts b/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts index 068abfe81..5603eb9c1 100644 --- a/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts +++ b/lib/build/recipe/thirdparty/api/authorisationUrl.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function authorisationUrlAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/thirdparty/api/implementation.d.ts b/lib/build/recipe/thirdparty/api/implementation.d.ts index d88ce94d8..a594ecb37 100644 --- a/lib/build/recipe/thirdparty/api/implementation.d.ts +++ b/lib/build/recipe/thirdparty/api/implementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface } from "../"; export default function getAPIInterface(): APIInterface; export declare function getActualClientIdFromDevelopmentClientId(client_id: string): string; diff --git a/lib/build/recipe/thirdparty/api/signinup.d.ts b/lib/build/recipe/thirdparty/api/signinup.d.ts index 93a9bd803..b8fc4501c 100644 --- a/lib/build/recipe/thirdparty/api/signinup.d.ts +++ b/lib/build/recipe/thirdparty/api/signinup.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface, APIOptions } from "../"; export default function signInUpAPI(apiImplementation: APIInterface, options: APIOptions): Promise; diff --git a/lib/build/recipe/thirdparty/constants.d.ts b/lib/build/recipe/thirdparty/constants.d.ts index 809ae0592..e2235e1bf 100644 --- a/lib/build/recipe/thirdparty/constants.d.ts +++ b/lib/build/recipe/thirdparty/constants.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare const AUTHORISATION_API = "/authorisationurl"; export declare const SIGN_IN_UP_API = "/signinup"; export declare const APPLE_REDIRECT_HANDLER = "/callback/apple"; diff --git a/lib/build/recipe/thirdparty/error.d.ts b/lib/build/recipe/thirdparty/error.d.ts index 248cddbeb..cc9e34552 100644 --- a/lib/build/recipe/thirdparty/error.d.ts +++ b/lib/build/recipe/thirdparty/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; export default class ThirdPartyError extends STError { constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); diff --git a/lib/build/recipe/thirdparty/index.d.ts b/lib/build/recipe/thirdparty/index.d.ts index f1dbcf15b..3d49463a7 100644 --- a/lib/build/recipe/thirdparty/index.d.ts +++ b/lib/build/recipe/thirdparty/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIInterface, APIOptions, TypeProvider } from "./types"; diff --git a/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts b/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts index e69de29bb..f6617924f 100644 --- a/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts +++ b/lib/build/recipe/thirdparty/providers/activeDirectory.d.ts @@ -0,0 +1 @@ +// @ts-nocheck diff --git a/lib/build/recipe/thirdparty/providers/apple.d.ts b/lib/build/recipe/thirdparty/providers/apple.d.ts index 897f6e5f7..5370e2111 100644 --- a/lib/build/recipe/thirdparty/providers/apple.d.ts +++ b/lib/build/recipe/thirdparty/providers/apple.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderAppleConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/discord.d.ts b/lib/build/recipe/thirdparty/providers/discord.d.ts index 2f39d56aa..926e9d737 100644 --- a/lib/build/recipe/thirdparty/providers/discord.d.ts +++ b/lib/build/recipe/thirdparty/providers/discord.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderDiscordConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/facebook.d.ts b/lib/build/recipe/thirdparty/providers/facebook.d.ts index 02d3c5d91..71b678eee 100644 --- a/lib/build/recipe/thirdparty/providers/facebook.d.ts +++ b/lib/build/recipe/thirdparty/providers/facebook.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderFacebookConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/github.d.ts b/lib/build/recipe/thirdparty/providers/github.d.ts index 17d76dc22..105f3adae 100644 --- a/lib/build/recipe/thirdparty/providers/github.d.ts +++ b/lib/build/recipe/thirdparty/providers/github.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderGithubConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/google.d.ts b/lib/build/recipe/thirdparty/providers/google.d.ts index f3e23cada..4baaaccce 100644 --- a/lib/build/recipe/thirdparty/providers/google.d.ts +++ b/lib/build/recipe/thirdparty/providers/google.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderGoogleConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts b/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts index fbd94579e..cf313c6ac 100644 --- a/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts +++ b/lib/build/recipe/thirdparty/providers/googleWorkspaces.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeProvider } from "../types"; declare type TypeThirdPartyProviderGoogleWorkspacesConfig = { clientId: string; diff --git a/lib/build/recipe/thirdparty/providers/index.d.ts b/lib/build/recipe/thirdparty/providers/index.d.ts index 0c0096be4..f1c5f5501 100644 --- a/lib/build/recipe/thirdparty/providers/index.d.ts +++ b/lib/build/recipe/thirdparty/providers/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import ProviderGoogle from "./google"; import ProviderFacebook from "./facebook"; import ProviderGithub from "./github"; diff --git a/lib/build/recipe/thirdparty/providers/okta.d.ts b/lib/build/recipe/thirdparty/providers/okta.d.ts index e69de29bb..f6617924f 100644 --- a/lib/build/recipe/thirdparty/providers/okta.d.ts +++ b/lib/build/recipe/thirdparty/providers/okta.d.ts @@ -0,0 +1 @@ +// @ts-nocheck diff --git a/lib/build/recipe/thirdparty/providers/utils.d.ts b/lib/build/recipe/thirdparty/providers/utils.d.ts index 7edad22c7..c3d294df8 100644 --- a/lib/build/recipe/thirdparty/providers/utils.d.ts +++ b/lib/build/recipe/thirdparty/providers/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { VerifyOptions } from "jsonwebtoken"; export declare function verifyIdTokenFromJWKSEndpoint( idToken: string, diff --git a/lib/build/recipe/thirdparty/recipe.d.ts b/lib/build/recipe/thirdparty/recipe.d.ts index e7f99ff8d..4c4f5dae3 100644 --- a/lib/build/recipe/thirdparty/recipe.d.ts +++ b/lib/build/recipe/thirdparty/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import { TypeInput, TypeNormalisedInput, TypeProvider, RecipeInterface, APIInterface } from "./types"; diff --git a/lib/build/recipe/thirdparty/recipeImplementation.d.ts b/lib/build/recipe/thirdparty/recipeImplementation.d.ts index 8db107c07..7d1180bfb 100644 --- a/lib/build/recipe/thirdparty/recipeImplementation.d.ts +++ b/lib/build/recipe/thirdparty/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeImplementation(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/thirdparty/types.d.ts b/lib/build/recipe/thirdparty/types.d.ts index b0b9b6f6b..bfc868c37 100644 --- a/lib/build/recipe/thirdparty/types.d.ts +++ b/lib/build/recipe/thirdparty/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import { NormalisedAppinfo } from "../../types"; import OverrideableBuilder from "supertokens-js-override"; diff --git a/lib/build/recipe/thirdparty/utils.d.ts b/lib/build/recipe/thirdparty/utils.d.ts index c83bcea11..2c878466d 100644 --- a/lib/build/recipe/thirdparty/utils.d.ts +++ b/lib/build/recipe/thirdparty/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeProvider } from "./types"; import { TypeInput, TypeNormalisedInput } from "./types"; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts index 3a64abf0d..74122e450 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface } from "../../emailpassword"; import { APIInterface as ThirdPartyEmailPasswordAPIInterface } from "../"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyEmailPasswordAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts index a1619b2fd..402db9918 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts index 7143eeaef..b0827c889 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface } from "../../thirdparty"; import { APIInterface as ThirdPartyEmailPasswordAPIInterface } from "../"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyEmailPasswordAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts index 68787c2e0..e3b6e87a8 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeThirdPartyEmailPasswordEmailDeliveryInput } from "../../../types"; import { RecipeInterface as EmailPasswordRecipeInterface } from "../../../../emailpassword"; import { NormalisedAppinfo } from "../../../../../types"; diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts index dd2ef062c..4de04d983 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/index.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts index 03dc8c577..debae94a2 100644 --- a/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/emaildelivery/services/smtp/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; import { TypeThirdPartyEmailPasswordEmailDeliveryInput } from "../../../types"; diff --git a/lib/build/recipe/thirdpartyemailpassword/error.d.ts b/lib/build/recipe/thirdpartyemailpassword/error.d.ts index 56d432191..1d9c33665 100644 --- a/lib/build/recipe/thirdpartyemailpassword/error.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; export default class ThirdPartyEmailPasswordError extends STError { constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); diff --git a/lib/build/recipe/thirdpartyemailpassword/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index cc1b4cf71..c9c985e29 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIInterface, EmailPasswordAPIOptions, ThirdPartyAPIOptions } from "./types"; @@ -24,12 +25,10 @@ export default class Wrapper { static emailPasswordSignUp( email: string, password: string, - doAccountLinking?: boolean, userContext?: any ): Promise< | { status: "OK"; - createdNewUser: boolean; user: import("../emailpassword").User; } | { @@ -49,8 +48,6 @@ export default class Wrapper { status: "WRONG_CREDENTIALS_ERROR"; } >; - static getUserById(userId: string, userContext?: any): Promise; - static getUsersByEmail(email: string, userContext?: any): Promise<(import("../emailpassword").User | User)[]>; static createResetPasswordToken( userId: string, email: string, @@ -64,9 +61,8 @@ export default class Wrapper { status: "UNKNOWN_USER_ID_ERROR"; } >; - static resetPasswordUsingToken( + static consumePasswordResetToken( token: string, - newPassword: string, userContext?: any ): Promise< | { @@ -83,13 +79,15 @@ export default class Wrapper { email?: string; password?: string; userContext?: any; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; - }>; + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + >; static Google: typeof import("../thirdparty/providers/google").default; static Github: typeof import("../thirdparty/providers/github").default; static Facebook: typeof import("../thirdparty/providers/facebook").default; @@ -107,11 +105,9 @@ export declare let Error: typeof SuperTokensError; export declare let emailPasswordSignUp: typeof Wrapper.emailPasswordSignUp; export declare let emailPasswordSignIn: typeof Wrapper.emailPasswordSignIn; export declare let thirdPartySignInUp: typeof Wrapper.thirdPartySignInUp; -export declare let getUserById: typeof Wrapper.getUserById; export declare let getUserByThirdPartyInfo: typeof Wrapper.getUserByThirdPartyInfo; -export declare let getUsersByEmail: typeof Wrapper.getUsersByEmail; export declare let createResetPasswordToken: typeof Wrapper.createResetPasswordToken; -export declare let resetPasswordUsingToken: typeof Wrapper.resetPasswordUsingToken; +export declare let consumePasswordResetToken: typeof Wrapper.consumePasswordResetToken; export declare let updateEmailOrPassword: typeof Wrapper.updateEmailOrPassword; export declare let Google: typeof import("../thirdparty/providers/google").default; export declare let Github: typeof import("../thirdparty/providers/github").default; diff --git a/lib/build/recipe/thirdpartyemailpassword/index.js b/lib/build/recipe/thirdpartyemailpassword/index.js index 281cbddf9..14d2fbb09 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/index.js @@ -86,7 +86,7 @@ var __importDefault = return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.sendEmail = exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.updateEmailOrPassword = exports.resetPasswordUsingToken = exports.createResetPasswordToken = exports.getUsersByEmail = exports.getUserByThirdPartyInfo = exports.getUserById = exports.thirdPartySignInUp = exports.emailPasswordSignIn = exports.emailPasswordSignUp = exports.Error = exports.init = void 0; +exports.sendEmail = exports.GoogleWorkspaces = exports.Discord = exports.Apple = exports.Facebook = exports.Github = exports.Google = exports.updateEmailOrPassword = exports.consumePasswordResetToken = exports.createResetPasswordToken = exports.getUserByThirdPartyInfo = exports.thirdPartySignInUp = exports.emailPasswordSignIn = exports.emailPasswordSignUp = exports.Error = exports.init = void 0; const recipe_1 = __importDefault(require("./recipe")); const error_1 = __importDefault(require("./error")); const thirdPartyProviders = __importStar(require("../thirdparty/providers")); @@ -106,11 +106,10 @@ class Wrapper { userContext, }); } - static emailPasswordSignUp(email, password, doAccountLinking = false, userContext = {}) { + static emailPasswordSignUp(email, password, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.emailPasswordSignUp({ email, password, - doAccountLinking, userContext, }); } @@ -121,12 +120,6 @@ class Wrapper { userContext, }); } - static getUserById(userId, userContext = {}) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUserById({ userId, userContext }); - } - static getUsersByEmail(email, userContext = {}) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsersByEmail({ email, userContext }); - } static createResetPasswordToken(userId, email, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createResetPasswordToken({ userId, @@ -134,10 +127,9 @@ class Wrapper { userContext, }); } - static resetPasswordUsingToken(token, newPassword, userContext = {}) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.resetPasswordUsingToken({ + static consumePasswordResetToken(token, userContext = {}) { + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.consumePasswordResetToken({ token, - newPassword, userContext, }); } @@ -170,11 +162,9 @@ exports.Error = Wrapper.Error; exports.emailPasswordSignUp = Wrapper.emailPasswordSignUp; exports.emailPasswordSignIn = Wrapper.emailPasswordSignIn; exports.thirdPartySignInUp = Wrapper.thirdPartySignInUp; -exports.getUserById = Wrapper.getUserById; exports.getUserByThirdPartyInfo = Wrapper.getUserByThirdPartyInfo; -exports.getUsersByEmail = Wrapper.getUsersByEmail; exports.createResetPasswordToken = Wrapper.createResetPasswordToken; -exports.resetPasswordUsingToken = Wrapper.resetPasswordUsingToken; +exports.consumePasswordResetToken = Wrapper.consumePasswordResetToken; exports.updateEmailOrPassword = Wrapper.updateEmailOrPassword; exports.Google = Wrapper.Google; exports.Github = Wrapper.Github; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts index 0d27e198f..36494b074 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import EmailPasswordRecipe from "../emailpassword/recipe"; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts index 919de07f8..26119b84e 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "../../emailpassword/types"; import { RecipeInterface as ThirdPartyEmailPasswordRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPasswordRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js index 8d8772bdd..cbbd113c3 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.js @@ -43,35 +43,19 @@ function getRecipeInterface(recipeInterface) { return recipeInterface.emailPasswordSignIn(input); }); }, - getUserById: function (input) { - return __awaiter(this, void 0, void 0, function* () { - let user = yield recipeInterface.getUserById(input); - if (user === undefined || user.thirdParty !== undefined) { - // either user is undefined or it's a thirdparty user. - return undefined; - } - return user; - }); - }, - getUserByEmail: function (input) { + createResetPasswordToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - let result = yield recipeInterface.getUsersByEmail(input); - for (let i = 0; i < result.length; i++) { - if (result[i].thirdParty === undefined) { - return result[i]; - } - } - return undefined; + return recipeInterface.createResetPasswordToken(input); }); }, - createResetPasswordToken: function (input) { + consumePasswordResetToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - return recipeInterface.createResetPasswordToken(input); + return recipeInterface.consumePasswordResetToken(input); }); }, - resetPasswordUsingToken: function (input) { + createNewRecipeUser: function (input) { return __awaiter(this, void 0, void 0, function* () { - return recipeInterface.resetPasswordUsingToken(input); + return recipeInterface.createNewEmailPasswordRecipeUser(input); }); }, updateEmailOrPassword: function (input) { diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts index 601b0f21c..d24f05e67 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "../types"; import { Querier } from "../../../querier"; export default function getRecipeInterface(emailPasswordQuerier: Querier, thirdPartyQuerier?: Querier): RecipeInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js index 333844ed6..23f596161 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js @@ -40,6 +40,7 @@ const recipeImplementation_1 = __importDefault(require("../../emailpassword/reci const recipeImplementation_2 = __importDefault(require("../../thirdparty/recipeImplementation")); const emailPasswordRecipeImplementation_1 = __importDefault(require("./emailPasswordRecipeImplementation")); const thirdPartyRecipeImplementation_1 = __importDefault(require("./thirdPartyRecipeImplementation")); +const __1 = require("../../../"); function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { let originalEmailPasswordImplementation = recipeImplementation_1.default(emailPasswordQuerier); let originalThirdPartyImplementation; @@ -71,74 +72,50 @@ function getRecipeInterface(emailPasswordQuerier, thirdPartyQuerier) { ); }); }, - getUserById: function (input) { + getUserByThirdPartyInfo: function (input) { return __awaiter(this, void 0, void 0, function* () { - let user = yield originalEmailPasswordImplementation.getUserById.bind( - emailPasswordRecipeImplementation_1.default(this) - )(input); - if (user !== undefined) { - return user; - } if (originalThirdPartyImplementation === undefined) { return undefined; } - return yield originalThirdPartyImplementation.getUserById.bind( + return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind( thirdPartyRecipeImplementation_1.default(this) )(input); }); }, - getUsersByEmail: function ({ email, userContext }) { + createResetPasswordToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - let userFromEmailPass = yield originalEmailPasswordImplementation.getUserByEmail.bind( + return originalEmailPasswordImplementation.createResetPasswordToken.bind( emailPasswordRecipeImplementation_1.default(this) - )({ - email, - userContext, - }); - if (originalThirdPartyImplementation === undefined) { - return userFromEmailPass === undefined ? [] : [userFromEmailPass]; - } - let usersFromThirdParty = yield originalThirdPartyImplementation.getUsersByEmail.bind( - thirdPartyRecipeImplementation_1.default(this) - )({ email, userContext }); - if (userFromEmailPass !== undefined) { - return [...usersFromThirdParty, userFromEmailPass]; - } - return usersFromThirdParty; - }); - }, - getUserByThirdPartyInfo: function (input) { - return __awaiter(this, void 0, void 0, function* () { - if (originalThirdPartyImplementation === undefined) { - return undefined; - } - return originalThirdPartyImplementation.getUserByThirdPartyInfo.bind( - thirdPartyRecipeImplementation_1.default(this) )(input); }); }, - createResetPasswordToken: function (input) { + consumePasswordResetToken: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.createResetPasswordToken.bind( + return originalEmailPasswordImplementation.consumePasswordResetToken.bind( emailPasswordRecipeImplementation_1.default(this) )(input); }); }, - resetPasswordUsingToken: function (input) { + createNewEmailPasswordRecipeUser: function (input) { return __awaiter(this, void 0, void 0, function* () { - return originalEmailPasswordImplementation.resetPasswordUsingToken.bind( + return originalEmailPasswordImplementation.createNewRecipeUser.bind( emailPasswordRecipeImplementation_1.default(this) )(input); }); }, updateEmailOrPassword: function (input) { return __awaiter(this, void 0, void 0, function* () { - let user = yield this.getUserById({ userId: input.userId, userContext: input.userContext }); + let user = yield __1.getUser(input.userId, input.userContext); if (user === undefined) { return { status: "UNKNOWN_USER_ID_ERROR", }; - } else if (user.thirdParty !== undefined) { + } + let emailPasswordUserExists = + user.loginMethods.find((lM) => { + lM.recipeId === "emailpassword"; + }) !== undefined; + if (!emailPasswordUserExists) { throw new Error("Cannot update email or password of a user who signed up using third party login."); } return originalEmailPasswordImplementation.updateEmailOrPassword.bind( diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts index 2ede71963..fc596f02a 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "../../thirdparty/types"; import { RecipeInterface as ThirdPartyEmailPasswordRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPasswordRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js index 25f155ca3..d3c4c248b 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.js @@ -67,23 +67,14 @@ function getRecipeInterface(recipeInterface) { }; }); }, - getUserById: function (input) { + getUserById: function (_) { return __awaiter(this, void 0, void 0, function* () { - let user = yield recipeInterface.getUserById(input); - if (user === undefined || user.thirdParty === undefined) { - // either user is undefined or it's an email password user. - return undefined; - } - return user; + throw new Error("This will be removed.."); }); }, - getUsersByEmail: function (input) { + getUsersByEmail: function (_) { return __awaiter(this, void 0, void 0, function* () { - let users = yield recipeInterface.getUsersByEmail(input); - // we filter out all non thirdparty users. - return users.filter((u) => { - return u.thirdParty !== undefined; - }); + throw new Error("This will be removed.."); }); }, }; diff --git a/lib/build/recipe/thirdpartyemailpassword/types.d.ts b/lib/build/recipe/thirdpartyemailpassword/types.d.ts index 1a46c9fa7..a65d20ba8 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -1,7 +1,7 @@ +// @ts-nocheck import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; import { NormalisedFormField, - TypeFormField, TypeInputFormField, APIOptions as EmailPasswordAPIOptionsOriginal, TypeEmailPasswordEmailDeliveryInput, @@ -24,17 +24,6 @@ export declare type User = { userId: string; }; }; -export declare type TypeContextEmailPasswordSignUp = { - loginType: "emailpassword"; - formFields: TypeFormField[]; -}; -export declare type TypeContextEmailPasswordSignIn = { - loginType: "emailpassword"; -}; -export declare type TypeContextThirdParty = { - loginType: "thirdparty"; - thirdPartyAuthCodeResponse: any; -}; export declare type TypeInputSignUp = { formFields?: TypeInputFormField[]; }; @@ -69,8 +58,6 @@ export declare type TypeNormalisedInput = { }; }; export declare type RecipeInterface = { - getUserById(input: { userId: string; userContext: any }): Promise; - getUsersByEmail(input: { email: string; userContext: any }): Promise<(User | GlobalUser)[]>; getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -89,12 +76,23 @@ export declare type RecipeInterface = { emailPasswordSignUp(input: { email: string; password: string; - doAccountLinking: boolean; userContext: any; }): Promise< | { status: "OK"; - createdNewUser: boolean; + user: GlobalUser; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >; + createNewEmailPasswordRecipeUser(input: { + email: string; + password: string; + userContext: any; + }): Promise< + | { + status: "OK"; user: GlobalUser; } | { @@ -127,9 +125,8 @@ export declare type RecipeInterface = { status: "UNKNOWN_USER_ID_ERROR"; } >; - resetPasswordUsingToken(input: { + consumePasswordResetToken(input: { token: string; - newPassword: string; userContext: any; }): Promise< | { @@ -146,13 +143,15 @@ export declare type RecipeInterface = { email?: string; password?: string; userContext: any; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; - }>; + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + >; }; export declare type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; export declare type ThirdPartyAPIOptions = ThirdPartyAPIOptionsOriginal; @@ -257,7 +256,7 @@ export declare type APIInterface = { | { status: "OK"; email: string; - userId: string; + user: GlobalUser; } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; @@ -310,29 +309,14 @@ export declare type APIInterface = { }) => Promise< | { status: "OK"; - user: GlobalUser; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; wereAccountsAlreadyLinked: boolean; } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; + status: "WRONG_CREDENTIALS_ERROR"; } | GeneralErrorResponse >); @@ -369,7 +353,6 @@ export declare type APIInterface = { | { status: "OK"; user: GlobalUser; - createdNewUser: boolean; session: SessionContainerInterface; } | { diff --git a/lib/build/recipe/thirdpartyemailpassword/utils.d.ts b/lib/build/recipe/thirdpartyemailpassword/utils.d.ts index 56c6f7b41..60b02c8b9 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; import Recipe from "./recipe"; diff --git a/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts b/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts index 75c1214f2..0218549fa 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/api/implementation.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import { APIInterface } from "../types"; export default function getAPIImplementation(): APIInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts index 2f1494c18..e37fd1b22 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface } from "../../passwordless"; import { APIInterface as ThirdPartyPasswordlessAPIInterface } from "../types"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyPasswordlessAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts index a61dbd963..11fc459c9 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { APIInterface } from "../../thirdparty"; import { APIInterface as ThirdPartyPasswordlessAPIInterface } from "../types"; export default function getIterfaceImpl(apiImplmentation: ThirdPartyPasswordlessAPIInterface): APIInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts index 4063bc85f..3e90372c3 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/backwardCompatibility/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../types"; import { NormalisedAppinfo } from "../../../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts index dd2ef062c..4de04d983 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/index.d.ts @@ -1,2 +1,3 @@ +// @ts-nocheck import SMTP from "./smtp"; export declare let SMTPService: typeof SMTP; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts index 9d3626b2f..ebb0eb32a 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { ServiceInterface, TypeInput } from "../../../../../ingredients/emaildelivery/services/smtp"; import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../types"; import { EmailDeliveryInterface } from "../../../../../ingredients/emaildelivery/types"; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts index a77545987..87aab5100 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../../types"; import { Transporter } from "nodemailer"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; diff --git a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts index bce1d3c64..0a0cece68 100644 --- a/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/emaildelivery/services/smtp/serviceImplementation/passwordlessServiceImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeThirdPartyPasswordlessEmailDeliveryInput } from "../../../../types"; import { ServiceInterface } from "../../../../../../ingredients/emaildelivery/services/smtp"; import { TypePasswordlessEmailDeliveryInput } from "../../../../../passwordless/types"; diff --git a/lib/build/recipe/thirdpartypasswordless/error.d.ts b/lib/build/recipe/thirdpartypasswordless/error.d.ts index 56d432191..1d9c33665 100644 --- a/lib/build/recipe/thirdpartypasswordless/error.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/error.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "../../error"; export default class ThirdPartyEmailPasswordError extends STError { constructor(options: { type: "BAD_INPUT_ERROR"; message: string }); diff --git a/lib/build/recipe/thirdpartypasswordless/index.d.ts b/lib/build/recipe/thirdpartypasswordless/index.d.ts index cfb5efe85..be4703e99 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts index 3a2aa624b..16351e8c5 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import PasswordlessRecipe from "../passwordless/recipe"; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts index eb5a8e6a8..d2d6c2bc2 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "../types"; import { Querier } from "../../../querier"; export default function getRecipeInterface(passwordlessQuerier: Querier, thirdPartyQuerier?: Querier): RecipeInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts index c61eaeb4e..aafe44945 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/passwordlessRecipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "../../passwordless/types"; import { RecipeInterface as ThirdPartyPasswordlessRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyPasswordlessRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts index 283d09f72..b93917947 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/thirdPartyRecipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "../../thirdparty/types"; import { RecipeInterface as ThirdPartyPasswordlessRecipeInterface } from "../types"; export default function getRecipeInterface(recipeInterface: ThirdPartyPasswordlessRecipeInterface): RecipeInterface; diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts index 5fd8e90a3..9e1f9745a 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/backwardCompatibility/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { NormalisedAppinfo } from "../../../../../types"; diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts index 4e73dbb4d..f14aacf83 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Twilio from "./twilio"; import Supertokens from "./supertokens"; export declare let TwilioService: typeof Twilio; diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts index e3729cb71..2be198af4 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/supertokens/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; export default class SupertokensService implements SmsDeliveryInterface { diff --git a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts index 8f19e409b..ec73adb1f 100644 --- a/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/smsdelivery/services/twilio/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeInput } from "../../../../../ingredients/smsdelivery/services/twilio"; import { SmsDeliveryInterface } from "../../../../../ingredients/smsdelivery/types"; import { TypeThirdPartyPasswordlessSmsDeliveryInput } from "../../../types"; diff --git a/lib/build/recipe/thirdpartypasswordless/types.d.ts b/lib/build/recipe/thirdpartypasswordless/types.d.ts index 558bc68e6..d4f86a976 100644 --- a/lib/build/recipe/thirdpartypasswordless/types.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; import { DeviceType as DeviceTypeOriginal, diff --git a/lib/build/recipe/thirdpartypasswordless/utils.d.ts b/lib/build/recipe/thirdpartypasswordless/utils.d.ts index 4cae3a2f0..0fde7f7fd 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import { TypeInput, TypeNormalisedInput } from "./types"; export declare function validateAndNormaliseUserInput( diff --git a/lib/build/recipe/usermetadata/index.d.ts b/lib/build/recipe/usermetadata/index.d.ts index 08475a87f..91f6865fa 100644 --- a/lib/build/recipe/usermetadata/index.d.ts +++ b/lib/build/recipe/usermetadata/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { JSONObject } from "../../types"; import Recipe from "./recipe"; import { RecipeInterface } from "./types"; diff --git a/lib/build/recipe/usermetadata/recipe.d.ts b/lib/build/recipe/usermetadata/recipe.d.ts index 3c8759b7e..bbce8012b 100644 --- a/lib/build/recipe/usermetadata/recipe.d.ts +++ b/lib/build/recipe/usermetadata/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; diff --git a/lib/build/recipe/usermetadata/recipeImplementation.d.ts b/lib/build/recipe/usermetadata/recipeImplementation.d.ts index 1bf5d18f5..0c838d977 100644 --- a/lib/build/recipe/usermetadata/recipeImplementation.d.ts +++ b/lib/build/recipe/usermetadata/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "."; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/usermetadata/types.d.ts b/lib/build/recipe/usermetadata/types.d.ts index 9b1ef77a0..a88b13312 100644 --- a/lib/build/recipe/usermetadata/types.d.ts +++ b/lib/build/recipe/usermetadata/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; import { JSONObject } from "../../types"; export declare type TypeInput = { diff --git a/lib/build/recipe/usermetadata/utils.d.ts b/lib/build/recipe/usermetadata/utils.d.ts index e368bc539..4025b1b44 100644 --- a/lib/build/recipe/usermetadata/utils.d.ts +++ b/lib/build/recipe/usermetadata/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; diff --git a/lib/build/recipe/userroles/index.d.ts b/lib/build/recipe/userroles/index.d.ts index c0f832dfb..0e2210593 100644 --- a/lib/build/recipe/userroles/index.d.ts +++ b/lib/build/recipe/userroles/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import Recipe from "./recipe"; import { RecipeInterface } from "./types"; export default class Wrapper { diff --git a/lib/build/recipe/userroles/permissionClaim.d.ts b/lib/build/recipe/userroles/permissionClaim.d.ts index f910f3f0b..d0c34d159 100644 --- a/lib/build/recipe/userroles/permissionClaim.d.ts +++ b/lib/build/recipe/userroles/permissionClaim.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { PrimitiveArrayClaim } from "../session/claimBaseClasses/primitiveArrayClaim"; /** * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. diff --git a/lib/build/recipe/userroles/recipe.d.ts b/lib/build/recipe/userroles/recipe.d.ts index 3c8759b7e..bbce8012b 100644 --- a/lib/build/recipe/userroles/recipe.d.ts +++ b/lib/build/recipe/userroles/recipe.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import normalisedURLPath from "../../normalisedURLPath"; diff --git a/lib/build/recipe/userroles/recipeImplementation.d.ts b/lib/build/recipe/userroles/recipeImplementation.d.ts index 8a3a26d7c..86bf78a27 100644 --- a/lib/build/recipe/userroles/recipeImplementation.d.ts +++ b/lib/build/recipe/userroles/recipeImplementation.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { RecipeInterface } from "./types"; import { Querier } from "../../querier"; export default function getRecipeInterface(querier: Querier): RecipeInterface; diff --git a/lib/build/recipe/userroles/types.d.ts b/lib/build/recipe/userroles/types.d.ts index af23a75a8..9552d9f54 100644 --- a/lib/build/recipe/userroles/types.d.ts +++ b/lib/build/recipe/userroles/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export declare type TypeInput = { skipAddingRolesToAccessToken?: boolean; diff --git a/lib/build/recipe/userroles/userRoleClaim.d.ts b/lib/build/recipe/userroles/userRoleClaim.d.ts index 3e0a5cd83..75c0635d5 100644 --- a/lib/build/recipe/userroles/userRoleClaim.d.ts +++ b/lib/build/recipe/userroles/userRoleClaim.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { PrimitiveArrayClaim } from "../session/claimBaseClasses/primitiveArrayClaim"; /** * We include "Class" in the class name, because it makes it easier to import the right thing (the instance) instead of this. diff --git a/lib/build/recipe/userroles/utils.d.ts b/lib/build/recipe/userroles/utils.d.ts index e368bc539..4025b1b44 100644 --- a/lib/build/recipe/userroles/utils.d.ts +++ b/lib/build/recipe/userroles/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput } from "./types"; diff --git a/lib/build/recipeModule.d.ts b/lib/build/recipeModule.d.ts index 269a2eb18..aef4fd4c8 100644 --- a/lib/build/recipeModule.d.ts +++ b/lib/build/recipeModule.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import STError from "./error"; import { NormalisedAppinfo, APIHandled, HTTPMethod } from "./types"; import NormalisedURLPath from "./normalisedURLPath"; diff --git a/lib/build/supertokens.d.ts b/lib/build/supertokens.d.ts index 5a6621e46..8bdf79f64 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import { TypeInput, NormalisedAppinfo, HTTPMethod, SuperTokensInfo } from "./types"; import RecipeModule from "./recipeModule"; import NormalisedURLPath from "./normalisedURLPath"; diff --git a/lib/build/types.d.ts b/lib/build/types.d.ts index 8462932d5..4de639a1c 100644 --- a/lib/build/types.d.ts +++ b/lib/build/types.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import RecipeModule from "./recipeModule"; import NormalisedURLDomain from "./normalisedURLDomain"; import NormalisedURLPath from "./normalisedURLPath"; diff --git a/lib/build/utils.d.ts b/lib/build/utils.d.ts index 79777afd8..c1ab0dd06 100644 --- a/lib/build/utils.d.ts +++ b/lib/build/utils.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck import type { AppInfo, NormalisedAppinfo, HTTPMethod, JSONObject } from "./types"; import type { BaseRequest, BaseResponse } from "./framework"; export declare function getLargestVersionFromIntersection(v1: string[], v2: string[]): string | undefined; diff --git a/lib/build/version.d.ts b/lib/build/version.d.ts index 55acadce2..2e5ff3046 100644 --- a/lib/build/version.d.ts +++ b/lib/build/version.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck export declare const version = "13.0.2"; export declare const cdiSupported: string[]; export declare const dashboardVersion = "0.3"; diff --git a/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts b/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts index c68952cc4..4e2f8b11c 100644 --- a/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts +++ b/lib/ts/recipe/dashboard/api/userdetails/userPasswordPut.ts @@ -4,7 +4,6 @@ import EmailPasswordRecipe from "../../../emailpassword/recipe"; import EmailPassword from "../../../emailpassword"; import ThirdPartyEmailPasswordRecipe from "../../../thirdpartyemailpassword/recipe"; import ThirdPartyEmailPassword from "../../../thirdpartyemailpassword"; -import { FORM_FIELD_PASSWORD_ID } from "../../../emailpassword/constants"; type Response = | { @@ -21,7 +20,6 @@ type Response = export const userPasswordPut = async (_: APIInterface, options: APIOptions): Promise => { const requestBody = await options.req.getJSONBody(); const userId = requestBody.userId; - const email = requestBody.email; const newPassword = requestBody.newPassword; if (userId === undefined || typeof userId !== "string") { @@ -58,19 +56,6 @@ export const userPasswordPut = async (_: APIInterface, options: APIOptions): Pro } if (recipeToUse === "emailpassword") { - let passwordFormFields = EmailPasswordRecipe.getInstanceOrThrowError().config.signUpFeature.formFields.filter( - (field) => field.id === FORM_FIELD_PASSWORD_ID - ); - - let passwordValidationError = await passwordFormFields[0].validate(newPassword); - - if (passwordValidationError !== undefined) { - return { - status: "INVALID_PASSWORD_ERROR", - error: passwordValidationError, - }; - } - const updateResponse = await EmailPassword.updateEmailOrPassword({ userId, password: newPassword, @@ -85,40 +70,40 @@ export const userPasswordPut = async (_: APIInterface, options: APIOptions): Pro throw new Error("Should never come here"); } // TODO: check for password policy error has well. + /** + * + * return { + status: "INVALID_PASSWORD_ERROR", + error: passwordValidationError, + }; + */ return { status: "OK", }; } - let passwordFormFields = ThirdPartyEmailPasswordRecipe.getInstanceOrThrowError().config.signUpFeature.formFields.filter( - (field) => field.id === FORM_FIELD_PASSWORD_ID - ); + const updateResponse = await ThirdPartyEmailPassword.updateEmailOrPassword({ + userId, + password: newPassword, + }); - let passwordValidationError = await passwordFormFields[0].validate(newPassword); - - if (passwordValidationError !== undefined) { - return { - status: "INVALID_PASSWORD_ERROR", - error: passwordValidationError, - }; - } - - const passwordResetToken = await ThirdPartyEmailPassword.createResetPasswordToken(userId, email); - - if (passwordResetToken.status === "UNKNOWN_USER_ID_ERROR") { + if ( + updateResponse.status === "UNKNOWN_USER_ID_ERROR" || + updateResponse.status === "EMAIL_ALREADY_EXISTS_ERROR" || + updateResponse.status === "EMAIL_CHANGE_NOT_ALLOWED_ERROR" + ) { // Techincally it can but its an edge case so we assume that it wont throw new Error("Should never come here"); } - - const passwordResetResponse = await ThirdPartyEmailPassword.resetPasswordUsingToken( - passwordResetToken.token, - newPassword - ); - - if (passwordResetResponse.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { - throw new Error("Should never come here"); - } + // TODO: check for password policy error has well. + /** + * + * return { + status: "INVALID_PASSWORD_ERROR", + error: passwordValidationError, + }; + */ return { status: "OK", diff --git a/lib/ts/recipe/dashboard/utils.ts b/lib/ts/recipe/dashboard/utils.ts index 992cf25d4..55507a4e3 100644 --- a/lib/ts/recipe/dashboard/utils.ts +++ b/lib/ts/recipe/dashboard/utils.ts @@ -46,7 +46,6 @@ import ThirdPartyEmailPasswordRecipe from "../thirdpartyemailpassword/recipe"; import ThirdPartyPasswordlessRecipe from "../thirdpartypasswordless/recipe"; import ThirdParty from "../thirdparty"; import Passwordless from "../passwordless"; -import ThirdPartyEmailPassword from "../thirdpartyemailpassword"; import ThirdPartyPasswordless from "../thirdpartypasswordless"; export function validateAndNormaliseUserInput(config: TypeInput): TypeNormalisedInput { @@ -211,7 +210,6 @@ async function _getUserForRecipeId( if (loginMethod !== undefined) { user = { ...loginMethod, - recipeId: "emailpassword", }; recipe = "emailpassword"; } @@ -222,22 +220,17 @@ async function _getUserForRecipeId( if (user === undefined) { try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - let loginMethod = userResponse.loginMethods.find( - (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId - ); - if (loginMethod !== undefined) { - user = { - ...loginMethod, - recipeId: "emailpassword", - }; - recipe = "thirdpartyemailpassword"; - } - } else { - throw new Error("Should never come here. TODO remove me"); + // we detect if this recipe has been init or not.. + ThirdPartyEmailPasswordRecipe.getInstanceOrThrowError(); + if (globalUser !== undefined) { + let loginMethod = globalUser.loginMethods.find( + (u) => u.recipeId === "emailpassword" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { + user = { + ...loginMethod, + }; + recipe = "thirdpartyemailpassword"; } } } catch (e) { @@ -261,15 +254,15 @@ async function _getUserForRecipeId( if (user === undefined) { try { - const userResponse = await ThirdPartyEmailPassword.getUserById(userId); - - if (userResponse !== undefined) { - if ("loginMethods" in userResponse) { - throw new Error("Should never come here. TODO remove me"); - } else { + // we detect if this recipe has been init or not.. + ThirdPartyEmailPasswordRecipe.getInstanceOrThrowError(); + if (globalUser !== undefined) { + let loginMethod = globalUser.loginMethods.find( + (u) => u.recipeId === "thirdparty" && u.recipeUserId === userId + ); + if (loginMethod !== undefined) { user = { - ...userResponse, - recipeId: "thirdparty", + ...loginMethod, }; recipe = "thirdpartyemailpassword"; } diff --git a/lib/ts/recipe/thirdpartyemailpassword/index.ts b/lib/ts/recipe/thirdpartyemailpassword/index.ts index 150d6f939..87b4ab4d7 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/index.ts @@ -42,11 +42,10 @@ export default class Wrapper { }); } - static emailPasswordSignUp(email: string, password: string, doAccountLinking = false, userContext: any = {}) { + static emailPasswordSignUp(email: string, password: string, userContext: any = {}) { return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.emailPasswordSignUp({ email, password, - doAccountLinking, userContext, }); } @@ -59,14 +58,6 @@ export default class Wrapper { }); } - static getUserById(userId: string, userContext: any = {}) { - return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUserById({ userId, userContext }); - } - - static getUsersByEmail(email: string, userContext: any = {}) { - return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.getUsersByEmail({ email, userContext }); - } - static createResetPasswordToken(userId: string, email: string, userContext: any = {}) { return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.createResetPasswordToken({ userId, @@ -75,10 +66,9 @@ export default class Wrapper { }); } - static resetPasswordUsingToken(token: string, newPassword: string, userContext: any = {}) { - return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.resetPasswordUsingToken({ + static consumePasswordResetToken(token: string, userContext: any = {}) { + return Recipe.getInstanceOrThrowError().recipeInterfaceImpl.consumePasswordResetToken({ token, - newPassword, userContext, }); } @@ -124,15 +114,11 @@ export let emailPasswordSignIn = Wrapper.emailPasswordSignIn; export let thirdPartySignInUp = Wrapper.thirdPartySignInUp; -export let getUserById = Wrapper.getUserById; - export let getUserByThirdPartyInfo = Wrapper.getUserByThirdPartyInfo; -export let getUsersByEmail = Wrapper.getUsersByEmail; - export let createResetPasswordToken = Wrapper.createResetPasswordToken; -export let resetPasswordUsingToken = Wrapper.resetPasswordUsingToken; +export let consumePasswordResetToken = Wrapper.consumePasswordResetToken; export let updateEmailOrPassword = Wrapper.updateEmailOrPassword; diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts index e9d7d9df9..e9b7afa3b 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/emailPasswordRecipeImplementation.ts @@ -7,9 +7,8 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw signUp: async function (input: { email: string; password: string; - doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; createdNewUser: boolean; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { + }): Promise<{ status: "OK"; user: User } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { return await recipeInterface.emailPasswordSignUp(input); }, @@ -21,25 +20,6 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw return recipeInterface.emailPasswordSignIn(input); }, - getUserById: async function (input: { userId: string; userContext: any }): Promise { - let user = await recipeInterface.getUserById(input); - if (user === undefined || user.thirdParty !== undefined) { - // either user is undefined or it's a thirdparty user. - return undefined; - } - return user as User; - }, - - getUserByEmail: async function (input: { email: string; userContext: any }): Promise { - let result = await recipeInterface.getUsersByEmail(input); - for (let i = 0; i < result.length; i++) { - if (result[i].thirdParty === undefined) { - return result[i] as User; - } - } - return undefined; - }, - createResetPasswordToken: async function (input: { userId: string; email: string; @@ -48,8 +28,22 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw return recipeInterface.createResetPasswordToken(input); }, - resetPasswordUsingToken: async function (input: { token: string; newPassword: string; userContext: any }) { - return recipeInterface.resetPasswordUsingToken(input); + consumePasswordResetToken: async function (input: { token: string; userContext: any }) { + return recipeInterface.consumePasswordResetToken(input); + }, + + createNewRecipeUser: async function (input: { + email: string; + password: string; + userContext: any; + }): Promise< + | { + status: "OK"; + user: User; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + > { + return recipeInterface.createNewEmailPasswordRecipeUser(input); }, updateEmailOrPassword: async function (input: { @@ -57,13 +51,15 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw email?: string; password?: string; userContext: any; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; - }> { + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + > { return recipeInterface.updateEmailOrPassword(input); }, }; diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts index ca7bca910..913cafa6f 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/index.ts @@ -7,6 +7,7 @@ import { Querier } from "../../../querier"; import DerivedEP from "./emailPasswordRecipeImplementation"; import DerivedTP from "./thirdPartyRecipeImplementation"; import { User as GlobalUser } from "../../../types"; +import { getUser } from "../../../"; export default function getRecipeInterface( emailPasswordQuerier: Querier, @@ -22,11 +23,8 @@ export default function getRecipeInterface( emailPasswordSignUp: async function (input: { email: string; password: string; - doAccountLinking: boolean; userContext: any; - }): Promise< - { status: "OK"; createdNewUser: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" } - > { + }): Promise<{ status: "OK"; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }> { return await originalEmailPasswordImplementation.signUp.bind(DerivedEP(this))(input); }, @@ -50,50 +48,6 @@ export default function getRecipeInterface( return originalThirdPartyImplementation.signInUp.bind(DerivedTP(this))(input); }, - getUserById: async function (input: { - userId: string; - userContext: any; - }): Promise { - let user: GlobalUser | User | undefined = await originalEmailPasswordImplementation.getUserById.bind( - DerivedEP(this) - )(input); - if (user !== undefined) { - return user; - } - if (originalThirdPartyImplementation === undefined) { - return undefined; - } - return await originalThirdPartyImplementation.getUserById.bind(DerivedTP(this))(input); - }, - - getUsersByEmail: async function ({ - email, - userContext, - }: { - email: string; - userContext: any; - }): Promise<(User | GlobalUser)[]> { - let userFromEmailPass: - | GlobalUser - | User - | undefined = await originalEmailPasswordImplementation.getUserByEmail.bind(DerivedEP(this))({ - email, - userContext, - }); - - if (originalThirdPartyImplementation === undefined) { - return userFromEmailPass === undefined ? [] : [userFromEmailPass]; - } - let usersFromThirdParty: User[] = await originalThirdPartyImplementation.getUsersByEmail.bind( - DerivedTP(this) - )({ email, userContext }); - - if (userFromEmailPass !== undefined) { - return [...usersFromThirdParty, userFromEmailPass]; - } - return usersFromThirdParty; - }, - getUserByThirdPartyInfo: async function (input: { thirdPartyId: string; thirdPartyUserId: string; @@ -113,8 +67,22 @@ export default function getRecipeInterface( return originalEmailPasswordImplementation.createResetPasswordToken.bind(DerivedEP(this))(input); }, - resetPasswordUsingToken: async function (input: { token: string; newPassword: string; userContext: any }) { - return originalEmailPasswordImplementation.resetPasswordUsingToken.bind(DerivedEP(this))(input); + consumePasswordResetToken: async function (input: { token: string; userContext: any }) { + return originalEmailPasswordImplementation.consumePasswordResetToken.bind(DerivedEP(this))(input); + }, + + createNewEmailPasswordRecipeUser: async function (input: { + email: string; + password: string; + userContext: any; + }): Promise< + | { + status: "OK"; + user: GlobalUser; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + > { + return originalEmailPasswordImplementation.createNewRecipeUser.bind(DerivedEP(this))(input); }, updateEmailOrPassword: async function ( @@ -125,19 +93,27 @@ export default function getRecipeInterface( password?: string; userContext: any; } - ): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; - }> { - let user = await this.getUserById({ userId: input.userId, userContext: input.userContext }); + ): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + > { + let user = await getUser(input.userId, input.userContext); if (user === undefined) { return { status: "UNKNOWN_USER_ID_ERROR", }; - } else if (user.thirdParty !== undefined) { + } + let emailPasswordUserExists = + user.loginMethods.find((lM) => { + lM.recipeId === "emailpassword"; + }) !== undefined; + + if (!emailPasswordUserExists) { throw new Error("Cannot update email or password of a user who signed up using third party login."); } return originalEmailPasswordImplementation.updateEmailOrPassword.bind(DerivedEP(this))(input); diff --git a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts index f4b10ee82..176b0b316 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/recipeImplementation/thirdPartyRecipeImplementation.ts @@ -44,22 +44,12 @@ export default function getRecipeInterface(recipeInterface: ThirdPartyEmailPassw }; }, - getUserById: async function (input: { userId: string; userContext: any }): Promise { - let user = await recipeInterface.getUserById(input); - if (user === undefined || user.thirdParty === undefined) { - // either user is undefined or it's an email password user. - return undefined; - } - return user as User; + getUserById: async function (_: { userId: string; userContext: any }): Promise { + throw new Error("This will be removed.."); }, - getUsersByEmail: async function (input: { email: string; userContext: any }): Promise { - let users = await recipeInterface.getUsersByEmail(input); - - // we filter out all non thirdparty users. - return users.filter((u) => { - return u.thirdParty !== undefined; - }) as User[]; + getUsersByEmail: async function (_: { email: string; userContext: any }): Promise { + throw new Error("This will be removed.."); }, }; } diff --git a/lib/ts/recipe/thirdpartyemailpassword/types.ts b/lib/ts/recipe/thirdpartyemailpassword/types.ts index 35b838e9f..70d5fd12a 100644 --- a/lib/ts/recipe/thirdpartyemailpassword/types.ts +++ b/lib/ts/recipe/thirdpartyemailpassword/types.ts @@ -15,7 +15,6 @@ import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; import { NormalisedFormField, - TypeFormField, TypeInputFormField, APIOptions as EmailPasswordAPIOptionsOriginal, TypeEmailPasswordEmailDeliveryInput, @@ -40,20 +39,6 @@ export type User = { }; }; -export type TypeContextEmailPasswordSignUp = { - loginType: "emailpassword"; - formFields: TypeFormField[]; -}; - -export type TypeContextEmailPasswordSignIn = { - loginType: "emailpassword"; -}; - -export type TypeContextThirdParty = { - loginType: "thirdparty"; - thirdPartyAuthCodeResponse: any; -}; - export type TypeInputSignUp = { formFields?: TypeInputFormField[]; }; @@ -92,10 +77,6 @@ export type TypeNormalisedInput = { }; export type RecipeInterface = { - getUserById(input: { userId: string; userContext: any }): Promise; - - getUsersByEmail(input: { email: string; userContext: any }): Promise<(User | GlobalUser)[]>; - getUserByThirdPartyInfo(input: { thirdPartyId: string; thirdPartyUserId: string; @@ -112,9 +93,20 @@ export type RecipeInterface = { emailPasswordSignUp(input: { email: string; password: string; - doAccountLinking: boolean; userContext: any; - }): Promise<{ status: "OK"; createdNewUser: boolean; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + }): Promise<{ status: "OK"; user: GlobalUser } | { status: "EMAIL_ALREADY_EXISTS_ERROR" }>; + + createNewEmailPasswordRecipeUser(input: { + email: string; + password: string; + userContext: any; + }): Promise< + | { + status: "OK"; + user: GlobalUser; + } + | { status: "EMAIL_ALREADY_EXISTS_ERROR" } + >; emailPasswordSignIn(input: { email: string; @@ -128,9 +120,8 @@ export type RecipeInterface = { userContext: any; }): Promise<{ status: "OK"; token: string } | { status: "UNKNOWN_USER_ID_ERROR" }>; - resetPasswordUsingToken(input: { + consumePasswordResetToken(input: { token: string; - newPassword: string; userContext: any; }): Promise< | { @@ -146,13 +137,15 @@ export type RecipeInterface = { email?: string; password?: string; userContext: any; - }): Promise<{ - status: - | "OK" - | "UNKNOWN_USER_ID_ERROR" - | "EMAIL_ALREADY_EXISTS_ERROR" - | "EMAIL_CHANGE_NOT_ALLOWED_DUE_TO_ACCOUNT_LINKING"; - }>; + }): Promise< + | { + status: "OK" | "UNKNOWN_USER_ID_ERROR" | "EMAIL_ALREADY_EXISTS_ERROR"; + } + | { + status: "EMAIL_CHANGE_NOT_ALLOWED_ERROR"; + reason: string; + } + >; }; export type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; @@ -263,7 +256,7 @@ export type APIInterface = { | { status: "OK"; email: string; - userId: string; + user: GlobalUser; } | { status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; @@ -318,29 +311,14 @@ export type APIInterface = { }) => Promise< | { status: "OK"; - user: GlobalUser; - createdNewRecipeUser: boolean; - session: SessionContainerInterface; wereAccountsAlreadyLinked: boolean; } | { - status: "RECIPE_USER_ID_ALREADY_LINKED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; + status: "NEW_ACCOUNT_NEEDS_TO_BE_VERIFIED_ERROR" | "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; description: string; } | { - status: "ACCOUNT_INFO_ALREADY_ASSOCIATED_WITH_ANOTHER_PRIMARY_USER_ID_ERROR"; - primaryUserId: string; - description: string; - } - | { - status: "ACCOUNT_LINKING_NOT_ALLOWED_ERROR"; - description: string; - } - | { - status: "ACCOUNT_NOT_VERIFIED_ERROR"; - isNotVerifiedAccountFromInputSession: boolean; - description: string; + status: "WRONG_CREDENTIALS_ERROR"; } | GeneralErrorResponse >); @@ -378,7 +356,6 @@ export type APIInterface = { | { status: "OK"; user: GlobalUser; - createdNewUser: boolean; session: SessionContainerInterface; } | { diff --git a/test/with-typescript/index.ts b/test/with-typescript/index.ts index 3235a335d..4762e932d 100644 --- a/test/with-typescript/index.ts +++ b/test/with-typescript/index.ts @@ -1064,10 +1064,14 @@ Supertokens.init({ // we check if the email exists in SuperTokens. If not, // then the sign in should be handled by you. if ( - (await supertokensImpl.getUserByEmail({ - email: input.email, - userContext: input.userContext, - })) === undefined + ( + await Supertokens.listUsersByAccountInfo( + { + email: input.email, + }, + input.userContext + ) + ).length === 0 ) { // TODO: sign in from your db // example return value if credentials don't match @@ -1082,24 +1086,6 @@ Supertokens.init({ // all new users are created in SuperTokens; return supertokensImpl.signUp(input); }, - getUserByEmail: async (input) => { - let superTokensUser = await supertokensImpl.getUserByEmail(input); - if (superTokensUser === undefined) { - let email = input.email; - // TODO: fetch and return user info from your database... - } else { - return superTokensUser; - } - }, - getUserById: async (input) => { - let superTokensUser = await supertokensImpl.getUserById(input); - if (superTokensUser === undefined) { - let userId = input.userId; - // TODO: fetch and return user info from your database... - } else { - return superTokensUser; - } - }, }; }, apis: (oI) => { @@ -1279,7 +1265,6 @@ ThirdPartyEmailPassword.sendEmail({ user: { email: "", id: "", - recipeUserId: "", }, }); ThirdPartyEmailPassword.sendEmail({ @@ -1288,7 +1273,6 @@ ThirdPartyEmailPassword.sendEmail({ user: { email: "", id: "", - recipeUserId: "", }, userContext: {}, });