From e4bd793890e23611e23065d5f9e8f72e44596f35 Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Fri, 29 Apr 2022 22:25:36 +0200 Subject: [PATCH 01/13] Trying to create support for H3 --- lib/ts/framework/h3/framework.ts | 169 ++++++++++++++++++++++++++ lib/ts/framework/h3/index.ts | 7 ++ lib/ts/framework/utils.ts | 52 ++++++++ lib/ts/recipe/session/framework/h3.ts | 25 ++++ package-lock.json | 13 +- package.json | 5 +- 6 files changed, 268 insertions(+), 3 deletions(-) create mode 100644 lib/ts/framework/h3/framework.ts create mode 100644 lib/ts/framework/h3/index.ts create mode 100644 lib/ts/recipe/session/framework/h3.ts diff --git a/lib/ts/framework/h3/framework.ts b/lib/ts/framework/h3/framework.ts new file mode 100644 index 000000000..18909ac36 --- /dev/null +++ b/lib/ts/framework/h3/framework.ts @@ -0,0 +1,169 @@ +import type {IncomingMessage, ServerResponse} from 'http'; +import { SessionContainerInterface } from '../../recipe/session/types'; +import SuperTokens from '../../supertokens'; +import { normaliseHttpMethod } from "../../utils"; +import { BaseRequest } from "../request"; +import { BaseResponse } from '../response'; +import { Framework } from '../types'; +import { + getHeaderValueFromIncomingMessage, setH3Header, useBody, useRawBody, setCookieForServerResponse +} from "../utils"; + +const defer = typeof setImmediate !== 'undefined' ? setImmediate : (fn: Function) => fn() + +export class H3Request extends BaseRequest { + private request: IncomingMessage; + constructor(request: IncomingMessage) { + super(); + this.original = request; + this.request = request; + }; + getCookieValue = (key: string) => { + return getHeaderValueFromIncomingMessage(this.request, key); + }; + getFormData = async (): Promise => { + return useRawBody(this.request); + }; + getMethod = () => { + return normaliseHttpMethod(this.request.method!) + }; + getHeaderValue = (key: string) => { + return getHeaderValueFromIncomingMessage(this.request, key); + }; + getOriginalURL = () => { + return this.request.url! + }; + getKeyValueFromQuery = (key: string) => { + let path = this.request.url || "/" + const queryIndex = path.lastIndexOf('?') + if(queryIndex > -1) { + const queryArray = path.substring(queryIndex + 1, path.length).split('&'); + const index = queryArray.findIndex(el => el.includes(key)); + if(index === -1) return undefined; + const value = queryArray[index].split('=')[1] + if(value === undefined || typeof value !== 'string') { + return undefined + } + return value; + } else { + return undefined; + } + } + getJSONBody = async () => { + return await useBody(this.request); + }; +} + +export class H3ResponseTokens extends BaseResponse { + private response: ServerResponse; + private statusCode: number; + constructor(response: ServerResponse) { + super(); + this.original = response; + this.response = response; + this.statusCode = 200 + } + + sendHTMLResponse = (html: string) => { + if(this.response.writable) { + this.response.setHeader('Content-Type', 'text/html') + this.response.statusCode = this.statusCode; + new Promise((resolve) => { + defer(() => { + this.response.end(html); + resolve(undefined); + }) + }) + } + }; + setHeader = (key: string, value: string, allowDuplicateKey: boolean) => { + setH3Header(this.response, key, value, allowDuplicateKey); + }; + setCookie = ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => { + setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); + }; + setStatusCode = (statusCode: number) => { + if(this.response.writable) { + this.statusCode = statusCode + } + }; + sendJSONResponse = (content: any) => { + if(this.response.writable) { + this.response.setHeader('Content-Type', 'application/json') + this.response.statusCode = this.statusCode; + new Promise((resolve) => { + defer(() => { + this.response.end(content); + resolve(undefined); + }) + }) + } + }; +} +export interface SessionRequest extends IncomingMessage { + session?: SessionContainerInterface +} + +export const middlware = () => { + return async (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => { + let supertokens; + const request = new H3Request(req); + const response = new H3ResponseTokens(res); + try { + supertokens = SuperTokens.getInstanceOrThrowError(); + const result = await supertokens.middleware(request, response); + if(!result) { + return next(); + } + } catch(err: any) { + if(supertokens) { + try { + await supertokens.errorHandler(err, request, response); + } catch { + next(err); + } + } else { + next(err); + } + } + + } +} + +export const errorHandler = () => { + return async (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => { + let supertokens = SuperTokens.getInstanceOrThrowError(); + let request = new H3Request(req); + let response = new H3ResponseTokens(res); + try { + await supertokens.errorHandler(err, request,response); + } catch(err: any) { + return next(err); + } + } +}; + +export interface H3Framework extends Framework { + middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise, + errorHandler: () => (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise +} + +export const H3Wrapper: H3Framework = { + middlware, + errorHandler, + wrapRequest: (unwrapped) => { + return new H3Request(unwrapped); + }, + wrapResponse: (unwrapped) => { + return new H3ResponseTokens(unwrapped) + } +} \ No newline at end of file diff --git a/lib/ts/framework/h3/index.ts b/lib/ts/framework/h3/index.ts new file mode 100644 index 000000000..6fcd57080 --- /dev/null +++ b/lib/ts/framework/h3/index.ts @@ -0,0 +1,7 @@ +import { H3Wrapper } from "./framework"; +export type {SessionRequest} from './framework'; + +export const middleware = H3Wrapper.middlware; +export const errorHandler = H3Wrapper.errorHandler; +export const wrapRequest = H3Wrapper.wrapRequest; +export const wrapResponse = H3Wrapper.wrapResponse; \ No newline at end of file diff --git a/lib/ts/framework/utils.ts b/lib/ts/framework/utils.ts index 1ea436307..255c76164 100644 --- a/lib/ts/framework/utils.ts +++ b/lib/ts/framework/utils.ts @@ -22,6 +22,7 @@ import STError from "../error"; import type { HTTPMethod } from "../types"; import { NextApiRequest } from "next"; import { COOKIE_HEADER } from "./constants"; +import destr from 'destr'; export function getCookieValueFromHeaders(headers: any, key: string): string | undefined { if (headers === undefined || headers === null) { @@ -217,6 +218,57 @@ export function setHeaderForExpressLikeResponse(res: Response, key: string, valu } } +export function useRawBody(req: IncomingMessage): Promise { + const RawBodySymbol = Symbol('h3RawBody'); + if(RawBodySymbol in this.request) { + const promise = Promise.resolve((req as any)[RawBodySymbol]) + return promise.then(buff => buff.toString('utf-8')); + } + if('body' in req) { + return Promise.resolve((this.request as any).body); + } + + const promise = (req as any)[RawBodySymbol] = new Promise((resolve, reject) => { + const bodyData: any[] = [] + req + .on('error', (err) => reject(err)) + .on('data', (chunk) => {bodyData.push(chunk)}) + .on('end', () => {resolve(Buffer.concat(bodyData))}) + }) + + return promise.then(buff => buff.toString('utf-8')); +} + +export async function useBody(req: IncomingMessage): Promise { + const ParsedBodySymbol = Symbol('h3RawBody') + if(ParsedBodySymbol in req) { + return (req as any)[ParsedBodySymbol] + } + + const body = await useRawBody(req) as string; + + const json = destr(body); + (req as any)[ParsedBodySymbol] = json; + return json +} + +export function setH3Header(res: ServerResponse, key: string, value: string, allowDuplicateKey: boolean) { + try { + let existingHeaders = res.getHeaders(); + let existingValue = existingHeaders[key.toLowerCase()]; + + if (existingValue === undefined) { + res.setHeader(key, value); + } else if (allowDuplicateKey) { + res.setHeader(key, existingValue + ", " + value); + } else { + res.setHeader(key, value); + } + } catch (err) { + throw new Error("Error while setting header with key: " + key + " and value: " + value); + } +} + /** * * @param res diff --git a/lib/ts/recipe/session/framework/h3.ts b/lib/ts/recipe/session/framework/h3.ts new file mode 100644 index 000000000..a49d01466 --- /dev/null +++ b/lib/ts/recipe/session/framework/h3.ts @@ -0,0 +1,25 @@ +import Session from '../recipe'; +import type { VerifySessionOptions } from '../types'; +import { H3Request, H3ResponseTokens } from '../../../framework/h3/framework'; +import type { SessionRequest } from '../../../framework/h3'; +import type { ServerResponse} from 'http'; +import SuperTokens from '../../../supertokens'; + +export function verifySession(options?: VerifySessionOptions) { + return async (req: SessionRequest, res: ServerResponse, next: (err?: Error) => any) => { + const request = new H3Request(req); + const response = new H3ResponseTokens(res); + try { + const sessionRecipe = Session.getInstanceOrThrowError(); + req.session = await sessionRecipe.verifySession(options, request, response); + next(); + } catch (err: any) { + try { + const supertokens = SuperTokens.getInstanceOrThrowError(); + await supertokens.errorHandler(err, request, response); + } catch(err: any) { + next(err); + } + } + } +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 5e185f1f2..27c15d417 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,7 +6,7 @@ "packages": { "": { "name": "supertokens-node", - "version": "9.1.2", + "version": "9.2.0", "license": "Apache-2.0", "dependencies": { "axios": "0.21.4", @@ -14,6 +14,7 @@ "co-body": "6.1.0", "cookie": "0.4.0", "debug": "^4.3.3", + "destr": "^1.1.1", "jsonwebtoken": "^8.5.1", "jwks-rsa": "^2.0.5", "libphonenumber-js": "^1.9.44", @@ -3185,6 +3186,11 @@ "minimalistic-assert": "^1.0.0" } }, + "node_modules/destr": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/destr/-/destr-1.1.1.tgz", + "integrity": "sha512-QqkneF8LrYmwATMdnuD2MLI3GHQIcBnG6qFC2q9bSH430VTCDAVjcspPmUaKhPGtAtPAftIUFqY1obQYQuwmbg==" + }, "node_modules/destroy": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.1.0.tgz", @@ -11971,6 +11977,11 @@ "minimalistic-assert": "^1.0.0" } }, + "destr": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/destr/-/destr-1.1.1.tgz", + "integrity": "sha512-QqkneF8LrYmwATMdnuD2MLI3GHQIcBnG6qFC2q9bSH430VTCDAVjcspPmUaKhPGtAtPAftIUFqY1obQYQuwmbg==" + }, "destroy": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.1.0.tgz", diff --git a/package.json b/package.json index 6df1abb2d..9af903698 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "co-body": "6.1.0", "cookie": "0.4.0", "debug": "^4.3.3", + "destr": "^1.1.1", "jsonwebtoken": "^8.5.1", "jwks-rsa": "^2.0.5", "libphonenumber-js": "^1.9.44", @@ -70,6 +71,7 @@ "glob": "7.1.7", "koa": "^2.13.3", "lambda-tester": "^4.0.1", + "loopback-datasource-juggler": "^4.26.0", "mocha": "6.1.4", "next": "11.1.3", "nock": "11.7.0", @@ -79,8 +81,7 @@ "react": "^17.0.2", "supertest": "4.0.2", "typedoc": "^0.22.5", - "typescript": "3.8.3", - "loopback-datasource-juggler": "^4.26.0" + "typescript": "3.8.3" }, "browser": { "fs": false From c6570641c78c0aa5de48593bed5c6c2265e3a444 Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Fri, 29 Apr 2022 22:36:16 +0200 Subject: [PATCH 02/13] added h3 type --- lib/ts/framework/types.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/ts/framework/types.ts b/lib/ts/framework/types.ts index 5707c65d5..505adc5e4 100644 --- a/lib/ts/framework/types.ts +++ b/lib/ts/framework/types.ts @@ -12,12 +12,12 @@ * License for the specific language governing permissions and limitations * under the License. */ -export type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda"; +export type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda" | "h3"; import { BaseRequest, BaseResponse } from "."; export let SchemaFramework = { type: "string", - enum: ["express", "fastify", "hapi", "loopback", "koa", "awsLambda"], + enum: ["express", "fastify", "hapi", "loopback", "koa", "awsLambda", "h3"], }; export interface Framework { From ad54ce33e63635b7d8e455576f33060541f0c56c Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Fri, 29 Apr 2022 22:36:57 +0200 Subject: [PATCH 03/13] qf --- lib/build/framework/types.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/build/framework/types.d.ts b/lib/build/framework/types.d.ts index f685b5e0a..8ff028750 100644 --- a/lib/build/framework/types.d.ts +++ b/lib/build/framework/types.d.ts @@ -1,5 +1,5 @@ // @ts-nocheck -export declare type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda"; +export declare type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda" | 'h3'; import { BaseRequest, BaseResponse } from "."; export declare let SchemaFramework: { type: string; From ca15711a8b19f43099105466fdc71128e57d61bc Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Sat, 30 Apr 2022 01:23:26 +0200 Subject: [PATCH 04/13] Creating sessions works --- framework/h3/index.d.ts | 3 + framework/h3/index.js | 6 + lib/build/constants.d.ts | 1 - lib/build/error.d.ts | 23 +- lib/build/framework/awsLambda/framework.d.ts | 24 +- lib/build/framework/awsLambda/framework.js | 193 ++--- lib/build/framework/awsLambda/index.d.ts | 5 +- lib/build/framework/constants.d.ts | 1 - lib/build/framework/express/framework.d.ts | 12 +- lib/build/framework/express/framework.js | 144 ++-- lib/build/framework/express/index.d.ts | 15 +- lib/build/framework/fastify/framework.d.ts | 28 +- lib/build/framework/fastify/framework.js | 110 +-- lib/build/framework/fastify/index.d.ts | 17 +- lib/build/framework/h3/framework.d.ts | 38 + lib/build/framework/h3/framework.js | 175 +++++ lib/build/framework/h3/index.d.ts | 6 + lib/build/framework/h3/index.js | 7 + lib/build/framework/h3/types.d.ts | 8 + lib/build/framework/h3/types.js | 2 + lib/build/framework/hapi/framework.d.ts | 12 +- lib/build/framework/hapi/framework.js | 136 ++-- lib/build/framework/hapi/index.d.ts | 1 - lib/build/framework/index.d.ts | 4 +- lib/build/framework/index.js | 3 + lib/build/framework/koa/framework.d.ts | 12 +- lib/build/framework/koa/framework.js | 101 +-- lib/build/framework/koa/index.d.ts | 3 +- lib/build/framework/loopback/framework.d.ts | 12 +- lib/build/framework/loopback/framework.js | 110 +-- lib/build/framework/loopback/index.d.ts | 1 - lib/build/framework/request.d.ts | 1 - lib/build/framework/response.d.ts | 12 +- lib/build/framework/types.d.ts | 3 +- lib/build/framework/types.js | 2 +- lib/build/framework/utils.d.ts | 48 +- lib/build/framework/utils.js | 120 +-- lib/build/index.d.ts | 5 +- lib/build/index.js | 8 +- lib/build/logger.d.ts | 1 - lib/build/logger.js | 6 +- lib/build/nextjs.d.ts | 7 +- lib/build/nextjs.js | 79 +- lib/build/normalisedURLDomain.d.ts | 1 - lib/build/normalisedURLDomain.js | 18 +- lib/build/normalisedURLPath.d.ts | 1 - lib/build/normalisedURLPath.js | 18 +- lib/build/processState.d.ts | 3 +- lib/build/processState.js | 86 +-- lib/build/querier.d.ts | 12 +- lib/build/querier.js | 374 ++++------ .../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 | 67 +- .../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 | 48 +- lib/build/recipe/emailpassword/api/utils.d.ts | 14 +- lib/build/recipe/emailpassword/api/utils.js | 43 +- lib/build/recipe/emailpassword/constants.d.ts | 1 - lib/build/recipe/emailpassword/error.d.ts | 27 +- lib/build/recipe/emailpassword/index.d.ts | 117 +-- lib/build/recipe/emailpassword/index.js | 44 +- .../emailpassword/passwordResetFunctions.d.ts | 5 +- .../emailpassword/passwordResetFunctions.js | 97 +-- lib/build/recipe/emailpassword/recipe.d.ts | 21 +- lib/build/recipe/emailpassword/recipe.js | 160 ++-- .../emailpassword/recipeImplementation.d.ts | 1 - .../emailpassword/recipeImplementation.js | 91 +-- lib/build/recipe/emailpassword/types.d.ts | 253 +++---- lib/build/recipe/emailpassword/utils.d.ts | 28 +- lib/build/recipe/emailpassword/utils.js | 217 ++---- .../emailverification/api/emailVerify.d.ts | 1 - .../emailverification/api/emailVerify.js | 46 +- .../api/generateEmailVerifyToken.d.ts | 6 +- .../api/generateEmailVerifyToken.js | 40 +- .../emailverification/api/implementation.d.ts | 1 - .../emailverification/api/implementation.js | 63 +- .../recipe/emailverification/constants.d.ts | 1 - .../emailVerificationFunctions.d.ts | 5 +- .../emailVerificationFunctions.js | 93 +-- lib/build/recipe/emailverification/error.d.ts | 6 +- lib/build/recipe/emailverification/index.d.ts | 50 +- lib/build/recipe/emailverification/index.js | 40 +- .../recipe/emailverification/recipe.d.ts | 9 +- lib/build/recipe/emailverification/recipe.js | 94 +-- .../recipeImplementation.d.ts | 1 - .../emailverification/recipeImplementation.js | 94 +-- lib/build/recipe/emailverification/types.d.ts | 102 ++- lib/build/recipe/emailverification/utils.d.ts | 7 +- lib/build/recipe/emailverification/utils.js | 22 +- lib/build/recipe/jwt/api/getJWKS.d.ts | 1 - lib/build/recipe/jwt/api/getJWKS.js | 40 +- 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/index.d.ts | 24 +- lib/build/recipe/jwt/index.js | 40 +- lib/build/recipe/jwt/recipe.d.ts | 9 +- 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 | 42 +- lib/build/recipe/jwt/utils.d.ts | 7 +- lib/build/recipe/jwt/utils.js | 13 +- .../api/getOpenIdDiscoveryConfiguration.d.ts | 6 +- .../api/getOpenIdDiscoveryConfiguration.js | 40 +- .../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/index.d.ts | 28 +- 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 | 64 +- lib/build/recipe/openid/utils.d.ts | 6 +- lib/build/recipe/openid/utils.js | 8 +- .../recipe/passwordless/api/consumeCode.d.ts | 1 - .../recipe/passwordless/api/consumeCode.js | 61 +- .../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 | 271 +++---- .../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/error.d.ts | 6 +- lib/build/recipe/passwordless/index.d.ts | 171 ++--- lib/build/recipe/passwordless/index.js | 52 +- lib/build/recipe/passwordless/recipe.d.ts | 45 +- lib/build/recipe/passwordless/recipe.js | 237 +++--- .../passwordless/recipeImplementation.d.ts | 1 - .../passwordless/recipeImplementation.js | 105 +-- lib/build/recipe/passwordless/types.d.ts | 502 ++++++------- lib/build/recipe/passwordless/utils.d.ts | 7 +- lib/build/recipe/passwordless/utils.js | 142 ++-- lib/build/recipe/session/accessToken.d.ts | 7 +- lib/build/recipe/session/accessToken.js | 52 +- .../recipe/session/api/implementation.d.ts | 1 - .../recipe/session/api/implementation.js | 52 +- lib/build/recipe/session/api/refresh.d.ts | 1 - lib/build/recipe/session/api/refresh.js | 40 +- lib/build/recipe/session/api/signout.d.ts | 1 - lib/build/recipe/session/api/signout.js | 40 +- lib/build/recipe/session/constants.d.ts | 1 - .../recipe/session/cookieAndHeaders.d.ts | 38 +- lib/build/recipe/session/cookieAndHeaders.js | 3 +- lib/build/recipe/session/error.d.ts | 40 +- lib/build/recipe/session/error.js | 13 +- .../recipe/session/faunadb/constants.d.ts | 1 - lib/build/recipe/session/faunadb/index.d.ts | 1 - .../session/faunadb/recipeImplementation.d.ts | 198 ++--- .../session/faunadb/recipeImplementation.js | 132 ++-- lib/build/recipe/session/faunadb/types.d.ts | 1 - .../recipe/session/framework/awsLambda.d.ts | 1 - .../recipe/session/framework/awsLambda.js | 74 +- .../recipe/session/framework/express.d.ts | 5 +- lib/build/recipe/session/framework/express.js | 71 +- .../recipe/session/framework/fastify.d.ts | 14 +- lib/build/recipe/session/framework/fastify.js | 66 +- lib/build/recipe/session/framework/h3.d.ts | 5 + lib/build/recipe/session/framework/h3.js | 35 + lib/build/recipe/session/framework/hapi.d.ts | 5 +- lib/build/recipe/session/framework/hapi.js | 55 +- lib/build/recipe/session/framework/index.d.ts | 4 +- lib/build/recipe/session/framework/index.js | 3 + lib/build/recipe/session/framework/koa.d.ts | 5 +- lib/build/recipe/session/framework/koa.js | 55 +- .../recipe/session/framework/loopback.d.ts | 1 - .../recipe/session/framework/loopback.js | 57 +- lib/build/recipe/session/index.d.ts | 76 +- lib/build/recipe/session/index.js | 24 +- lib/build/recipe/session/jwt.d.ts | 10 +- lib/build/recipe/session/jwt.js | 32 +- lib/build/recipe/session/recipe.d.ts | 15 +- lib/build/recipe/session/recipe.js | 189 ++--- .../recipe/session/recipeImplementation.d.ts | 9 +- .../recipe/session/recipeImplementation.js | 242 ++----- lib/build/recipe/session/sessionClass.d.ts | 10 +- lib/build/recipe/session/sessionClass.js | 213 +++--- .../recipe/session/sessionFunctions.d.ts | 29 +- lib/build/recipe/session/sessionFunctions.js | 173 ++--- lib/build/recipe/session/types.d.ts | 148 ++-- lib/build/recipe/session/utils.d.ts | 35 +- lib/build/recipe/session/utils.js | 120 +-- .../recipe/session/with-jwt/constants.d.ts | 1 - lib/build/recipe/session/with-jwt/index.d.ts | 1 - .../with-jwt/recipeImplementation.d.ts | 7 +- .../session/with-jwt/recipeImplementation.js | 66 +- .../recipe/session/with-jwt/sessionClass.d.ts | 1 - .../recipe/session/with-jwt/sessionClass.js | 107 ++- lib/build/recipe/session/with-jwt/utils.d.ts | 10 +- lib/build/recipe/session/with-jwt/utils.js | 65 +- .../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 | 94 +-- 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/error.d.ts | 6 +- lib/build/recipe/thirdparty/index.d.ts | 78 +- lib/build/recipe/thirdparty/index.js | 40 +- .../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/okta.d.ts | 1 - .../recipe/thirdparty/providers/utils.d.ts | 7 +- .../recipe/thirdparty/providers/utils.js | 43 +- lib/build/recipe/thirdparty/recipe.d.ts | 21 +- lib/build/recipe/thirdparty/recipe.js | 139 ++-- .../thirdparty/recipeImplementation.d.ts | 1 - .../recipe/thirdparty/recipeImplementation.js | 59 +- lib/build/recipe/thirdparty/types.d.ts | 144 ++-- lib/build/recipe/thirdparty/utils.d.ts | 13 +- lib/build/recipe/thirdparty/utils.js | 147 ++-- .../api/emailPasswordAPIImplementation.d.ts | 1 - .../api/emailPasswordAPIImplementation.js | 23 +- .../api/implementation.d.ts | 1 - .../api/implementation.js | 40 +- .../api/thirdPartyAPIImplementation.d.ts | 1 - .../api/thirdPartyAPIImplementation.js | 84 +-- .../recipe/thirdpartyemailpassword/error.d.ts | 6 +- .../recipe/thirdpartyemailpassword/index.d.ts | 153 ++-- .../recipe/thirdpartyemailpassword/index.js | 48 +- .../thirdpartyemailpassword/recipe.d.ts | 31 +- .../recipe/thirdpartyemailpassword/recipe.js | 201 ++--- .../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 | 353 ++++----- .../recipe/thirdpartyemailpassword/utils.d.ts | 7 +- .../recipe/thirdpartyemailpassword/utils.js | 141 +--- .../api/implementation.d.ts | 1 - .../api/implementation.js | 40 +- .../api/passwordlessAPIImplementation.d.ts | 1 - .../api/passwordlessAPIImplementation.js | 19 +- .../api/thirdPartyAPIImplementation.d.ts | 1 - .../api/thirdPartyAPIImplementation.js | 84 +-- .../recipe/thirdpartypasswordless/error.d.ts | 6 +- .../recipe/thirdpartypasswordless/index.d.ts | 366 ++++------ .../recipe/thirdpartypasswordless/index.js | 92 +-- .../recipe/thirdpartypasswordless/recipe.d.ts | 31 +- .../recipe/thirdpartypasswordless/recipe.js | 302 +++----- .../recipeImplementation/index.d.ts | 1 - .../recipeImplementation/index.js | 115 +-- .../passwordlessRecipeImplementation.d.ts | 1 - .../passwordlessRecipeImplementation.js | 40 +- .../thirdPartyRecipeImplementation.d.ts | 1 - .../thirdPartyRecipeImplementation.js | 40 +- .../recipe/thirdpartypasswordless/types.d.ts | 684 ++++++++---------- .../recipe/thirdpartypasswordless/utils.d.ts | 7 +- .../recipe/thirdpartypasswordless/utils.js | 139 ++-- lib/build/recipe/usermetadata/index.d.ts | 17 +- lib/build/recipe/usermetadata/index.js | 40 +- lib/build/recipe/usermetadata/recipe.d.ts | 9 +- lib/build/recipe/usermetadata/recipe.js | 54 +- .../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 | 8 +- lib/build/recipeModule.d.ts | 9 +- lib/build/recipeModule.js | 6 +- lib/build/supertokens.d.ts | 10 +- lib/build/supertokens.js | 403 +++++------ lib/build/types.d.ts | 1 - lib/build/utils.d.ts | 1 - lib/build/utils.js | 29 +- lib/build/version.d.ts | 1 - lib/ts/framework/h3/framework.ts | 51 +- lib/ts/framework/h3/types.ts | 9 + lib/ts/framework/index.ts | 3 + lib/ts/framework/utils.ts | 18 - lib/ts/recipe/session/framework/index.ts | 3 + package-lock.json | 53 ++ package.json | 3 +- 303 files changed, 5169 insertions(+), 9433 deletions(-) create mode 100644 framework/h3/index.d.ts create mode 100644 framework/h3/index.js create mode 100644 lib/build/framework/h3/framework.d.ts create mode 100644 lib/build/framework/h3/framework.js create mode 100644 lib/build/framework/h3/index.d.ts create mode 100644 lib/build/framework/h3/index.js create mode 100644 lib/build/framework/h3/types.d.ts create mode 100644 lib/build/framework/h3/types.js create mode 100644 lib/build/recipe/session/framework/h3.d.ts create mode 100644 lib/build/recipe/session/framework/h3.js create mode 100644 lib/ts/framework/h3/types.ts diff --git a/framework/h3/index.d.ts b/framework/h3/index.d.ts new file mode 100644 index 000000000..83866c9bf --- /dev/null +++ b/framework/h3/index.d.ts @@ -0,0 +1,3 @@ +export * from "../../lib/build/framework/h3"; +import * as _default from "../../lib/build/framework/h3"; +export default _default; diff --git a/framework/h3/index.js b/framework/h3/index.js new file mode 100644 index 000000000..c5d36868b --- /dev/null +++ b/framework/h3/index.js @@ -0,0 +1,6 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +exports.__esModule = true; +__export(require("../../lib/build/framework/h3")); 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/error.d.ts b/lib/build/error.d.ts index 93cb2b9e7..eb4b12907 100644 --- a/lib/build/error.d.ts +++ b/lib/build/error.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck export default class SuperTokensError { private static errMagic; static BAD_INPUT_ERROR: "BAD_INPUT_ERROR"; @@ -7,18 +6,14 @@ export default class SuperTokensError { 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..a0e58c33e 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,13 @@ 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; + 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 0ecc14e2f..bdf0f3afc 100644 --- a/lib/build/framework/awsLambda/framework.js +++ b/lib/build/framework/awsLambda/framework.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 request_1 = require("../request"); @@ -41,20 +19,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 +43,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 +66,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; }; @@ -147,16 +120,7 @@ class AWSResponse extends response_1.BaseResponse { }); }; 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); }; /** @@ -204,7 +168,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 +179,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; } }; @@ -255,37 +218,37 @@ 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`, - }); + 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.AWSWrapper = { middleware: exports.middleware, 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/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/express/framework.d.ts b/lib/build/framework/express/framework.d.ts index ba1865f51..474a180d8 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,7 @@ 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; + 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 a40def3d3..25a1b62a5 100644 --- a/lib/build/framework/express/framework.js +++ b/lib/build/framework/express/framework.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 request_1 = require("../request"); @@ -53,14 +31,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.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -71,14 +48,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); }; @@ -111,17 +87,7 @@ class ExpressResponse extends response_1.BaseResponse { utils_2.setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; 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 @@ -143,42 +109,44 @@ 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(); + 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); } } - }); + else { + 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); - } - }); + 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.ExpressWrapper = { middleware: exports.middleware, 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/fastify/framework.d.ts b/lib/build/framework/fastify/framework.d.ts index a57cc3efa..d9fd306da 100644 --- a/lib/build/framework/fastify/framework.d.ts +++ b/lib/build/framework/fastify/framework.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck /// import type { FastifyRequest as OriginalFastifyRequest, FastifyReply, FastifyPluginCallback } from "fastify"; import type { HTTPMethod } from "../../types"; @@ -23,16 +22,7 @@ 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; + 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 3dbce7cf5..c41b0a914 100644 --- a/lib/build/framework/fastify/framework.js +++ b/lib/build/framework/fastify/framework.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 request_1 = require("../request"); @@ -54,10 +32,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 +45,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 +81,21 @@ 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.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); let prev = this.response.getHeader(constants_1.COOKIE_HEADER); let cookieValueToSetInHeader = utils_2.getCookieValueToSetInHeader(prev, serialisedCookie, key); this.response.header(constants_1.COOKIE_HEADER, cookieValueToSetInHeader); @@ -154,29 +124,27 @@ 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); - }); + 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.FastifyWrapper = { plugin, 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/h3/framework.d.ts b/lib/build/framework/h3/framework.d.ts new file mode 100644 index 000000000..a010cba3e --- /dev/null +++ b/lib/build/framework/h3/framework.d.ts @@ -0,0 +1,38 @@ +/// +import type { IncomingMessage, ServerResponse } from 'http'; +import { SessionContainerInterface } from '../../recipe/session/types'; +import { BaseRequest } from "../request"; +import { BaseResponse } from '../response'; +import { Framework } from '../types'; +import { Response } from './types'; +export declare class H3Request extends BaseRequest { + private request; + constructor(request: IncomingMessage); + getCookieValue: (key: string) => string | undefined; + getFormData: () => Promise; + getMethod: () => import("../../types").HTTPMethod; + getHeaderValue: (key: string) => string | undefined; + getOriginalURL: () => string; + getKeyValueFromQuery: (key: string) => string | undefined; + getJSONBody: () => Promise; +} +export declare class H3ResponseTokens extends BaseResponse { + private response; + private statusCode; + 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; + setStatusCode: (statusCode: number) => void; + sendJSONResponse: (content: any) => void; +} +export interface SessionRequest extends IncomingMessage { + session?: SessionContainerInterface; +} +export declare const middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; +export declare const errorHandler: () => (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; +export interface H3Framework extends Framework { + middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise; + errorHandler: () => (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise; +} +export declare const H3Wrapper: H3Framework; diff --git a/lib/build/framework/h3/framework.js b/lib/build/framework/h3/framework.js new file mode 100644 index 000000000..a7fe768fe --- /dev/null +++ b/lib/build/framework/h3/framework.js @@ -0,0 +1,175 @@ +"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 supertokens_1 = require("../../supertokens"); +const utils_1 = require("../../utils"); +const request_1 = require("../request"); +const response_1 = require("../response"); +const utils_2 = require("../utils"); +const defer = typeof setImmediate !== 'undefined' ? setImmediate : (fn) => fn(); +class H3Request extends request_1.BaseRequest { + constructor(request) { + super(); + this.getCookieValue = (key) => { + return utils_2.getHeaderValueFromIncomingMessage(this.request, key); + }; + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + return utils_2.useRawBody(this.request); + }); + this.getMethod = () => { + return utils_1.normaliseHttpMethod(this.request.method); + }; + this.getHeaderValue = (key) => { + return utils_2.getHeaderValueFromIncomingMessage(this.request, key); + }; + this.getOriginalURL = () => { + return this.request.url; + }; + this.getKeyValueFromQuery = (key) => { + let path = this.request.url || "/"; + const queryIndex = path.lastIndexOf('?'); + if (queryIndex > -1) { + const queryArray = path.substring(queryIndex + 1, path.length).split('&'); + const index = queryArray.findIndex(el => el.includes(key)); + if (index === -1) + return undefined; + const value = queryArray[index].split('=')[1]; + if (value === undefined || typeof value !== 'string') { + return undefined; + } + return value; + } + else { + return undefined; + } + }; + this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { + return yield utils_2.useBody(this.request); + }); + this.original = request; + this.request = request; + } + ; +} +exports.H3Request = H3Request; +class H3ResponseTokens extends response_1.BaseResponse { + constructor(response) { + super(); + this.sendHTMLResponse = (html) => { + if (this.response.res.writable) { + this.response.res.setHeader('Content-Type', 'text/html'); + this.response.res.statusCode = this.statusCode; + new Promise((resolve) => { + defer(() => { + this.response.res.end(html); + resolve(undefined); + }); + }); + } + }; + this.setHeader = (key, value, allowDuplicateKey) => { + try { + console.log(this.response.res.setHeader); + const allheaders = this.response.res.getHeaders(); + let existingValue = allheaders[key]; + // we have the this.response.header for compatibility with nextJS + if (existingValue === undefined) { + this.response.res.setHeader(key, value); + } + else if (allowDuplicateKey) { + this.response.res.setHeader(key, existingValue + ", " + value); + } + else { + // we overwrite the current one with the new one + this.response.res.setHeader(key, value); + } + } + catch (err) { + console.log(err); + throw new Error("Error while setting header with key: " + key + " and value: " + value); + } + }; + this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { + utils_2.setCookieForServerResponse(this.response.res, key, value, domain, secure, httpOnly, expires, path, sameSite); + }; + this.setStatusCode = (statusCode) => { + if (this.response.res.writable) { + this.statusCode = statusCode; + } + }; + this.sendJSONResponse = (content) => { + if (this.response.res.writable) { + this.response.res.setHeader('Content-Type', 'application/json'); + this.response.res.statusCode = this.statusCode; + new Promise((resolve) => { + defer(() => { + this.response.res.end(content); + resolve(undefined); + }); + }); + } + }; + this.original = response; + this.response = response; + this.statusCode = 200; + } +} +exports.H3ResponseTokens = H3ResponseTokens; +exports.middlware = () => { + return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { + let supertokens; + const request = new H3Request(req); + const response = new H3ResponseTokens({ res: 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 (_a) { + next(err); + } + } + else { + 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 H3Request(req); + let response = new H3ResponseTokens({ res: res }); + try { + yield supertokens.errorHandler(err, request, response); + } + catch (err) { + return next(err); + } + }); +}; +exports.H3Wrapper = { + middlware: exports.middlware, + errorHandler: exports.errorHandler, + wrapRequest: (unwrapped) => { + return new H3Request(unwrapped); + }, + wrapResponse: (unwrapped) => { + return new H3ResponseTokens(unwrapped); + } +}; diff --git a/lib/build/framework/h3/index.d.ts b/lib/build/framework/h3/index.d.ts new file mode 100644 index 000000000..bc1c5bec3 --- /dev/null +++ b/lib/build/framework/h3/index.d.ts @@ -0,0 +1,6 @@ +/// +export type { SessionRequest } from './framework'; +export declare const middleware: () => (req: import("http").IncomingMessage, res: import("http").ServerResponse, next: (err?: Error | undefined) => any) => Promise; +export declare const errorHandler: () => (err: any, req: import("http").IncomingMessage, res: import("http").ServerResponse, next: (err?: Error | undefined) => any) => Promise; +export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; +export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/h3/index.js b/lib/build/framework/h3/index.js new file mode 100644 index 000000000..fa25d0f02 --- /dev/null +++ b/lib/build/framework/h3/index.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const framework_1 = require("./framework"); +exports.middleware = framework_1.H3Wrapper.middlware; +exports.errorHandler = framework_1.H3Wrapper.errorHandler; +exports.wrapRequest = framework_1.H3Wrapper.wrapRequest; +exports.wrapResponse = framework_1.H3Wrapper.wrapResponse; diff --git a/lib/build/framework/h3/types.d.ts b/lib/build/framework/h3/types.d.ts new file mode 100644 index 000000000..39d77e223 --- /dev/null +++ b/lib/build/framework/h3/types.d.ts @@ -0,0 +1,8 @@ +/// +import { ServerResponse, IncomingMessage } from 'http'; +export interface Response { + res: ServerResponse; +} +export interface Request { + req: IncomingMessage; +} diff --git a/lib/build/framework/h3/types.js b/lib/build/framework/h3/types.js new file mode 100644 index 000000000..c8ad2e549 --- /dev/null +++ b/lib/build/framework/h3/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/lib/build/framework/hapi/framework.d.ts b/lib/build/framework/hapi/framework.d.ts index a49deac96..9fb0d6ace 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"; @@ -28,16 +27,7 @@ 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; + 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 5c3be72f4..271d5e3b1 100644 --- a/lib/build/framework/hapi/framework.js +++ b/lib/build/framework/hapi/framework.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 request_1 = require("../request"); @@ -53,10 +31,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 +44,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,7 +78,8 @@ 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); } }; @@ -117,7 +94,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,49 +137,47 @@ 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; - 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; + 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 }); 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/index.d.ts b/lib/build/framework/index.d.ts index 8fd8891ce..cee83d482 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"; @@ -7,6 +6,7 @@ import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; +import * as h3Framework from './h3'; declare const _default: { express: typeof expressFramework; fastify: typeof fastifyFramework; @@ -14,6 +14,7 @@ declare const _default: { loopback: typeof loopbackFramework; koa: typeof koaFramework; awsLambda: typeof awsLambdaFramework; + h3: typeof h3Framework; }; export default _default; export declare let express: typeof expressFramework; @@ -22,3 +23,4 @@ export declare let hapi: typeof hapiFramework; export declare let loopback: typeof loopbackFramework; export declare let koa: typeof koaFramework; export declare let awsLambda: typeof awsLambdaFramework; +export declare let h3: typeof h3Framework; diff --git a/lib/build/framework/index.js b/lib/build/framework/index.js index de9aa84e2..e13034290 100644 --- a/lib/build/framework/index.js +++ b/lib/build/framework/index.js @@ -24,6 +24,7 @@ const hapiFramework = require("./hapi"); const loopbackFramework = require("./loopback"); const koaFramework = require("./koa"); const awsLambdaFramework = require("./awsLambda"); +const h3Framework = require("./h3"); exports.default = { express: expressFramework, fastify: fastifyFramework, @@ -31,6 +32,7 @@ exports.default = { loopback: loopbackFramework, koa: koaFramework, awsLambda: awsLambdaFramework, + h3: h3Framework }; exports.express = expressFramework; exports.fastify = fastifyFramework; @@ -38,3 +40,4 @@ exports.hapi = hapiFramework; exports.loopback = loopbackFramework; exports.koa = koaFramework; exports.awsLambda = awsLambdaFramework; +exports.h3 = h3Framework; diff --git a/lib/build/framework/koa/framework.d.ts b/lib/build/framework/koa/framework.d.ts index 36fa51dec..1a4cefe86 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,7 @@ 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; + 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..643e2cfa6 100644 --- a/lib/build/framework/koa/framework.js +++ b/lib/build/framework/koa/framework.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 request_1 = require("../request"); @@ -54,13 +32,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 +48,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,13 +107,16 @@ 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); } }; @@ -172,20 +151,20 @@ 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); + 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.KoaWrapper = { middleware: exports.middleware, diff --git a/lib/build/framework/koa/index.d.ts b/lib/build/framework/koa/index.d.ts index 1d6395964..3e440bb7a 100644 --- a/lib/build/framework/koa/index.d.ts +++ b/lib/build/framework/koa/index.d.ts @@ -1,4 +1,5 @@ -// @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 ae474aa56..584720d18 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,7 @@ 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; + 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 be04274a0..9ff8588c9 100644 --- a/lib/build/framework/loopback/framework.js +++ b/lib/build/framework/loopback/framework.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 request_1 = require("../request"); @@ -53,14 +31,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.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -71,14 +48,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); }; @@ -111,17 +87,7 @@ class LoopbackResponse extends response_1.BaseResponse { utils_2.setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; 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 +105,21 @@ 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); +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); + } +}); 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/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/response.d.ts b/lib/build/framework/response.d.ts index f09730a92..33e0716fb 100644 --- a/lib/build/framework/response.d.ts +++ b/lib/build/framework/response.d.ts @@ -1,19 +1,9 @@ -// @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 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/types.d.ts b/lib/build/framework/types.d.ts index 8ff028750..954d4fcc9 100644 --- a/lib/build/framework/types.d.ts +++ b/lib/build/framework/types.d.ts @@ -1,5 +1,4 @@ -// @ts-nocheck -export declare type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda" | 'h3'; +export declare type TypeFramework = "express" | "fastify" | "hapi" | "loopback" | "koa" | "awsLambda" | "h3"; import { BaseRequest, BaseResponse } from "."; export declare let SchemaFramework: { type: string; diff --git a/lib/build/framework/types.js b/lib/build/framework/types.js index e3e7797ed..a635dfe9f 100644 --- a/lib/build/framework/types.js +++ b/lib/build/framework/types.js @@ -2,5 +2,5 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.SchemaFramework = { type: "string", - enum: ["express", "fastify", "hapi", "loopback", "koa", "awsLambda"], + enum: ["express", "fastify", "hapi", "loopback", "koa", "awsLambda", "h3"], }; diff --git a/lib/build/framework/utils.d.ts b/lib/build/framework/utils.d.ts index 3356de62b..f09253455 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,19 +8,11 @@ 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 -): Promise; -export declare function assertForDataBodyParserHasBeenUsedForExpressLikeRequest( - request: Request | NextApiRequest -): Promise; -export declare function setHeaderForExpressLikeResponse( - res: Response, - key: string, - value: string, - allowDuplicateKey: boolean -): void; +export declare function assertThatBodyParserHasBeenUsedForExpressLikeRequest(method: HTTPMethod, request: Request | NextApiRequest): Promise; +export declare function assertForDataBodyParserHasBeenUsedForExpressLikeRequest(request: Request | NextApiRequest): Promise; +export declare function setHeaderForExpressLikeResponse(res: Response, key: string, value: string, allowDuplicateKey: boolean): void; +export declare function useRawBody(req: IncomingMessage): Promise; +export declare function useBody(req: IncomingMessage): Promise; /** * * @param res @@ -33,29 +24,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 3547b9f1e..e41c8ad10 100644 --- a/lib/build/framework/utils.js +++ b/lib/build/framework/utils.js @@ -13,43 +13,22 @@ * 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 cookie_1 = require("cookie"); const body_parser_1 = require("body-parser"); const http_1 = require("http"); const error_1 = require("../error"); const constants_1 = require("./constants"); +const destr_1 = require("destr"); function getCookieValueFromHeaders(headers, key) { if (headers === undefined || headers === null) { return undefined; @@ -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 thr 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) => { @@ -173,7 +154,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)); @@ -209,28 +191,66 @@ 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); } } exports.setHeaderForExpressLikeResponse = setHeaderForExpressLikeResponse; +function useRawBody(req) { + const RawBodySymbol = Symbol('h3RawBody'); + if (RawBodySymbol in this.request) { + const promise = Promise.resolve(req[RawBodySymbol]); + return promise.then(buff => buff.toString('utf-8')); + } + if ('body' in req) { + return Promise.resolve(this.request.body); + } + const promise = req[RawBodySymbol] = new Promise((resolve, reject) => { + const bodyData = []; + req + .on('error', (err) => reject(err)) + .on('data', (chunk) => { bodyData.push(chunk); }) + .on('end', () => { resolve(Buffer.concat(bodyData)); }); + }); + return promise.then(buff => buff.toString('utf-8')); +} +exports.useRawBody = useRawBody; +function useBody(req) { + return __awaiter(this, void 0, void 0, function* () { + const ParsedBodySymbol = Symbol('h3RawBody'); + if (ParsedBodySymbol in req) { + return req[ParsedBodySymbol]; + } + const body = yield useRawBody(req); + const json = destr_1.default(body); + req[ParsedBodySymbol] = json; + return json; + }); +} +exports.useBody = useBody; /** * * @param res @@ -243,12 +263,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; /** @@ -280,7 +295,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 40c6340dd..a1c3e9853 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"; export default class SuperTokensWrapper { @@ -28,9 +27,7 @@ export default class SuperTokensWrapper { }[]; nextPaginationToken?: string; }>; - static deleteUser( - userId: string - ): Promise<{ + static deleteUser(userId: string): Promise<{ status: "OK"; }>; } diff --git a/lib/build/index.js b/lib/build/index.js index dd18aae30..ca292fa57 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -25,14 +25,10 @@ class SuperTokensWrapper { return supertokens_1.default.getInstanceOrThrowError().getUserCount(includeRecipeIds); } static getUsersOldestFirst(input) { - return supertokens_1.default - .getInstanceOrThrowError() - .getUsers(Object.assign({ timeJoinedOrder: "ASC" }, input)); + return supertokens_1.default.getInstanceOrThrowError().getUsers(Object.assign({ timeJoinedOrder: "ASC" }, input)); } static getUsersNewestFirst(input) { - return supertokens_1.default - .getInstanceOrThrowError() - .getUsers(Object.assign({ timeJoinedOrder: "DESC" }, input)); + return supertokens_1.default.getInstanceOrThrowError().getUsers(Object.assign({ timeJoinedOrder: "DESC" }, input)); } static deleteUser(userId) { return supertokens_1.default.getInstanceOrThrowError().deleteUser({ 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..92d2097ef 100644 --- a/lib/build/logger.js +++ b/lib/build/logger.js @@ -23,11 +23,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 d3ec960fe..2a5cf1897 100644 --- a/lib/build/nextjs.js +++ b/lib/build/nextjs.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. * @@ -64,27 +42,26 @@ 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* () { - 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* () { + 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/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..dd66e044d 100644 --- a/lib/build/processState.js +++ b/lib/build/processState.js @@ -13,46 +13,23 @@ * 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 }); 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 +49,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 a22c95c25..963f9fed7 100644 --- a/lib/build/querier.js +++ b/lib/build/querier.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. * @@ -54,44 +32,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 +64,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 }; - 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: "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 }; + 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: "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/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 b8421e952..f530d64e3 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 0bf07146d..c085edcda 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"); @@ -54,10 +32,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, userContext: {} }); utils_1.send200Response(options.res, result); return true; 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 53e7fb1fb..d00409a58 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.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 session_1 = require("../../session"); function getAPIImplementation() { return { - 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 { @@ -43,7 +21,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 }); @@ -61,8 +39,7 @@ function getAPIImplementation() { status: "OK", }; } - let passwordResetLink = - (yield options.config.resetPasswordUsingTokenFeature.getResetPasswordURL(user, userContext)) + + let passwordResetLink = (yield options.config.resetPasswordUsingTokenFeature.getResetPasswordURL(user, userContext)) + "?token=" + response.token + "&rid=" + @@ -71,22 +48,20 @@ function getAPIImplementation() { if (!options.isInServerlessEnv) { options.config.resetPasswordUsingTokenFeature .createAndSendCustomEmail(user, passwordResetLink, userContext) - .catch((_) => {}); - } else { + .catch((_) => { }); + } + else { // see https://github.com/supertokens/supertokens-node/pull/135 - yield options.config.resetPasswordUsingTokenFeature.createAndSendCustomEmail( - user, - passwordResetLink, - userContext - ); + yield options.config.resetPasswordUsingTokenFeature.createAndSendCustomEmail(user, passwordResetLink, userContext); } - } catch (_) {} + } + catch (_) { } return { status: "OK", }; }); }, - 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({ @@ -97,7 +72,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; @@ -114,7 +89,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; 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 8b446c4d5..59fa1b178 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"); @@ -55,10 +33,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({ @@ -73,14 +48,11 @@ function passwordReset(apiImplementation, options) { }); } let result = yield apiImplementation.passwordResetPOST({ formFields, token, options, userContext: {} }); - 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 760cf1971..131e0ab0d 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"); @@ -54,17 +32,15 @@ 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, userContext: {} }); if (result.status === "OK") { utils_1.send200Response(options.res, { 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 e5e3e2f72..2561afee9 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"); @@ -55,17 +33,15 @@ 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, userContext: {} }); if (result.status === "OK") { utils_1.send200Response(options.res, { status: "OK", user: result.user, }); - } 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..eb3160e10 100644 --- a/lib/build/recipe/emailpassword/api/utils.js +++ b/lib/build/recipe/emailpassword/api/utils.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 constants_1 = require("../constants"); @@ -91,7 +69,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/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 aa7589815..91fdc950b 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -1,63 +1,35 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIOptions, APIInterface } 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; - static createResetPasswordToken( - userId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "UNKNOWN_USER_ID_ERROR"; - } - >; - static resetPasswordUsingToken( - token: string, - newPassword: string, - userContext?: any - ): Promise< - | { - status: "OK"; - userId?: string | undefined; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + static createResetPasswordToken(userId: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "UNKNOWN_USER_ID_ERROR"; + }>; + static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ + status: "OK"; + userId?: string | undefined; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; static updateEmailOrPassword(input: { userId: string; email?: string; @@ -66,39 +38,20 @@ export default class Wrapper { }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; }>; - static createEmailVerificationToken( - userId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - } - >; - static verifyEmailUsingToken( - token: string, - userContext?: any - ): Promise< - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - | User - | undefined - >; + static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + }>; + static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } | User | undefined>; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens( - userId: string, - userContext?: any - ): Promise<{ + static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ status: "OK"; }>; - static unverifyEmail( - userId: string, - userContext?: any - ): Promise<{ + static unverifyEmail(userId: string, userContext?: any): Promise<{ status: "OK"; }>; } diff --git a/lib/build/recipe/emailpassword/index.js b/lib/build/recipe/emailpassword/index.js index 40c5c9494..2b2cb30e2 100644 --- a/lib/build/recipe/emailpassword/index.js +++ b/lib/build/recipe/emailpassword/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); @@ -88,9 +66,7 @@ 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 createEmailVerificationToken(userId, userContext) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index 43f375d8a..755b16f17 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; export declare function getResetPasswordURL(appInfo: NormalisedAppinfo): (_: User) => Promise; -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 69b6ec934..198e4c31a 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.js +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.js @@ -13,72 +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 }); const axios_1 = require("axios"); function getResetPasswordURL(appInfo) { - return (_) => - __awaiter(this, void 0, void 0, function* () { - // according to https://github.com/supertokens/supertokens-auth-react/issues/6 - return ( - appInfo.websiteDomain.getAsStringDangerous() + - appInfo.websiteBasePath.getAsStringDangerous() + - "/reset-password" - ); - }); + return (_) => __awaiter(this, void 0, void 0, function* () { + // according to https://github.com/supertokens/supertokens-auth-react/issues/6 + return (appInfo.websiteDomain.getAsStringDangerous() + + appInfo.websiteBasePath.getAsStringDangerous() + + "/reset-password"); + }); } exports.getResetPasswordURL = getResetPasswordURL; 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, - }, - }); - } catch (ignored) {} - }); + 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, + }, + }); + } + catch (ignored) { } + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; diff --git a/lib/build/recipe/emailpassword/recipe.d.ts b/lib/build/recipe/emailpassword/recipe.d.ts index 2e1355acd..f226e9b93 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, RecipeListFunction, HTTPMethod } from "../../types"; @@ -14,26 +13,14 @@ export default class Recipe extends RecipeModule { recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; isInServerlessEnv: boolean; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput | undefined, - recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput | undefined, recipes: { + emailVerificationInstance: EmailVerificationRecipe | 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 46308befd..bbd6e8bde 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"); @@ -81,9 +59,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, }, @@ -102,79 +78,74 @@ class Recipe extends recipeModule_1.default { ...this.emailVerificationRecipe.getAPIsHandled(), ]; }; - 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, - emailVerificationRecipeImplementation: this.emailVerificationRecipe.recipeInterfaceImpl, - req, - res, - }; - 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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + 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, + emailVerificationRecipeImplementation: this.emailVerificationRecipe.recipeInterfaceImpl, + req, + res, + }; + 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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + } + }); + 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.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 { - return yield this.emailVerificationRecipe.handleError(err, request, response); + else { + throw err; } - }); + } + else { + return yield this.emailVerificationRecipe.handleError(err, request, response); + } + }); this.getAllCORSHeaders = () => { return [...this.emailVerificationRecipe.getAllCORSHeaders()]; }; this.isErrorFromThisRecipe = (err) => { - return ( - error_1.default.isErrorFromSuperTokens(err) && - (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err)) - ); + return (error_1.default.isErrorFromSuperTokens(err) && + (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err))); }; // 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) { - throw Error("Unknown User ID provided"); - } - return userInfo.email; - }); + this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw Error("Unknown User ID provided"); + } + return userInfo.email; + }); this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default( - recipeId, - appInfo, - isInServerlessEnv, - Object.assign({}, this.config.emailVerificationFeature) - ); + : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign({}, this.config.emailVerificationFeature)); { - 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(); } { @@ -195,7 +166,8 @@ class Recipe extends recipeModule_1.default { emailVerificationInstance: 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 fce33bd12..cadefa2af 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -1,8 +1,4 @@ -// @ts-nocheck -import { - RecipeInterface as EmailVerificationRecipeInterface, - APIInterface as EmailVerificationAPIInterface, -} from "../emailverification"; +import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; @@ -13,20 +9,11 @@ export declare type TypeNormalisedInput = { resetPasswordUsingTokenFeature: TypeNormalisedInputResetPasswordUsingTokenFeature; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; @@ -77,20 +64,11 @@ export declare type TypeInput = { resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; emailVerificationFeature?: TypeInputEmailVerificationFeature; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; @@ -99,59 +77,53 @@ 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; createResetPasswordToken(input: { userId: 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"; - /** - * The id of the user whose password was reset. - * Defined for Core versions 3.9 or later - */ - userId?: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + /** + * The id of the user whose password was reset. + * Defined for Core versions 3.9 or later + */ + userId?: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; updateEmailOrPassword(input: { userId: string; email?: string; @@ -171,83 +143,64 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - emailExistsGET: - | undefined - | ((input: { - email: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); - generatePasswordResetTokenPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - }>); - passwordResetPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - userId?: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >); - signInPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - >); - signUpPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - >); + emailExistsGET: undefined | ((input: { + email: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); + generatePasswordResetTokenPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + }>); + passwordResetPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + userId?: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>); + signInPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + session: SessionContainerInterface; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + }>); + signUpPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + session: SessionContainerInterface; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + }>); }; diff --git a/lib/build/recipe/emailpassword/utils.d.ts b/lib/build/recipe/emailpassword/utils.d.ts index 590ced94b..361dbc878 100644 --- a/lib/build/recipe/emailpassword/utils.d.ts +++ b/lib/build/recipe/emailpassword/utils.d.ts @@ -1,29 +1,9 @@ -// @ts-nocheck import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput, NormalisedFormField, TypeInputFormField } from "./types"; import { NormalisedAppinfo } from "../../types"; import { TypeInput as TypeNormalisedInputEmailVerification } from "../emailverification/types"; -export declare function validateAndNormaliseUserInput( - recipeInstance: Recipe, - appInfo: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInput; -export declare function validateAndNormaliseEmailVerificationConfig( - recipeInstance: Recipe, - _: NormalisedAppinfo, - config?: TypeInput -): TypeNormalisedInputEmailVerification; +export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; +export declare function validateAndNormaliseEmailVerificationConfig(recipeInstance: Recipe, _: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInputEmailVerification; 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 2be253382..631290900 100644 --- a/lib/build/recipe/emailpassword/utils.js +++ b/lib/build/recipe/emailpassword/utils.js @@ -13,61 +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 }); const constants_1 = require("./constants"); const passwordResetFunctions_1 = require("./passwordResetFunctions"); 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( - recipeInstance, - appInfo, - signUpFeature, - config === undefined ? undefined : config.resetPasswordUsingTokenFeature - ); + let resetPasswordUsingTokenFeature = validateAndNormaliseResetPasswordUsingTokenConfig(recipeInstance, appInfo, signUpFeature, config === undefined ? undefined : config.resetPasswordUsingTokenFeature); let emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, appInfo, 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 { signUpFeature, signInFeature, @@ -81,64 +44,35 @@ function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserId, - override: - (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 - ? void 0 - : _a.emailVerificationFeature, - createAndSendCustomEmail: - ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _b === void 0 - ? void 0 - : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_d = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _d === void 0 - ? void 0 - : _d.createAndSendCustomEmail) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail( - userInfo, - link, - userContext - ); - }), - getEmailVerificationURL: - ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _c === void 0 - ? void 0 - : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_e = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _e === void 0 - ? void 0 - : _e.getEmailVerificationURL) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, + createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); + }), + getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } exports.validateAndNormaliseEmailVerificationConfig = validateAndNormaliseEmailVerificationConfig; @@ -146,29 +80,27 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(_, appInfo, signUpCon 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, - }; - }); - let getResetPasswordURL = - config === undefined || config.getResetPasswordURL === undefined - ? passwordResetFunctions_1.getResetPasswordURL(appInfo) - : config.getResetPasswordURL; - let createAndSendCustomEmail = - config === undefined || config.createAndSendCustomEmail === undefined - ? passwordResetFunctions_1.createAndSendCustomEmail(appInfo) - : config.createAndSendCustomEmail; + return { + id: field.id, + validate: field.validate, + optional: false, + }; + }); + let getResetPasswordURL = config === undefined || config.getResetPasswordURL === undefined + ? passwordResetFunctions_1.getResetPasswordURL(appInfo) + : config.getResetPasswordURL; + let createAndSendCustomEmail = config === undefined || config.createAndSendCustomEmail === undefined + ? passwordResetFunctions_1.createAndSendCustomEmail(appInfo) + : config.createAndSendCustomEmail; return { formFieldsForPasswordResetForm, formFieldsForGenerateTokenForm, @@ -178,18 +110,15 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(_, appInfo, signUpCon } 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); @@ -207,13 +136,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, @@ -284,11 +215,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 7532a974c..74cae3735 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,10 +49,12 @@ function emailVerify(apiImplementation, options) { let response = yield apiImplementation.verifyEmailPOST({ token, options, userContext: {} }); if (response.status === "OK") { result = { status: "OK" }; - } else { + } + else { result = response; } - } else { + } + else { if (apiImplementation.isEmailVerifiedGET === undefined) { return false; } 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 a2853f69d..0d2b1145d 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"); function generateEmailVerifyToken(apiImplementation, options) { 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 4eb0f1d07..a5a67a4db 100644 --- a/lib/build/recipe/emailverification/api/implementation.js +++ b/lib/build/recipe/emailverification/api/implementation.js @@ -1,45 +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 session_1 = require("../../session"); function getAPIInterface() { return { - verifyEmailPOST: function ({ token, options, userContext }) { + verifyEmailPOST: function ({ token, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.verifyEmailUsingToken({ token, userContext }); }); }, - isEmailVerifiedGET: function ({ options, userContext }) { + isEmailVerifiedGET: function ({ options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let session = yield session_1.default.getSession(options.req, options.res, userContext); if (session === undefined) { @@ -53,7 +31,7 @@ function getAPIInterface() { }; }); }, - generateEmailVerifyTokenPOST: function ({ options, userContext }) { + generateEmailVerifyTokenPOST: function ({ options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let session = yield session_1.default.getSession(options.req, options.res, userContext); if (session === undefined) { @@ -69,8 +47,7 @@ function getAPIInterface() { if (response.status === "EMAIL_ALREADY_VERIFIED_ERROR") { return response; } - let emailVerifyLink = - (yield options.config.getEmailVerificationURL({ id: userId, email }, userContext)) + + let emailVerifyLink = (yield options.config.getEmailVerificationURL({ id: userId, email }, userContext)) + "?token=" + response.token + "&rid=" + @@ -79,16 +56,14 @@ function getAPIInterface() { if (!options.isInServerlessEnv) { options.config .createAndSendCustomEmail({ id: userId, email }, emailVerifyLink, userContext) - .catch((_) => {}); - } else { + .catch((_) => { }); + } + else { // see https://github.com/supertokens/supertokens-node/pull/135 - yield options.config.createAndSendCustomEmail( - { id: userId, email }, - emailVerifyLink, - userContext - ); + yield options.config.createAndSendCustomEmail({ id: userId, email }, emailVerifyLink, userContext); } - } catch (_) {} + } + catch (_) { } return { status: "OK", }; 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/emailVerificationFunctions.d.ts b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts index 5f9117973..9bcec8cce 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts @@ -1,7 +1,4 @@ -// @ts-nocheck import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; export declare function getEmailVerificationURL(appInfo: NormalisedAppinfo): (_: User) => Promise; -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 5dda388f7..d8916c6fb 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.js +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.js @@ -13,70 +13,45 @@ * 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"); function getEmailVerificationURL(appInfo) { - return (_) => - __awaiter(this, void 0, void 0, function* () { - return ( - appInfo.websiteDomain.getAsStringDangerous() + - appInfo.websiteBasePath.getAsStringDangerous() + - "/verify-email" - ); - }); + return (_) => __awaiter(this, void 0, void 0, function* () { + return (appInfo.websiteDomain.getAsStringDangerous() + + appInfo.websiteBasePath.getAsStringDangerous() + + "/verify-email"); + }); } exports.getEmailVerificationURL = getEmailVerificationURL; 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, - }, - }); - } catch (ignored) {} - }); + 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, + }, + }); + } + catch (ignored) { } + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; 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 0b3c90113..8a25c8acc 100644 --- a/lib/build/recipe/emailverification/index.d.ts +++ b/lib/build/recipe/emailverification/index.d.ts @@ -1,48 +1,26 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, APIOptions, APIInterface, User } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - 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: "OK"; }>; - static unverifyEmail( - userId: string, - email: string, - userContext?: any - ): Promise<{ + static unverifyEmail(userId: string, email: string, userContext?: any): Promise<{ status: "OK"; }>; } diff --git a/lib/build/recipe/emailverification/index.js b/lib/build/recipe/emailverification/index.js index 78adaa4b0..418f4d1b1 100644 --- a/lib/build/recipe/emailverification/index.js +++ b/lib/build/recipe/emailverification/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); diff --git a/lib/build/recipe/emailverification/recipe.d.ts b/lib/build/recipe/emailverification/recipe.d.ts index 685c1e4a2..a2c0cd110 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 } from "./types"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } 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: 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 b51569ef0..ceaf49a35 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"); @@ -64,9 +42,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, }, @@ -84,26 +60,25 @@ 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, - }; - 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, + }; + 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 []; }; @@ -113,9 +88,7 @@ class Recipe extends recipeModule_1.default { 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(); } { @@ -134,10 +107,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/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 3d8e50f1b..0ad72d3a9 100644 --- a/lib/build/recipe/emailverification/types.d.ts +++ b/lib/build/recipe/emailverification/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; export declare type TypeInput = { @@ -6,10 +5,7 @@ export declare type TypeInput = { getEmailVerificationURL?: (user: User, userContext: any) => Promise; 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; }; }; @@ -18,10 +14,7 @@ export declare type TypeNormalisedInput = { getEmailVerificationURL: (user: User, userContext: any) => Promise; 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; }; }; @@ -34,28 +27,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; @@ -80,36 +71,27 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - verifyEmailPOST: - | undefined - | ((input: { - token: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - } - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - >); - isEmailVerifiedGET: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - isVerified: boolean; - }>); - generateEmailVerifyTokenPOST: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; - }>); + verifyEmailPOST: undefined | ((input: { + token: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + } | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + }>); + isEmailVerifiedGET: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + isVerified: boolean; + }>); + generateEmailVerifyTokenPOST: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; + }>); }; diff --git a/lib/build/recipe/emailverification/utils.d.ts b/lib/build/recipe/emailverification/utils.d.ts index 488e181a2..24dd27270 100644 --- a/lib/build/recipe/emailverification/utils.d.ts +++ b/lib/build/recipe/emailverification/utils.d.ts @@ -1,9 +1,4 @@ -// @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; diff --git a/lib/build/recipe/emailverification/utils.js b/lib/build/recipe/emailverification/utils.js index 11ebbfd7a..f9c0df54b 100644 --- a/lib/build/recipe/emailverification/utils.js +++ b/lib/build/recipe/emailverification/utils.js @@ -16,22 +16,14 @@ Object.defineProperty(exports, "__esModule", { value: true }); const emailVerificationFunctions_1 = require("./emailVerificationFunctions"); function validateAndNormaliseUserInput(_, appInfo, config) { - let getEmailVerificationURL = - config.getEmailVerificationURL === undefined - ? emailVerificationFunctions_1.getEmailVerificationURL(appInfo) - : config.getEmailVerificationURL; - let createAndSendCustomEmail = - config.createAndSendCustomEmail === undefined - ? emailVerificationFunctions_1.createAndSendCustomEmail(appInfo) - : config.createAndSendCustomEmail; + let getEmailVerificationURL = config.getEmailVerificationURL === undefined + ? emailVerificationFunctions_1.getEmailVerificationURL(appInfo) + : config.getEmailVerificationURL; + let createAndSendCustomEmail = config.createAndSendCustomEmail === undefined + ? emailVerificationFunctions_1.createAndSendCustomEmail(appInfo) + : config.createAndSendCustomEmail; let getEmailForUserId = config.getEmailForUserId; - 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 { getEmailForUserId, getEmailVerificationURL, 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 3cc065852..eb20bbe2f 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"); function getJWKS(apiImplementation, options) { 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/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..0a1dc6b3b 100644 --- a/lib/build/recipe/jwt/index.js +++ b/lib/build/recipe/jwt/index.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 recipe_1 = require("./recipe"); class Wrapper { diff --git a/lib/build/recipe/jwt/recipe.d.ts b/lib/build/recipe/jwt/recipe.d.ts index 714362caa..64c3eec96 100644 --- a/lib/build/recipe/jwt/recipe.d.ts +++ b/lib/build/recipe/jwt/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import error from "../../error"; import { BaseRequest, BaseResponse } from "../../framework"; import NormalisedURLPath from "../../normalisedURLPath"; @@ -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 48465c3db..f1bf9744e 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"; export declare type JsonWebKey = { @@ -12,20 +11,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; }; }; @@ -42,15 +35,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<{ @@ -59,13 +49,11 @@ export declare type RecipeInterface = { }>; }; export declare type APIInterface = { - getJWKSGET: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - keys: JsonWebKey[]; - }>); + getJWKSGET: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + keys: JsonWebKey[]; + }>); }; 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..8e9ae1108 100644 --- a/lib/build/recipe/jwt/utils.js +++ b/lib/build/recipe/jwt/utils.js @@ -16,18 +16,9 @@ Object.defineProperty(exports, "__esModule", { value: true }); 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 f99e266f2..be42a3c92 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. * 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/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/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 46d7e48ea..3514fd456 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"; @@ -8,20 +7,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; }; }; }; @@ -30,20 +20,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; }; }; }; @@ -55,16 +36,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; - }>); + getOpenIdDiscoveryConfigurationGET: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + issuer: string; + jwks_uri: string; + }>); }; export declare type RecipeInterface = { getOpenIdDiscoveryConfiguration(input: { @@ -78,15 +57,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..38125abca 100644 --- a/lib/build/recipe/openid/utils.js +++ b/lib/build/recipe/openid/utils.js @@ -28,13 +28,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 a157ade17..3362ed94e 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"); @@ -76,22 +54,21 @@ 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", }); } - 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 183ccf444..9550739da 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"); @@ -75,10 +53,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) { @@ -89,10 +65,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, { @@ -106,15 +80,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: {} } - : { phoneNumber: phoneNumber, options, userContext: {} } - ); + let result = yield apiImplementation.createCodePOST(email !== undefined + ? { email, options, userContext: {} } + : { phoneNumber: phoneNumber, options, userContext: {} }); 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 2c824d60a..73457cb97 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 53973957e..d086c608f 100644 --- a/lib/build/recipe/passwordless/api/implementation.js +++ b/lib/build/recipe/passwordless/api/implementation.js @@ -1,66 +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 }); const session_1 = require("../../session"); 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; } let user = response.user; - const session = yield session_1.default.createNewSession( - input.options.res, - user.id, - {}, - {}, - input.userContext - ); + const session = yield session_1.default.createNewSession(input.options.res, user.id, {}, {}, input.userContext); return { status: "OK", createdNewUser: response.createdNewUser, @@ -71,47 +41,40 @@ 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; const flowType = input.options.config.flowType; if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = - (yield input.options.config.getLinkDomainAndPath( - "phoneNumber" in input - ? { - phoneNumber: input.phoneNumber, - } - : { - email: input.email, - }, - input.userContext - )) + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + (yield input.options.config.getLinkDomainAndPath("phoneNumber" in input + ? { + phoneNumber: input.phoneNumber, + } + : { + email: input.email, + }, input.userContext)) + + "?rid=" + + input.options.recipeId + + "&preAuthSessionId=" + + response.preAuthSessionId + + "#" + + response.linkCode; } if (flowType === "USER_INPUT_CODE" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { userInputCode = response.userInputCode; @@ -120,33 +83,27 @@ 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) - ) { - yield input.options.config.createAndSendCustomTextMessage( - { - codeLifetime: response.codeLifetime, - phoneNumber: input.phoneNumber, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, - input.userContext - ); - } else { - yield input.options.config.createAndSendCustomEmail( - { - codeLifetime: response.codeLifetime, - email: input.email, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, - input.userContext - ); + if (input.options.config.contactMethod === "PHONE" || + (input.options.config.contactMethod === "EMAIL_OR_PHONE" && "phoneNumber" in input)) { + yield input.options.config.createAndSendCustomTextMessage({ + codeLifetime: response.codeLifetime, + phoneNumber: input.phoneNumber, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, input.userContext); + } + else { + yield input.options.config.createAndSendCustomEmail({ + codeLifetime: response.codeLifetime, + email: input.email, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, input.userContext); } - } catch (err) { + } + catch (err) { return { status: "GENERAL_ERROR", message: err.message, @@ -195,10 +152,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", }; @@ -209,10 +164,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) { @@ -230,22 +184,19 @@ function getAPIImplementation() { const flowType = input.options.config.flowType; if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = - (yield input.options.config.getLinkDomainAndPath( - deviceInfo.email === undefined - ? { - phoneNumber: deviceInfo.phoneNumber, - } - : { - email: deviceInfo.email, - }, - input.userContext - )) + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + (yield input.options.config.getLinkDomainAndPath(deviceInfo.email === undefined + ? { + phoneNumber: deviceInfo.phoneNumber, + } + : { + email: deviceInfo.email, + }, input.userContext)) + + "?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,34 +205,28 @@ 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) - ) { - yield input.options.config.createAndSendCustomTextMessage( - { - codeLifetime: response.codeLifetime, - phoneNumber: deviceInfo.phoneNumber, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, - input.userContext - ); - } else { - yield input.options.config.createAndSendCustomEmail( - { - codeLifetime: response.codeLifetime, - email: deviceInfo.email, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, - input.userContext - ); + deviceInfo.phoneNumber !== undefined)) { + yield input.options.config.createAndSendCustomTextMessage({ + codeLifetime: response.codeLifetime, + phoneNumber: deviceInfo.phoneNumber, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, input.userContext); + } + else { + yield input.options.config.createAndSendCustomEmail({ + codeLifetime: response.codeLifetime, + email: deviceInfo.email, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, input.userContext); } - } catch (err) { + } + catch (err) { return { status: "GENERAL_ERROR", message: err.message, 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 1c5dedf79..763cc9c0c 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 78d4e5277..7aa92c61f 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/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 d312d041a..05993a795 100644 --- a/lib/build/recipe/passwordless/index.d.ts +++ b/lib/build/recipe/passwordless/index.d.ts @@ -1,23 +1,17 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIOptions, APIInterface } 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; @@ -31,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; @@ -85,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: { @@ -104,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; @@ -117,28 +108,20 @@ 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; diff --git a/lib/build/recipe/passwordless/index.js b/lib/build/recipe/passwordless/index.js index 8bda0ad5a..60c222b03 100644 --- a/lib/build/recipe/passwordless/index.js +++ b/lib/build/recipe/passwordless/index.js @@ -18,69 +18,43 @@ 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)); diff --git a/lib/build/recipe/passwordless/recipe.d.ts b/lib/build/recipe/passwordless/recipe.d.ts index b63528e17..e9e320f5a 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"; @@ -17,38 +16,24 @@ 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: 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 867c6aba1..5f372b16f 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"); @@ -97,32 +75,34 @@ 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, - }; - 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, + }; + 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 []; }; @@ -130,87 +110,73 @@ 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, - } - ); - let magicLink = - (yield this.config.getLinkDomainAndPath( - "phoneNumber" in input - ? { - phoneNumber: input.phoneNumber, - } - : { - email: input.email, - }, - input.userContext - )) + - "?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, + }); + let magicLink = (yield this.config.getLinkDomainAndPath("phoneNumber" in input + ? { + phoneNumber: input.phoneNumber, + } + : { + email: input.email, + }, input.userContext)) + + "?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.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(); } { @@ -229,7 +195,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("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/types.d.ts b/lib/build/recipe/passwordless/types.d.ts index 9ede59083..9f012bcd9 100644 --- a/lib/build/recipe/passwordless/types.d.ts +++ b/lib/build/recipe/passwordless/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; @@ -8,170 +7,117 @@ export declare type User = { phoneNumber?: string; timeJoined: number; }; -export declare type TypeInput = ( - | { - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - 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; + createAndSendCustomTextMessage: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + 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"; - getLinkDomainAndPath?: ( - contactInfo: - | { - email: string; - } - | { - phoneNumber: string; - }, - userContext: any - ) => Promise | string; + getLinkDomainAndPath?: (contactInfo: { + email: string; + } | { + phoneNumber: string; + }, userContext: any) => Promise | string; 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; - createAndSendCustomTextMessage: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } -) & { +export declare type TypeNormalisedInput = ({ + contactMethod: "PHONE"; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; + createAndSendCustomTextMessage: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL"; + validateEmailAddress: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; + 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"; - getLinkDomainAndPath: ( - contactInfo: - | { - email: string; - } - | { - phoneNumber: string; - }, - userContext: any - ) => Promise | string; + getLinkDomainAndPath: (contactInfo: { + email: string; + } | { + phoneNumber: string; + }, userContext: any) => Promise | string; 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 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; @@ -185,52 +131,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; @@ -239,17 +183,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: { @@ -258,9 +198,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; @@ -286,82 +235,59 @@ export declare type APIOptions = { res: BaseResponse; }; 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"; - } - | { - status: "GENERAL_ERROR"; - message: string; - } - >; - resendCodePOST?: ( - input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: APIOptions; - userContext: any; - } - ) => Promise< - | { - status: "GENERAL_ERROR"; - message: string; - } - | { - 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; - user: User; - session: SessionContainerInterface; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | { - status: "GENERAL_ERROR"; - message: string; - } - | { - status: "RESTART_FLOW_ERROR"; - } - >; + 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"; + } | { + status: "GENERAL_ERROR"; + message: string; + }>; + resendCodePOST?: (input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "GENERAL_ERROR"; + message: string; + } | { + 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; + user: User; + session: SessionContainerInterface; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | { + status: "GENERAL_ERROR"; + message: string; + } | { + status: "RESTART_FLOW_ERROR"; + }>; emailExistsGET?: (input: { email: string; options: APIOptions; diff --git a/lib/build/recipe/passwordless/utils.d.ts b/lib/build/recipe/passwordless/utils.d.ts index 488e181a2..24dd27270 100644 --- a/lib/build/recipe/passwordless/utils.d.ts +++ b/lib/build/recipe/passwordless/utils.d.ts @@ -1,9 +1,4 @@ -// @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; diff --git a/lib/build/recipe/passwordless/utils.js b/lib/build/recipe/passwordless/utils.js index 740228ab9..f7d8978f7 100644 --- a/lib/build/recipe/passwordless/utils.js +++ b/lib/build/recipe/passwordless/utils.js @@ -13,57 +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 }); const max_1 = require("libphonenumber-js/max"); 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); if (config.contactMethod === "EMAIL") { if (config.createAndSendCustomEmail === undefined) { throw new Error("Please provide a callback function (createAndSendCustomEmail) to send emails. "); @@ -72,73 +42,61 @@ function validateAndNormaliseUserInput(_, appInfo, config) { override, flowType: config.flowType, contactMethod: "EMAIL", - createAndSendCustomEmail: - // until we add a service to send emails, config.createAndSendCustomEmail will never be undefined - config.createAndSendCustomEmail === undefined - ? defaultCreateAndSendCustomEmail - : config.createAndSendCustomEmail, - getLinkDomainAndPath: - config.getLinkDomainAndPath === undefined - ? getDefaultGetLinkDomainAndPath(appInfo) - : config.getLinkDomainAndPath, - validateEmailAddress: - config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + createAndSendCustomEmail: + // until we add a service to send emails, config.createAndSendCustomEmail will never be undefined + config.createAndSendCustomEmail === undefined + ? defaultCreateAndSendCustomEmail + : config.createAndSendCustomEmail, + getLinkDomainAndPath: config.getLinkDomainAndPath === undefined + ? getDefaultGetLinkDomainAndPath(appInfo) + : config.getLinkDomainAndPath, + validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, getCustomUserInputCode: config.getCustomUserInputCode, }; - } else if (config.contactMethod === "PHONE") { + } + else if (config.contactMethod === "PHONE") { if (config.createAndSendCustomTextMessage === undefined) { - throw new Error( - "Please provide a callback function (createAndSendCustomTextMessage) to send text messages. " - ); + throw new Error("Please provide a callback function (createAndSendCustomTextMessage) to send text messages. "); } return { override, flowType: config.flowType, contactMethod: "PHONE", // until we add a service to send sms, config.createAndSendCustomTextMessage will never be undefined - createAndSendCustomTextMessage: - config.createAndSendCustomTextMessage === undefined - ? defaultCreateAndSendTextMessage - : config.createAndSendCustomTextMessage, - getLinkDomainAndPath: - config.getLinkDomainAndPath === undefined - ? getDefaultGetLinkDomainAndPath(appInfo) - : config.getLinkDomainAndPath, - validatePhoneNumber: - config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + createAndSendCustomTextMessage: config.createAndSendCustomTextMessage === undefined + ? defaultCreateAndSendTextMessage + : config.createAndSendCustomTextMessage, + getLinkDomainAndPath: config.getLinkDomainAndPath === undefined + ? getDefaultGetLinkDomainAndPath(appInfo) + : config.getLinkDomainAndPath, + validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; - } else { + } + else { if (config.createAndSendCustomEmail === undefined) { throw new Error("Please provide a callback function (createAndSendCustomEmail) to send emails. "); } if (config.createAndSendCustomTextMessage === undefined) { - throw new Error( - "Please provide a callback function (createAndSendCustomTextMessage) to send text messages. " - ); + throw new Error("Please provide a callback function (createAndSendCustomTextMessage) to send text messages. "); } return { override, flowType: config.flowType, contactMethod: "EMAIL_OR_PHONE", // until we add a service to send email, config.createAndSendCustomEmail will never be undefined - createAndSendCustomEmail: - config.createAndSendCustomEmail === undefined - ? defaultCreateAndSendCustomEmail - : config.createAndSendCustomEmail, - validateEmailAddress: - config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + createAndSendCustomEmail: config.createAndSendCustomEmail === undefined + ? defaultCreateAndSendCustomEmail + : config.createAndSendCustomEmail, + validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, // until we add a service to send sms, config.createAndSendCustomTextMessage will never be undefined - createAndSendCustomTextMessage: - config.createAndSendCustomTextMessage === undefined - ? defaultCreateAndSendTextMessage - : config.createAndSendCustomTextMessage, - getLinkDomainAndPath: - config.getLinkDomainAndPath === undefined - ? getDefaultGetLinkDomainAndPath(appInfo) - : config.getLinkDomainAndPath, - validatePhoneNumber: - config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + createAndSendCustomTextMessage: config.createAndSendCustomTextMessage === undefined + ? defaultCreateAndSendTextMessage + : config.createAndSendCustomTextMessage, + getLinkDomainAndPath: config.getLinkDomainAndPath === undefined + ? getDefaultGetLinkDomainAndPath(appInfo) + : config.getLinkDomainAndPath, + validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; } @@ -146,9 +104,7 @@ function validateAndNormaliseUserInput(_, appInfo, config) { exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function getDefaultGetLinkDomainAndPath(appInfo) { return (_, __) => { - return ( - appInfo.websiteDomain.getAsStringDangerous() + appInfo.websiteBasePath.getAsStringDangerous() + "/verify" - ); + return (appInfo.websiteDomain.getAsStringDangerous() + appInfo.websiteBasePath.getAsStringDangerous() + "/verify"); }; } function defaultValidatePhoneNumber(value) { @@ -179,11 +135,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 e40021bb8..cd85c6cd8 100644 --- a/lib/build/recipe/session/accessToken.d.ts +++ b/lib/build/recipe/session/accessToken.d.ts @@ -1,9 +1,4 @@ -// @ts-nocheck -export declare function getInfoFromAccessToken( - token: string, - jwtSigningPublicKey: string, - doAntiCsrfCheck: boolean -): Promise<{ +export declare function getInfoFromAccessToken(token: string, jwtSigningPublicKey: string, doAntiCsrfCheck: boolean): Promise<{ sessionHandle: string; userId: string; refreshTokenHash1: string; diff --git a/lib/build/recipe/session/accessToken.js b/lib/build/recipe/session/accessToken.js index 1a4bbe5c4..9ec26e92f 100644 --- a/lib/build/recipe/session/accessToken.js +++ b/lib/build/recipe/session/accessToken.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 jwt_1 = require("./jwt"); @@ -59,15 +37,13 @@ function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { let antiCsrfToken = sanitizeStringInput(payload.antiCsrfToken); let expiryTime = sanitizeNumberInput(payload.expiryTime); let timeCreated = sanitizeNumberInput(payload.timeCreated); - if ( - sessionHandle === undefined || + if (sessionHandle === undefined || userId === undefined || refreshTokenHash1 === undefined || userData === undefined || (antiCsrfToken === undefined && doAntiCsrfCheck) || expiryTime === undefined || - timeCreated === 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?"); } @@ -84,7 +60,8 @@ function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { expiryTime, timeCreated, }; - } catch (err) { + } + catch (err) { throw new error_1.default({ message: "Failed to verify access token", type: error_1.default.TRY_REFRESH_TOKEN, @@ -103,7 +80,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 76a565246..f9dfa8c34 100644 --- a/lib/build/recipe/session/api/implementation.js +++ b/lib/build/recipe/session/api/implementation.js @@ -1,47 +1,25 @@ "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 utils_1 = require("../../../utils"); const normalisedURLPath_1 = require("../../../normalisedURLPath"); function getAPIInterface() { return { - refreshPOST: function ({ options, userContext }) { + refreshPOST: function ({ options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { yield options.recipeImplementation.refreshSession({ req: options.req, res: options.res, userContext }); }); }, - 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") { @@ -55,7 +33,8 @@ function getAPIInterface() { res: options.res, userContext, }); - } else { + } + else { return yield options.recipeImplementation.getSession({ req: options.req, res: options.res, @@ -65,7 +44,7 @@ function getAPIInterface() { } }); }, - signOutPOST: function ({ options, userContext }) { + signOutPOST: function ({ options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let session; try { @@ -74,7 +53,8 @@ function getAPIInterface() { res: options.res, userContext, }); - } catch (err) { + } + catch (err) { if (error_1.default.isErrorFromSuperTokens(err) && err.type === error_1.default.UNAUTHORISED) { // The session is expired / does not exist anyway. So we return OK return { 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 58bc46079..4e3e18fd8 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"); function handleRefreshAPI(apiImplementation, options) { 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 4f4971a94..fba8ac7cf 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"); function signOutAPI(apiImplementation, options) { diff --git a/lib/build/recipe/session/constants.d.ts b/lib/build/recipe/session/constants.d.ts index 82a2b430c..4b327324d 100644 --- a/lib/build/recipe/session/constants.d.ts +++ b/lib/build/recipe/session/constants.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck 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 7bd9547b6..e2aae3665 100644 --- a/lib/build/recipe/session/cookieAndHeaders.d.ts +++ b/lib/build/recipe/session/cookieAndHeaders.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BaseRequest, BaseResponse } from "../../framework"; import { TypeNormalisedInput } from "./types"; /** @@ -8,39 +7,19 @@ export declare function clearSessionFromCookie(config: TypeNormalisedInput, res: /** * @param expiry: must be time in milliseconds from epoch time. */ -export declare function attachAccessTokenToCookie( - config: TypeNormalisedInput, - res: BaseResponse, - token: string, - expiry: number -): void; +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 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; 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 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 getCORSAllowedHeaders(): string[]; /** * @@ -53,11 +32,4 @@ 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; diff --git a/lib/build/recipe/session/cookieAndHeaders.js b/lib/build/recipe/session/cookieAndHeaders.js index b279b35b2..c1cf8a933 100644 --- a/lib/build/recipe/session/cookieAndHeaders.js +++ b/lib/build/recipe/session/cookieAndHeaders.js @@ -96,7 +96,8 @@ 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 7f2868e10..2ca39f81b 100644 --- a/lib/build/recipe/session/error.d.ts +++ b/lib/build/recipe/session/error.d.ts @@ -1,29 +1,23 @@ -// @ts-nocheck import STError from "../../error"; export default class SessionError extends STError { static UNAUTHORISED: "UNAUTHORISED"; static TRY_REFRESH_TOKEN: "TRY_REFRESH_TOKEN"; static TOKEN_THEFT_DETECTED: "TOKEN_THEFT_DETECTED"; - constructor( - options: - | { - message: string; - type: "UNAUTHORISED"; - payload?: { - clearCookies: boolean; - }; - } - | { - message: string; - type: "TRY_REFRESH_TOKEN"; - } - | { - message: string; - type: "TOKEN_THEFT_DETECTED"; - payload: { - userId: string; - sessionHandle: string; - }; - } - ); + constructor(options: { + message: string; + type: "UNAUTHORISED"; + payload?: { + clearCookies: boolean; + }; + } | { + message: string; + type: "TRY_REFRESH_TOKEN"; + } | { + message: string; + type: "TOKEN_THEFT_DETECTED"; + payload: { + userId: string; + sessionHandle: string; + }; + }); } diff --git a/lib/build/recipe/session/error.js b/lib/build/recipe/session/error.js index 244ea77d9..6fd4ea846 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: { + clearCookies: true, + } }) : Object.assign({}, options)); this.fromRecipe = "session"; } } diff --git a/lib/build/recipe/session/faunadb/constants.d.ts b/lib/build/recipe/session/faunadb/constants.d.ts index 5866986e1..91c164f3d 100644 --- a/lib/build/recipe/session/faunadb/constants.d.ts +++ b/lib/build/recipe/session/faunadb/constants.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck export declare const FAUNADB_TOKEN_TIME_LAG_MILLI: number; export declare const FAUNADB_SESSION_KEY = "faunadbToken"; diff --git a/lib/build/recipe/session/faunadb/index.d.ts b/lib/build/recipe/session/faunadb/index.d.ts index ad4b0fa84..9d4df0e1b 100644 --- a/lib/build/recipe/session/faunadb/index.d.ts +++ b/lib/build/recipe/session/faunadb/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import OriginalRecipeImplementation from "./recipeImplementation"; import { Session } from "./types"; export default OriginalRecipeImplementation; diff --git a/lib/build/recipe/session/faunadb/recipeImplementation.d.ts b/lib/build/recipe/session/faunadb/recipeImplementation.d.ts index 723584c3b..2e0c72f18 100644 --- a/lib/build/recipe/session/faunadb/recipeImplementation.d.ts +++ b/lib/build/recipe/session/faunadb/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { VerifySessionOptions, RecipeInterface } from "../"; import * as faunadb from "faunadb"; import type { Session as FaunaDBSessionContainer } from "./types"; @@ -12,138 +11,69 @@ export default class RecipeImplementation implements RecipeInterface { }; q: typeof faunadb.query; originalImplementation: RecipeInterface; - constructor( - originalImplementation: RecipeInterface, - config: { - accessFaunadbTokenFromFrontend?: boolean; - userCollectionName: string; - faunaDBClient: faunadb.Client; - } - ); + constructor(originalImplementation: RecipeInterface, config: { + accessFaunadbTokenFromFrontend?: boolean; + userCollectionName: string; + faunaDBClient: faunadb.Client; + }); getFDAT: (userId: string, userContext: any) => Promise; - createNewSession: ( - this: RecipeImplementation, - { - res, - userId, - accessTokenPayload, - sessionData, - userContext, - }: { - res: BaseResponse; - userId: string; - accessTokenPayload?: any; - sessionData?: any; - userContext: any; - } - ) => Promise; - getSession: ( - this: RecipeImplementation, - { - req, - res, - options, - userContext, - }: { - req: BaseRequest; - res: BaseResponse; - options?: VerifySessionOptions | undefined; - userContext: any; - } - ) => Promise; - getSessionInformation: ( - this: RecipeImplementation, - { - sessionHandle, - userContext, - }: { - sessionHandle: string; - userContext: any; - } - ) => Promise; - refreshSession: ( - this: RecipeImplementation, - { - req, - res, - userContext, - }: { - req: BaseRequest; - res: BaseResponse; - userContext: any; - } - ) => Promise; - revokeAllSessionsForUser: ( - this: RecipeImplementation, - { - userId, - userContext, - }: { - userId: string; - userContext: any; - } - ) => Promise; - getAllSessionHandlesForUser: ( - this: RecipeImplementation, - { - userId, - userContext, - }: { - userId: string; - userContext: any; - } - ) => Promise; - revokeSession: ( - this: RecipeImplementation, - { - sessionHandle, - userContext, - }: { - sessionHandle: string; - userContext: any; - } - ) => Promise; - revokeMultipleSessions: ( - this: RecipeImplementation, - { - sessionHandles, - userContext, - }: { - sessionHandles: string[]; - userContext: any; - } - ) => Promise; - updateSessionData: ( - this: RecipeImplementation, - { - sessionHandle, - newSessionData, - userContext, - }: { - sessionHandle: string; - newSessionData: any; - userContext: any; - } - ) => Promise; - updateAccessTokenPayload: ( - this: RecipeImplementation, - input: { - sessionHandle: string; - newAccessTokenPayload: any; - userContext: any; - } - ) => Promise; - regenerateAccessToken: (input: { accessToken: string; newAccessTokenPayload?: any; userContext: any }) => any; - getAccessTokenLifeTimeMS: ( - this: RecipeImplementation, - input: { - userContext: any; - } - ) => Promise; - getRefreshTokenLifeTimeMS: ( - this: RecipeImplementation, - input: { - userContext: any; - } - ) => Promise; + createNewSession: (this: RecipeImplementation, { res, userId, accessTokenPayload, sessionData, userContext, }: { + res: BaseResponse; + userId: string; + accessTokenPayload?: any; + sessionData?: any; + userContext: any; + }) => Promise; + getSession: (this: RecipeImplementation, { req, res, options, userContext, }: { + req: BaseRequest; + res: BaseResponse; + options?: VerifySessionOptions | undefined; + userContext: any; + }) => Promise; + getSessionInformation: (this: RecipeImplementation, { sessionHandle, userContext }: { + sessionHandle: string; + userContext: any; + }) => Promise; + refreshSession: (this: RecipeImplementation, { req, res, userContext, }: { + req: BaseRequest; + res: BaseResponse; + userContext: any; + }) => Promise; + revokeAllSessionsForUser: (this: RecipeImplementation, { userId, userContext }: { + userId: string; + userContext: any; + }) => Promise; + getAllSessionHandlesForUser: (this: RecipeImplementation, { userId, userContext }: { + userId: string; + userContext: any; + }) => Promise; + revokeSession: (this: RecipeImplementation, { sessionHandle, userContext }: { + sessionHandle: string; + userContext: any; + }) => Promise; + revokeMultipleSessions: (this: RecipeImplementation, { sessionHandles, userContext }: { + sessionHandles: string[]; + userContext: any; + }) => Promise; + updateSessionData: (this: RecipeImplementation, { sessionHandle, newSessionData, userContext }: { + sessionHandle: string; + newSessionData: any; + userContext: any; + }) => Promise; + updateAccessTokenPayload: (this: RecipeImplementation, input: { + sessionHandle: string; + newAccessTokenPayload: any; + userContext: any; + }) => Promise; + regenerateAccessToken: (input: { + accessToken: string; + newAccessTokenPayload?: any; + userContext: any; + }) => any; + getAccessTokenLifeTimeMS: (this: RecipeImplementation, input: { + userContext: any; + }) => Promise; + getRefreshTokenLifeTimeMS: (this: RecipeImplementation, input: { + userContext: any; + }) => Promise; } diff --git a/lib/build/recipe/session/faunadb/recipeImplementation.js b/lib/build/recipe/session/faunadb/recipeImplementation.js index 0cf335f0c..4427bf385 100644 --- a/lib/build/recipe/session/faunadb/recipeImplementation.js +++ b/lib/build/recipe/session/faunadb/recipeImplementation.js @@ -1,85 +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 faunadb = require("faunadb"); const constants_1 = require("./constants"); class RecipeImplementation { constructor(originalImplementation, config) { this.q = faunadb.query; - this.getFDAT = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - function getFaunadbTokenTimeLag() { - if (process.env.INSTALL_PATH !== undefined) { - // if in testing... - return 2 * 1000; - } - return constants_1.FAUNADB_TOKEN_TIME_LAG_MILLI; + this.getFDAT = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + function getFaunadbTokenTimeLag() { + if (process.env.INSTALL_PATH !== undefined) { + // if in testing... + return 2 * 1000; } - let accessTokenLifetime = yield this.originalImplementation.getAccessTokenLifeTimeMS({ userContext }); - let faunaResponse = yield this.config.faunaDBClient.query( - this.q.Create(this.q.Tokens(), { - instance: this.q.Ref(this.q.Collection(this.config.userCollectionName), userId), - ttl: this.q.TimeAdd( - this.q.Now(), - accessTokenLifetime + getFaunadbTokenTimeLag(), - "millisecond" - ), - }) - ); - return faunaResponse.secret; - }); - this.createNewSession = function ({ res, userId, accessTokenPayload = {}, sessionData = {}, userContext }) { + return constants_1.FAUNADB_TOKEN_TIME_LAG_MILLI; + } + let accessTokenLifetime = yield this.originalImplementation.getAccessTokenLifeTimeMS({ userContext }); + let faunaResponse = yield this.config.faunaDBClient.query(this.q.Create(this.q.Tokens(), { + instance: this.q.Ref(this.q.Collection(this.config.userCollectionName), userId), + ttl: this.q.TimeAdd(this.q.Now(), accessTokenLifetime + getFaunadbTokenTimeLag(), "millisecond"), + })); + return faunaResponse.secret; + }); + this.createNewSession = function ({ res, userId, accessTokenPayload = {}, sessionData = {}, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let fdat = yield this.getFDAT(userId, userContext); if (this.config.accessFaunadbTokenFromFrontend) { accessTokenPayload = Object.assign({}, accessTokenPayload); accessTokenPayload[constants_1.FAUNADB_SESSION_KEY] = fdat; - } else { + } + else { sessionData = Object.assign({}, sessionData); sessionData[constants_1.FAUNADB_SESSION_KEY] = fdat; } - return getModifiedSession( - yield this.originalImplementation.createNewSession({ - res, - userId, - accessTokenPayload, - sessionData, - userContext, - }) - ); + return getModifiedSession(yield this.originalImplementation.createNewSession({ + res, + userId, + accessTokenPayload, + sessionData, + userContext, + })); }); }; - this.getSession = function ({ req, res, options, userContext }) { + this.getSession = function ({ req, res, options, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let originalSession = yield this.originalImplementation.getSession({ req, res, options, userContext }); if (originalSession === undefined) { @@ -91,7 +61,7 @@ class RecipeImplementation { this.getSessionInformation = function ({ sessionHandle, userContext }) { return this.originalImplementation.getSessionInformation({ sessionHandle, userContext }); }; - this.refreshSession = function ({ req, res, userContext }) { + this.refreshSession = function ({ req, res, userContext, }) { return __awaiter(this, void 0, void 0, function* () { let originalSession = yield this.originalImplementation.refreshSession({ req, res, userContext }); let session = getModifiedSession(originalSession); @@ -102,8 +72,9 @@ class RecipeImplementation { let newPayload = Object.assign({}, session.getAccessTokenPayload()); newPayload[constants_1.FAUNADB_SESSION_KEY] = fdat; yield session.updateAccessTokenPayload(newPayload); - } else { - let newPayload = Object.assign({}, yield session.getSessionData()); + } + else { + let newPayload = Object.assign({}, (yield session.getSessionData())); newPayload[constants_1.FAUNADB_SESSION_KEY] = fdat; yield session.updateSessionData(newPayload); } @@ -143,8 +114,7 @@ class RecipeImplementation { }; this.originalImplementation = originalImplementation; this.config = { - accessFaunadbTokenFromFrontend: - config.accessFaunadbTokenFromFrontend === undefined ? false : config.accessFaunadbTokenFromFrontend, + accessFaunadbTokenFromFrontend: config.accessFaunadbTokenFromFrontend === undefined ? false : config.accessFaunadbTokenFromFrontend, userCollectionName: config.userCollectionName, faunaDBClient: config.faunaDBClient, }; @@ -152,17 +122,15 @@ class RecipeImplementation { } exports.default = RecipeImplementation; function getModifiedSession(session) { - return Object.assign(Object.assign({}, session), { - getFaunadbToken: (userContext) => - __awaiter(this, void 0, void 0, function* () { - let accessTokenPayload = session.getAccessTokenPayload(userContext); - if (accessTokenPayload[constants_1.FAUNADB_SESSION_KEY] !== undefined) { - // this operation costs nothing. So we can check - return accessTokenPayload[constants_1.FAUNADB_SESSION_KEY]; - } else { - let sessionData = yield session.getSessionData(userContext); - return sessionData[constants_1.FAUNADB_SESSION_KEY]; - } - }), - }); + return Object.assign(Object.assign({}, session), { getFaunadbToken: (userContext) => __awaiter(this, void 0, void 0, function* () { + let accessTokenPayload = session.getAccessTokenPayload(userContext); + if (accessTokenPayload[constants_1.FAUNADB_SESSION_KEY] !== undefined) { + // this operation costs nothing. So we can check + return accessTokenPayload[constants_1.FAUNADB_SESSION_KEY]; + } + else { + let sessionData = yield session.getSessionData(userContext); + return sessionData[constants_1.FAUNADB_SESSION_KEY]; + } + }) }); } diff --git a/lib/build/recipe/session/faunadb/types.d.ts b/lib/build/recipe/session/faunadb/types.d.ts index a04bbfbdd..6afb4b410 100644 --- a/lib/build/recipe/session/faunadb/types.d.ts +++ b/lib/build/recipe/session/faunadb/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { SessionContainer } from "../"; export declare type Session = SessionContainer & { getFaunadbToken: (userContext?: any) => Promise; 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..83278e46c 100644 --- a/lib/build/recipe/session/framework/awsLambda.js +++ b/lib/build/recipe/session/framework/awsLambda.js @@ -1,57 +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 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..844d9df04 100644 --- a/lib/build/recipe/session/framework/express.js +++ b/lib/build/recipe/session/framework/express.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. * @@ -49,22 +27,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..c7483db62 100644 --- a/lib/build/recipe/session/framework/fastify.d.ts +++ b/lib/build/recipe/session/framework/fastify.d.ts @@ -1,17 +1,5 @@ -// @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..9785897cd 100644 --- a/lib/build/recipe/session/framework/fastify.js +++ b/lib/build/recipe/session/framework/fastify.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. * @@ -49,18 +27,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/h3.d.ts b/lib/build/recipe/session/framework/h3.d.ts new file mode 100644 index 000000000..ae0a57c6c --- /dev/null +++ b/lib/build/recipe/session/framework/h3.d.ts @@ -0,0 +1,5 @@ +/// +import type { VerifySessionOptions } from '../types'; +import type { SessionRequest } from '../../../framework/h3'; +import type { ServerResponse } from 'http'; +export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; diff --git a/lib/build/recipe/session/framework/h3.js b/lib/build/recipe/session/framework/h3.js new file mode 100644 index 000000000..8abd748c3 --- /dev/null +++ b/lib/build/recipe/session/framework/h3.js @@ -0,0 +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()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const recipe_1 = require("../recipe"); +const framework_1 = require("../../../framework/h3/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.H3Request(req); + const response = new framework_1.H3ResponseTokens(res); + 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 (err) { + next(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..63e6c2a21 100644 --- a/lib/build/recipe/session/framework/hapi.js +++ b/lib/build/recipe/session/framework/hapi.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. * @@ -48,13 +26,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..ac4d08eb1 100644 --- a/lib/build/recipe/session/framework/index.d.ts +++ b/lib/build/recipe/session/framework/index.d.ts @@ -1,10 +1,10 @@ -// @ts-nocheck import * as expressFramework from "./express"; import * as fastifyFramework from "./fastify"; import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; +import * as h3Framework from './h3'; declare const _default: { express: typeof expressFramework; fastify: typeof fastifyFramework; @@ -12,6 +12,7 @@ declare const _default: { loopback: typeof loopbackFramework; koa: typeof koaFramework; awsLambda: typeof awsLambdaFramework; + h3: typeof h3Framework; }; export default _default; export declare let express: typeof expressFramework; @@ -20,3 +21,4 @@ export declare let hapi: typeof hapiFramework; export declare let loopback: typeof loopbackFramework; export declare let koa: typeof koaFramework; export declare let awsLambda: typeof awsLambdaFramework; +export declare let h3: typeof h3Framework; diff --git a/lib/build/recipe/session/framework/index.js b/lib/build/recipe/session/framework/index.js index 0f0ccf5cd..6bee76f22 100644 --- a/lib/build/recipe/session/framework/index.js +++ b/lib/build/recipe/session/framework/index.js @@ -20,6 +20,7 @@ const hapiFramework = require("./hapi"); const loopbackFramework = require("./loopback"); const koaFramework = require("./koa"); const awsLambdaFramework = require("./awsLambda"); +const h3Framework = require("./h3"); exports.default = { express: expressFramework, fastify: fastifyFramework, @@ -27,6 +28,7 @@ exports.default = { loopback: loopbackFramework, koa: koaFramework, awsLambda: awsLambdaFramework, + h3: h3Framework, }; exports.express = expressFramework; exports.fastify = fastifyFramework; @@ -34,3 +36,4 @@ exports.hapi = hapiFramework; exports.loopback = loopbackFramework; exports.koa = koaFramework; exports.awsLambda = awsLambdaFramework; +exports.h3 = h3Framework; 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..6c26d1e1a 100644 --- a/lib/build/recipe/session/framework/koa.js +++ b/lib/build/recipe/session/framework/koa.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. * @@ -48,13 +26,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..0729815d2 100644 --- a/lib/build/recipe/session/framework/loopback.js +++ b/lib/build/recipe/session/framework/loopback.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. * @@ -48,14 +26,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 952e846f3..294086f67 100644 --- a/lib/build/recipe/session/index.d.ts +++ b/lib/build/recipe/session/index.d.ts @@ -1,30 +1,11 @@ -// @ts-nocheck import SuperTokensError from "./error"; -import { - VerifySessionOptions, - RecipeInterface, - SessionContainerInterface as SessionContainer, - SessionInformation, - APIInterface, - APIOptions, -} from "./types"; +import { VerifySessionOptions, RecipeInterface, SessionContainerInterface as SessionContainer, SessionInformation, APIInterface, APIOptions } from "./types"; import Recipe from "./recipe"; export default class SessionWrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static createNewSession( - res: any, - userId: string, - accessTokenPayload?: any, - sessionData?: any, - userContext?: any - ): Promise; - static getSession( - req: any, - res: any, - options?: VerifySessionOptions, - userContext?: any - ): Promise; + static createNewSession(res: any, userId: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise; + static getSession(req: any, res: any, options?: VerifySessionOptions, 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; @@ -32,52 +13,31 @@ 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<{ + static regenerateAccessToken(accessToken: string, newAccessTokenPayload?: any, userContext?: any): Promise<{ status: "OK"; session: { handle: string; userId: string; userDataInJWT: any; }; - accessToken?: - | { - token: string; - expiry: number; - createdTime: number; - } - | undefined; + accessToken?: { + token: string; + expiry: number; + createdTime: number; + } | undefined; }>; - static updateAccessTokenPayload( - sessionHandle: string, - newAccessTokenPayload: any, - 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 updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, 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; diff --git a/lib/build/recipe/session/index.js b/lib/build/recipe/session/index.js index 6dfc459b0..26d6709ab 100644 --- a/lib/build/recipe/session/index.js +++ b/lib/build/recipe/session/index.js @@ -28,9 +28,7 @@ class SessionWrapper { }); } static getSession(req, res, options, userContext = {}) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.getSession({ req, res, options, userContext }); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getSession({ req, res, options, userContext }); } static getSessionInformation(sessionHandle, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getSessionInformation({ @@ -42,9 +40,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({ @@ -53,9 +49,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({ @@ -89,27 +83,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"); } } exports.default = SessionWrapper; diff --git a/lib/build/recipe/session/jwt.d.ts b/lib/build/recipe/session/jwt.d.ts index 04e1066e4..c72639760 100644 --- a/lib/build/recipe/session/jwt.d.ts +++ b/lib/build/recipe/session/jwt.d.ts @@ -1,12 +1,6 @@ -// @ts-nocheck -export declare function verifyJWTAndGetPayload( - jwt: string, - jwtSigningPublicKey: string -): { +export declare function verifyJWTAndGetPayload(jwt: string, jwtSigningPublicKey: string): { [key: string]: any; }; -export declare function getPayloadWithoutVerifiying( - jwt: string -): { +export declare function getPayloadWithoutVerifiying(jwt: string): { [key: string]: any; }; diff --git a/lib/build/recipe/session/jwt.js b/lib/build/recipe/session/jwt.js index e544545ce..b51c4a45d 100644 --- a/lib/build/recipe/session/jwt.js +++ b/lib/build/recipe/session/jwt.js @@ -16,20 +16,16 @@ 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) { const splittedInput = jwt.split("."); @@ -44,13 +40,7 @@ function verifyJWTAndGetPayload(jwt, 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" - ) - ) { + if (!verifier.verify("-----BEGIN PUBLIC KEY-----\n" + jwtSigningPublicKey + "\n-----END PUBLIC KEY-----", splittedInput[2], "base64")) { throw new Error("JWT verification failed"); } // sending payload diff --git a/lib/build/recipe/session/recipe.d.ts b/lib/build/recipe/session/recipe.d.ts index 02c1df910..c976a10de 100644 --- a/lib/build/recipe/session/recipe.d.ts +++ b/lib/build/recipe/session/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { TypeInput, TypeNormalisedInput, RecipeInterface, APIInterface, VerifySessionOptions } from "./types"; import STError from "./error"; @@ -19,19 +18,9 @@ export default class SessionRecipe extends RecipeModule { 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; - 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 06e03914b..fdaddfa47 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"); @@ -85,52 +63,53 @@ 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.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"); + return yield this.config.errorHandlers.onUnauthorised(err.message, request, response); } - }); - 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"); - 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"); - return yield this.config.errorHandlers.onTokenTheftDetected( - err.payload.sessionHandle, - err.payload.userId, - request, - response - ); - } else { - throw err; - } - } else if (this.openIdRecipe !== undefined) { - return yield this.openIdRecipe.handleError(err, request, response); - } else { + 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"); + return yield this.config.errorHandlers.onTokenTheftDetected(err.payload.sessionHandle, err.payload.userId, 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) { @@ -139,35 +118,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: {}, - }); + 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: {}, }); + }); 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) { @@ -175,25 +149,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) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config)); 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) - ); + 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(); } } @@ -213,7 +181,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 6c54641d8..163856bf2 100644 --- a/lib/build/recipe/session/recipeImplementation.d.ts +++ b/lib/build/recipe/session/recipeImplementation.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { RecipeInterface, TypeNormalisedInput, KeyInfo, AntiCsrfType } from "./types"; import { Querier } from "../../querier"; export declare class HandshakeInfo { @@ -7,13 +6,7 @@ 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; diff --git a/lib/build/recipe/session/recipeImplementation.js b/lib/build/recipe/session/recipeImplementation.js index 1d07bd735..1f9e90d6d 100644 --- a/lib/build/recipe/session/recipeImplementation.js +++ b/lib/build/recipe/session/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 SessionFunctions = require("./sessionFunctions"); const cookieAndHeaders_1 = require("./cookieAndHeaders"); @@ -43,13 +21,7 @@ const supertokens_1 = require("../../supertokens"); const framework_1 = require("../../framework"); const logger_1 = require("../../logger"); class HandshakeInfo { - constructor( - antiCsrf, - accessTokenBlacklistingEnabled, - accessTokenValidity, - refreshTokenValidity, - rawJwtSigningPublicKeyList - ) { + constructor(antiCsrf, accessTokenBlacklistingEnabled, accessTokenValidity, refreshTokenValidity, rawJwtSigningPublicKeyList) { this.antiCsrf = antiCsrf; this.accessTokenBlacklistingEnabled = accessTokenBlacklistingEnabled; this.accessTokenValidity = accessTokenValidity; @@ -63,13 +35,7 @@ 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; @@ -77,28 +43,12 @@ function getRecipeInterface(querier, config) { 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; }); @@ -113,42 +63,24 @@ function getRecipeInterface(querier, config) { } } let obj = { - createNewSession: function ({ res, userId, accessTokenPayload = {}, sessionData = {} }) { + createNewSession: function ({ res, userId, accessTokenPayload = {}, sessionData = {}, }) { return __awaiter(this, void 0, void 0, function* () { if (!res.wrapperUsed) { - res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse( - res - ); + res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse(res); } - let response = yield SessionFunctions.createNewSession( - helpers, - userId, - accessTokenPayload, - sessionData - ); + let response = yield SessionFunctions.createNewSession(helpers, userId, 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.userDataInJWT, - res - ); + return new sessionClass_1.default(helpers, response.accessToken.token, response.session.handle, response.session.userId, response.session.userDataInJWT, res); }); }, - getSession: function ({ req, res, options }) { + getSession: function ({ req, res, options, }) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("getSession: Started"); if (!res.wrapperUsed) { - res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse( - res - ); + res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse(res); } if (!req.wrapperUsed) { - req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest( - req - ); + req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest(req); } logger_1.logDebugMessage("getSession: rid in header: " + utils_2.frontendHasInterceptor(req)); logger_1.logDebugMessage("getSession: request method: " + req.getMethod()); @@ -158,19 +90,14 @@ function getRecipeInterface(querier, config) { // 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" - ); + logger_1.logDebugMessage("getSession: returning undefined because idRefreshToken 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 idRefreshToken from cookies 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 as cookies?", type: error_1.default.UNAUTHORISED, }); } @@ -183,15 +110,11 @@ function getRecipeInterface(querier, config) { * options.sessionRequired === true || (frontendHasInterceptor or request method is get), * else we should return undefined */ - if ( - options === 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" - ); + 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, @@ -205,38 +128,16 @@ function getRecipeInterface(querier, config) { doAntiCsrfCheck = utils_2.normaliseHttpMethod(req.getMethod()) !== "get"; } 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, cookieAndHeaders_1.getRidFromHeader(req) !== undefined); 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 - ); + 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; } logger_1.logDebugMessage("getSession: Success!"); - return new sessionClass_1.default( - helpers, - accessToken, - response.session.handle, - response.session.userId, - response.session.userDataInJWT, - res - ); - } catch (err) { + return new sessionClass_1.default(helpers, accessToken, response.session.handle, response.session.userId, response.session.userDataInJWT, res); + } + catch (err) { if (err.type === error_1.default.UNAUTHORISED) { logger_1.logDebugMessage("getSession: Clearing cookies because of UNAUTHORISED response"); cookieAndHeaders_1.clearSessionFromCookie(config, res); @@ -245,7 +146,7 @@ function getRecipeInterface(querier, config) { } }); }, - getSessionInformation: function ({ sessionHandle }) { + getSessionInformation: function ({ sessionHandle, }) { return __awaiter(this, void 0, void 0, function* () { return SessionFunctions.getSessionInformation(helpers, sessionHandle); }); @@ -254,65 +155,40 @@ function getRecipeInterface(querier, config) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("refreshSession: Started"); if (!res.wrapperUsed) { - res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse( - res - ); + res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse(res); } if (!req.wrapperUsed) { - req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest( - req - ); + req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest(req); } let inputIdRefreshToken = cookieAndHeaders_1.getIdRefreshTokenFromCookie(req); if (inputIdRefreshToken === undefined) { - logger_1.logDebugMessage( - "refreshSession: UNAUTHORISED because idRefreshToken from cookies is 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?", + message: "Session does not exist. Are you sending the session tokens in the request as cookies?", type: error_1.default.UNAUTHORISED, }); } try { let inputRefreshToken = cookieAndHeaders_1.getRefreshTokenFromCookie(req); if (inputRefreshToken === undefined) { - logger_1.logDebugMessage( - "refreshSession: UNAUTHORISED because refresh token from cookies is undefined" - ); + logger_1.logDebugMessage("refreshSession: UNAUTHORISED because refresh token from cookies 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 as a cookie?", type: error_1.default.UNAUTHORISED, }); } let antiCsrfToken = cookieAndHeaders_1.getAntiCsrfTokenFromHeaders(req); - let response = yield SessionFunctions.refreshSession( - helpers, - inputRefreshToken, - antiCsrfToken, - cookieAndHeaders_1.getRidFromHeader(req) !== undefined - ); + 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.userDataInJWT, - res - ); - } catch (err) { - if ( - (err.type === error_1.default.UNAUTHORISED && err.payload.clearCookies) || - err.type === error_1.default.TOKEN_THEFT_DETECTED - ) { - logger_1.logDebugMessage( - "refreshSession: Clearing cookies because of UNAUTHORISED or TOKEN_THEFT_DETECTED response" - ); + return new sessionClass_1.default(helpers, response.accessToken.token, response.session.handle, response.session.userId, response.session.userDataInJWT, res); + } + catch (err) { + if ((err.type === error_1.default.UNAUTHORISED && err.payload.clearCookies) || + err.type === error_1.default.TOKEN_THEFT_DETECTED) { + logger_1.logDebugMessage("refreshSession: Clearing cookies because of UNAUTHORISED or TOKEN_THEFT_DETECTED response"); cookieAndHeaders_1.clearSessionFromCookie(config, res); } throw err; @@ -321,17 +197,13 @@ function getRecipeInterface(querier, config) { }, 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") { throw new error_1.default({ message: response.message, @@ -353,10 +225,10 @@ function getRecipeInterface(querier, config) { 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); }, getAccessTokenLifeTimeMS: function () { diff --git a/lib/build/recipe/session/sessionClass.d.ts b/lib/build/recipe/session/sessionClass.d.ts index 11fd84103..468d45a46 100644 --- a/lib/build/recipe/session/sessionClass.d.ts +++ b/lib/build/recipe/session/sessionClass.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { BaseResponse } from "../../framework"; import { SessionContainerInterface } from "./types"; import { Helpers } from "./recipeImplementation"; @@ -9,14 +8,7 @@ export default class Session implements SessionContainerInterface { protected res: BaseResponse; protected accessToken: string; protected helpers: Helpers; - constructor( - helpers: Helpers, - accessToken: string, - sessionHandle: string, - userId: string, - userDataInAccessToken: any, - res: BaseResponse - ); + constructor(helpers: Helpers, accessToken: string, sessionHandle: string, userId: string, userDataInAccessToken: any, res: BaseResponse); revokeSession: (userContext?: any) => Promise; getSessionData: (userContext?: any) => Promise; updateSessionData: (newSessionData: any, userContext?: any) => Promise; diff --git a/lib/build/recipe/session/sessionClass.js b/lib/build/recipe/session/sessionClass.js index 01605bf47..3f91fec88 100644 --- a/lib/build/recipe/session/sessionClass.js +++ b/lib/build/recipe/session/sessionClass.js @@ -1,80 +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 cookieAndHeaders_1 = require("./cookieAndHeaders"); const error_1 = require("./error"); class Session { constructor(helpers, accessToken, sessionHandle, userId, userDataInAccessToken, res) { - this.revokeSession = (userContext) => - __awaiter(this, void 0, void 0, function* () { - if ( - yield this.helpers.sessionRecipeImpl.revokeSession({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - }) - ) { + this.revokeSession = (userContext) => __awaiter(this, void 0, void 0, function* () { + if (yield this.helpers.sessionRecipeImpl.revokeSession({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + })) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + } + }); + this.getSessionData = (userContext) => __awaiter(this, void 0, void 0, function* () { + try { + return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + })).sessionData; + } + catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); } - }); - this.getSessionData = (userContext) => - __awaiter(this, void 0, void 0, function* () { - try { - return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - })).sessionData; - } catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); - } - throw err; - } - }); - this.updateSessionData = (newSessionData, userContext) => - __awaiter(this, void 0, void 0, function* () { - try { - yield this.helpers.sessionRecipeImpl.updateSessionData({ - sessionHandle: this.sessionHandle, - newSessionData, - userContext: userContext === undefined ? {} : userContext, - }); - } catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); - } - throw err; + throw err; + } + }); + this.updateSessionData = (newSessionData, userContext) => __awaiter(this, void 0, void 0, function* () { + try { + yield this.helpers.sessionRecipeImpl.updateSessionData({ + sessionHandle: this.sessionHandle, + newSessionData, + userContext: userContext === undefined ? {} : userContext, + }); + } + catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); } - }); + throw err; + } + }); this.getUserId = () => { return this.userId; }; @@ -87,65 +62,55 @@ class Session { this.getAccessToken = () => { return this.accessToken; }; - this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => - __awaiter(this, void 0, void 0, function* () { - try { - let response = yield this.helpers.sessionRecipeImpl.regenerateAccessToken({ - accessToken: this.getAccessToken(), - newAccessTokenPayload, - userContext: userContext === undefined ? {} : userContext, - }); - 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 - ); - } - } catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); - } - throw err; + this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => __awaiter(this, void 0, void 0, function* () { + try { + let response = yield this.helpers.sessionRecipeImpl.regenerateAccessToken({ + accessToken: this.getAccessToken(), + newAccessTokenPayload, + userContext: userContext === undefined ? {} : userContext, + }); + 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); + } + } + catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); } - }); - this.getTimeCreated = (userContext) => - __awaiter(this, void 0, void 0, function* () { - try { - return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - })).timeCreated; - } catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); - } - throw err; + throw err; + } + }); + this.getTimeCreated = (userContext) => __awaiter(this, void 0, void 0, function* () { + try { + return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + })).timeCreated; + } + catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); } - }); - this.getExpiry = (userContext) => - __awaiter(this, void 0, void 0, function* () { - try { - return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - })).expiry; - } catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); - } - throw err; + throw err; + } + }); + this.getExpiry = (userContext) => __awaiter(this, void 0, void 0, function* () { + try { + return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + })).expiry; + } + catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); } - }); + throw err; + } + }); this.sessionHandle = sessionHandle; this.userId = userId; this.userDataInAccessToken = userDataInAccessToken; diff --git a/lib/build/recipe/session/sessionFunctions.d.ts b/lib/build/recipe/session/sessionFunctions.d.ts index 3e5458f9a..3e12ae77b 100644 --- a/lib/build/recipe/session/sessionFunctions.d.ts +++ b/lib/build/recipe/session/sessionFunctions.d.ts @@ -1,25 +1,13 @@ -// @ts-nocheck import { CreateOrRefreshAPIResponse, SessionInformation } from "./types"; import { Helpers } from "./recipeImplementation"; /** * @description call this to "login" a user. */ -export declare function createNewSession( - helpers: Helpers, - userId: string, - accessTokenPayload?: any, - sessionData?: any -): Promise; +export declare function createNewSession(helpers: Helpers, userId: 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, accessToken: string, antiCsrfToken: string | undefined, doAntiCsrfCheck: boolean, containsCustomHeader: boolean): Promise<{ session: { handle: string; userId: string; @@ -40,12 +28,7 @@ export declare function getSessionInformation(helpers: Helpers, sessionHandle: s * @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): 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. @@ -74,8 +57,4 @@ export declare function updateSessionData(helpers: Helpers, sessionHandle: strin * @returns access token payload as provided by the user earlier */ export declare function getAccessTokenPayload(helpers: Helpers, sessionHandle: string): Promise; -export declare function updateAccessTokenPayload( - helpers: Helpers, - sessionHandle: string, - newAccessTokenPayload: 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 9344ed5b5..e9ccd1023 100644 --- a/lib/build/recipe/session/sessionFunctions.js +++ b/lib/build/recipe/session/sessionFunctions.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. * @@ -66,15 +44,8 @@ function createNewSession(helpers, userId, accessTokenPayload = {}, 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 - ); + 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; @@ -97,13 +68,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(accessToken, 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 @@ -132,7 +100,8 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai let payload; try { payload = jwt_1.getPayloadWithoutVerifiying(accessToken); - } catch (_) { + } + catch (_) { throw err; } if (payload === undefined) { @@ -173,18 +142,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, @@ -192,24 +157,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, @@ -225,39 +186,29 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai 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); } @@ -290,7 +241,8 @@ function getSessionInformation(helpers, sessionHandle) { delete response.userDataInJWT; delete response.userDataInJWT; return response; - } else { + } + else { throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, @@ -313,9 +265,7 @@ function refreshSession(helpers, refreshToken, antiCsrfToken, containsCustomHead }; if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { 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, @@ -325,20 +275,19 @@ 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", @@ -358,12 +307,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 +332,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 +345,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; }); } @@ -442,7 +382,8 @@ function getAccessTokenPayload(helpers, sessionHandle) { }); if (response.status === "OK") { return response.userDataInJWT; - } else { + } + else { throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, diff --git a/lib/build/recipe/session/types.d.ts b/lib/build/recipe/session/types.d.ts index 5afa5169d..e1e77058e 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"; @@ -15,16 +14,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; @@ -59,39 +55,22 @@ export declare type TypeInput = { cookieDomain?: string; 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; }; }; }; @@ -110,29 +89,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; }; }; }; @@ -169,18 +133,41 @@ export declare type RecipeInterface = { options?: VerifySessionOptions; userContext: any; }): Promise; - refreshSession(input: { req: any; res: any; userContext: any }): Promise; + refreshSession(input: { + req: any; + res: any; + userContext: any; + }): Promise; /** * Used to retrieve all session information for a given session handle. Can be used in place of: * - getSessionData * - getAccessTokenPayload */ - 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; updateAccessTokenPayload(input: { sessionHandle: string; newAccessTokenPayload: any; @@ -203,8 +190,12 @@ export declare type RecipeInterface = { createdTime: number; }; }>; - getAccessTokenLifeTimeMS(input: { userContext: any }): Promise; - getRefreshTokenLifeTimeMS(input: { userContext: any }): Promise; + getAccessTokenLifeTimeMS(input: { + userContext: any; + }): Promise; + getRefreshTokenLifeTimeMS(input: { + userContext: any; + }): Promise; }; export interface SessionContainerInterface { revokeSession(userContext?: any): Promise; @@ -227,15 +218,16 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - refreshPOST: undefined | ((input: { options: APIOptions; userContext: any }) => Promise); - signOutPOST: - | undefined - | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - }>); + refreshPOST: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise); + signOutPOST: undefined | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + }>); verifySession(input: { verifySessionOptions: VerifySessionOptions | undefined; options: APIOptions; diff --git a/lib/build/recipe/session/utils.d.ts b/lib/build/recipe/session/utils.d.ts index a13680795..34d0d5032 100644 --- a/lib/build/recipe/session/utils.d.ts +++ b/lib/build/recipe/session/utils.d.ts @@ -1,38 +1,13 @@ -// @ts-nocheck import { CreateOrRefreshAPIResponse, TypeInput, TypeNormalisedInput } 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 sendTokenTheftDetectedResponse( - recipeInstance: SessionRecipe, - sessionHandle: 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 sendTokenTheftDetectedResponse(recipeInstance: SessionRecipe, sessionHandle: 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 attachCreateOrRefreshSessionResponseToExpressRes(config: TypeNormalisedInput, res: BaseResponse, response: CreateOrRefreshAPIResponse): void; diff --git a/lib/build/recipe/session/utils.js b/lib/build/recipe/session/utils.js index 3dd8ee784..8ae46e9aa 100644 --- a/lib/build/recipe/session/utils.js +++ b/lib/build/recipe/session/utils.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 cookieAndHeaders_1 = require("./cookieAndHeaders"); const url_1 = require("url"); @@ -90,7 +68,8 @@ function normaliseSessionScopeOrThrowError(sessionScope) { sessionScope = sessionScope.substr(1); } return sessionScope; - } catch (err) { + } + catch (err) { throw new Error("Please provide a valid sessionScope"); } } @@ -124,50 +103,42 @@ function getURLProtocol(url) { } exports.getURLProtocol = getURLProtocol; function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { - let cookieDomain = - config === undefined || config.cookieDomain === undefined - ? undefined - : normaliseSessionScopeOrThrowError(config.cookieDomain); + let cookieDomain = config === undefined || config.cookieDomain === undefined + ? 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 = - topLevelAPIDomain !== topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain ? "none" : "lax"; + let cookieSameSite = topLevelAPIDomain !== 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; + let cookieSecure = config === undefined || config.cookieSecure === undefined + ? appInfo.apiDomain.getAsStringDangerous().startsWith("https") + : config.cookieSecure; + let sessionExpiredStatusCode = config === undefined || config.sessionExpiredStatusCode === undefined ? 401 : config.sessionExpiredStatusCode; if (config !== undefined && config.antiCsrf !== undefined) { if (config.antiCsrf !== "NONE" && config.antiCsrf !== "VIA_CUSTOM_HEADER" && config.antiCsrf !== "VIA_TOKEN") { 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, request, response) => - __awaiter(this, void 0, void 0, function* () { - return yield sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, userId, 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, request, response) => __awaiter(this, void 0, void 0, function* () { + return yield sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, userId, 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); + }), }; if (config !== undefined && config.errorHandlers !== undefined) { if (config.errorHandlers.onTokenTheftDetected !== undefined) { @@ -177,15 +148,11 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { errorHandlers.onUnauthorised = config.errorHandlers.onUnauthorised; } } - if ( - cookieSameSite === "none" && + if (cookieSameSite === "none" && !cookieSecure && !(topLevelAPIDomain === "localhost" || utils_1.isAnIpAddress(topLevelAPIDomain)) && - !(topLevelWebsiteDomain === "localhost" || utils_1.isAnIpAddress(topLevelWebsiteDomain)) - ) { - 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." - ); + !(topLevelWebsiteDomain === "localhost" || utils_1.isAnIpAddress(topLevelWebsiteDomain))) { + 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"; @@ -201,13 +168,7 @@ 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)), cookieDomain, @@ -238,12 +199,7 @@ function attachCreateOrRefreshSessionResponseToExpressRes(config, res, response) 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.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); 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/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 5324e6382..d0ca100a8 100644 --- a/lib/build/recipe/session/with-jwt/recipeImplementation.js +++ b/lib/build/recipe/session/with-jwt/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 }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -64,14 +42,11 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { function getJWTExpiry(accessTokenExpiry) { return accessTokenExpiry + EXPIRY_OFFSET_SECONDS; } - return Object.assign(Object.assign({}, originalImplementation), { - createNewSession: function ({ res, userId, accessTokenPayload, sessionData, userContext }) { + return Object.assign(Object.assign({}, originalImplementation), { createNewSession: function ({ res, userId, 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), @@ -89,8 +64,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) { @@ -98,12 +72,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(); @@ -118,15 +89,13 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { yield newSession.updateAccessTokenPayload(accessTokenPayload); return new sessionClass_1.default(newSession, openIdRecipeImplementation); }); - }, - updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext }) { + }, updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext, }) { return __awaiter(this, void 0, void 0, function* () { newAccessTokenPayload = newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; let sessionInformation = yield this.getSessionInformation({ sessionHandle, userContext }); let accessTokenPayload = sessionInformation.accessTokenPayload; - let existingJwtPropertyName = - accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; + let existingJwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; if (existingJwtPropertyName === undefined) { return yield originalImplementation.updateAccessTokenPayload({ sessionHandle, @@ -165,7 +134,6 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { 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 6912ae928..945666439 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 { SessionContainerInterface } from "../types"; export default class SessionClassWithJWT implements SessionContainerInterface { diff --git a/lib/build/recipe/session/with-jwt/sessionClass.js b/lib/build/recipe/session/with-jwt/sessionClass.js index 1e9c37986..fa95bdf25 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. * @@ -78,41 +56,40 @@ class SessionClassWithJWT { this.getExpiry = (userContext) => { return this.originalSessionClass.getExpiry(userContext); }; - this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => - __awaiter(this, void 0, void 0, function* () { - newAccessTokenPayload = - newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; - let accessTokenPayload = this.getAccessTokenPayload(userContext); - let jwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; - if (jwtPropertyName === undefined) { - return this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); - } - let existingJWT = accessTokenPayload[jwtPropertyName]; - assert.notStrictEqual(existingJWT, undefined); - let currentTimeInSeconds = Date.now() / 1000; - let decodedPayload = JsonWebToken.decode(existingJWT, { json: true }); - // JsonWebToken.decode possibly returns null - if (decodedPayload === null) { - throw new Error("Error reading JWT from session"); - } - let jwtExpiry = decodedPayload.exp - currentTimeInSeconds; - if (jwtExpiry <= 0) { - // it can come here if someone calls this function well after - // the access token and the jwt payload have expired (which can happen if an API takes a VERY long time). In this case, we still want the jwt payload to update, but the resulting JWT should - // not be alive for too long (since it's expired already). So we set it to - // 1 second lifetime. - jwtExpiry = 1; - } - newAccessTokenPayload = yield utils_1.addJWTToAccessTokenPayload({ - accessTokenPayload: newAccessTokenPayload, - jwtExpiry, - userId: this.getUserId(), - jwtPropertyName, - openIdRecipeImplementation: this.openIdRecipeImplementation, - userContext, - }); - return yield this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); + this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => __awaiter(this, void 0, void 0, function* () { + newAccessTokenPayload = + newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; + let accessTokenPayload = this.getAccessTokenPayload(userContext); + let jwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; + if (jwtPropertyName === undefined) { + return this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); + } + let existingJWT = accessTokenPayload[jwtPropertyName]; + assert.notStrictEqual(existingJWT, undefined); + let currentTimeInSeconds = Date.now() / 1000; + let decodedPayload = JsonWebToken.decode(existingJWT, { json: true }); + // JsonWebToken.decode possibly returns null + if (decodedPayload === null) { + throw new Error("Error reading JWT from session"); + } + let jwtExpiry = decodedPayload.exp - currentTimeInSeconds; + if (jwtExpiry <= 0) { + // it can come here if someone calls this function well after + // the access token and the jwt payload have expired (which can happen if an API takes a VERY long time). In this case, we still want the jwt payload to update, but the resulting JWT should + // not be alive for too long (since it's expired already). So we set it to + // 1 second lifetime. + jwtExpiry = 1; + } + newAccessTokenPayload = yield utils_1.addJWTToAccessTokenPayload({ + accessTokenPayload: newAccessTokenPayload, + jwtExpiry, + userId: this.getUserId(), + jwtPropertyName, + openIdRecipeImplementation: this.openIdRecipeImplementation, + userContext, }); + return yield this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); + }); this.openIdRecipeImplementation = openIdRecipeImplementation; this.originalSessionClass = originalSessionClass; } 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..9f4a72f43 100644 --- a/lib/build/recipe/session/with-jwt/utils.js +++ b/lib/build/recipe/session/with-jwt/utils.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. * @@ -46,14 +24,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 +35,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 +49,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 +66,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 32d249bf4..f7a2bd08f 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 }); function appleRedirectHandler(apiImplementation, options) { return __awaiter(this, void 0, void 0, function* () { 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 08a72b0ef..33c1d035e 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 c30026102..8ad0191ed 100644 --- a/lib/build/recipe/thirdparty/api/implementation.js +++ b/lib/build/recipe/thirdparty/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 session_1 = require("../../session"); const url_1 = require("url"); @@ -37,7 +15,7 @@ const axios = require("axios"); const qs = require("querystring"); function getAPIInterface() { return { - 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 = {}; @@ -47,10 +25,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 @@ -63,9 +39,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)); } }); } @@ -80,7 +54,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; @@ -88,7 +62,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); @@ -99,14 +74,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)); } }); } @@ -122,7 +96,8 @@ function getAPIInterface() { } try { userInfo = yield providerInfo.getProfileInfo(accessTokenAPIResponse.data, userContext); - } catch (err) { + } + catch (err) { if (err.message !== undefined) { return { status: "FIELD_ERROR", @@ -149,13 +124,11 @@ function getAPIInterface() { // we set the email as verified if already verified by the OAuth provider. // This block was added because of https://github.com/supertokens/supertokens-core/issues/295 if (emailInfo.isVerified) { - const tokenResponse = yield options.emailVerificationRecipeImplementation.createEmailVerificationToken( - { - userId: response.user.id, - email: response.user.email, - userContext, - } - ); + const tokenResponse = yield options.emailVerificationRecipeImplementation.createEmailVerificationToken({ + userId: response.user.id, + email: response.user.email, + userContext, + }); if (tokenResponse.status === "OK") { yield options.emailVerificationRecipeImplementation.verifyEmailUsingToken({ token: tokenResponse.token, @@ -163,13 +136,7 @@ function getAPIInterface() { }); } } - let session = yield session_1.default.createNewSession( - options.res, - response.user.id, - {}, - {}, - userContext - ); + let session = yield session_1.default.createNewSession(options.res, response.user.id, {}, {}, userContext); return { status: "OK", createdNewUser: response.createdNewUser, @@ -181,16 +148,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(``); }); }, }; 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 62e05eb24..a9d32fbba 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"); @@ -94,14 +72,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.`, }); @@ -122,11 +99,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, { status: "FIELD_ERROR", error: result.error, 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/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 b96ce5525..50797952b 100644 --- a/lib/build/recipe/thirdparty/index.d.ts +++ b/lib/build/recipe/thirdparty/index.d.ts @@ -1,69 +1,37 @@ -// @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: { - id: string; - isVerified: boolean; - }, - userContext?: any - ): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "FIELD_ERROR"; - error: string; - } - >; + static signInUp(thirdPartyId: string, thirdPartyUserId: string, email: { + id: string; + isVerified: boolean; + }, userContext?: any): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "FIELD_ERROR"; + error: string; + }>; static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise; - static getUserByThirdPartyInfo( - thirdPartyId: string, - thirdPartyUserId: string, - userContext?: any - ): Promise; - static createEmailVerificationToken( - userId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - } - >; - static verifyEmailUsingToken( - token: string, - userContext?: any - ): Promise< - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - | User - | undefined - >; + static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; + static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + }>; + static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } | User | undefined>; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens( - userId: string, - userContext?: any - ): Promise<{ + static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ status: "OK"; }>; - static unverifyEmail( - userId: string, - userContext?: any - ): Promise<{ + static unverifyEmail(userId: string, userContext?: any): Promise<{ status: "OK"; }>; static Google: typeof import("./providers/google").default; diff --git a/lib/build/recipe/thirdparty/index.js b/lib/build/recipe/thirdparty/index.js index 8c10b0c58..6fe0b81f6 100644 --- a/lib/build/recipe/thirdparty/index.js +++ b/lib/build/recipe/thirdparty/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); 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 2587fd9ca..93e0dd2f5 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 1a808b91d..3e5900f0d 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/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..8fce5a38e 100644 --- a/lib/build/recipe/thirdparty/providers/utils.js +++ b/lib/build/recipe/thirdparty/providers/utils.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 jwt = require("jsonwebtoken"); const jwksClient = require("jwks-rsa"); @@ -48,7 +26,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 50bf15fd1..bed75b2b5 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"; @@ -15,26 +14,14 @@ export default class Recipe extends RecipeModule { recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; isInServerlessEnv: boolean; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { + emailVerificationInstance: EmailVerificationRecipe | undefined; + }); 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 3e7184571..60cbe516b 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,71 +62,63 @@ class Recipe extends recipeModule_1.default { ...this.emailVerificationRecipe.getAPIsHandled(), ]; }; - 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, - emailVerificationRecipeImplementation: this.emailVerificationRecipe.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); - } else { - return yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); - } - }); - this.handleError = (err, request, response) => - __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - throw err; - } else { - return yield this.emailVerificationRecipe.handleError(err, request, 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, + emailVerificationRecipeImplementation: this.emailVerificationRecipe.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); + } + else { + return yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + } + }); + this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + throw err; + } + else { + return yield this.emailVerificationRecipe.handleError(err, request, response); + } + }); this.getAllCORSHeaders = () => { return [...this.emailVerificationRecipe.getAllCORSHeaders()]; }; this.isErrorFromThisRecipe = (err) => { - return ( - error_1.default.isErrorFromSuperTokens(err) && - (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err)) - ); + return (error_1.default.isErrorFromSuperTokens(err) && + (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err))); }; // helper functions... - this.getEmailForUserId = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo === undefined) { - throw Error("Unknown User ID provided"); - } - return userInfo.email; - }); + this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw Error("Unknown User ID provided"); + } + return userInfo.email; + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default( - recipeId, - appInfo, - isInServerlessEnv, - Object.assign({}, this.config.emailVerificationFeature) - ); + : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign({}, this.config.emailVerificationFeature)); 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(); } { @@ -163,7 +133,8 @@ class Recipe extends recipeModule_1.default { emailVerificationInstance: 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 7f0c83637..dafb92577 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 e3787815c..7a364e921 100644 --- a/lib/build/recipe/thirdparty/types.d.ts +++ b/lib/build/recipe/thirdparty/types.d.ts @@ -1,8 +1,4 @@ -// @ts-nocheck -import { - RecipeInterface as EmailVerificationRecipeInterface, - APIInterface as EmailVerificationAPIInterface, -} from "../emailverification"; +import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; import { BaseRequest, BaseResponse } from "../../framework"; import { NormalisedAppinfo } from "../../types"; @@ -34,11 +30,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 = { @@ -64,20 +56,11 @@ export declare type TypeInput = { signInAndUpFeature: TypeInputSignInAndUp; emailVerificationFeature?: TypeInputEmailVerificationFeature; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; @@ -85,26 +68,23 @@ export declare type TypeNormalisedInput = { signInAndUpFeature: TypeNormalisedInputSignInAndUp; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; 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; @@ -118,17 +98,14 @@ export declare type RecipeInterface = { isVerified: boolean; }; userContext: any; - }): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "FIELD_ERROR"; - error: string; - } - >; + }): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "FIELD_ERROR"; + error: string; + }>; }; export declare type APIOptions = { recipeImplementation: RecipeInterface; @@ -142,43 +119,38 @@ export declare type APIOptions = { appInfo: NormalisedAppinfo; }; export declare type APIInterface = { - authorisationUrlGET: - | undefined - | ((input: { - provider: TypeProvider; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - url: string; - }>); - signInUpPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: APIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } - | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } - | { - status: "FIELD_ERROR"; - error: string; - } - >); - 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; + }>); + signInUpPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } | { + status: "FIELD_ERROR"; + error: string; + }>); + 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 828d15afd..b37ed4cf4 100644 --- a/lib/build/recipe/thirdparty/utils.d.ts +++ b/lib/build/recipe/thirdparty/utils.d.ts @@ -1,15 +1,6 @@ -// @ts-nocheck import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeProvider } from "./types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput( - recipeInstance: Recipe, - appInfo: NormalisedAppinfo, - config: TypeInput -): TypeNormalisedInput; -export declare function findRightProvider( - providers: TypeProvider[], - thirdPartyId: string, - clientId?: string -): TypeProvider | undefined; +export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, 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 2599914f9..4919096c8 100644 --- a/lib/build/recipe/thirdparty/utils.js +++ b/lib/build/recipe/thirdparty/utils.js @@ -13,48 +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 }); function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { let emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, 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 { emailVerificationFeature, signInAndUpFeature, @@ -86,9 +58,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.. @@ -108,18 +78,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, @@ -129,63 +95,34 @@ function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserId, - override: - (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 - ? void 0 - : _a.emailVerificationFeature, - createAndSendCustomEmail: - ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _b === void 0 - ? void 0 - : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_d = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _d === void 0 - ? void 0 - : _d.createAndSendCustomEmail) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail( - userInfo, - link, - userContext - ); - }), - getEmailVerificationURL: - ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _c === void 0 - ? void 0 - : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_e = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _e === void 0 - ? void 0 - : _e.getEmailVerificationURL) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, + createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); + }), + getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } 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 c8d9d033a..86a6a2bed 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js @@ -3,24 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e; 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), + 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), }; } 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 f9420149f..4d90d420a 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/implementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/implementation.js @@ -9,38 +9,14 @@ 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)), - passwordResetPOST: - (_f = emailPasswordImplementation.passwordResetPOST) === null || _f === void 0 - ? void 0 - : _f.bind(emailPasswordAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: - (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 - ? void 0 - : _g.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: - (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 - ? void 0 - : _h.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)), + passwordResetPOST: (_f = emailPasswordImplementation.passwordResetPOST) === null || _f === void 0 ? void 0 : _f.bind(emailPasswordAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 ? void 0 : _h.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 0023e4411..ac7562f07 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js @@ -1,66 +1,34 @@ "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; - const signInUpPOSTFromThirdPartyEmailPassword = - (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyEmailPassword = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); return { - authorisationUrlGET: - (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), - appleRedirectHandlerPOST: - (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 - ? void 0 - : _c.bind(apiImplmentation), - 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: (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), + appleRedirectHandlerPOST: (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + 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/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 f5c7d34a3..73f881664 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"; @@ -6,83 +5,44 @@ import { TypeProvider } from "../thirdparty/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp( - thirdPartyId: string, - thirdPartyUserId: string, - email: { - id: string; - isVerified: boolean; - }, - userContext?: any - ): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "FIELD_ERROR"; - error: string; - } - >; - 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 thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: { + id: string; + isVerified: boolean; + }, userContext?: any): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "FIELD_ERROR"; + error: string; + }>; + 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, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "UNKNOWN_USER_ID_ERROR"; - } - >; - static resetPasswordUsingToken( - token: string, - newPassword: string, - userContext?: any - ): Promise< - | { - status: "OK"; - userId?: string | undefined; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + static createResetPasswordToken(userId: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "UNKNOWN_USER_ID_ERROR"; + }>; + static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ + status: "OK"; + userId?: string | undefined; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; static updateEmailOrPassword(input: { userId: string; email?: string; @@ -91,39 +51,20 @@ export default class Wrapper { }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; }>; - static createEmailVerificationToken( - userId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - } - >; - static verifyEmailUsingToken( - token: string, - userContext?: any - ): Promise< - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - | User - | undefined - >; + static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + }>; + static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } | User | undefined>; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens( - userId: string, - userContext?: any - ): Promise<{ + static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ status: "OK"; }>; - static unverifyEmail( - userId: string, - userContext?: any - ): Promise<{ + static unverifyEmail(userId: string, userContext?: any): Promise<{ status: "OK"; }>; static Google: typeof import("../thirdparty/providers/google").default; diff --git a/lib/build/recipe/thirdpartyemailpassword/index.js b/lib/build/recipe/thirdpartyemailpassword/index.js index 9bdbc5d65..1a8a52895 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); @@ -85,9 +63,7 @@ class Wrapper { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsersByEmail({ email, userContext }); } static createResetPasswordToken(userId, userContext = {}) { - return recipe_1.default - .getInstanceOrThrowError() - .recipeInterfaceImpl.createResetPasswordToken({ userId, userContext }); + return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createResetPasswordToken({ userId, userContext }); } static resetPasswordUsingToken(token, newPassword, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.resetPasswordUsingToken({ @@ -97,9 +73,7 @@ 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 createEmailVerificationToken(userId, userContext = {}) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts index d358bea66..b90b37d45 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import EmailVerificationRecipe from "../emailverification/recipe"; @@ -19,33 +18,17 @@ export default class Recipe extends RecipeModule { private thirdPartyRecipe; recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - thirdPartyInstance: ThirdPartyRecipe | undefined; - emailPasswordInstance: EmailPasswordRecipe | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { + emailVerificationInstance: EmailVerificationRecipe | undefined; + thirdPartyInstance: ThirdPartyRecipe | undefined; + emailPasswordInstance: EmailPasswordRecipe | 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; getEmailForUserId: (userId: string, userContext: any) => Promise; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.js b/lib/build/recipe/thirdpartyemailpassword/recipe.js index 44d068448..d6e82126b 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. * @@ -72,35 +50,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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + }); + 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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); - }); - 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); - } - return yield this.emailVerificationRecipe.handleError(err, request, response); + else if (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)) { + return yield this.thirdPartyRecipe.handleError(err, request, response); } - }); + return yield this.emailVerificationRecipe.handleError(err, request, response); + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [ ...this.emailVerificationRecipe.getAllCORSHeaders(), @@ -112,31 +85,23 @@ 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.emailVerificationRecipe.isErrorFromThisRecipe(err) || this.emailPasswordRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) - ); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); }; // helper functions... - this.getEmailForUserId = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo === undefined) { - throw new Error("Unknown User ID provided"); - } - return userInfo.email; - }); + this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw new Error("Unknown User ID provided"); + } + return userInfo.email; + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default( - querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), - querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID) - ) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -146,60 +111,43 @@ class Recipe extends recipeModule_1.default { this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default( - recipeId, - appInfo, - isInServerlessEnv, - Object.assign({}, this.config.emailVerificationFeature) - ); + : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign({}, this.config.emailVerificationFeature)); this.emailPasswordRecipe = recipes.emailPasswordInstance !== undefined ? recipes.emailPasswordInstance - : new recipe_2.default( - recipeId, - appInfo, - isInServerlessEnv, - { - override: { - functions: (_) => { - return emailPasswordRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return emailPasswordAPIImplementation_1.default(this.apiImpl); - }, - }, - signUpFeature: { - formFields: this.config.signUpFeature.formFields, - }, - resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, - }, - { emailVerificationInstance: this.emailVerificationRecipe } - ); + : new recipe_2.default(recipeId, appInfo, isInServerlessEnv, { + override: { + functions: (_) => { + return emailPasswordRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return emailPasswordAPIImplementation_1.default(this.apiImpl); + }, + }, + signUpFeature: { + formFields: this.config.signUpFeature.formFields, + }, + resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, + }, { emailVerificationInstance: this.emailVerificationRecipe }); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_3.default( - recipeId, - appInfo, - isInServerlessEnv, - { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, - { - emailVerificationInstance: this.emailVerificationRecipe, - } - ); + : new recipe_3.default(recipeId, appInfo, isInServerlessEnv, { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, { + emailVerificationInstance: this.emailVerificationRecipe, + }); } } static init(config) { @@ -211,10 +159,9 @@ class Recipe extends recipeModule_1.default { thirdPartyInstance: 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 481c0a3db..52907c9f1 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 43efd9a15..11ef357ce 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -1,17 +1,7 @@ -// @ts-nocheck import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; -import { - RecipeInterface as EmailVerificationRecipeInterface, - APIInterface as EmailVerificationAPIInterface, -} from "../emailverification"; -import { - NormalisedFormField, - TypeFormField, - TypeInputFormField, - TypeInputResetPasswordUsingTokenFeature, - APIOptions as EmailPasswordAPIOptionsOriginal, -} from "../emailpassword/types"; +import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; +import { NormalisedFormField, TypeFormField, TypeInputFormField, TypeInputResetPasswordUsingTokenFeature, APIOptions as EmailPasswordAPIOptionsOriginal } from "../emailpassword/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; export declare type User = { @@ -50,20 +40,11 @@ export declare type TypeInput = { resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; emailVerificationFeature?: TypeInputEmailVerificationFeature; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; @@ -73,26 +54,23 @@ export declare type TypeNormalisedInput = { resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; 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; @@ -106,72 +84,57 @@ export declare type RecipeInterface = { isVerified: boolean; }; userContext: any; - }): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "FIELD_ERROR"; - error: string; - } - >; + }): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "FIELD_ERROR"; + error: string; + }>; emailPasswordSignUp(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"; + }>; 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; 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"; - /** - * The id of the user whose password was reset. - * Defined for Core versions 3.9 or later - */ - userId?: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >; + }): Promise<{ + status: "OK"; + /** + * The id of the user whose password was reset. + * Defined for Core versions 3.9 or later + */ + userId?: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>; updateEmailOrPassword(input: { userId: string; email?: string; @@ -184,122 +147,98 @@ export declare type RecipeInterface = { export declare type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; export declare type ThirdPartyAPIOptions = ThirdPartyAPIOptionsOriginal; export declare type APIInterface = { - authorisationUrlGET: - | undefined - | ((input: { - provider: TypeProvider; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - url: string; - }>); - emailPasswordEmailExistsGET: - | undefined - | ((input: { - email: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); - generatePasswordResetTokenPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - }>); - passwordResetPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - userId?: string; - } - | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - } - >); - thirdPartySignInUpPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } - | { - status: "FIELD_ERROR"; - error: string; - } - | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } - >); - emailPasswordSignInPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "WRONG_CREDENTIALS_ERROR"; - } - >); - emailPasswordSignUpPOST: - | undefined - | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - user: User; - session: SessionContainerInterface; - } - | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - } - >); - appleRedirectHandlerPOST: - | undefined - | ((input: { code: string; state: string; options: ThirdPartyAPIOptions; userContext: any }) => Promise); + authorisationUrlGET: undefined | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + url: string; + }>); + emailPasswordEmailExistsGET: undefined | ((input: { + email: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); + generatePasswordResetTokenPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + }>); + passwordResetPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + userId?: string; + } | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + }>); + thirdPartySignInUpPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } | { + status: "FIELD_ERROR"; + error: string; + } | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + }>); + emailPasswordSignInPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + session: SessionContainerInterface; + } | { + status: "WRONG_CREDENTIALS_ERROR"; + }>); + emailPasswordSignUpPOST: undefined | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + user: User; + session: SessionContainerInterface; + } | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + }>); + appleRedirectHandlerPOST: undefined | ((input: { + code: string; + state: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise); }; 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 23c016a7a..d8097494b 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.js +++ b/lib/build/recipe/thirdpartyemailpassword/utils.js @@ -13,55 +13,23 @@ * 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("../emailpassword/utils"); 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 emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, appInfo, 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, signUpFeature, @@ -81,63 +49,34 @@ function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserId, - override: - (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 - ? void 0 - : _a.emailVerificationFeature, - createAndSendCustomEmail: - ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _b === void 0 - ? void 0 - : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_d = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _d === void 0 - ? void 0 - : _d.createAndSendCustomEmail) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail( - userInfo, - link, - userContext - ); - }), - getEmailVerificationURL: - ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _c === void 0 - ? void 0 - : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_e = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _e === void 0 - ? void 0 - : _e.getEmailVerificationURL) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, + createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); + }), + getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } 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 e97a96569..b08e28e0b 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/implementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/implementation.js @@ -9,38 +9,14 @@ 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)), - resendCodePOST: - (_e = passwordlessImplementation.resendCodePOST) === null || _e === void 0 - ? void 0 - : _e.bind(passwordlessAPIImplementation_1.default(this)), - authorisationUrlGET: - (_f = thirdPartyImplementation.authorisationUrlGET) === null || _f === void 0 - ? void 0 - : _f.bind(thirdPartyAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: - (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 - ? void 0 - : _g.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: - (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 - ? void 0 - : _h.bind(thirdPartyAPIImplementation_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)), + resendCodePOST: (_e = passwordlessImplementation.resendCodePOST) === null || _e === void 0 ? void 0 : _e.bind(passwordlessAPIImplementation_1.default(this)), + authorisationUrlGET: (_f = thirdPartyImplementation.authorisationUrlGET) === null || _f === void 0 ? void 0 : _f.bind(thirdPartyAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 ? void 0 : _h.bind(thirdPartyAPIImplementation_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 25e56c8b2..d47f4307c 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js @@ -3,20 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e; 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), + 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), }; } 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 e3d01c889..a26a501e8 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js @@ -1,66 +1,34 @@ "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; - const signInUpPOSTFromThirdPartyPasswordless = - (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyPasswordless = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); return { - authorisationUrlGET: - (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), - appleRedirectHandlerPOST: - (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 - ? void 0 - : _c.bind(apiImplmentation), - 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: (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), + appleRedirectHandlerPOST: (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), + 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/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 d1d371cd1..e43f9f78a 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/index.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import Recipe from "./recipe"; import SuperTokensError from "./error"; import { RecipeInterface, User, APIInterface, PasswordlessAPIOptions, ThirdPartyAPIOptions } from "./types"; @@ -6,137 +5,89 @@ import { TypeProvider } from "../thirdparty/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp( - thirdPartyId: string, - thirdPartyUserId: string, - email: { + static thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: { + id: string; + isVerified: boolean; + }, userContext?: any): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "FIELD_ERROR"; + error: string; + }>; + static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) | ({ + email: string; + thirdParty: { id: string; - isVerified: boolean; - }, - userContext?: any - ): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "FIELD_ERROR"; - error: string; - } - >; - static getUserByThirdPartyInfo( - thirdPartyId: string, - thirdPartyUserId: string, - userContext?: any - ): Promise< - | ({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - timeJoined: number; - }) - | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) - | undefined - >; - static getUserById( - userId: string, - userContext?: any - ): Promise< - | ({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - timeJoined: number; - }) - | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) - | undefined - >; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) | undefined>; + static getUserById(userId: string, userContext?: any): Promise<({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) | ({ + email: string; + thirdParty: { + id: string; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) | undefined>; static getUsersByEmail(email: string, userContext?: any): Promise; - static createEmailVerificationToken( - userId: string, - userContext?: any - ): Promise< - | { - status: "OK"; - token: string; - } - | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - } - >; - static verifyEmailUsingToken( - token: string, - userContext?: any - ): Promise< - | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } - | ({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - timeJoined: number; - }) - | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) - | undefined - >; + static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ + status: "OK"; + token: string; + } | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + }>; + static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } | ({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) | ({ + email: string; + thirdParty: { + id: string; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) | undefined>; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens( - userId: string, - userContext?: any - ): Promise<{ + static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ status: "OK"; }>; - static unverifyEmail( - userId: string, - userContext?: any - ): Promise<{ + static unverifyEmail(userId: string, userContext?: any): Promise<{ status: "OK"; }>; - 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; @@ -150,72 +101,57 @@ 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; - timeJoined: number; - }) - | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) - | undefined - >; + }): Promise<({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) | ({ + email: string; + thirdParty: { + id: string; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) | undefined>; static updatePasswordlessUser(input: { userId: string; email?: string | null; @@ -224,17 +160,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: { @@ -259,28 +191,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").User; diff --git a/lib/build/recipe/thirdpartypasswordless/index.js b/lib/build/recipe/thirdpartypasswordless/index.js index 80ab6a4ec..86d524efc 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.js +++ b/lib/build/recipe/thirdpartypasswordless/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); @@ -128,69 +106,43 @@ 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 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)); } } exports.default = Wrapper; diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts index d2a66e48c..ea6df8e59 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import RecipeModule from "../../recipeModule"; import { NormalisedAppinfo, APIHandled, RecipeListFunction, HTTPMethod } from "../../types"; import EmailVerificationRecipe from "../emailverification/recipe"; @@ -19,33 +18,17 @@ export default class Recipe extends RecipeModule { private thirdPartyRecipe; recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; - constructor( - recipeId: string, - appInfo: NormalisedAppinfo, - isInServerlessEnv: boolean, - config: TypeInput, - recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - thirdPartyInstance: ThirdPartyRecipe | undefined; - passwordlessInstance: PasswordlessRecipe | undefined; - } - ); + constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { + emailVerificationInstance: EmailVerificationRecipe | undefined; + thirdPartyInstance: ThirdPartyRecipe | undefined; + passwordlessInstance: PasswordlessRecipe | 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; getEmailForUserIdForEmailVerification: (userId: string, userContext: any) => Promise; diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.js b/lib/build/recipe/thirdpartypasswordless/recipe.js index 8e66a7682..0a12dd928 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. * @@ -72,35 +50,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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + }); + 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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); - }); - 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); - } - return yield this.emailVerificationRecipe.handleError(err, request, response); + else if (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)) { + return yield this.thirdPartyRecipe.handleError(err, request, response); } - }); + return yield this.emailVerificationRecipe.handleError(err, request, response); + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [ ...this.emailVerificationRecipe.getAllCORSHeaders(), @@ -112,36 +85,29 @@ 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.emailVerificationRecipe.isErrorFromThisRecipe(err) || this.passwordlessRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) - ); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); }; // helper functions... - this.getEmailForUserIdForEmailVerification = (userId, userContext) => - __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo === undefined) { - throw new Error("Unknown User ID provided"); - } else if (!("thirdParty" in userInfo)) { - // this is a passwordless user.. so we always return some random email, - // and in the function for isEmailVerified, we will check if the user - // is a passwordless user, and if they are, we will return true in there - return "_____supertokens_passwordless_user@supertokens.com"; - } - return userInfo.email; - }); + this.getEmailForUserIdForEmailVerification = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw new Error("Unknown User ID provided"); + } + else if (!("thirdParty" in userInfo)) { + // this is a passwordless user.. so we always return some random email, + // and in the function for isEmailVerified, we will check if the user + // is a passwordless user, and if they are, we will return true in there + return "_____supertokens_passwordless_user@supertokens.com"; + } + return userInfo.email; + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default( - recipeImplementation_1.default( - querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), - querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID) - ) - ); + let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID))); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -153,110 +119,83 @@ class Recipe extends recipeModule_1.default { this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default( - recipeId, - appInfo, - isInServerlessEnv, - Object.assign(Object.assign({}, this.config.emailVerificationFeature), { - override: Object.assign(Object.assign({}, this.config.emailVerificationFeature.override), { - functions: (oI, builder) => { - var _a; - let passwordlessOverride = (oI) => { - return Object.assign(Object.assign({}, oI), { - createEmailVerificationToken: function (input) { - return __awaiter(this, void 0, void 0, function* () { - let user = yield recipImplReference.getUserById({ - userId: input.userId, - userContext: input.userContext, - }); - if (user === undefined || "thirdParty" in user) { - return oI.createEmailVerificationToken(input); - } else { - return { - status: "EMAIL_ALREADY_VERIFIED_ERROR", - }; - } - }); - }, - isEmailVerified: function (input) { - return __awaiter(this, void 0, void 0, function* () { - let user = yield recipImplReference.getUserById({ - userId: input.userId, - userContext: input.userContext, - }); - if (user === undefined || "thirdParty" in user) { - return oI.isEmailVerified(input); - } else { - // this is a passwordless user, so we always want - // to return that their info / email is verified - return true; - } - }); - }, - }); - }; - if ( - ((_a = emailVerificationConfig.override) === null || _a === void 0 - ? void 0 - : _a.functions) !== undefined - ) { - // First we apply the override from what we have above, - // and then we apply their override. Notice that we don't - // pass in oI in here, but that is OK since that's how the - // override works! - return builder - .override(passwordlessOverride) - .override(emailVerificationConfig.override.functions) - .build(); - } - return passwordlessOverride(oI); - }, - }), - }) - ); + : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign(Object.assign({}, this.config.emailVerificationFeature), { override: Object.assign(Object.assign({}, this.config.emailVerificationFeature.override), { functions: (oI, builder) => { + var _a; + let passwordlessOverride = (oI) => { + return Object.assign(Object.assign({}, oI), { createEmailVerificationToken: function (input) { + return __awaiter(this, void 0, void 0, function* () { + let user = yield recipImplReference.getUserById({ + userId: input.userId, + userContext: input.userContext, + }); + if (user === undefined || "thirdParty" in user) { + return oI.createEmailVerificationToken(input); + } + else { + return { + status: "EMAIL_ALREADY_VERIFIED_ERROR", + }; + } + }); + }, isEmailVerified: function (input) { + return __awaiter(this, void 0, void 0, function* () { + let user = yield recipImplReference.getUserById({ + userId: input.userId, + userContext: input.userContext, + }); + if (user === undefined || "thirdParty" in user) { + return oI.isEmailVerified(input); + } + else { + // this is a passwordless user, so we always want + // to return that their info / email is verified + return true; + } + }); + } }); + }; + if (((_a = emailVerificationConfig.override) === null || _a === void 0 ? void 0 : _a.functions) !== undefined) { + // First we apply the override from what we have above, + // and then we apply their override. Notice that we don't + // pass in oI in here, but that is OK since that's how the + // override works! + return builder + .override(passwordlessOverride) + .override(emailVerificationConfig.override.functions) + .build(); + } + return passwordlessOverride(oI); + } }) })); this.passwordlessRecipe = recipes.passwordlessInstance !== undefined ? recipes.passwordlessInstance - : new recipe_2.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); - }, - }, - }) - ); + : new recipe_2.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); + }, + } })); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_3.default( - recipeId, - appInfo, - isInServerlessEnv, - { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, - { - emailVerificationInstance: this.emailVerificationRecipe, - } - ); + : new recipe_3.default(recipeId, appInfo, isInServerlessEnv, { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, { + emailVerificationInstance: this.emailVerificationRecipe, + }); } } static init(config) { @@ -268,10 +207,9 @@ class Recipe extends recipeModule_1.default { thirdPartyInstance: 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 d16ff3c59..7377bd5fe 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/types.d.ts b/lib/build/recipe/thirdpartypasswordless/types.d.ts index 23422e04c..c5b93d6f3 100644 --- a/lib/build/recipe/thirdpartypasswordless/types.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/types.d.ts @@ -1,27 +1,20 @@ -// @ts-nocheck import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; -import { - RecipeInterface as EmailVerificationRecipeInterface, - APIInterface as EmailVerificationAPIInterface, -} from "../emailverification"; +import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; import { DeviceType as DeviceTypeOriginal, APIOptions as PasswordlessAPIOptionsOriginal } from "../passwordless/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/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; timeJoined: number; }; @@ -29,184 +22,133 @@ export declare type TypeInputEmailVerificationFeature = { getEmailVerificationURL?: (user: User, userContext: any) => Promise; createAndSendCustomEmail?: (user: User, emailVerificationURLWithToken: string, userContext: any) => Promise; }; -export declare type TypeInput = ( - | { - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - 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; + createAndSendCustomTextMessage: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + createAndSendCustomTextMessage: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +}) & { providers?: TypeProvider[]; emailVerificationFeature?: TypeInputEmailVerificationFeature; flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; - getLinkDomainAndPath?: ( - contactInfo: - | { - email: string; - } - | { - phoneNumber: string; - }, - userContext: any - ) => Promise | string; + getLinkDomainAndPath?: (contactInfo: { + email: string; + } | { + phoneNumber: string; + }, userContext: any) => Promise | string; getCustomUserInputCode?: (userContext: any) => Promise | string; override?: { - functions?: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; -export declare type TypeNormalisedInput = ( - | { - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } - | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: ( - input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: ( - input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, - userContext: any - ) => Promise; - } -) & { +export declare type TypeNormalisedInput = ({ + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + createAndSendCustomTextMessage: (input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; +} | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: (input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, userContext: any) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + 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"; - getLinkDomainAndPath?: ( - contactInfo: - | { - email: string; - } - | { - phoneNumber: string; - }, - userContext: any - ) => Promise | string; + getLinkDomainAndPath?: (contactInfo: { + email: string; + } | { + phoneNumber: string; + }, userContext: any) => Promise | string; getCustomUserInputCode?: (userContext: any) => Promise | string; providers: TypeProvider[]; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: ( - originalImplementation: RecipeInterface, - builder?: OverrideableBuilder - ) => RecipeInterface; + functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: ( - originalImplementation: EmailVerificationRecipeInterface, - builder?: OverrideableBuilder - ) => EmailVerificationRecipeInterface; - apis?: ( - originalImplementation: EmailVerificationAPIInterface, - builder?: OverrideableBuilder - ) => EmailVerificationAPIInterface; + functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; + apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; }; }; }; 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; @@ -220,30 +162,22 @@ export declare type RecipeInterface = { isVerified: boolean; }; userContext: any; - }): Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - } - | { - status: "FIELD_ERROR"; - error: string; - } - >; - createCode: ( - input: ( - | { - email: string; - } - | { - phoneNumber: string; - } - ) & { - userInputCode?: string; - userContext: any; - } - ) => Promise<{ + }): Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + } | { + status: "FIELD_ERROR"; + error: string; + }>; + createCode: (input: ({ + email: string; + } | { + phoneNumber: string; + }) & { + userInputCode?: string; + userContext: any; + }) => Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -257,49 +191,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; @@ -308,17 +231,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: { @@ -327,9 +246,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; @@ -338,145 +266,107 @@ 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; - }>); - thirdPartySignInUpPOST: - | undefined - | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise< - | { - status: "OK"; - createdNewUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } - | { - status: "FIELD_ERROR"; - error: string; - } - | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } - >); - 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"; - } - | { - status: "GENERAL_ERROR"; - message: string; - } - >); - resendCodePOST: - | undefined - | (( - input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: PasswordlessAPIOptions; - userContext: any; - } - ) => Promise< - | { - status: "GENERAL_ERROR"; - message: string; - } - | { - 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; - user: User; - session: SessionContainerInterface; - } - | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } - | { - status: "GENERAL_ERROR"; - message: string; - } - | { - status: "RESTART_FLOW_ERROR"; - } - >); - passwordlessUserEmailExistsGET: - | undefined - | ((input: { - email: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); - passwordlessUserPhoneNumberExistsGET: - | undefined - | ((input: { - phoneNumber: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); + authorisationUrlGET: undefined | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + url: string; + }>); + thirdPartySignInUpPOST: undefined | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + createdNewUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } | { + status: "FIELD_ERROR"; + error: string; + } | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + }>); + 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"; + } | { + status: "GENERAL_ERROR"; + message: string; + }>); + resendCodePOST: undefined | ((input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "GENERAL_ERROR"; + message: string; + } | { + 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; + user: User; + session: SessionContainerInterface; + } | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } | { + status: "GENERAL_ERROR"; + message: string; + } | { + status: "RESTART_FLOW_ERROR"; + }>); + passwordlessUserEmailExistsGET: undefined | ((input: { + email: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); + passwordlessUserPhoneNumberExistsGET: undefined | ((input: { + phoneNumber: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); }; diff --git a/lib/build/recipe/thirdpartypasswordless/utils.d.ts b/lib/build/recipe/thirdpartypasswordless/utils.d.ts index 2cf4314fd..fa143e5f9 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/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/thirdpartypasswordless/utils.js b/lib/build/recipe/thirdpartypasswordless/utils.js index b7641cf5b..05be71037 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.js +++ b/lib/build/recipe/thirdpartypasswordless/utils.js @@ -13,112 +13,57 @@ * 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 validateAndNormaliseUserInput(recipeInstance, appInfo, config) { let providers = config.providers === undefined ? [] : config.providers; let emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, appInfo, config); - let override = Object.assign( - { - functions: (originalImplementation) => originalImplementation, - apis: (originalImplementation) => originalImplementation, - }, - config === null || config === void 0 ? void 0 : config.override - ); - return Object.assign(Object.assign({}, config), { providers, emailVerificationFeature, override }); + let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); + return Object.assign(Object.assign({}, config), { providers, + emailVerificationFeature, + override }); } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) { var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserIdForEmailVerification, - override: - (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 - ? void 0 - : _a.emailVerificationFeature, - createAndSendCustomEmail: - ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _b === void 0 - ? void 0 - : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_d = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _d === void 0 - ? void 0 - : _d.createAndSendCustomEmail) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail( - userInfo, - link, - userContext - ); - }), - getEmailVerificationURL: - ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || - _c === void 0 - ? void 0 - : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => - __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if ( - userInfo === undefined || - ((_e = - config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === - null || _e === void 0 - ? void 0 - : _e.getEmailVerificationURL) === undefined - ) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, + createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); + }), + getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if (userInfo === undefined || + ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } diff --git a/lib/build/recipe/usermetadata/index.d.ts b/lib/build/recipe/usermetadata/index.d.ts index 0d20839e5..ea604c3af 100644 --- a/lib/build/recipe/usermetadata/index.d.ts +++ b/lib/build/recipe/usermetadata/index.d.ts @@ -1,27 +1,16 @@ -// @ts-nocheck import Recipe from "./recipe"; import { RecipeInterface, JSONObject } 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: JSONObject; }>; - 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..3a23e391a 100644 --- a/lib/build/recipe/usermetadata/index.js +++ b/lib/build/recipe/usermetadata/index.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 recipe_1 = require("./recipe"); class Wrapper { 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 c03c030e6..db70af5b7 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(); } } @@ -80,7 +55,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("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 ef223860e..be4a81dd3 100644 --- a/lib/build/recipe/usermetadata/types.d.ts +++ b/lib/build/recipe/usermetadata/types.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import OverrideableBuilder from "supertokens-js-override"; export declare type JSONPrimitive = string | number | boolean | null; export declare type JSONArray = Array; @@ -8,19 +7,13 @@ export interface JSONObject { } 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..b77b71bcd 100644 --- a/lib/build/recipe/usermetadata/utils.js +++ b/lib/build/recipe/usermetadata/utils.js @@ -15,13 +15,7 @@ */ Object.defineProperty(exports, "__esModule", { value: true }); 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/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 3f1e59888..8f28fbfc1 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import { TypeInput, NormalisedAppinfo, HTTPMethod } from "./types"; import RecipeModule from "./recipeModule"; import NormalisedURLPath from "./normalisedURLPath"; @@ -15,14 +14,7 @@ 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; getUsers: (input: { diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index e41d8e7cd..971d6bc55 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"); @@ -56,33 +34,32 @@ const logger_1 = require("./logger"); 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.io/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.io/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); @@ -95,197 +72,158 @@ 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, }); - 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 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.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 { - users: response.users, - nextPaginationToken: response.nextPaginationToken, + status: "OK", }; - }); - 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"); + } + else { + throw new global.Error("Please upgrade the SuperTokens core to >= 3.7.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 = 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; + } + 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; + } } - }); - 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() - ); + 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: Not handling because no recipe matched"); + 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; } - }); - 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.sendNon200Response(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); + 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; } } - throw err; - }); + 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.sendNon200Response(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; + }); 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); - 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"); } @@ -306,7 +244,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 cc5a4f57e..6735488d1 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"; diff --git a/lib/build/utils.d.ts b/lib/build/utils.d.ts index 592cc8c43..6850b2ef7 100644 --- a/lib/build/utils.d.ts +++ b/lib/build/utils.d.ts @@ -1,4 +1,3 @@ -// @ts-nocheck import type { AppInfo, NormalisedAppinfo, HTTPMethod } from "./types"; import type { BaseRequest, BaseResponse } from "./framework"; export declare function getLargestVersionFromIntersection(v1: string[], v2: string[]): string | undefined; diff --git a/lib/build/utils.js b/lib/build/utils.js index 7bb320024..16d9b8a9f 100644 --- a/lib/build/utils.js +++ b/lib/build/utils.js @@ -25,7 +25,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,23 +49,19 @@ 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(""); 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), + 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, }; } @@ -93,9 +90,7 @@ 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 frontendHasInterceptor(req) { diff --git a/lib/build/version.d.ts b/lib/build/version.d.ts index f71d8b72a..ea715cdc5 100644 --- a/lib/build/version.d.ts +++ b/lib/build/version.d.ts @@ -1,3 +1,2 @@ -// @ts-nocheck export declare const version = "9.2.0"; export declare const cdiSupported: string[]; diff --git a/lib/ts/framework/h3/framework.ts b/lib/ts/framework/h3/framework.ts index 18909ac36..6db54490c 100644 --- a/lib/ts/framework/h3/framework.ts +++ b/lib/ts/framework/h3/framework.ts @@ -6,9 +6,9 @@ import { BaseRequest } from "../request"; import { BaseResponse } from '../response'; import { Framework } from '../types'; import { - getHeaderValueFromIncomingMessage, setH3Header, useBody, useRawBody, setCookieForServerResponse + getHeaderValueFromIncomingMessage, useBody, useRawBody, setCookieForServerResponse } from "../utils"; - +import {Response, Request} from './types'; const defer = typeof setImmediate !== 'undefined' ? setImmediate : (fn: Function) => fn() export class H3Request extends BaseRequest { @@ -55,9 +55,9 @@ export class H3Request extends BaseRequest { } export class H3ResponseTokens extends BaseResponse { - private response: ServerResponse; + private response: Response; private statusCode: number; - constructor(response: ServerResponse) { + constructor(response: Response) { super(); this.original = response; this.response = response; @@ -65,19 +65,36 @@ export class H3ResponseTokens extends BaseResponse { } sendHTMLResponse = (html: string) => { - if(this.response.writable) { - this.response.setHeader('Content-Type', 'text/html') - this.response.statusCode = this.statusCode; + if(this.response.res.writable) { + this.response.res.setHeader('Content-Type', 'text/html') + this.response.res.statusCode = this.statusCode; new Promise((resolve) => { defer(() => { - this.response.end(html); + this.response.res.end(html); resolve(undefined); }) }) } }; setHeader = (key: string, value: string, allowDuplicateKey: boolean) => { - setH3Header(this.response, key, value, allowDuplicateKey); + try { + console.log(this.response.res.setHeader); + const allheaders = this.response.res.getHeaders(); + let existingValue = allheaders[key]; + + // we have the this.response.header for compatibility with nextJS + if (existingValue === undefined) { + this.response.res.setHeader(key, value); + } else if (allowDuplicateKey) { + this.response.res.setHeader(key, existingValue + ", " + value); + } else { + // we overwrite the current one with the new one + this.response.res.setHeader(key, value); + } + } catch (err) { + console.log(err); + throw new Error("Error while setting header with key: " + key + " and value: " + value); + } }; setCookie = ( key: string, @@ -89,20 +106,20 @@ export class H3ResponseTokens extends BaseResponse { path: string, sameSite: "strict" | "lax" | "none" ) => { - setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); + setCookieForServerResponse(this.response.res, key, value, domain, secure, httpOnly, expires, path, sameSite); }; setStatusCode = (statusCode: number) => { - if(this.response.writable) { + if(this.response.res.writable) { this.statusCode = statusCode } }; sendJSONResponse = (content: any) => { - if(this.response.writable) { - this.response.setHeader('Content-Type', 'application/json') - this.response.statusCode = this.statusCode; + if(this.response.res.writable) { + this.response.res.setHeader('Content-Type', 'application/json') + this.response.res.statusCode = this.statusCode; new Promise((resolve) => { defer(() => { - this.response.end(content); + this.response.res.end(content); resolve(undefined); }) }) @@ -117,7 +134,7 @@ export const middlware = () => { return async (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => { let supertokens; const request = new H3Request(req); - const response = new H3ResponseTokens(res); + const response = new H3ResponseTokens({res: res}); try { supertokens = SuperTokens.getInstanceOrThrowError(); const result = await supertokens.middleware(request, response); @@ -143,7 +160,7 @@ export const errorHandler = () => { return async (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => { let supertokens = SuperTokens.getInstanceOrThrowError(); let request = new H3Request(req); - let response = new H3ResponseTokens(res); + let response = new H3ResponseTokens({res: res}); try { await supertokens.errorHandler(err, request,response); } catch(err: any) { diff --git a/lib/ts/framework/h3/types.ts b/lib/ts/framework/h3/types.ts new file mode 100644 index 000000000..4d9947365 --- /dev/null +++ b/lib/ts/framework/h3/types.ts @@ -0,0 +1,9 @@ +import {ServerResponse, IncomingMessage} from 'http' + +export interface Response { + res: ServerResponse +} + +export interface Request { + req: IncomingMessage +} \ No newline at end of file diff --git a/lib/ts/framework/index.ts b/lib/ts/framework/index.ts index 3d38c264a..eef367e7c 100644 --- a/lib/ts/framework/index.ts +++ b/lib/ts/framework/index.ts @@ -21,6 +21,7 @@ import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; +import * as h3Framework from './h3' export default { express: expressFramework, @@ -29,6 +30,7 @@ export default { loopback: loopbackFramework, koa: koaFramework, awsLambda: awsLambdaFramework, + h3: h3Framework }; export let express = expressFramework; @@ -37,3 +39,4 @@ export let hapi = hapiFramework; export let loopback = loopbackFramework; export let koa = koaFramework; export let awsLambda = awsLambdaFramework; +export let h3 = h3Framework; \ No newline at end of file diff --git a/lib/ts/framework/utils.ts b/lib/ts/framework/utils.ts index 255c76164..694b42afd 100644 --- a/lib/ts/framework/utils.ts +++ b/lib/ts/framework/utils.ts @@ -251,24 +251,6 @@ export async function useBody(req: IncomingMessage): Promise { (req as any)[ParsedBodySymbol] = json; return json } - -export function setH3Header(res: ServerResponse, key: string, value: string, allowDuplicateKey: boolean) { - try { - let existingHeaders = res.getHeaders(); - let existingValue = existingHeaders[key.toLowerCase()]; - - if (existingValue === undefined) { - res.setHeader(key, value); - } else if (allowDuplicateKey) { - res.setHeader(key, existingValue + ", " + value); - } else { - res.setHeader(key, value); - } - } catch (err) { - throw new Error("Error while setting header with key: " + key + " and value: " + value); - } -} - /** * * @param res diff --git a/lib/ts/recipe/session/framework/index.ts b/lib/ts/recipe/session/framework/index.ts index c984f7879..42ea9d11a 100644 --- a/lib/ts/recipe/session/framework/index.ts +++ b/lib/ts/recipe/session/framework/index.ts @@ -18,6 +18,7 @@ import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; +import * as h3Framework from './h3'; export default { express: expressFramework, @@ -26,6 +27,7 @@ export default { loopback: loopbackFramework, koa: koaFramework, awsLambda: awsLambdaFramework, + h3: h3Framework, }; export let express = expressFramework; @@ -34,3 +36,4 @@ export let hapi = hapiFramework; export let loopback = loopbackFramework; export let koa = koaFramework; export let awsLambda = awsLambdaFramework; +export let h3 = h3Framework; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 27c15d417..db20f02ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "cookie": "0.4.0", "debug": "^4.3.3", "destr": "^1.1.1", + "h3": "^0.7.6", "jsonwebtoken": "^8.5.1", "jwks-rsa": "^2.0.5", "libphonenumber-js": "^1.9.44", @@ -2858,6 +2859,11 @@ "node": ">= 0.6" } }, + "node_modules/cookie-es": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-0.5.0.tgz", + "integrity": "sha512-RyZrFi6PNpBFbIaQjXDlFIhFVqV42QeKSZX1yQIl6ihImq6vcHNGMtqQ/QzY3RMPuYSkvsRwtnt5M9NeYxKt0g==" + }, "node_modules/cookie-parser": { "version": "1.4.6", "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.6.tgz", @@ -4116,6 +4122,17 @@ "node": ">=4.x" } }, + "node_modules/h3": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/h3/-/h3-0.7.6.tgz", + "integrity": "sha512-OoxDWBBpGNAStSVCOQagN+3EKRbCSgwQKFIeu4p4XvsLvd4L9KaQV6GDY5H8ZDYHsWfnsx4KTa2eFwSw530jnQ==", + "dependencies": { + "cookie-es": "^0.5.0", + "destr": "^1.1.1", + "radix3": "^0.1.1", + "ufo": "^0.8.3" + } + }, "node_modules/has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", @@ -7200,6 +7217,11 @@ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", "dev": true }, + "node_modules/radix3": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/radix3/-/radix3-0.1.1.tgz", + "integrity": "sha512-9Np01fn+penHvC05A9EkRpyObPMS0ht3t1UP6KlnQPCfTNzArmEZW/+t2SLsDtPcZyXPDbYCGWA8dSQqWaVwQQ==" + }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -8434,6 +8456,11 @@ "node": ">=4.2.0" } }, + "node_modules/ufo": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-0.8.3.tgz", + "integrity": "sha512-AIkk06G21y/P+NCatfU+1qldCmI0XCszZLn8AkuKotffF3eqCvlce0KuwM7ZemLE/my0GSYADOAeM5zDYWMB+A==" + }, "node_modules/unbox-primitive": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", @@ -11711,6 +11738,11 @@ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" }, + "cookie-es": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-0.5.0.tgz", + "integrity": "sha512-RyZrFi6PNpBFbIaQjXDlFIhFVqV42QeKSZX1yQIl6ihImq6vcHNGMtqQ/QzY3RMPuYSkvsRwtnt5M9NeYxKt0g==" + }, "cookie-parser": { "version": "1.4.6", "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.6.tgz", @@ -12720,6 +12752,17 @@ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", "dev": true }, + "h3": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/h3/-/h3-0.7.6.tgz", + "integrity": "sha512-OoxDWBBpGNAStSVCOQagN+3EKRbCSgwQKFIeu4p4XvsLvd4L9KaQV6GDY5H8ZDYHsWfnsx4KTa2eFwSw530jnQ==", + "requires": { + "cookie-es": "^0.5.0", + "destr": "^1.1.1", + "radix3": "^0.1.1", + "ufo": "^0.8.3" + } + }, "has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", @@ -15163,6 +15206,11 @@ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", "dev": true }, + "radix3": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/radix3/-/radix3-0.1.1.tgz", + "integrity": "sha512-9Np01fn+penHvC05A9EkRpyObPMS0ht3t1UP6KlnQPCfTNzArmEZW/+t2SLsDtPcZyXPDbYCGWA8dSQqWaVwQQ==" + }, "randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -16187,6 +16235,11 @@ "integrity": "sha512-MYlEfn5VrLNsgudQTVJeNaQFUAI7DkhnOjdpAp4T+ku1TfQClewlbSuTVHiA+8skNBgaf02TL/kLOvig4y3G8w==", "dev": true }, + "ufo": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-0.8.3.tgz", + "integrity": "sha512-AIkk06G21y/P+NCatfU+1qldCmI0XCszZLn8AkuKotffF3eqCvlce0KuwM7ZemLE/my0GSYADOAeM5zDYWMB+A==" + }, "unbox-primitive": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", diff --git a/package.json b/package.json index 9af903698..9127ad1b9 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "test": "TEST_MODE=testing npx mocha --timeout 500000", "build-check": "cd lib && npx tsc -p tsconfig.json --noEmit && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit", - "build": "cd lib && rm -rf build && npx tsc -p tsconfig.json && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit && cd ../.. && npm run post-build", + "build": "cd lib && DEL -rf build && npx tsc -p tsconfig.json && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit && cd ../.. && npm run post-build", "pretty": "npx pretty-quick .", "post-build": "node add-ts-no-check.js", "build-pretty": "npm run build && npm run pretty && npm run pretty", @@ -40,6 +40,7 @@ "cookie": "0.4.0", "debug": "^4.3.3", "destr": "^1.1.1", + "h3": "^0.7.6", "jsonwebtoken": "^8.5.1", "jwks-rsa": "^2.0.5", "libphonenumber-js": "^1.9.44", From 73d290efabb8a22dca25c4bdf41f73566f5de871 Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Sun, 1 May 2022 00:27:24 +0200 Subject: [PATCH 05/13] everything seems to work fine now --- lib/build/framework/h3/framework.d.ts | 8 +-- lib/build/framework/h3/framework.js | 65 +++++++----------- lib/build/framework/h3/index.d.ts | 2 +- lib/build/framework/h3/types.d.ts | 4 +- lib/build/recipe/session/framework/h3.d.ts | 2 +- lib/ts/framework/h3/framework.ts | 78 +++++++++------------- lib/ts/framework/h3/types.ts | 9 --- lib/ts/recipe/session/framework/h3.ts | 2 +- recipe/session/framework/h3/index.d.ts | 3 + recipe/session/framework/h3/index.js | 6 ++ 10 files changed, 72 insertions(+), 107 deletions(-) delete mode 100644 lib/ts/framework/h3/types.ts create mode 100644 recipe/session/framework/h3/index.d.ts create mode 100644 recipe/session/framework/h3/index.js diff --git a/lib/build/framework/h3/framework.d.ts b/lib/build/framework/h3/framework.d.ts index a010cba3e..3e12149d8 100644 --- a/lib/build/framework/h3/framework.d.ts +++ b/lib/build/framework/h3/framework.d.ts @@ -1,10 +1,10 @@ /// +import { H3Event } from 'h3'; import type { IncomingMessage, ServerResponse } from 'http'; import { SessionContainerInterface } from '../../recipe/session/types'; import { BaseRequest } from "../request"; import { BaseResponse } from '../response'; import { Framework } from '../types'; -import { Response } from './types'; export declare class H3Request extends BaseRequest { private request; constructor(request: IncomingMessage); @@ -19,7 +19,7 @@ export declare class H3Request extends BaseRequest { export declare class H3ResponseTokens extends BaseResponse { private response; private statusCode; - constructor(response: Response); + constructor(response: ServerResponse); 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; @@ -30,9 +30,9 @@ export interface SessionRequest extends IncomingMessage { session?: SessionContainerInterface; } export declare const middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; -export declare const errorHandler: () => (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; +export declare const errorHandler: () => (event: H3Event, errorPlain: Error, statusCode: number) => Promise; export interface H3Framework extends Framework { middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise; - errorHandler: () => (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise; + errorHandler: () => (event: H3Event, errorPlain: Error, statusCode: number) => Promise; } export declare const H3Wrapper: H3Framework; diff --git a/lib/build/framework/h3/framework.js b/lib/build/framework/h3/framework.js index a7fe768fe..878287e44 100644 --- a/lib/build/framework/h3/framework.js +++ b/lib/build/framework/h3/framework.js @@ -9,17 +9,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", { value: true }); +const h3_1 = require("h3"); const supertokens_1 = require("../../supertokens"); const utils_1 = require("../../utils"); const request_1 = require("../request"); const response_1 = require("../response"); const utils_2 = require("../utils"); -const defer = typeof setImmediate !== 'undefined' ? setImmediate : (fn) => fn(); class H3Request extends request_1.BaseRequest { constructor(request) { super(); this.getCookieValue = (key) => { - return utils_2.getHeaderValueFromIncomingMessage(this.request, key); + return utils_2.getCookieValueFromIncomingMessage(this.request, key); }; this.getFormData = () => __awaiter(this, void 0, void 0, function* () { return utils_2.useRawBody(this.request); @@ -64,57 +64,46 @@ class H3ResponseTokens extends response_1.BaseResponse { constructor(response) { super(); this.sendHTMLResponse = (html) => { - if (this.response.res.writable) { - this.response.res.setHeader('Content-Type', 'text/html'); - this.response.res.statusCode = this.statusCode; - new Promise((resolve) => { - defer(() => { - this.response.res.end(html); - resolve(undefined); - }); - }); + if (this.response.writable) { + this.response.setHeader('Content-Type', 'text/html'); + this.response.statusCode = this.statusCode; + this.response.end(html); } }; this.setHeader = (key, value, allowDuplicateKey) => { try { - console.log(this.response.res.setHeader); - const allheaders = this.response.res.getHeaders(); + const allheaders = this.response.getHeaders(); let existingValue = allheaders[key]; // we have the this.response.header for compatibility with nextJS if (existingValue === undefined) { - this.response.res.setHeader(key, value); + this.response.setHeader(key, value); } else if (allowDuplicateKey) { - this.response.res.setHeader(key, existingValue + ", " + value); + this.response.setHeader(key, existingValue + ", " + value); } else { // we overwrite the current one with the new one - this.response.res.setHeader(key, value); + this.response.setHeader(key, value); } } catch (err) { - console.log(err); throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; this.setCookie = (key, value, domain, secure, httpOnly, expires, path, sameSite) => { - utils_2.setCookieForServerResponse(this.response.res, 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.res.writable) { + if (this.response.writable) { this.statusCode = statusCode; } }; this.sendJSONResponse = (content) => { - if (this.response.res.writable) { - this.response.res.setHeader('Content-Type', 'application/json'); - this.response.res.statusCode = this.statusCode; - new Promise((resolve) => { - defer(() => { - this.response.res.end(content); - resolve(undefined); - }); - }); + if (this.response.writable) { + content = JSON.stringify(content); + this.response.setHeader('Content-Type', 'application/json'); + this.response.statusCode = this.statusCode; + this.response.end(content, 'utf-8'); } }; this.original = response; @@ -127,7 +116,7 @@ exports.middlware = () => { return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { let supertokens; const request = new H3Request(req); - const response = new H3ResponseTokens({ res: res }); + const response = new H3ResponseTokens(res); try { supertokens = supertokens_1.default.getInstanceOrThrowError(); const result = yield supertokens.middleware(request, response); @@ -151,25 +140,19 @@ exports.middlware = () => { }); }; exports.errorHandler = () => { - return (err, req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens = supertokens_1.default.getInstanceOrThrowError(); - let request = new H3Request(req); - let response = new H3ResponseTokens({ res: res }); - try { - yield supertokens.errorHandler(err, request, response); - } - catch (err) { - return next(err); - } + return (event, errorPlain, statusCode) => __awaiter(void 0, void 0, void 0, function* () { + const error = h3_1.createError(errorPlain); + error.statusCode = statusCode; + h3_1.sendError(event, error); }); }; exports.H3Wrapper = { middlware: exports.middlware, errorHandler: exports.errorHandler, wrapRequest: (unwrapped) => { - return new H3Request(unwrapped); + return new H3Request(unwrapped.req); }, wrapResponse: (unwrapped) => { - return new H3ResponseTokens(unwrapped); + return new H3ResponseTokens(unwrapped.res); } }; diff --git a/lib/build/framework/h3/index.d.ts b/lib/build/framework/h3/index.d.ts index bc1c5bec3..4c089b51e 100644 --- a/lib/build/framework/h3/index.d.ts +++ b/lib/build/framework/h3/index.d.ts @@ -1,6 +1,6 @@ /// export type { SessionRequest } from './framework'; export declare const middleware: () => (req: import("http").IncomingMessage, res: import("http").ServerResponse, next: (err?: Error | undefined) => any) => Promise; -export declare const errorHandler: () => (err: any, req: import("http").IncomingMessage, res: import("http").ServerResponse, next: (err?: Error | undefined) => any) => Promise; +export declare const errorHandler: () => (event: import("h3").H3Event, errorPlain: Error, statusCode: number) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/h3/types.d.ts b/lib/build/framework/h3/types.d.ts index 39d77e223..c6200591b 100644 --- a/lib/build/framework/h3/types.d.ts +++ b/lib/build/framework/h3/types.d.ts @@ -1,8 +1,6 @@ /// import { ServerResponse, IncomingMessage } from 'http'; -export interface Response { +export interface Event { res: ServerResponse; -} -export interface Request { req: IncomingMessage; } diff --git a/lib/build/recipe/session/framework/h3.d.ts b/lib/build/recipe/session/framework/h3.d.ts index ae0a57c6c..71679250f 100644 --- a/lib/build/recipe/session/framework/h3.d.ts +++ b/lib/build/recipe/session/framework/h3.d.ts @@ -1,5 +1,5 @@ /// import type { VerifySessionOptions } from '../types'; import type { SessionRequest } from '../../../framework/h3'; -import type { ServerResponse } from 'http'; +import { ServerResponse } from 'http'; export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; diff --git a/lib/ts/framework/h3/framework.ts b/lib/ts/framework/h3/framework.ts index 6db54490c..cce9a1c77 100644 --- a/lib/ts/framework/h3/framework.ts +++ b/lib/ts/framework/h3/framework.ts @@ -1,3 +1,4 @@ +import { createError, H3Event, sendError } from 'h3'; import type {IncomingMessage, ServerResponse} from 'http'; import { SessionContainerInterface } from '../../recipe/session/types'; import SuperTokens from '../../supertokens'; @@ -6,10 +7,8 @@ import { BaseRequest } from "../request"; import { BaseResponse } from '../response'; import { Framework } from '../types'; import { - getHeaderValueFromIncomingMessage, useBody, useRawBody, setCookieForServerResponse + getCookieValueFromIncomingMessage, getHeaderValueFromIncomingMessage, useBody, useRawBody, setCookieForServerResponse } from "../utils"; -import {Response, Request} from './types'; -const defer = typeof setImmediate !== 'undefined' ? setImmediate : (fn: Function) => fn() export class H3Request extends BaseRequest { private request: IncomingMessage; @@ -19,7 +18,7 @@ export class H3Request extends BaseRequest { this.request = request; }; getCookieValue = (key: string) => { - return getHeaderValueFromIncomingMessage(this.request, key); + return getCookieValueFromIncomingMessage(this.request, key); }; getFormData = async (): Promise => { return useRawBody(this.request); @@ -55,9 +54,9 @@ export class H3Request extends BaseRequest { } export class H3ResponseTokens extends BaseResponse { - private response: Response; + private response: ServerResponse; private statusCode: number; - constructor(response: Response) { + constructor(response: ServerResponse) { super(); this.original = response; this.response = response; @@ -65,34 +64,27 @@ export class H3ResponseTokens extends BaseResponse { } sendHTMLResponse = (html: string) => { - if(this.response.res.writable) { - this.response.res.setHeader('Content-Type', 'text/html') - this.response.res.statusCode = this.statusCode; - new Promise((resolve) => { - defer(() => { - this.response.res.end(html); - resolve(undefined); - }) - }) + if(this.response.writable) { + this.response.setHeader('Content-Type', 'text/html') + this.response.statusCode = this.statusCode; + this.response.end(html); } }; setHeader = (key: string, value: string, allowDuplicateKey: boolean) => { try { - console.log(this.response.res.setHeader); - const allheaders = this.response.res.getHeaders(); + const allheaders = this.response.getHeaders(); let existingValue = allheaders[key]; // we have the this.response.header for compatibility with nextJS if (existingValue === undefined) { - this.response.res.setHeader(key, value); + this.response.setHeader(key, value); } else if (allowDuplicateKey) { - this.response.res.setHeader(key, existingValue + ", " + value); + this.response.setHeader(key, existingValue + ", " + value); } else { // we overwrite the current one with the new one - this.response.res.setHeader(key, value); + this.response.setHeader(key, value); } } catch (err) { - console.log(err); throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; @@ -106,23 +98,19 @@ export class H3ResponseTokens extends BaseResponse { path: string, sameSite: "strict" | "lax" | "none" ) => { - setCookieForServerResponse(this.response.res, key, value, domain, secure, httpOnly, expires, path, sameSite); + setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); }; setStatusCode = (statusCode: number) => { - if(this.response.res.writable) { - this.statusCode = statusCode + if(this.response.writable) { + this.statusCode = statusCode; } }; sendJSONResponse = (content: any) => { - if(this.response.res.writable) { - this.response.res.setHeader('Content-Type', 'application/json') - this.response.res.statusCode = this.statusCode; - new Promise((resolve) => { - defer(() => { - this.response.res.end(content); - resolve(undefined); - }) - }) + if(this.response.writable) { + content = JSON.stringify(content); + this.response.setHeader('Content-Type', 'application/json') + this.response.statusCode = this.statusCode; + this.response.end(content, 'utf-8'); } }; } @@ -134,7 +122,7 @@ export const middlware = () => { return async (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => { let supertokens; const request = new H3Request(req); - const response = new H3ResponseTokens({res: res}); + const response = new H3ResponseTokens(res); try { supertokens = SuperTokens.getInstanceOrThrowError(); const result = await supertokens.middleware(request, response); @@ -157,30 +145,26 @@ export const middlware = () => { } export const errorHandler = () => { - return async (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => { - let supertokens = SuperTokens.getInstanceOrThrowError(); - let request = new H3Request(req); - let response = new H3ResponseTokens({res: res}); - try { - await supertokens.errorHandler(err, request,response); - } catch(err: any) { - return next(err); - } + return async (event: H3Event, errorPlain: Error, statusCode: number) => { + const error = createError(errorPlain); + error.statusCode = statusCode; + sendError(event, error) } -}; + +} export interface H3Framework extends Framework { middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise, - errorHandler: () => (err: any, req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise + errorHandler: () => (event: H3Event, errorPlain: Error, statusCode: number) => Promise } export const H3Wrapper: H3Framework = { middlware, errorHandler, wrapRequest: (unwrapped) => { - return new H3Request(unwrapped); + return new H3Request(unwrapped.req); }, wrapResponse: (unwrapped) => { - return new H3ResponseTokens(unwrapped) + return new H3ResponseTokens(unwrapped.res) } } \ No newline at end of file diff --git a/lib/ts/framework/h3/types.ts b/lib/ts/framework/h3/types.ts deleted file mode 100644 index 4d9947365..000000000 --- a/lib/ts/framework/h3/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {ServerResponse, IncomingMessage} from 'http' - -export interface Response { - res: ServerResponse -} - -export interface Request { - req: IncomingMessage -} \ No newline at end of file diff --git a/lib/ts/recipe/session/framework/h3.ts b/lib/ts/recipe/session/framework/h3.ts index a49d01466..a09d45a8a 100644 --- a/lib/ts/recipe/session/framework/h3.ts +++ b/lib/ts/recipe/session/framework/h3.ts @@ -2,8 +2,8 @@ import Session from '../recipe'; import type { VerifySessionOptions } from '../types'; import { H3Request, H3ResponseTokens } from '../../../framework/h3/framework'; import type { SessionRequest } from '../../../framework/h3'; -import type { ServerResponse} from 'http'; import SuperTokens from '../../../supertokens'; +import {ServerResponse} from 'http'; export function verifySession(options?: VerifySessionOptions) { return async (req: SessionRequest, res: ServerResponse, next: (err?: Error) => any) => { diff --git a/recipe/session/framework/h3/index.d.ts b/recipe/session/framework/h3/index.d.ts new file mode 100644 index 000000000..b76888d1e --- /dev/null +++ b/recipe/session/framework/h3/index.d.ts @@ -0,0 +1,3 @@ +export * from "../../../../lib/build/recipe/session/framework/h3"; +import * as _default from "../../../../lib/build/recipe/session/framework/h3"; +export default _default; diff --git a/recipe/session/framework/h3/index.js b/recipe/session/framework/h3/index.js new file mode 100644 index 000000000..06fb4c8b7 --- /dev/null +++ b/recipe/session/framework/h3/index.js @@ -0,0 +1,6 @@ +"use strict"; +function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} +exports.__esModule = true; +__export(require("../../../../lib/build/recipe/session/framework/h3")); From 7e731b98986b90c98f8dfc6cf134b7d9b91c53e1 Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Sun, 1 May 2022 11:36:29 +0200 Subject: [PATCH 06/13] restored previous package.json scripts --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9127ad1b9..32a5c67ae 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "test": "TEST_MODE=testing npx mocha --timeout 500000", "build-check": "cd lib && npx tsc -p tsconfig.json --noEmit && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit", - "build": "cd lib && DEL -rf build && npx tsc -p tsconfig.json && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit && cd ../.. && npm run post-build", + "build": "cd lib && rm -rf build && npx tsc -p tsconfig.json && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit && cd ../.. && npm run post-build", "pretty": "npx pretty-quick .", "post-build": "node add-ts-no-check.js", "build-pretty": "npm run build && npm run pretty && npm run pretty", From 60f075ec768fe9cf85953eb5a411cf857c7f897d Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Sun, 1 May 2022 11:37:20 +0200 Subject: [PATCH 07/13] Added tests for h3 framework --- test/framework/h3.test.js | 85 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 test/framework/h3.test.js diff --git a/test/framework/h3.test.js b/test/framework/h3.test.js new file mode 100644 index 000000000..e3b57b180 --- /dev/null +++ b/test/framework/h3.test.js @@ -0,0 +1,85 @@ +const { ProcessState } = require("../../lib/build/processState"); +const {createServer, request} = require('http'); +const { default: SuperTokens } = require("../../lib/build/supertokens"); +const { killAllST, setupST, cleanST, startST, extractInfoFromResponse, printPath } = require("../utils") +const Session = require("../../recipe/session"); +const { createApp, createRouter } = require("h3"); +const { middleware } = require("../../lib/build/framework/h3"); +const { assert } = require("console"); +describe(`h3: ${printPath("[test/framework/h3.test.js]")}`, function () { + beforeEach(async function() { + await killAllST(); + await setupST(); + ProcessState.getInstance().reset(); + }) + + after(async function() { + await killAllST(); + await cleanST(); + }) + + it("test that if disabling api, the default refresh API does not work", async function() { + await startST(); + SuperTokens.init({ + supertokens: { + connectionURI: "http://localhost:8080", + }, + appInfo: { + apiDomain: "api.supertokens.io", + appName: "SuperTokens", + websiteDomain: "supertokens.io" + }, + recipeList: [ + Session.init({ + override: { + apis: (oI) => { + return { + ...oI, + refreshPOST: undefined, + }; + }, + }, + antiCsrf: "VIA_TOKEN", + }) + ] + }) + const app = createApp(); + const router = createRouter(); + router.post('/create', async (req, res) => { + await Session.createNewSession(res, "", {}, {}); + return ""; + }) + app.use(router); + app.use(middleware()); + const server = createServer(app); + let res = extractInfoFromResponse( + await new Promise((resolve) => { + request(server) + .post("/create") + .expect(200) + .end((err, res) => { + if(err) { + resolve(undefined) + } else { + resolve(res); + } + }) + }) + ) + + let res2 = await new Promise((resolve) => { + request(server) + .post("/auth/session/refresh") + .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) + .set("anti-csrf", res.antiCsrf) + .end((err, res) => { + if (err) { + resolve(undefined); + } else { + resolve(res); + } + }) + }) + assert(res2.status === 404); + }) +}) \ No newline at end of file From d8aac4ccfe9dd84841b5187943c2be9643f09028 Mon Sep 17 00:00:00 2001 From: KitsuneKenshi Date: Sun, 1 May 2022 13:12:57 +0200 Subject: [PATCH 08/13] Changes before PR --- add-ts-no-check.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/add-ts-no-check.js b/add-ts-no-check.js index 4a256e98f..0edd5f5c8 100644 --- a/add-ts-no-check.js +++ b/add-ts-no-check.js @@ -8,7 +8,7 @@ glob(__dirname + "/lib/**/*.d.ts", (err, files) => { let lines = contents.split("\n"); let newContents = `// @ts-nocheck`; for (line of lines) { - if (line.match(/\/\/\/\ \ Date: Thu, 5 May 2022 11:15:58 +0200 Subject: [PATCH 09/13] fix(changelog): Added change log for update --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bd3e2e20..9eb8f39aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [unreleased] +## [9.2.1] - 2022-05-05 + +# Adds + +- Support for h3 freamwork. + ## [9.2.0] - 2022-04-18 # Adds From 6bdad19c0e9a279373955f991615812aa2bb9c6f Mon Sep 17 00:00:00 2001 From: Kall7 <63537545+Kall7@users.noreply.github.com> Date: Thu, 5 May 2022 11:20:01 +0200 Subject: [PATCH 10/13] fix(changelog): Added changelog data --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bd3e2e20..76d6d4a19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [unreleased] +## [9.2.1] - 2022-05-05 + +# Adds + +- Support for h3 freamwork. + + ## [9.2.0] - 2022-04-18 # Adds From abc925830db60082808316f8aaae27c4aad80c53 Mon Sep 17 00:00:00 2001 From: Kall7 <63537545+Kall7@users.noreply.github.com> Date: Thu, 5 May 2022 20:49:19 +0200 Subject: [PATCH 11/13] fix(changelog): Wrong place for changelog --- CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76d6d4a19..9fa3d1c83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [unreleased] -## [9.2.1] - 2022-05-05 - # Adds - Support for h3 freamwork. From 98180e5c93cca32b5372c1ef43c26f29d4fbbf98 Mon Sep 17 00:00:00 2001 From: Kenshi Date: Mon, 13 Jun 2022 12:10:06 +0200 Subject: [PATCH 12/13] fix(tests and build): Built pretty and removed wrongly made tests --- CHANGELOG.md | 3 +- lib/build/error.d.ts | 22 +- lib/build/framework/awsLambda/framework.d.ts | 23 +- lib/build/framework/awsLambda/framework.js | 193 +++-- lib/build/framework/awsLambda/index.d.ts | 4 +- lib/build/framework/express/framework.d.ts | 11 +- lib/build/framework/express/framework.js | 144 ++-- lib/build/framework/express/index.d.ts | 13 +- lib/build/framework/fastify/framework.d.ts | 27 +- lib/build/framework/fastify/framework.js | 110 ++- lib/build/framework/fastify/index.d.ts | 16 +- lib/build/framework/h3/framework.d.ts | 27 +- lib/build/framework/h3/framework.js | 151 ++-- lib/build/framework/h3/index.d.ts | 14 +- lib/build/framework/h3/types.d.ts | 2 +- lib/build/framework/hapi/framework.d.ts | 11 +- lib/build/framework/hapi/framework.js | 136 ++-- lib/build/framework/index.d.ts | 2 +- lib/build/framework/index.js | 2 +- lib/build/framework/koa/framework.d.ts | 11 +- lib/build/framework/koa/framework.js | 101 ++- lib/build/framework/loopback/framework.d.ts | 11 +- lib/build/framework/loopback/framework.js | 110 ++- lib/build/framework/response.d.ts | 11 +- lib/build/framework/utils.d.ts | 45 +- lib/build/framework/utils.js | 112 +-- lib/build/index.d.ts | 4 +- lib/build/index.js | 8 +- lib/build/logger.js | 6 +- lib/build/nextjs.d.ts | 6 +- lib/build/nextjs.js | 79 +- 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 | 374 ++++++---- .../recipe/emailpassword/api/emailExists.js | 40 +- .../api/generatePasswordResetToken.d.ts | 5 +- .../api/generatePasswordResetToken.js | 45 +- .../emailpassword/api/implementation.js | 67 +- .../recipe/emailpassword/api/passwordReset.js | 58 +- lib/build/recipe/emailpassword/api/signin.js | 48 +- lib/build/recipe/emailpassword/api/signup.js | 48 +- lib/build/recipe/emailpassword/api/utils.d.ts | 13 +- lib/build/recipe/emailpassword/api/utils.js | 43 +- lib/build/recipe/emailpassword/error.d.ts | 26 +- lib/build/recipe/emailpassword/index.d.ts | 116 ++- lib/build/recipe/emailpassword/index.js | 44 +- .../emailpassword/passwordResetFunctions.d.ts | 4 +- .../emailpassword/passwordResetFunctions.js | 97 ++- lib/build/recipe/emailpassword/recipe.d.ts | 20 +- lib/build/recipe/emailpassword/recipe.js | 160 ++-- .../emailpassword/recipeImplementation.js | 91 ++- lib/build/recipe/emailpassword/types.d.ts | 252 ++++--- lib/build/recipe/emailpassword/utils.d.ts | 27 +- lib/build/recipe/emailpassword/utils.js | 217 ++++-- .../emailverification/api/emailVerify.js | 46 +- .../api/generateEmailVerifyToken.d.ts | 5 +- .../api/generateEmailVerifyToken.js | 40 +- .../emailverification/api/implementation.js | 63 +- .../emailVerificationFunctions.d.ts | 4 +- .../emailVerificationFunctions.js | 93 ++- lib/build/recipe/emailverification/error.d.ts | 5 +- lib/build/recipe/emailverification/index.d.ts | 49 +- lib/build/recipe/emailverification/index.js | 40 +- .../recipe/emailverification/recipe.d.ts | 8 +- lib/build/recipe/emailverification/recipe.js | 94 ++- .../emailverification/recipeImplementation.js | 94 ++- lib/build/recipe/emailverification/types.d.ts | 101 +-- lib/build/recipe/emailverification/utils.d.ts | 6 +- lib/build/recipe/emailverification/utils.js | 22 +- lib/build/recipe/jwt/api/getJWKS.js | 40 +- lib/build/recipe/jwt/api/implementation.js | 42 +- lib/build/recipe/jwt/index.d.ts | 23 +- lib/build/recipe/jwt/index.js | 40 +- lib/build/recipe/jwt/recipe.d.ts | 8 +- lib/build/recipe/jwt/recipe.js | 74 +- .../recipe/jwt/recipeImplementation.d.ts | 6 +- lib/build/recipe/jwt/recipeImplementation.js | 45 +- lib/build/recipe/jwt/types.d.ts | 41 +- lib/build/recipe/jwt/utils.d.ts | 6 +- lib/build/recipe/jwt/utils.js | 13 +- .../api/getOpenIdDiscoveryConfiguration.d.ts | 5 +- .../api/getOpenIdDiscoveryConfiguration.js | 40 +- lib/build/recipe/openid/api/implementation.js | 42 +- lib/build/recipe/openid/index.d.ts | 27 +- lib/build/recipe/openid/recipe.d.ts | 8 +- lib/build/recipe/openid/recipe.js | 99 ++- .../recipe/openid/recipeImplementation.d.ts | 5 +- .../recipe/openid/recipeImplementation.js | 49 +- lib/build/recipe/openid/types.d.ts | 63 +- lib/build/recipe/openid/utils.d.ts | 5 +- lib/build/recipe/openid/utils.js | 8 +- .../recipe/passwordless/api/consumeCode.js | 61 +- .../recipe/passwordless/api/createCode.js | 63 +- .../recipe/passwordless/api/emailExists.js | 40 +- .../recipe/passwordless/api/implementation.js | 271 ++++--- .../passwordless/api/phoneNumberExists.js | 40 +- .../recipe/passwordless/api/resendCode.js | 40 +- lib/build/recipe/passwordless/error.d.ts | 5 +- lib/build/recipe/passwordless/index.d.ts | 170 +++-- lib/build/recipe/passwordless/index.js | 52 +- lib/build/recipe/passwordless/recipe.d.ts | 44 +- lib/build/recipe/passwordless/recipe.js | 237 +++--- .../passwordless/recipeImplementation.js | 105 ++- lib/build/recipe/passwordless/types.d.ts | 501 +++++++------ lib/build/recipe/passwordless/utils.d.ts | 6 +- lib/build/recipe/passwordless/utils.js | 142 ++-- lib/build/recipe/session/accessToken.d.ts | 6 +- lib/build/recipe/session/accessToken.js | 52 +- .../recipe/session/api/implementation.js | 52 +- lib/build/recipe/session/api/refresh.js | 40 +- lib/build/recipe/session/api/signout.js | 40 +- .../recipe/session/cookieAndHeaders.d.ts | 37 +- lib/build/recipe/session/cookieAndHeaders.js | 3 +- lib/build/recipe/session/error.d.ts | 39 +- lib/build/recipe/session/error.js | 13 +- .../session/faunadb/recipeImplementation.d.ts | 197 +++-- .../session/faunadb/recipeImplementation.js | 132 ++-- .../recipe/session/framework/awsLambda.js | 74 +- .../recipe/session/framework/express.d.ts | 4 +- lib/build/recipe/session/framework/express.js | 71 +- .../recipe/session/framework/fastify.d.ts | 13 +- lib/build/recipe/session/framework/fastify.js | 66 +- lib/build/recipe/session/framework/h3.d.ts | 10 +- lib/build/recipe/session/framework/h3.js | 71 +- lib/build/recipe/session/framework/hapi.d.ts | 4 +- lib/build/recipe/session/framework/hapi.js | 55 +- lib/build/recipe/session/framework/index.d.ts | 2 +- lib/build/recipe/session/framework/koa.d.ts | 4 +- lib/build/recipe/session/framework/koa.js | 55 +- .../recipe/session/framework/loopback.js | 57 +- lib/build/recipe/session/index.d.ts | 75 +- lib/build/recipe/session/index.js | 24 +- lib/build/recipe/session/jwt.d.ts | 9 +- lib/build/recipe/session/jwt.js | 32 +- lib/build/recipe/session/recipe.d.ts | 14 +- lib/build/recipe/session/recipe.js | 189 +++-- .../recipe/session/recipeImplementation.d.ts | 8 +- .../recipe/session/recipeImplementation.js | 242 +++++-- lib/build/recipe/session/sessionClass.d.ts | 9 +- lib/build/recipe/session/sessionClass.js | 213 +++--- .../recipe/session/sessionFunctions.d.ts | 28 +- lib/build/recipe/session/sessionFunctions.js | 173 +++-- lib/build/recipe/session/types.d.ts | 147 ++-- lib/build/recipe/session/utils.d.ts | 34 +- lib/build/recipe/session/utils.js | 120 ++- .../with-jwt/recipeImplementation.d.ts | 6 +- .../session/with-jwt/recipeImplementation.js | 66 +- .../recipe/session/with-jwt/sessionClass.js | 107 +-- 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 | 40 +- .../recipe/thirdparty/api/implementation.js | 94 ++- lib/build/recipe/thirdparty/api/signinup.js | 55 +- lib/build/recipe/thirdparty/error.d.ts | 5 +- lib/build/recipe/thirdparty/index.d.ts | 77 +- lib/build/recipe/thirdparty/index.js | 40 +- .../recipe/thirdparty/providers/apple.js | 93 ++- .../recipe/thirdparty/providers/discord.js | 65 +- .../recipe/thirdparty/providers/facebook.js | 40 +- .../recipe/thirdparty/providers/github.js | 65 +- .../recipe/thirdparty/providers/google.js | 58 +- .../thirdparty/providers/googleWorkspaces.js | 71 +- .../recipe/thirdparty/providers/utils.d.ts | 6 +- .../recipe/thirdparty/providers/utils.js | 43 +- lib/build/recipe/thirdparty/recipe.d.ts | 20 +- lib/build/recipe/thirdparty/recipe.js | 139 ++-- .../recipe/thirdparty/recipeImplementation.js | 59 +- lib/build/recipe/thirdparty/types.d.ts | 143 ++-- lib/build/recipe/thirdparty/utils.d.ts | 12 +- lib/build/recipe/thirdparty/utils.js | 147 ++-- .../api/emailPasswordAPIImplementation.js | 23 +- .../api/implementation.js | 40 +- .../api/thirdPartyAPIImplementation.js | 84 ++- .../recipe/thirdpartyemailpassword/error.d.ts | 5 +- .../recipe/thirdpartyemailpassword/index.d.ts | 152 ++-- .../recipe/thirdpartyemailpassword/index.js | 48 +- .../thirdpartyemailpassword/recipe.d.ts | 30 +- .../recipe/thirdpartyemailpassword/recipe.js | 201 ++++-- .../emailPasswordRecipeImplementation.js | 40 +- .../recipeImplementation/index.js | 87 ++- .../thirdPartyRecipeImplementation.js | 40 +- .../recipe/thirdpartyemailpassword/types.d.ts | 352 +++++---- .../recipe/thirdpartyemailpassword/utils.d.ts | 6 +- .../recipe/thirdpartyemailpassword/utils.js | 141 +++- .../api/implementation.js | 40 +- .../api/passwordlessAPIImplementation.js | 19 +- .../api/thirdPartyAPIImplementation.js | 84 ++- .../recipe/thirdpartypasswordless/error.d.ts | 5 +- .../recipe/thirdpartypasswordless/index.d.ts | 365 ++++++---- .../recipe/thirdpartypasswordless/index.js | 92 ++- .../recipe/thirdpartypasswordless/recipe.d.ts | 30 +- .../recipe/thirdpartypasswordless/recipe.js | 302 +++++--- .../recipeImplementation/index.js | 115 ++- .../passwordlessRecipeImplementation.js | 40 +- .../thirdPartyRecipeImplementation.js | 40 +- .../recipe/thirdpartypasswordless/types.d.ts | 683 ++++++++++-------- .../recipe/thirdpartypasswordless/utils.d.ts | 6 +- .../recipe/thirdpartypasswordless/utils.js | 139 ++-- lib/build/recipe/usermetadata/index.d.ts | 16 +- lib/build/recipe/usermetadata/index.js | 40 +- lib/build/recipe/usermetadata/recipe.d.ts | 8 +- lib/build/recipe/usermetadata/recipe.js | 54 +- 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/recipeModule.d.ts | 8 +- lib/build/recipeModule.js | 6 +- lib/build/supertokens.d.ts | 9 +- lib/build/supertokens.js | 403 ++++++----- lib/build/utils.js | 29 +- lib/ts/framework/h3/framework.ts | 92 +-- lib/ts/framework/h3/index.ts | 4 +- lib/ts/framework/index.ts | 6 +- lib/ts/framework/utils.ts | 43 +- lib/ts/recipe/session/framework/h3.ts | 20 +- lib/ts/recipe/session/framework/index.ts | 4 +- package.json | 2 +- test/framework/h3.test.js | 85 --- 222 files changed, 9508 insertions(+), 5014 deletions(-) delete mode 100644 test/framework/h3.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fa3d1c83..3244f0b58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 # Adds -- Support for h3 freamwork. - +- Support for h3 freamwork. ## [9.2.0] - 2022-04-18 diff --git a/lib/build/error.d.ts b/lib/build/error.d.ts index eb4b12907..122f79f0b 100644 --- a/lib/build/error.d.ts +++ b/lib/build/error.d.ts @@ -6,14 +6,18 @@ export default class SuperTokensError { 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 a0e58c33e..fcc51ee5b 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"; @@ -50,13 +56,24 @@ 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; + 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 bdf0f3afc..0ecc14e2f 100644 --- a/lib/build/framework/awsLambda/framework.js +++ b/lib/build/framework/awsLambda/framework.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 request_1 = require("../request"); @@ -19,20 +41,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; @@ -43,20 +65,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) { @@ -66,15 +88,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; }; @@ -120,7 +147,16 @@ class AWSResponse extends response_1.BaseResponse { }); }; 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); }; /** @@ -168,8 +204,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; } } @@ -179,26 +214,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; } }; @@ -218,37 +255,37 @@ 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`, - }); - 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.AWSWrapper = { middleware: exports.middleware, 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 474a180d8..28f91f4d6 100644 --- a/lib/build/framework/express/framework.d.ts +++ b/lib/build/framework/express/framework.d.ts @@ -23,7 +23,16 @@ 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; + 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 25a1b62a5..a40def3d3 100644 --- a/lib/build/framework/express/framework.js +++ b/lib/build/framework/express/framework.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 request_1 = require("../request"); @@ -31,13 +53,14 @@ 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.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -48,13 +71,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); }; @@ -87,7 +111,17 @@ class ExpressResponse extends response_1.BaseResponse { utils_2.setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; 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 @@ -109,44 +143,42 @@ 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(); - } - } - 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.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.ExpressWrapper = { middleware: exports.middleware, 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 d9fd306da..3e308824d 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 { 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; + setCookie: ( + key: string, + value: string, + domain: string | undefined, + secure: boolean, + httpOnly: boolean, + expires: number, + path: string, + sameSite: "strict" | "lax" | "none" + ) => void; /** * @param {number} statusCode */ @@ -39,5 +48,19 @@ export interface FasitfyFramework extends Framework { plugin: FastifyPluginCallback; errorHandler: () => (err: any, req: OriginalFastifyRequest, res: FastifyReply) => Promise; } -export declare const 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 FastifyWrapper: FasitfyFramework; diff --git a/lib/build/framework/fastify/framework.js b/lib/build/framework/fastify/framework.js index c41b0a914..3dbce7cf5 100644 --- a/lib/build/framework/fastify/framework.js +++ b/lib/build/framework/fastify/framework.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 request_1 = require("../request"); @@ -32,9 +54,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; @@ -45,9 +68,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); }; @@ -81,21 +105,27 @@ 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.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 + ); let prev = this.response.getHeader(constants_1.COOKIE_HEADER); let cookieValueToSetInHeader = utils_2.getCookieValueToSetInHeader(prev, serialisedCookie, key); this.response.header(constants_1.COOKIE_HEADER, cookieValueToSetInHeader); @@ -124,27 +154,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); - }); + 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.FastifyWrapper = { plugin, 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/h3/framework.d.ts b/lib/build/framework/h3/framework.d.ts index 3e12149d8..e775a2a66 100644 --- a/lib/build/framework/h3/framework.d.ts +++ b/lib/build/framework/h3/framework.d.ts @@ -1,10 +1,10 @@ /// -import { H3Event } from 'h3'; -import type { IncomingMessage, ServerResponse } from 'http'; -import { SessionContainerInterface } from '../../recipe/session/types'; +import { H3Event } from "h3"; +import type { IncomingMessage, ServerResponse } from "http"; +import { SessionContainerInterface } from "../../recipe/session/types"; import { BaseRequest } from "../request"; -import { BaseResponse } from '../response'; -import { Framework } from '../types'; +import { BaseResponse } from "../response"; +import { Framework } from "../types"; export declare class H3Request extends BaseRequest { private request; constructor(request: IncomingMessage); @@ -22,14 +22,27 @@ export declare class H3ResponseTokens extends BaseResponse { constructor(response: ServerResponse); 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; + 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; } export interface SessionRequest extends IncomingMessage { session?: SessionContainerInterface; } -export declare const middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; +export declare const middlware: () => ( + req: IncomingMessage, + res: ServerResponse, + next: (err?: Error | undefined) => any +) => Promise; export declare const errorHandler: () => (event: H3Event, errorPlain: Error, statusCode: number) => Promise; export interface H3Framework extends Framework { middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise; diff --git a/lib/build/framework/h3/framework.js b/lib/build/framework/h3/framework.js index 878287e44..09d148c15 100644 --- a/lib/build/framework/h3/framework.js +++ b/lib/build/framework/h3/framework.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 h3_1 = require("h3"); const supertokens_1 = require("../../supertokens"); @@ -21,9 +43,10 @@ class H3Request extends request_1.BaseRequest { this.getCookieValue = (key) => { return utils_2.getCookieValueFromIncomingMessage(this.request, key); }; - this.getFormData = () => __awaiter(this, void 0, void 0, function* () { - return utils_2.useRawBody(this.request); - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + return utils_2.useRawBody(this.request); + }); this.getMethod = () => { return utils_1.normaliseHttpMethod(this.request.method); }; @@ -35,29 +58,27 @@ class H3Request extends request_1.BaseRequest { }; this.getKeyValueFromQuery = (key) => { let path = this.request.url || "/"; - const queryIndex = path.lastIndexOf('?'); + const queryIndex = path.lastIndexOf("?"); if (queryIndex > -1) { - const queryArray = path.substring(queryIndex + 1, path.length).split('&'); - const index = queryArray.findIndex(el => el.includes(key)); - if (index === -1) - return undefined; - const value = queryArray[index].split('=')[1]; - if (value === undefined || typeof value !== 'string') { + const queryArray = path.substring(queryIndex + 1, path.length).split("&"); + const index = queryArray.findIndex((el) => el.includes(key)); + if (index === -1) return undefined; + const value = queryArray[index].split("=")[1]; + if (value === undefined || typeof value !== "string") { return undefined; } return value; - } - else { + } else { return undefined; } }; - this.getJSONBody = () => __awaiter(this, void 0, void 0, function* () { - return yield utils_2.useBody(this.request); - }); + this.getJSONBody = () => + __awaiter(this, void 0, void 0, function* () { + return yield utils_2.useBody(this.request); + }); this.original = request; this.request = request; } - ; } exports.H3Request = H3Request; class H3ResponseTokens extends response_1.BaseResponse { @@ -65,7 +86,7 @@ class H3ResponseTokens extends response_1.BaseResponse { super(); this.sendHTMLResponse = (html) => { if (this.response.writable) { - this.response.setHeader('Content-Type', 'text/html'); + this.response.setHeader("Content-Type", "text/html"); this.response.statusCode = this.statusCode; this.response.end(html); } @@ -77,21 +98,28 @@ class H3ResponseTokens extends response_1.BaseResponse { // we have the this.response.header for compatibility with nextJS if (existingValue === undefined) { this.response.setHeader(key, value); - } - else if (allowDuplicateKey) { + } else if (allowDuplicateKey) { this.response.setHeader(key, existingValue + ", " + value); - } - else { + } else { // we overwrite the current one with the new one this.response.setHeader(key, value); } - } - catch (err) { + } catch (err) { throw new Error("Error while setting header with key: " + key + " and value: " + value); } }; 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.writable) { @@ -101,9 +129,9 @@ class H3ResponseTokens extends response_1.BaseResponse { this.sendJSONResponse = (content) => { if (this.response.writable) { content = JSON.stringify(content); - this.response.setHeader('Content-Type', 'application/json'); + this.response.setHeader("Content-Type", "application/json"); this.response.statusCode = this.statusCode; - this.response.end(content, 'utf-8'); + this.response.end(content, "utf-8"); } }; this.original = response; @@ -113,38 +141,37 @@ class H3ResponseTokens extends response_1.BaseResponse { } exports.H3ResponseTokens = H3ResponseTokens; exports.middlware = () => { - return (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - let supertokens; - const request = new H3Request(req); - const response = new H3ResponseTokens(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 H3Request(req); + const response = new H3ResponseTokens(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.errorHandler = () => { - return (event, errorPlain, statusCode) => __awaiter(void 0, void 0, void 0, function* () { - const error = h3_1.createError(errorPlain); - error.statusCode = statusCode; - h3_1.sendError(event, error); - }); + return (event, errorPlain, statusCode) => + __awaiter(void 0, void 0, void 0, function* () { + const error = h3_1.createError(errorPlain); + error.statusCode = statusCode; + h3_1.sendError(event, error); + }); }; exports.H3Wrapper = { middlware: exports.middlware, @@ -154,5 +181,5 @@ exports.H3Wrapper = { }, wrapResponse: (unwrapped) => { return new H3ResponseTokens(unwrapped.res); - } + }, }; diff --git a/lib/build/framework/h3/index.d.ts b/lib/build/framework/h3/index.d.ts index 4c089b51e..dae4850e7 100644 --- a/lib/build/framework/h3/index.d.ts +++ b/lib/build/framework/h3/index.d.ts @@ -1,6 +1,14 @@ /// -export type { SessionRequest } from './framework'; -export declare const middleware: () => (req: import("http").IncomingMessage, res: import("http").ServerResponse, next: (err?: Error | undefined) => any) => Promise; -export declare const errorHandler: () => (event: import("h3").H3Event, errorPlain: Error, statusCode: number) => Promise; +export type { SessionRequest } from "./framework"; +export declare const middleware: () => ( + req: import("http").IncomingMessage, + res: import("http").ServerResponse, + next: (err?: Error | undefined) => any +) => Promise; +export declare const errorHandler: () => ( + event: import("h3").H3Event, + errorPlain: Error, + statusCode: number +) => Promise; export declare const wrapRequest: (unwrapped: any) => import("..").BaseRequest; export declare const wrapResponse: (unwrapped: any) => import("..").BaseResponse; diff --git a/lib/build/framework/h3/types.d.ts b/lib/build/framework/h3/types.d.ts index c6200591b..ef9d271bf 100644 --- a/lib/build/framework/h3/types.d.ts +++ b/lib/build/framework/h3/types.d.ts @@ -1,5 +1,5 @@ /// -import { ServerResponse, IncomingMessage } from 'http'; +import { ServerResponse, IncomingMessage } from "http"; export interface Event { res: ServerResponse; req: IncomingMessage; diff --git a/lib/build/framework/hapi/framework.d.ts b/lib/build/framework/hapi/framework.d.ts index 9fb0d6ace..4486ebac5 100644 --- a/lib/build/framework/hapi/framework.d.ts +++ b/lib/build/framework/hapi/framework.d.ts @@ -27,7 +27,16 @@ 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; + 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 271d5e3b1..5c3be72f4 100644 --- a/lib/build/framework/hapi/framework.js +++ b/lib/build/framework/hapi/framework.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 request_1 = require("../request"); @@ -31,9 +53,10 @@ 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; @@ -44,9 +67,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); }; @@ -78,8 +102,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); } }; @@ -94,8 +117,7 @@ class HapiResponse extends response_1.BaseResponse { ttl: expires - now, isSameSite: sameSite === "lax" ? "Lax" : sameSite === "none" ? "None" : "Strict", }); - } - else { + } else { this.response.unstate(key); } }; @@ -137,47 +159,49 @@ 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; + 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; } - else { - request.response.header(key, value, { append: allowDuplicateKey }); - } - }); - if (request.response.isBoom) { - let err = request.response.data; - 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; + 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 }); diff --git a/lib/build/framework/index.d.ts b/lib/build/framework/index.d.ts index cee83d482..4ad55393c 100644 --- a/lib/build/framework/index.d.ts +++ b/lib/build/framework/index.d.ts @@ -6,7 +6,7 @@ import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; -import * as h3Framework from './h3'; +import * as h3Framework from "./h3"; declare const _default: { express: typeof expressFramework; fastify: typeof fastifyFramework; diff --git a/lib/build/framework/index.js b/lib/build/framework/index.js index e13034290..222e80db6 100644 --- a/lib/build/framework/index.js +++ b/lib/build/framework/index.js @@ -32,7 +32,7 @@ exports.default = { loopback: loopbackFramework, koa: koaFramework, awsLambda: awsLambdaFramework, - h3: h3Framework + h3: h3Framework, }; exports.express = expressFramework; exports.fastify = fastifyFramework; diff --git a/lib/build/framework/koa/framework.d.ts b/lib/build/framework/koa/framework.d.ts index 1a4cefe86..b24d57872 100644 --- a/lib/build/framework/koa/framework.d.ts +++ b/lib/build/framework/koa/framework.d.ts @@ -24,7 +24,16 @@ 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; + 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 643e2cfa6..94d4b1ae1 100644 --- a/lib/build/framework/koa/framework.js +++ b/lib/build/framework/koa/framework.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 request_1 = require("../request"); @@ -32,12 +54,13 @@ 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; @@ -48,12 +71,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); }; @@ -107,16 +131,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); } }; @@ -151,20 +172,20 @@ 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(); + 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.KoaWrapper = { middleware: exports.middleware, diff --git a/lib/build/framework/loopback/framework.d.ts b/lib/build/framework/loopback/framework.d.ts index 584720d18..22718e646 100644 --- a/lib/build/framework/loopback/framework.d.ts +++ b/lib/build/framework/loopback/framework.d.ts @@ -23,7 +23,16 @@ 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; + 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 9ff8588c9..be04274a0 100644 --- a/lib/build/framework/loopback/framework.js +++ b/lib/build/framework/loopback/framework.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 request_1 = require("../request"); @@ -31,13 +53,14 @@ 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.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); - this.formDataParserChecked = true; - } - return this.request.body; - }); + this.getFormData = () => + __awaiter(this, void 0, void 0, function* () { + if (!this.formDataParserChecked) { + yield utils_2.assertForDataBodyParserHasBeenUsedForExpressLikeRequest(this.request); + this.formDataParserChecked = true; + } + return this.request.body; + }); this.getKeyValueFromQuery = (key) => { if (this.request.query === undefined) { return undefined; @@ -48,13 +71,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); }; @@ -87,7 +111,17 @@ class LoopbackResponse extends response_1.BaseResponse { utils_2.setHeaderForExpressLikeResponse(this.response, key, value, allowDuplicateKey); }; 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) { @@ -105,21 +139,21 @@ 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(); +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); } - return; - } - catch (err) { - return yield supertokens.errorHandler(err, request, response); - } -}); + }); exports.LoopbackWrapper = { middleware: exports.middleware, wrapRequest: (unwrapped) => { diff --git a/lib/build/framework/response.d.ts b/lib/build/framework/response.d.ts index 33e0716fb..b94d17627 100644 --- a/lib/build/framework/response.d.ts +++ b/lib/build/framework/response.d.ts @@ -3,7 +3,16 @@ export declare abstract class BaseResponse { 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 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 f09253455..2b9067b1a 100644 --- a/lib/build/framework/utils.d.ts +++ b/lib/build/framework/utils.d.ts @@ -8,9 +8,19 @@ 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): Promise; -export declare function assertForDataBodyParserHasBeenUsedForExpressLikeRequest(request: Request | NextApiRequest): Promise; -export declare function setHeaderForExpressLikeResponse(res: Response, key: string, value: string, allowDuplicateKey: boolean): void; +export declare function assertThatBodyParserHasBeenUsedForExpressLikeRequest( + method: HTTPMethod, + request: Request | NextApiRequest +): Promise; +export declare function assertForDataBodyParserHasBeenUsedForExpressLikeRequest( + request: Request | NextApiRequest +): Promise; +export declare function setHeaderForExpressLikeResponse( + res: Response, + key: string, + value: string, + allowDuplicateKey: boolean +): void; export declare function useRawBody(req: IncomingMessage): Promise; export declare function useBody(req: IncomingMessage): Promise; /** @@ -24,6 +34,29 @@ export declare function useBody(req: IncomingMessage): Promise; * @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 e41c8ad10..f50ee1aed 100644 --- a/lib/build/framework/utils.js +++ b/lib/build/framework/utils.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 cookie_1 = require("cookie"); const body_parser_1 = require("body-parser"); @@ -77,8 +99,7 @@ function JSONCookie(str) { } try { return JSON.parse(str.slice(2)); - } - catch (err) { + } catch (err) { return undefined; } } @@ -109,22 +130,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 thr 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) => { @@ -154,8 +174,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)); @@ -191,56 +210,53 @@ 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); } } exports.setHeaderForExpressLikeResponse = setHeaderForExpressLikeResponse; function useRawBody(req) { - const RawBodySymbol = Symbol('h3RawBody'); + const RawBodySymbol = Symbol("h3RawBody"); if (RawBodySymbol in this.request) { const promise = Promise.resolve(req[RawBodySymbol]); - return promise.then(buff => buff.toString('utf-8')); + return promise.then((buff) => buff.toString("utf-8")); } - if ('body' in req) { + if ("body" in req) { return Promise.resolve(this.request.body); } - const promise = req[RawBodySymbol] = new Promise((resolve, reject) => { + const promise = (req[RawBodySymbol] = new Promise((resolve, reject) => { const bodyData = []; - req - .on('error', (err) => reject(err)) - .on('data', (chunk) => { bodyData.push(chunk); }) - .on('end', () => { resolve(Buffer.concat(bodyData)); }); - }); - return promise.then(buff => buff.toString('utf-8')); + req.on("error", (err) => reject(err)) + .on("data", (chunk) => { + bodyData.push(chunk); + }) + .on("end", () => { + resolve(Buffer.concat(bodyData)); + }); + })); + return promise.then((buff) => buff.toString("utf-8")); } exports.useRawBody = useRawBody; function useBody(req) { return __awaiter(this, void 0, void 0, function* () { - const ParsedBodySymbol = Symbol('h3RawBody'); + const ParsedBodySymbol = Symbol("h3RawBody"); if (ParsedBodySymbol in req) { return req[ParsedBodySymbol]; } @@ -263,7 +279,12 @@ exports.useBody = useBody; * @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; /** @@ -295,8 +316,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 a1c3e9853..68d94be5d 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -27,7 +27,9 @@ export default class SuperTokensWrapper { }[]; nextPaginationToken?: string; }>; - static deleteUser(userId: string): Promise<{ + static deleteUser( + userId: string + ): Promise<{ status: "OK"; }>; } diff --git a/lib/build/index.js b/lib/build/index.js index ca292fa57..dd18aae30 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -25,10 +25,14 @@ class SuperTokensWrapper { return supertokens_1.default.getInstanceOrThrowError().getUserCount(includeRecipeIds); } static getUsersOldestFirst(input) { - return supertokens_1.default.getInstanceOrThrowError().getUsers(Object.assign({ timeJoinedOrder: "ASC" }, input)); + return supertokens_1.default + .getInstanceOrThrowError() + .getUsers(Object.assign({ timeJoinedOrder: "ASC" }, input)); } static getUsersNewestFirst(input) { - return supertokens_1.default.getInstanceOrThrowError().getUsers(Object.assign({ timeJoinedOrder: "DESC" }, input)); + return supertokens_1.default + .getInstanceOrThrowError() + .getUsers(Object.assign({ timeJoinedOrder: "DESC" }, input)); } static deleteUser(userId) { return supertokens_1.default.getInstanceOrThrowError().deleteUser({ diff --git a/lib/build/logger.js b/lib/build/logger.js index 92d2097ef..510a2cad8 100644 --- a/lib/build/logger.js +++ b/lib/build/logger.js @@ -23,7 +23,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 2a5cf1897..d3ec960fe 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 }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -42,26 +64,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* () { - 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* () { + 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 dd66e044d..76a6ccc76 100644 --- a/lib/build/processState.js +++ b/lib/build/processState.js @@ -13,23 +13,46 @@ * 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 }); 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 = []; @@ -49,27 +72,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 963f9fed7..a22c95c25 100644 --- a/lib/build/querier.js +++ b/lib/build/querier.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. * @@ -32,31 +54,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"); @@ -64,128 +99,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 }; - 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: "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 }; + 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: "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/emailpassword/api/emailExists.js b/lib/build/recipe/emailpassword/api/emailExists.js index f530d64e3..b8421e952 100644 --- a/lib/build/recipe/emailpassword/api/emailExists.js +++ b/lib/build/recipe/emailpassword/api/emailExists.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 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 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 c085edcda..0bf07146d 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"); @@ -32,7 +54,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, userContext: {} }); utils_1.send200Response(options.res, result); return true; diff --git a/lib/build/recipe/emailpassword/api/implementation.js b/lib/build/recipe/emailpassword/api/implementation.js index d00409a58..53e7fb1fb 100644 --- a/lib/build/recipe/emailpassword/api/implementation.js +++ b/lib/build/recipe/emailpassword/api/implementation.js @@ -1,18 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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 session_1 = require("../../session"); function getAPIImplementation() { return { - 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 { @@ -21,7 +43,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 }); @@ -39,7 +61,8 @@ function getAPIImplementation() { status: "OK", }; } - let passwordResetLink = (yield options.config.resetPasswordUsingTokenFeature.getResetPasswordURL(user, userContext)) + + let passwordResetLink = + (yield options.config.resetPasswordUsingTokenFeature.getResetPasswordURL(user, userContext)) + "?token=" + response.token + "&rid=" + @@ -48,20 +71,22 @@ function getAPIImplementation() { if (!options.isInServerlessEnv) { options.config.resetPasswordUsingTokenFeature .createAndSendCustomEmail(user, passwordResetLink, userContext) - .catch((_) => { }); - } - else { + .catch((_) => {}); + } else { // see https://github.com/supertokens/supertokens-node/pull/135 - yield options.config.resetPasswordUsingTokenFeature.createAndSendCustomEmail(user, passwordResetLink, userContext); + yield options.config.resetPasswordUsingTokenFeature.createAndSendCustomEmail( + user, + passwordResetLink, + userContext + ); } - } - catch (_) { } + } catch (_) {} return { status: "OK", }; }); }, - 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({ @@ -72,7 +97,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; @@ -89,7 +114,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; diff --git a/lib/build/recipe/emailpassword/api/passwordReset.js b/lib/build/recipe/emailpassword/api/passwordReset.js index 59fa1b178..8b446c4d5 100644 --- a/lib/build/recipe/emailpassword/api/passwordReset.js +++ b/lib/build/recipe/emailpassword/api/passwordReset.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 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({ @@ -48,11 +73,14 @@ function passwordReset(apiImplementation, options) { }); } let result = yield apiImplementation.passwordResetPOST({ formFields, token, options, userContext: {} }); - 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 131e0ab0d..760cf1971 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"); @@ -32,15 +54,17 @@ 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, userContext: {} }); if (result.status === "OK") { utils_1.send200Response(options.res, { 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 2561afee9..e5e3e2f72 100644 --- a/lib/build/recipe/emailpassword/api/signup.js +++ b/lib/build/recipe/emailpassword/api/signup.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,15 +55,17 @@ 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, userContext: {} }); if (result.status === "OK") { utils_1.send200Response(options.res, { status: "OK", user: result.user, }); - } - 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 eb3160e10..1d9784a5b 100644 --- a/lib/build/recipe/emailpassword/api/utils.js +++ b/lib/build/recipe/emailpassword/api/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 }); const error_1 = require("../error"); const constants_1 = require("../constants"); @@ -69,8 +91,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/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/index.d.ts b/lib/build/recipe/emailpassword/index.d.ts index 91fdc950b..cc6f13f47 100644 --- a/lib/build/recipe/emailpassword/index.d.ts +++ b/lib/build/recipe/emailpassword/index.d.ts @@ -4,32 +4,59 @@ import { RecipeInterface, User, APIOptions, APIInterface } 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; - static createResetPasswordToken(userId: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "UNKNOWN_USER_ID_ERROR"; - }>; - static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ - status: "OK"; - userId?: string | undefined; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + static createResetPasswordToken( + userId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "UNKNOWN_USER_ID_ERROR"; + } + >; + static resetPasswordUsingToken( + token: string, + newPassword: string, + userContext?: any + ): Promise< + | { + status: "OK"; + userId?: string | undefined; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; static updateEmailOrPassword(input: { userId: string; email?: string; @@ -38,20 +65,39 @@ export default class Wrapper { }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; }>; - static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - }>; - static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } | User | undefined>; + static createEmailVerificationToken( + userId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + } + >; + static verifyEmailUsingToken( + token: string, + userContext?: any + ): Promise< + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + | User + | undefined + >; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ + static revokeEmailVerificationTokens( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; - static unverifyEmail(userId: string, userContext?: any): Promise<{ + static unverifyEmail( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; } diff --git a/lib/build/recipe/emailpassword/index.js b/lib/build/recipe/emailpassword/index.js index 2b2cb30e2..40c5c9494 100644 --- a/lib/build/recipe/emailpassword/index.js +++ b/lib/build/recipe/emailpassword/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); @@ -66,7 +88,9 @@ 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 createEmailVerificationToken(userId, userContext) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts index 755b16f17..f75771b52 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.d.ts @@ -1,4 +1,6 @@ import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; export declare function getResetPasswordURL(appInfo: NormalisedAppinfo): (_: User) => Promise; -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 198e4c31a..69b6ec934 100644 --- a/lib/build/recipe/emailpassword/passwordResetFunctions.js +++ b/lib/build/recipe/emailpassword/passwordResetFunctions.js @@ -13,47 +13,72 @@ * 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"); function getResetPasswordURL(appInfo) { - return (_) => __awaiter(this, void 0, void 0, function* () { - // according to https://github.com/supertokens/supertokens-auth-react/issues/6 - return (appInfo.websiteDomain.getAsStringDangerous() + - appInfo.websiteBasePath.getAsStringDangerous() + - "/reset-password"); - }); + return (_) => + __awaiter(this, void 0, void 0, function* () { + // according to https://github.com/supertokens/supertokens-auth-react/issues/6 + return ( + appInfo.websiteDomain.getAsStringDangerous() + + appInfo.websiteBasePath.getAsStringDangerous() + + "/reset-password" + ); + }); } exports.getResetPasswordURL = getResetPasswordURL; 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, - }, - }); - } - catch (ignored) { } - }); + 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, + }, + }); + } catch (ignored) {} + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; diff --git a/lib/build/recipe/emailpassword/recipe.d.ts b/lib/build/recipe/emailpassword/recipe.d.ts index f226e9b93..23dcf8309 100644 --- a/lib/build/recipe/emailpassword/recipe.d.ts +++ b/lib/build/recipe/emailpassword/recipe.d.ts @@ -13,14 +13,26 @@ export default class Recipe extends RecipeModule { recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; isInServerlessEnv: boolean; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput | undefined, recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput | undefined, + recipes: { + emailVerificationInstance: EmailVerificationRecipe | 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 bbd6e8bde..46308befd 100644 --- a/lib/build/recipe/emailpassword/recipe.js +++ b/lib/build/recipe/emailpassword/recipe.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 recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -59,7 +81,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, }, @@ -78,74 +102,79 @@ class Recipe extends recipeModule_1.default { ...this.emailVerificationRecipe.getAPIsHandled(), ]; }; - 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, - emailVerificationRecipeImplementation: this.emailVerificationRecipe.recipeInterfaceImpl, - req, - res, - }; - 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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); - } - }); - 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, + emailVerificationRecipeImplementation: this.emailVerificationRecipe.recipeInterfaceImpl, + req, + res, + }; + 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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); } - else { - throw err; + }); + 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 { + return yield this.emailVerificationRecipe.handleError(err, request, response); } - } - else { - return yield this.emailVerificationRecipe.handleError(err, request, response); - } - }); + }); this.getAllCORSHeaders = () => { return [...this.emailVerificationRecipe.getAllCORSHeaders()]; }; this.isErrorFromThisRecipe = (err) => { - return (error_1.default.isErrorFromSuperTokens(err) && - (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err))); + return ( + error_1.default.isErrorFromSuperTokens(err) && + (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err)) + ); }; // 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) { - throw Error("Unknown User ID provided"); - } - return userInfo.email; - }); + this.getEmailForUserId = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw Error("Unknown User ID provided"); + } + return userInfo.email; + }); this.isInServerlessEnv = isInServerlessEnv; this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign({}, this.config.emailVerificationFeature)); + : new recipe_1.default( + recipeId, + appInfo, + isInServerlessEnv, + Object.assign({}, this.config.emailVerificationFeature) + ); { - 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(); } { @@ -166,8 +195,7 @@ class Recipe extends recipeModule_1.default { emailVerificationInstance: 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 b222492f0..307ac1e64 100644 --- a/lib/build/recipe/emailpassword/recipeImplementation.js +++ b/lib/build/recipe/emailpassword/recipeImplementation.js @@ -1,18 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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, @@ -20,15 +42,14 @@ 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, @@ -36,8 +57,7 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return response; - } - else { + } else { return { status: "WRONG_CREDENTIALS_ERROR", }; @@ -51,8 +71,7 @@ function getRecipeInterface(querier) { }); if (response.status === "OK") { return Object.assign({}, response.user); - } - else { + } else { return undefined; } }); @@ -64,37 +83,41 @@ 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; }); }, @@ -109,13 +132,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 cadefa2af..f2d7ad2ea 100644 --- a/lib/build/recipe/emailpassword/types.d.ts +++ b/lib/build/recipe/emailpassword/types.d.ts @@ -1,4 +1,7 @@ -import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; +import { + RecipeInterface as EmailVerificationRecipeInterface, + APIInterface as EmailVerificationAPIInterface, +} from "../emailverification"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; import { BaseRequest, BaseResponse } from "../../framework"; import OverrideableBuilder from "supertokens-js-override"; @@ -9,11 +12,20 @@ export declare type TypeNormalisedInput = { resetPasswordUsingTokenFeature: TypeNormalisedInputResetPasswordUsingTokenFeature; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; @@ -64,11 +76,20 @@ export declare type TypeInput = { resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; emailVerificationFeature?: TypeInputEmailVerificationFeature; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; @@ -77,53 +98,59 @@ 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; createResetPasswordToken(input: { userId: 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"; - /** - * The id of the user whose password was reset. - * Defined for Core versions 3.9 or later - */ - userId?: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + /** + * The id of the user whose password was reset. + * Defined for Core versions 3.9 or later + */ + userId?: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; updateEmailOrPassword(input: { userId: string; email?: string; @@ -143,64 +170,83 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - emailExistsGET: undefined | ((input: { - email: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); - generatePasswordResetTokenPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - }>); - passwordResetPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - userId?: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>); - signInPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - session: SessionContainerInterface; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - }>); - signUpPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - session: SessionContainerInterface; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - }>); + emailExistsGET: + | undefined + | ((input: { + email: string; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); + generatePasswordResetTokenPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + }>); + passwordResetPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + userId?: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >); + signInPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + >); + signUpPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >); }; diff --git a/lib/build/recipe/emailpassword/utils.d.ts b/lib/build/recipe/emailpassword/utils.d.ts index 361dbc878..14fa3d4b6 100644 --- a/lib/build/recipe/emailpassword/utils.d.ts +++ b/lib/build/recipe/emailpassword/utils.d.ts @@ -2,8 +2,27 @@ import Recipe from "./recipe"; import { TypeInput, TypeNormalisedInput, NormalisedFormField, TypeInputFormField } from "./types"; import { NormalisedAppinfo } from "../../types"; import { TypeInput as TypeNormalisedInputEmailVerification } from "../emailverification/types"; -export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, appInfo: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInput; -export declare function validateAndNormaliseEmailVerificationConfig(recipeInstance: Recipe, _: NormalisedAppinfo, config?: TypeInput): TypeNormalisedInputEmailVerification; +export declare function validateAndNormaliseUserInput( + recipeInstance: Recipe, + appInfo: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInput; +export declare function validateAndNormaliseEmailVerificationConfig( + recipeInstance: Recipe, + _: NormalisedAppinfo, + config?: TypeInput +): TypeNormalisedInputEmailVerification; 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 631290900..2be253382 100644 --- a/lib/build/recipe/emailpassword/utils.js +++ b/lib/build/recipe/emailpassword/utils.js @@ -13,24 +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 }); const constants_1 = require("./constants"); const passwordResetFunctions_1 = require("./passwordResetFunctions"); 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(recipeInstance, appInfo, signUpFeature, config === undefined ? undefined : config.resetPasswordUsingTokenFeature); + let resetPasswordUsingTokenFeature = validateAndNormaliseResetPasswordUsingTokenConfig( + recipeInstance, + appInfo, + signUpFeature, + config === undefined ? undefined : config.resetPasswordUsingTokenFeature + ); let emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, appInfo, 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 { signUpFeature, signInFeature, @@ -44,35 +81,64 @@ function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserId, - override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, - createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); - }), - getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: + (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 + ? void 0 + : _a.emailVerificationFeature, + createAndSendCustomEmail: + ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _b === void 0 + ? void 0 + : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_d = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _d === void 0 + ? void 0 + : _d.createAndSendCustomEmail) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail( + userInfo, + link, + userContext + ); + }), + getEmailVerificationURL: + ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _c === void 0 + ? void 0 + : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_e = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _e === void 0 + ? void 0 + : _e.getEmailVerificationURL) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } exports.validateAndNormaliseEmailVerificationConfig = validateAndNormaliseEmailVerificationConfig; @@ -80,27 +146,29 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(_, appInfo, signUpCon 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, - }; - }); - let getResetPasswordURL = config === undefined || config.getResetPasswordURL === undefined - ? passwordResetFunctions_1.getResetPasswordURL(appInfo) - : config.getResetPasswordURL; - let createAndSendCustomEmail = config === undefined || config.createAndSendCustomEmail === undefined - ? passwordResetFunctions_1.createAndSendCustomEmail(appInfo) - : config.createAndSendCustomEmail; + return { + id: field.id, + validate: field.validate, + optional: false, + }; + }); + let getResetPasswordURL = + config === undefined || config.getResetPasswordURL === undefined + ? passwordResetFunctions_1.getResetPasswordURL(appInfo) + : config.getResetPasswordURL; + let createAndSendCustomEmail = + config === undefined || config.createAndSendCustomEmail === undefined + ? passwordResetFunctions_1.createAndSendCustomEmail(appInfo) + : config.createAndSendCustomEmail; return { formFieldsForPasswordResetForm, formFieldsForGenerateTokenForm, @@ -110,15 +178,18 @@ function validateAndNormaliseResetPasswordUsingTokenConfig(_, appInfo, signUpCon } 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); @@ -136,15 +207,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, @@ -215,7 +284,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 74cae3735..7532a974c 100644 --- a/lib/build/recipe/emailverification/api/emailVerify.js +++ b/lib/build/recipe/emailverification/api/emailVerify.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 error_1 = require("../error"); @@ -49,12 +71,10 @@ function emailVerify(apiImplementation, options) { let response = yield apiImplementation.verifyEmailPOST({ token, options, userContext: {} }); if (response.status === "OK") { result = { status: "OK" }; - } - else { + } else { result = response; } - } - else { + } else { if (apiImplementation.isEmailVerifiedGET === undefined) { return false; } 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 0d2b1145d..a2853f69d 100644 --- a/lib/build/recipe/emailverification/api/generateEmailVerifyToken.js +++ b/lib/build/recipe/emailverification/api/generateEmailVerifyToken.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 generateEmailVerifyToken(apiImplementation, options) { diff --git a/lib/build/recipe/emailverification/api/implementation.js b/lib/build/recipe/emailverification/api/implementation.js index a5a67a4db..4eb0f1d07 100644 --- a/lib/build/recipe/emailverification/api/implementation.js +++ b/lib/build/recipe/emailverification/api/implementation.js @@ -1,23 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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 session_1 = require("../../session"); function getAPIInterface() { return { - verifyEmailPOST: function ({ token, options, userContext, }) { + verifyEmailPOST: function ({ token, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { return yield options.recipeImplementation.verifyEmailUsingToken({ token, userContext }); }); }, - isEmailVerifiedGET: function ({ options, userContext, }) { + isEmailVerifiedGET: function ({ options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let session = yield session_1.default.getSession(options.req, options.res, userContext); if (session === undefined) { @@ -31,7 +53,7 @@ function getAPIInterface() { }; }); }, - generateEmailVerifyTokenPOST: function ({ options, userContext, }) { + generateEmailVerifyTokenPOST: function ({ options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let session = yield session_1.default.getSession(options.req, options.res, userContext); if (session === undefined) { @@ -47,7 +69,8 @@ function getAPIInterface() { if (response.status === "EMAIL_ALREADY_VERIFIED_ERROR") { return response; } - let emailVerifyLink = (yield options.config.getEmailVerificationURL({ id: userId, email }, userContext)) + + let emailVerifyLink = + (yield options.config.getEmailVerificationURL({ id: userId, email }, userContext)) + "?token=" + response.token + "&rid=" + @@ -56,14 +79,16 @@ function getAPIInterface() { if (!options.isInServerlessEnv) { options.config .createAndSendCustomEmail({ id: userId, email }, emailVerifyLink, userContext) - .catch((_) => { }); - } - else { + .catch((_) => {}); + } else { // see https://github.com/supertokens/supertokens-node/pull/135 - yield options.config.createAndSendCustomEmail({ id: userId, email }, emailVerifyLink, userContext); + yield options.config.createAndSendCustomEmail( + { id: userId, email }, + emailVerifyLink, + userContext + ); } - } - catch (_) { } + } catch (_) {} return { status: "OK", }; diff --git a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts index 9bcec8cce..bc6bd6cc7 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.d.ts @@ -1,4 +1,6 @@ import { User } from "./types"; import { NormalisedAppinfo } from "../../types"; export declare function getEmailVerificationURL(appInfo: NormalisedAppinfo): (_: User) => Promise; -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 d8916c6fb..5dda388f7 100644 --- a/lib/build/recipe/emailverification/emailVerificationFunctions.js +++ b/lib/build/recipe/emailverification/emailVerificationFunctions.js @@ -13,45 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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 getEmailVerificationURL(appInfo) { - return (_) => __awaiter(this, void 0, void 0, function* () { - return (appInfo.websiteDomain.getAsStringDangerous() + - appInfo.websiteBasePath.getAsStringDangerous() + - "/verify-email"); - }); + return (_) => + __awaiter(this, void 0, void 0, function* () { + return ( + appInfo.websiteDomain.getAsStringDangerous() + + appInfo.websiteBasePath.getAsStringDangerous() + + "/verify-email" + ); + }); } exports.getEmailVerificationURL = getEmailVerificationURL; 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, - }, - }); - } - catch (ignored) { } - }); + 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, + }, + }); + } catch (ignored) {} + }); } exports.createAndSendCustomEmail = createAndSendCustomEmail; 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/index.d.ts b/lib/build/recipe/emailverification/index.d.ts index 8a25c8acc..32b0d1313 100644 --- a/lib/build/recipe/emailverification/index.d.ts +++ b/lib/build/recipe/emailverification/index.d.ts @@ -4,23 +4,44 @@ import { RecipeInterface, APIOptions, APIInterface, User } from "./types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - 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: "OK"; }>; - static unverifyEmail(userId: string, email: string, userContext?: any): Promise<{ + static unverifyEmail( + userId: string, + email: string, + userContext?: any + ): Promise<{ status: "OK"; }>; } diff --git a/lib/build/recipe/emailverification/index.js b/lib/build/recipe/emailverification/index.js index 418f4d1b1..78adaa4b0 100644 --- a/lib/build/recipe/emailverification/index.js +++ b/lib/build/recipe/emailverification/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); diff --git a/lib/build/recipe/emailverification/recipe.d.ts b/lib/build/recipe/emailverification/recipe.d.ts index a2c0cd110..ec8314c02 100644 --- a/lib/build/recipe/emailverification/recipe.d.ts +++ b/lib/build/recipe/emailverification/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: 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 ceaf49a35..b51569ef0 100644 --- a/lib/build/recipe/emailverification/recipe.js +++ b/lib/build/recipe/emailverification/recipe.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 recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -42,7 +64,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, }, @@ -60,25 +84,26 @@ 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, - }; - 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, + }; + 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 []; }; @@ -88,7 +113,9 @@ class Recipe extends recipeModule_1.default { 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(); } { @@ -107,9 +134,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/emailverification/recipeImplementation.js b/lib/build/recipe/emailverification/recipeImplementation.js index f7ddb1ed8..a5baedfae 100644 --- a/lib/build/recipe/emailverification/recipeImplementation.js +++ b/lib/build/recipe/emailverification/recipeImplementation.js @@ -1,42 +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 }); 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", @@ -45,8 +72,7 @@ function getRecipeInterface(querier) { email: response.email, }, }; - } - else { + } else { return { status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR", }; @@ -55,19 +81,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 0ad72d3a9..922a0ef57 100644 --- a/lib/build/recipe/emailverification/types.d.ts +++ b/lib/build/recipe/emailverification/types.d.ts @@ -5,7 +5,10 @@ export declare type TypeInput = { getEmailVerificationURL?: (user: User, userContext: any) => Promise; 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; }; }; @@ -14,7 +17,10 @@ export declare type TypeNormalisedInput = { getEmailVerificationURL: (user: User, userContext: any) => Promise; 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; }; }; @@ -27,26 +33,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; @@ -71,27 +79,36 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - verifyEmailPOST: undefined | ((input: { - token: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - } | { - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - }>); - isEmailVerifiedGET: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - isVerified: boolean; - }>); - generateEmailVerifyTokenPOST: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; - }>); + verifyEmailPOST: + | undefined + | ((input: { + token: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + } + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + >); + isEmailVerifiedGET: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + isVerified: boolean; + }>); + generateEmailVerifyTokenPOST: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "EMAIL_ALREADY_VERIFIED_ERROR" | "OK"; + }>); }; diff --git a/lib/build/recipe/emailverification/utils.d.ts b/lib/build/recipe/emailverification/utils.d.ts index 24dd27270..1219cbcbc 100644 --- a/lib/build/recipe/emailverification/utils.d.ts +++ b/lib/build/recipe/emailverification/utils.d.ts @@ -1,4 +1,8 @@ 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; diff --git a/lib/build/recipe/emailverification/utils.js b/lib/build/recipe/emailverification/utils.js index f9c0df54b..11ebbfd7a 100644 --- a/lib/build/recipe/emailverification/utils.js +++ b/lib/build/recipe/emailverification/utils.js @@ -16,14 +16,22 @@ Object.defineProperty(exports, "__esModule", { value: true }); const emailVerificationFunctions_1 = require("./emailVerificationFunctions"); function validateAndNormaliseUserInput(_, appInfo, config) { - let getEmailVerificationURL = config.getEmailVerificationURL === undefined - ? emailVerificationFunctions_1.getEmailVerificationURL(appInfo) - : config.getEmailVerificationURL; - let createAndSendCustomEmail = config.createAndSendCustomEmail === undefined - ? emailVerificationFunctions_1.createAndSendCustomEmail(appInfo) - : config.createAndSendCustomEmail; + let getEmailVerificationURL = + config.getEmailVerificationURL === undefined + ? emailVerificationFunctions_1.getEmailVerificationURL(appInfo) + : config.getEmailVerificationURL; + let createAndSendCustomEmail = + config.createAndSendCustomEmail === undefined + ? emailVerificationFunctions_1.createAndSendCustomEmail(appInfo) + : config.createAndSendCustomEmail; let getEmailForUserId = config.getEmailForUserId; - 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 { getEmailForUserId, getEmailVerificationURL, diff --git a/lib/build/recipe/jwt/api/getJWKS.js b/lib/build/recipe/jwt/api/getJWKS.js index eb20bbe2f..3cc065852 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"); function getJWKS(apiImplementation, options) { 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 0a1dc6b3b..3d04b204d 100644 --- a/lib/build/recipe/jwt/index.js +++ b/lib/build/recipe/jwt/index.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 recipe_1 = require("./recipe"); class Wrapper { diff --git a/lib/build/recipe/jwt/recipe.d.ts b/lib/build/recipe/jwt/recipe.d.ts index 64c3eec96..1c3cd5664 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 4a4b60a8d..4e472d87b 100644 --- a/lib/build/recipe/jwt/recipe.js +++ b/lib/build/recipe/jwt/recipe.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 error_1 = require("../../error"); const normalisedURLPath_1 = require("../../normalisedURLPath"); @@ -36,21 +58,28 @@ 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(); } { @@ -70,8 +99,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 f81d1c0b2..8e7cb7bb3 100644 --- a/lib/build/recipe/jwt/recipeImplementation.js +++ b/lib/build/recipe/jwt/recipeImplementation.js @@ -13,20 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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) @@ -43,8 +65,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 f1bf9744e..e4f292890 100644 --- a/lib/build/recipe/jwt/types.d.ts +++ b/lib/build/recipe/jwt/types.d.ts @@ -11,14 +11,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; }; }; @@ -35,12 +41,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<{ @@ -49,11 +58,13 @@ export declare type RecipeInterface = { }>; }; export declare type APIInterface = { - getJWKSGET: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - keys: JsonWebKey[]; - }>); + getJWKSGET: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + keys: JsonWebKey[]; + }>); }; 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 8e9ae1108..f09ea36a2 100644 --- a/lib/build/recipe/jwt/utils.js +++ b/lib/build/recipe/jwt/utils.js @@ -16,9 +16,18 @@ Object.defineProperty(exports, "__esModule", { value: true }); 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 be42a3c92..f99e266f2 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. * 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/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 658647a53..e7463fb80 100644 --- a/lib/build/recipe/openid/recipe.js +++ b/lib/build/recipe/openid/recipe.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. * @@ -47,42 +69,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(); @@ -98,8 +124,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 8b8b68384..d673f5973 100644 --- a/lib/build/recipe/openid/recipeImplementation.js +++ b/lib/build/recipe/openid/recipeImplementation.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 normalisedURLPath_1 = require("../../normalisedURLPath"); const constants_1 = require("../jwt/constants"); @@ -16,8 +38,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, @@ -25,7 +50,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 3514fd456..b80a59079 100644 --- a/lib/build/recipe/openid/types.d.ts +++ b/lib/build/recipe/openid/types.d.ts @@ -7,11 +7,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; }; }; }; @@ -20,11 +29,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; }; }; }; @@ -36,14 +54,16 @@ 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; - }>); + getOpenIdDiscoveryConfigurationGET: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + issuer: string; + jwks_uri: string; + }>); }; export declare type RecipeInterface = { getOpenIdDiscoveryConfiguration(input: { @@ -57,12 +77,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 38125abca..394ba1783 100644 --- a/lib/build/recipe/openid/utils.js +++ b/lib/build/recipe/openid/utils.js @@ -28,7 +28,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 3362ed94e..a157ade17 100644 --- a/lib/build/recipe/passwordless/api/consumeCode.js +++ b/lib/build/recipe/passwordless/api/consumeCode.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 error_1 = require("../error"); @@ -54,21 +76,22 @@ 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", }); } - 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 9550739da..183ccf444 100644 --- a/lib/build/recipe/passwordless/api/createCode.js +++ b/lib/build/recipe/passwordless/api/createCode.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 error_1 = require("../error"); @@ -53,8 +75,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) { @@ -65,8 +89,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, { @@ -80,14 +106,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: {} } - : { phoneNumber: phoneNumber, options, userContext: {} }); + let result = yield apiImplementation.createCodePOST( + email !== undefined + ? { email, options, userContext: {} } + : { phoneNumber: phoneNumber, options, userContext: {} } + ); 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 73457cb97..2c824d60a 100644 --- a/lib/build/recipe/passwordless/api/emailExists.js +++ b/lib/build/recipe/passwordless/api/emailExists.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 error_1 = require("../error"); diff --git a/lib/build/recipe/passwordless/api/implementation.js b/lib/build/recipe/passwordless/api/implementation.js index d086c608f..53973957e 100644 --- a/lib/build/recipe/passwordless/api/implementation.js +++ b/lib/build/recipe/passwordless/api/implementation.js @@ -1,36 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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 session_1 = require("../../session"); 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; } let user = response.user; - const session = yield session_1.default.createNewSession(input.options.res, user.id, {}, {}, input.userContext); + const session = yield session_1.default.createNewSession( + input.options.res, + user.id, + {}, + {}, + input.userContext + ); return { status: "OK", createdNewUser: response.createdNewUser, @@ -41,40 +71,47 @@ 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; const flowType = input.options.config.flowType; if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = - (yield input.options.config.getLinkDomainAndPath("phoneNumber" in input - ? { - phoneNumber: input.phoneNumber, - } - : { - email: input.email, - }, input.userContext)) + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + (yield input.options.config.getLinkDomainAndPath( + "phoneNumber" in input + ? { + phoneNumber: input.phoneNumber, + } + : { + email: input.email, + }, + input.userContext + )) + + "?rid=" + + input.options.recipeId + + "&preAuthSessionId=" + + response.preAuthSessionId + + "#" + + response.linkCode; } if (flowType === "USER_INPUT_CODE" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { userInputCode = response.userInputCode; @@ -83,27 +120,33 @@ 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)) { - yield input.options.config.createAndSendCustomTextMessage({ - codeLifetime: response.codeLifetime, - phoneNumber: input.phoneNumber, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, input.userContext); - } - else { - yield input.options.config.createAndSendCustomEmail({ - codeLifetime: response.codeLifetime, - email: input.email, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, input.userContext); + if ( + input.options.config.contactMethod === "PHONE" || + (input.options.config.contactMethod === "EMAIL_OR_PHONE" && "phoneNumber" in input) + ) { + yield input.options.config.createAndSendCustomTextMessage( + { + codeLifetime: response.codeLifetime, + phoneNumber: input.phoneNumber, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, + input.userContext + ); + } else { + yield input.options.config.createAndSendCustomEmail( + { + codeLifetime: response.codeLifetime, + email: input.email, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, + input.userContext + ); } - } - catch (err) { + } catch (err) { return { status: "GENERAL_ERROR", message: err.message, @@ -152,8 +195,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", }; @@ -164,9 +209,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) { @@ -184,19 +230,22 @@ function getAPIImplementation() { const flowType = input.options.config.flowType; if (flowType === "MAGIC_LINK" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { magicLink = - (yield input.options.config.getLinkDomainAndPath(deviceInfo.email === undefined - ? { - phoneNumber: deviceInfo.phoneNumber, - } - : { - email: deviceInfo.email, - }, input.userContext)) + - "?rid=" + - input.options.recipeId + - "&preAuthSessionId=" + - response.preAuthSessionId + - "#" + - response.linkCode; + (yield input.options.config.getLinkDomainAndPath( + deviceInfo.email === undefined + ? { + phoneNumber: deviceInfo.phoneNumber, + } + : { + email: deviceInfo.email, + }, + input.userContext + )) + + "?rid=" + + input.options.recipeId + + "&preAuthSessionId=" + + response.preAuthSessionId + + "#" + + response.linkCode; } if (flowType === "USER_INPUT_CODE" || flowType === "USER_INPUT_CODE_AND_MAGIC_LINK") { userInputCode = response.userInputCode; @@ -205,28 +254,34 @@ 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)) { - yield input.options.config.createAndSendCustomTextMessage({ - codeLifetime: response.codeLifetime, - phoneNumber: deviceInfo.phoneNumber, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, input.userContext); - } - else { - yield input.options.config.createAndSendCustomEmail({ - codeLifetime: response.codeLifetime, - email: deviceInfo.email, - preAuthSessionId: response.preAuthSessionId, - urlWithLinkCode: magicLink, - userInputCode, - }, input.userContext); + deviceInfo.phoneNumber !== undefined) + ) { + yield input.options.config.createAndSendCustomTextMessage( + { + codeLifetime: response.codeLifetime, + phoneNumber: deviceInfo.phoneNumber, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, + input.userContext + ); + } else { + yield input.options.config.createAndSendCustomEmail( + { + codeLifetime: response.codeLifetime, + email: deviceInfo.email, + preAuthSessionId: response.preAuthSessionId, + urlWithLinkCode: magicLink, + userInputCode, + }, + input.userContext + ); } - } - catch (err) { + } catch (err) { return { status: "GENERAL_ERROR", message: err.message, diff --git a/lib/build/recipe/passwordless/api/phoneNumberExists.js b/lib/build/recipe/passwordless/api/phoneNumberExists.js index 763cc9c0c..1c5dedf79 100644 --- a/lib/build/recipe/passwordless/api/phoneNumberExists.js +++ b/lib/build/recipe/passwordless/api/phoneNumberExists.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 error_1 = require("../error"); diff --git a/lib/build/recipe/passwordless/api/resendCode.js b/lib/build/recipe/passwordless/api/resendCode.js index 7aa92c61f..78d4e5277 100644 --- a/lib/build/recipe/passwordless/api/resendCode.js +++ b/lib/build/recipe/passwordless/api/resendCode.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 error_1 = require("../error"); 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/index.d.ts b/lib/build/recipe/passwordless/index.d.ts index 05993a795..7796a61cd 100644 --- a/lib/build/recipe/passwordless/index.d.ts +++ b/lib/build/recipe/passwordless/index.d.ts @@ -4,14 +4,19 @@ import { RecipeInterface, User, APIOptions, APIInterface } 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 +30,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 +84,17 @@ 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: { @@ -92,10 +103,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,20 +116,28 @@ 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; diff --git a/lib/build/recipe/passwordless/index.js b/lib/build/recipe/passwordless/index.js index 60c222b03..8bda0ad5a 100644 --- a/lib/build/recipe/passwordless/index.js +++ b/lib/build/recipe/passwordless/index.js @@ -18,43 +18,69 @@ 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)); diff --git a/lib/build/recipe/passwordless/recipe.d.ts b/lib/build/recipe/passwordless/recipe.d.ts index e9e320f5a..918518665 100644 --- a/lib/build/recipe/passwordless/recipe.d.ts +++ b/lib/build/recipe/passwordless/recipe.d.ts @@ -16,24 +16,38 @@ 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: 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 5f372b16f..867c6aba1 100644 --- a/lib/build/recipe/passwordless/recipe.js +++ b/lib/build/recipe/passwordless/recipe.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 recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -75,34 +97,32 @@ 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, - }; - 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, + }; + 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 []; }; @@ -110,73 +130,87 @@ 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, - }); - let magicLink = (yield this.config.getLinkDomainAndPath("phoneNumber" in input - ? { - phoneNumber: input.phoneNumber, - } - : { - email: input.email, - }, input.userContext)) + - "?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, + 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, + } + ); + let magicLink = + (yield this.config.getLinkDomainAndPath( + "phoneNumber" in input + ? { + phoneNumber: input.phoneNumber, + } + : { + email: input.email, + }, + input.userContext + )) + + "?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"); } - : { - 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.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(); } { @@ -195,8 +229,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("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 48085373e..dc0d87d31 100644 --- a/lib/build/recipe/passwordless/recipeImplementation.js +++ b/lib/build/recipe/passwordless/recipeImplementation.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 normalisedURLPath_1 = require("../../normalisedURLPath"); function getRecipeInterface(querier) { @@ -19,25 +41,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; } @@ -46,7 +80,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; } @@ -55,7 +92,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; } @@ -64,31 +104,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", }; @@ -96,13 +151,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/types.d.ts b/lib/build/recipe/passwordless/types.d.ts index 9f012bcd9..e4bc0d4ea 100644 --- a/lib/build/recipe/passwordless/types.d.ts +++ b/lib/build/recipe/passwordless/types.d.ts @@ -7,117 +7,170 @@ export declare type User = { phoneNumber?: string; timeJoined: number; }; -export declare type TypeInput = ({ - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - 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; + createAndSendCustomTextMessage: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + 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"; - getLinkDomainAndPath?: (contactInfo: { - email: string; - } | { - phoneNumber: string; - }, userContext: any) => Promise | string; + getLinkDomainAndPath?: ( + contactInfo: + | { + email: string; + } + | { + phoneNumber: string; + }, + userContext: any + ) => Promise | string; 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; - createAndSendCustomTextMessage: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL"; - validateEmailAddress: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -}) & { +export declare type TypeNormalisedInput = ( + | { + contactMethod: "PHONE"; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; + createAndSendCustomTextMessage: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + validatePhoneNumber: (phoneNumber: string) => Promise | string | undefined; + 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"; - getLinkDomainAndPath: (contactInfo: { - email: string; - } | { - phoneNumber: string; - }, userContext: any) => Promise | string; + getLinkDomainAndPath: ( + contactInfo: + | { + email: string; + } + | { + phoneNumber: string; + }, + userContext: any + ) => Promise | string; 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 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; @@ -131,50 +184,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; @@ -183,13 +238,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: { @@ -198,18 +257,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; @@ -235,59 +285,82 @@ export declare type APIOptions = { res: BaseResponse; }; 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"; - } | { - status: "GENERAL_ERROR"; - message: string; - }>; - resendCodePOST?: (input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "GENERAL_ERROR"; - message: string; - } | { - 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; - user: User; - session: SessionContainerInterface; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | { - status: "GENERAL_ERROR"; - message: string; - } | { - status: "RESTART_FLOW_ERROR"; - }>; + 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"; + } + | { + status: "GENERAL_ERROR"; + message: string; + } + >; + resendCodePOST?: ( + input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: APIOptions; + userContext: any; + } + ) => Promise< + | { + status: "GENERAL_ERROR"; + message: string; + } + | { + 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; + user: User; + session: SessionContainerInterface; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | { + status: "GENERAL_ERROR"; + message: string; + } + | { + status: "RESTART_FLOW_ERROR"; + } + >; emailExistsGET?: (input: { email: string; options: APIOptions; diff --git a/lib/build/recipe/passwordless/utils.d.ts b/lib/build/recipe/passwordless/utils.d.ts index 24dd27270..1219cbcbc 100644 --- a/lib/build/recipe/passwordless/utils.d.ts +++ b/lib/build/recipe/passwordless/utils.d.ts @@ -1,4 +1,8 @@ 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; diff --git a/lib/build/recipe/passwordless/utils.js b/lib/build/recipe/passwordless/utils.js index f7d8978f7..740228ab9 100644 --- a/lib/build/recipe/passwordless/utils.js +++ b/lib/build/recipe/passwordless/utils.js @@ -13,27 +13,57 @@ * 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 max_1 = require("libphonenumber-js/max"); 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 + ); if (config.contactMethod === "EMAIL") { if (config.createAndSendCustomEmail === undefined) { throw new Error("Please provide a callback function (createAndSendCustomEmail) to send emails. "); @@ -42,61 +72,73 @@ function validateAndNormaliseUserInput(_, appInfo, config) { override, flowType: config.flowType, contactMethod: "EMAIL", - createAndSendCustomEmail: - // until we add a service to send emails, config.createAndSendCustomEmail will never be undefined - config.createAndSendCustomEmail === undefined - ? defaultCreateAndSendCustomEmail - : config.createAndSendCustomEmail, - getLinkDomainAndPath: config.getLinkDomainAndPath === undefined - ? getDefaultGetLinkDomainAndPath(appInfo) - : config.getLinkDomainAndPath, - validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + createAndSendCustomEmail: + // until we add a service to send emails, config.createAndSendCustomEmail will never be undefined + config.createAndSendCustomEmail === undefined + ? defaultCreateAndSendCustomEmail + : config.createAndSendCustomEmail, + getLinkDomainAndPath: + config.getLinkDomainAndPath === undefined + ? getDefaultGetLinkDomainAndPath(appInfo) + : config.getLinkDomainAndPath, + validateEmailAddress: + config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, getCustomUserInputCode: config.getCustomUserInputCode, }; - } - else if (config.contactMethod === "PHONE") { + } else if (config.contactMethod === "PHONE") { if (config.createAndSendCustomTextMessage === undefined) { - throw new Error("Please provide a callback function (createAndSendCustomTextMessage) to send text messages. "); + throw new Error( + "Please provide a callback function (createAndSendCustomTextMessage) to send text messages. " + ); } return { override, flowType: config.flowType, contactMethod: "PHONE", // until we add a service to send sms, config.createAndSendCustomTextMessage will never be undefined - createAndSendCustomTextMessage: config.createAndSendCustomTextMessage === undefined - ? defaultCreateAndSendTextMessage - : config.createAndSendCustomTextMessage, - getLinkDomainAndPath: config.getLinkDomainAndPath === undefined - ? getDefaultGetLinkDomainAndPath(appInfo) - : config.getLinkDomainAndPath, - validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + createAndSendCustomTextMessage: + config.createAndSendCustomTextMessage === undefined + ? defaultCreateAndSendTextMessage + : config.createAndSendCustomTextMessage, + getLinkDomainAndPath: + config.getLinkDomainAndPath === undefined + ? getDefaultGetLinkDomainAndPath(appInfo) + : config.getLinkDomainAndPath, + validatePhoneNumber: + config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; - } - else { + } else { if (config.createAndSendCustomEmail === undefined) { throw new Error("Please provide a callback function (createAndSendCustomEmail) to send emails. "); } if (config.createAndSendCustomTextMessage === undefined) { - throw new Error("Please provide a callback function (createAndSendCustomTextMessage) to send text messages. "); + throw new Error( + "Please provide a callback function (createAndSendCustomTextMessage) to send text messages. " + ); } return { override, flowType: config.flowType, contactMethod: "EMAIL_OR_PHONE", // until we add a service to send email, config.createAndSendCustomEmail will never be undefined - createAndSendCustomEmail: config.createAndSendCustomEmail === undefined - ? defaultCreateAndSendCustomEmail - : config.createAndSendCustomEmail, - validateEmailAddress: config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, + createAndSendCustomEmail: + config.createAndSendCustomEmail === undefined + ? defaultCreateAndSendCustomEmail + : config.createAndSendCustomEmail, + validateEmailAddress: + config.validateEmailAddress === undefined ? defaultValidateEmail : config.validateEmailAddress, // until we add a service to send sms, config.createAndSendCustomTextMessage will never be undefined - createAndSendCustomTextMessage: config.createAndSendCustomTextMessage === undefined - ? defaultCreateAndSendTextMessage - : config.createAndSendCustomTextMessage, - getLinkDomainAndPath: config.getLinkDomainAndPath === undefined - ? getDefaultGetLinkDomainAndPath(appInfo) - : config.getLinkDomainAndPath, - validatePhoneNumber: config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, + createAndSendCustomTextMessage: + config.createAndSendCustomTextMessage === undefined + ? defaultCreateAndSendTextMessage + : config.createAndSendCustomTextMessage, + getLinkDomainAndPath: + config.getLinkDomainAndPath === undefined + ? getDefaultGetLinkDomainAndPath(appInfo) + : config.getLinkDomainAndPath, + validatePhoneNumber: + config.validatePhoneNumber === undefined ? defaultValidatePhoneNumber : config.validatePhoneNumber, getCustomUserInputCode: config.getCustomUserInputCode, }; } @@ -104,7 +146,9 @@ function validateAndNormaliseUserInput(_, appInfo, config) { exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function getDefaultGetLinkDomainAndPath(appInfo) { return (_, __) => { - return (appInfo.websiteDomain.getAsStringDangerous() + appInfo.websiteBasePath.getAsStringDangerous() + "/verify"); + return ( + appInfo.websiteDomain.getAsStringDangerous() + appInfo.websiteBasePath.getAsStringDangerous() + "/verify" + ); }; } function defaultValidatePhoneNumber(value) { @@ -135,7 +179,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 cd85c6cd8..3aa8315e6 100644 --- a/lib/build/recipe/session/accessToken.d.ts +++ b/lib/build/recipe/session/accessToken.d.ts @@ -1,4 +1,8 @@ -export declare function getInfoFromAccessToken(token: string, jwtSigningPublicKey: string, doAntiCsrfCheck: boolean): Promise<{ +export declare function getInfoFromAccessToken( + token: string, + jwtSigningPublicKey: string, + doAntiCsrfCheck: boolean +): Promise<{ sessionHandle: string; userId: string; refreshTokenHash1: string; diff --git a/lib/build/recipe/session/accessToken.js b/lib/build/recipe/session/accessToken.js index 9ec26e92f..1a4bbe5c4 100644 --- a/lib/build/recipe/session/accessToken.js +++ b/lib/build/recipe/session/accessToken.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 error_1 = require("./error"); const jwt_1 = require("./jwt"); @@ -37,13 +59,15 @@ function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { let antiCsrfToken = sanitizeStringInput(payload.antiCsrfToken); let expiryTime = sanitizeNumberInput(payload.expiryTime); let timeCreated = sanitizeNumberInput(payload.timeCreated); - if (sessionHandle === undefined || + if ( + sessionHandle === undefined || userId === undefined || refreshTokenHash1 === undefined || userData === undefined || (antiCsrfToken === undefined && doAntiCsrfCheck) || expiryTime === undefined || - timeCreated === 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?"); } @@ -60,8 +84,7 @@ function getInfoFromAccessToken(token, jwtSigningPublicKey, doAntiCsrfCheck) { expiryTime, timeCreated, }; - } - catch (err) { + } catch (err) { throw new error_1.default({ message: "Failed to verify access token", type: error_1.default.TRY_REFRESH_TOKEN, @@ -80,8 +103,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 f9dfa8c34..76a565246 100644 --- a/lib/build/recipe/session/api/implementation.js +++ b/lib/build/recipe/session/api/implementation.js @@ -1,25 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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"); const normalisedURLPath_1 = require("../../../normalisedURLPath"); function getAPIInterface() { return { - refreshPOST: function ({ options, userContext, }) { + refreshPOST: function ({ options, userContext }) { return __awaiter(this, void 0, void 0, function* () { yield options.recipeImplementation.refreshSession({ req: options.req, res: options.res, userContext }); }); }, - 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") { @@ -33,8 +55,7 @@ function getAPIInterface() { res: options.res, userContext, }); - } - else { + } else { return yield options.recipeImplementation.getSession({ req: options.req, res: options.res, @@ -44,7 +65,7 @@ function getAPIInterface() { } }); }, - signOutPOST: function ({ options, userContext, }) { + signOutPOST: function ({ options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let session; try { @@ -53,8 +74,7 @@ function getAPIInterface() { res: options.res, userContext, }); - } - catch (err) { + } catch (err) { if (error_1.default.isErrorFromSuperTokens(err) && err.type === error_1.default.UNAUTHORISED) { // The session is expired / does not exist anyway. So we return OK return { diff --git a/lib/build/recipe/session/api/refresh.js b/lib/build/recipe/session/api/refresh.js index 4e3e18fd8..58bc46079 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"); function handleRefreshAPI(apiImplementation, options) { diff --git a/lib/build/recipe/session/api/signout.js b/lib/build/recipe/session/api/signout.js index fba8ac7cf..4f4971a94 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"); function signOutAPI(apiImplementation, options) { diff --git a/lib/build/recipe/session/cookieAndHeaders.d.ts b/lib/build/recipe/session/cookieAndHeaders.d.ts index e2aae3665..5101ab168 100644 --- a/lib/build/recipe/session/cookieAndHeaders.d.ts +++ b/lib/build/recipe/session/cookieAndHeaders.d.ts @@ -7,19 +7,39 @@ export declare function clearSessionFromCookie(config: TypeNormalisedInput, res: /** * @param expiry: must be time in milliseconds from epoch time. */ -export declare function attachAccessTokenToCookie(config: TypeNormalisedInput, res: BaseResponse, token: string, expiry: number): void; +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 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; 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 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 getCORSAllowedHeaders(): string[]; /** * @@ -32,4 +52,11 @@ 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; diff --git a/lib/build/recipe/session/cookieAndHeaders.js b/lib/build/recipe/session/cookieAndHeaders.js index c1cf8a933..b279b35b2 100644 --- a/lib/build/recipe/session/cookieAndHeaders.js +++ b/lib/build/recipe/session/cookieAndHeaders.js @@ -96,8 +96,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 2ca39f81b..6bb2fe866 100644 --- a/lib/build/recipe/session/error.d.ts +++ b/lib/build/recipe/session/error.d.ts @@ -3,21 +3,26 @@ export default class SessionError extends STError { static UNAUTHORISED: "UNAUTHORISED"; static TRY_REFRESH_TOKEN: "TRY_REFRESH_TOKEN"; static TOKEN_THEFT_DETECTED: "TOKEN_THEFT_DETECTED"; - constructor(options: { - message: string; - type: "UNAUTHORISED"; - payload?: { - clearCookies: boolean; - }; - } | { - message: string; - type: "TRY_REFRESH_TOKEN"; - } | { - message: string; - type: "TOKEN_THEFT_DETECTED"; - payload: { - userId: string; - sessionHandle: string; - }; - }); + constructor( + options: + | { + message: string; + type: "UNAUTHORISED"; + payload?: { + clearCookies: boolean; + }; + } + | { + message: string; + type: "TRY_REFRESH_TOKEN"; + } + | { + message: string; + type: "TOKEN_THEFT_DETECTED"; + payload: { + userId: string; + sessionHandle: string; + }; + } + ); } diff --git a/lib/build/recipe/session/error.js b/lib/build/recipe/session/error.js index 6fd4ea846..244ea77d9 100644 --- a/lib/build/recipe/session/error.js +++ b/lib/build/recipe/session/error.js @@ -17,10 +17,15 @@ 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: { + clearCookies: true, + }, + }) + : Object.assign({}, options) + ); this.fromRecipe = "session"; } } diff --git a/lib/build/recipe/session/faunadb/recipeImplementation.d.ts b/lib/build/recipe/session/faunadb/recipeImplementation.d.ts index 2e0c72f18..e09f182b7 100644 --- a/lib/build/recipe/session/faunadb/recipeImplementation.d.ts +++ b/lib/build/recipe/session/faunadb/recipeImplementation.d.ts @@ -11,69 +11,138 @@ export default class RecipeImplementation implements RecipeInterface { }; q: typeof faunadb.query; originalImplementation: RecipeInterface; - constructor(originalImplementation: RecipeInterface, config: { - accessFaunadbTokenFromFrontend?: boolean; - userCollectionName: string; - faunaDBClient: faunadb.Client; - }); + constructor( + originalImplementation: RecipeInterface, + config: { + accessFaunadbTokenFromFrontend?: boolean; + userCollectionName: string; + faunaDBClient: faunadb.Client; + } + ); getFDAT: (userId: string, userContext: any) => Promise; - createNewSession: (this: RecipeImplementation, { res, userId, accessTokenPayload, sessionData, userContext, }: { - res: BaseResponse; - userId: string; - accessTokenPayload?: any; - sessionData?: any; - userContext: any; - }) => Promise; - getSession: (this: RecipeImplementation, { req, res, options, userContext, }: { - req: BaseRequest; - res: BaseResponse; - options?: VerifySessionOptions | undefined; - userContext: any; - }) => Promise; - getSessionInformation: (this: RecipeImplementation, { sessionHandle, userContext }: { - sessionHandle: string; - userContext: any; - }) => Promise; - refreshSession: (this: RecipeImplementation, { req, res, userContext, }: { - req: BaseRequest; - res: BaseResponse; - userContext: any; - }) => Promise; - revokeAllSessionsForUser: (this: RecipeImplementation, { userId, userContext }: { - userId: string; - userContext: any; - }) => Promise; - getAllSessionHandlesForUser: (this: RecipeImplementation, { userId, userContext }: { - userId: string; - userContext: any; - }) => Promise; - revokeSession: (this: RecipeImplementation, { sessionHandle, userContext }: { - sessionHandle: string; - userContext: any; - }) => Promise; - revokeMultipleSessions: (this: RecipeImplementation, { sessionHandles, userContext }: { - sessionHandles: string[]; - userContext: any; - }) => Promise; - updateSessionData: (this: RecipeImplementation, { sessionHandle, newSessionData, userContext }: { - sessionHandle: string; - newSessionData: any; - userContext: any; - }) => Promise; - updateAccessTokenPayload: (this: RecipeImplementation, input: { - sessionHandle: string; - newAccessTokenPayload: any; - userContext: any; - }) => Promise; - regenerateAccessToken: (input: { - accessToken: string; - newAccessTokenPayload?: any; - userContext: any; - }) => any; - getAccessTokenLifeTimeMS: (this: RecipeImplementation, input: { - userContext: any; - }) => Promise; - getRefreshTokenLifeTimeMS: (this: RecipeImplementation, input: { - userContext: any; - }) => Promise; + createNewSession: ( + this: RecipeImplementation, + { + res, + userId, + accessTokenPayload, + sessionData, + userContext, + }: { + res: BaseResponse; + userId: string; + accessTokenPayload?: any; + sessionData?: any; + userContext: any; + } + ) => Promise; + getSession: ( + this: RecipeImplementation, + { + req, + res, + options, + userContext, + }: { + req: BaseRequest; + res: BaseResponse; + options?: VerifySessionOptions | undefined; + userContext: any; + } + ) => Promise; + getSessionInformation: ( + this: RecipeImplementation, + { + sessionHandle, + userContext, + }: { + sessionHandle: string; + userContext: any; + } + ) => Promise; + refreshSession: ( + this: RecipeImplementation, + { + req, + res, + userContext, + }: { + req: BaseRequest; + res: BaseResponse; + userContext: any; + } + ) => Promise; + revokeAllSessionsForUser: ( + this: RecipeImplementation, + { + userId, + userContext, + }: { + userId: string; + userContext: any; + } + ) => Promise; + getAllSessionHandlesForUser: ( + this: RecipeImplementation, + { + userId, + userContext, + }: { + userId: string; + userContext: any; + } + ) => Promise; + revokeSession: ( + this: RecipeImplementation, + { + sessionHandle, + userContext, + }: { + sessionHandle: string; + userContext: any; + } + ) => Promise; + revokeMultipleSessions: ( + this: RecipeImplementation, + { + sessionHandles, + userContext, + }: { + sessionHandles: string[]; + userContext: any; + } + ) => Promise; + updateSessionData: ( + this: RecipeImplementation, + { + sessionHandle, + newSessionData, + userContext, + }: { + sessionHandle: string; + newSessionData: any; + userContext: any; + } + ) => Promise; + updateAccessTokenPayload: ( + this: RecipeImplementation, + input: { + sessionHandle: string; + newAccessTokenPayload: any; + userContext: any; + } + ) => Promise; + regenerateAccessToken: (input: { accessToken: string; newAccessTokenPayload?: any; userContext: any }) => any; + getAccessTokenLifeTimeMS: ( + this: RecipeImplementation, + input: { + userContext: any; + } + ) => Promise; + getRefreshTokenLifeTimeMS: ( + this: RecipeImplementation, + input: { + userContext: any; + } + ) => Promise; } diff --git a/lib/build/recipe/session/faunadb/recipeImplementation.js b/lib/build/recipe/session/faunadb/recipeImplementation.js index 4427bf385..0cf335f0c 100644 --- a/lib/build/recipe/session/faunadb/recipeImplementation.js +++ b/lib/build/recipe/session/faunadb/recipeImplementation.js @@ -1,55 +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 faunadb = require("faunadb"); const constants_1 = require("./constants"); class RecipeImplementation { constructor(originalImplementation, config) { this.q = faunadb.query; - this.getFDAT = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - function getFaunadbTokenTimeLag() { - if (process.env.INSTALL_PATH !== undefined) { - // if in testing... - return 2 * 1000; + this.getFDAT = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + function getFaunadbTokenTimeLag() { + if (process.env.INSTALL_PATH !== undefined) { + // if in testing... + return 2 * 1000; + } + return constants_1.FAUNADB_TOKEN_TIME_LAG_MILLI; } - return constants_1.FAUNADB_TOKEN_TIME_LAG_MILLI; - } - let accessTokenLifetime = yield this.originalImplementation.getAccessTokenLifeTimeMS({ userContext }); - let faunaResponse = yield this.config.faunaDBClient.query(this.q.Create(this.q.Tokens(), { - instance: this.q.Ref(this.q.Collection(this.config.userCollectionName), userId), - ttl: this.q.TimeAdd(this.q.Now(), accessTokenLifetime + getFaunadbTokenTimeLag(), "millisecond"), - })); - return faunaResponse.secret; - }); - this.createNewSession = function ({ res, userId, accessTokenPayload = {}, sessionData = {}, userContext, }) { + let accessTokenLifetime = yield this.originalImplementation.getAccessTokenLifeTimeMS({ userContext }); + let faunaResponse = yield this.config.faunaDBClient.query( + this.q.Create(this.q.Tokens(), { + instance: this.q.Ref(this.q.Collection(this.config.userCollectionName), userId), + ttl: this.q.TimeAdd( + this.q.Now(), + accessTokenLifetime + getFaunadbTokenTimeLag(), + "millisecond" + ), + }) + ); + return faunaResponse.secret; + }); + this.createNewSession = function ({ res, userId, accessTokenPayload = {}, sessionData = {}, userContext }) { return __awaiter(this, void 0, void 0, function* () { let fdat = yield this.getFDAT(userId, userContext); if (this.config.accessFaunadbTokenFromFrontend) { accessTokenPayload = Object.assign({}, accessTokenPayload); accessTokenPayload[constants_1.FAUNADB_SESSION_KEY] = fdat; - } - else { + } else { sessionData = Object.assign({}, sessionData); sessionData[constants_1.FAUNADB_SESSION_KEY] = fdat; } - return getModifiedSession(yield this.originalImplementation.createNewSession({ - res, - userId, - accessTokenPayload, - sessionData, - userContext, - })); + return getModifiedSession( + yield this.originalImplementation.createNewSession({ + res, + userId, + accessTokenPayload, + sessionData, + userContext, + }) + ); }); }; - this.getSession = function ({ req, res, options, userContext, }) { + this.getSession = function ({ req, res, options, userContext }) { return __awaiter(this, void 0, void 0, function* () { let originalSession = yield this.originalImplementation.getSession({ req, res, options, userContext }); if (originalSession === undefined) { @@ -61,7 +91,7 @@ class RecipeImplementation { this.getSessionInformation = function ({ sessionHandle, userContext }) { return this.originalImplementation.getSessionInformation({ sessionHandle, userContext }); }; - this.refreshSession = function ({ req, res, userContext, }) { + this.refreshSession = function ({ req, res, userContext }) { return __awaiter(this, void 0, void 0, function* () { let originalSession = yield this.originalImplementation.refreshSession({ req, res, userContext }); let session = getModifiedSession(originalSession); @@ -72,9 +102,8 @@ class RecipeImplementation { let newPayload = Object.assign({}, session.getAccessTokenPayload()); newPayload[constants_1.FAUNADB_SESSION_KEY] = fdat; yield session.updateAccessTokenPayload(newPayload); - } - else { - let newPayload = Object.assign({}, (yield session.getSessionData())); + } else { + let newPayload = Object.assign({}, yield session.getSessionData()); newPayload[constants_1.FAUNADB_SESSION_KEY] = fdat; yield session.updateSessionData(newPayload); } @@ -114,7 +143,8 @@ class RecipeImplementation { }; this.originalImplementation = originalImplementation; this.config = { - accessFaunadbTokenFromFrontend: config.accessFaunadbTokenFromFrontend === undefined ? false : config.accessFaunadbTokenFromFrontend, + accessFaunadbTokenFromFrontend: + config.accessFaunadbTokenFromFrontend === undefined ? false : config.accessFaunadbTokenFromFrontend, userCollectionName: config.userCollectionName, faunaDBClient: config.faunaDBClient, }; @@ -122,15 +152,17 @@ class RecipeImplementation { } exports.default = RecipeImplementation; function getModifiedSession(session) { - return Object.assign(Object.assign({}, session), { getFaunadbToken: (userContext) => __awaiter(this, void 0, void 0, function* () { - let accessTokenPayload = session.getAccessTokenPayload(userContext); - if (accessTokenPayload[constants_1.FAUNADB_SESSION_KEY] !== undefined) { - // this operation costs nothing. So we can check - return accessTokenPayload[constants_1.FAUNADB_SESSION_KEY]; - } - else { - let sessionData = yield session.getSessionData(userContext); - return sessionData[constants_1.FAUNADB_SESSION_KEY]; - } - }) }); + return Object.assign(Object.assign({}, session), { + getFaunadbToken: (userContext) => + __awaiter(this, void 0, void 0, function* () { + let accessTokenPayload = session.getAccessTokenPayload(userContext); + if (accessTokenPayload[constants_1.FAUNADB_SESSION_KEY] !== undefined) { + // this operation costs nothing. So we can check + return accessTokenPayload[constants_1.FAUNADB_SESSION_KEY]; + } else { + let sessionData = yield session.getSessionData(userContext); + return sessionData[constants_1.FAUNADB_SESSION_KEY]; + } + }), + }); } diff --git a/lib/build/recipe/session/framework/awsLambda.js b/lib/build/recipe/session/framework/awsLambda.js index 83278e46c..ad6ab8ed3 100644 --- a/lib/build/recipe/session/framework/awsLambda.js +++ b/lib/build/recipe/session/framework/awsLambda.js @@ -1,35 +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 }); 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({}); + 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 844d9df04..07cd4bdb8 100644 --- a/lib/build/recipe/session/framework/express.js +++ b/lib/build/recipe/session/framework/express.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. * @@ -27,23 +49,22 @@ 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); - 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 c7483db62..cfba856bc 100644 --- a/lib/build/recipe/session/framework/fastify.d.ts +++ b/lib/build/recipe/session/framework/fastify.d.ts @@ -2,4 +2,15 @@ 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< + import("http").Server, + import("http").IncomingMessage, + import("http").ServerResponse, + import("fastify/types/route").RouteGenericInterface, + unknown + > +) => Promise; diff --git a/lib/build/recipe/session/framework/fastify.js b/lib/build/recipe/session/framework/fastify.js index 9785897cd..1675b9cd1 100644 --- a/lib/build/recipe/session/framework/fastify.js +++ b/lib/build/recipe/session/framework/fastify.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. * @@ -27,18 +49,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/h3.d.ts b/lib/build/recipe/session/framework/h3.d.ts index 71679250f..4ef9a68f2 100644 --- a/lib/build/recipe/session/framework/h3.d.ts +++ b/lib/build/recipe/session/framework/h3.d.ts @@ -1,5 +1,7 @@ /// -import type { VerifySessionOptions } from '../types'; -import type { SessionRequest } from '../../../framework/h3'; -import { ServerResponse } from 'http'; -export declare function verifySession(options?: VerifySessionOptions): (req: SessionRequest, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; +import type { VerifySessionOptions } from "../types"; +import type { SessionRequest } from "../../../framework/h3"; +import { ServerResponse } from "http"; +export declare function verifySession( + options?: VerifySessionOptions +): (req: SessionRequest, res: ServerResponse, next: (err?: Error | undefined) => any) => Promise; diff --git a/lib/build/recipe/session/framework/h3.js b/lib/build/recipe/session/framework/h3.js index 8abd748c3..e5a0d2968 100644 --- a/lib/build/recipe/session/framework/h3.js +++ b/lib/build/recipe/session/framework/h3.js @@ -1,35 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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"); const framework_1 = require("../../../framework/h3/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.H3Request(req); - const response = new framework_1.H3ResponseTokens(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.H3Request(req); + const response = new framework_1.H3ResponseTokens(res); try { - const supertokens = supertokens_1.default.getInstanceOrThrowError(); - yield supertokens.errorHandler(err, request, response); - } - catch (err) { - 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 (err) { + next(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 63e6c2a21..9f2d4ce11 100644 --- a/lib/build/recipe/session/framework/hapi.js +++ b/lib/build/recipe/session/framework/hapi.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. * @@ -26,12 +48,13 @@ 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 ac4d08eb1..c54549cd2 100644 --- a/lib/build/recipe/session/framework/index.d.ts +++ b/lib/build/recipe/session/framework/index.d.ts @@ -4,7 +4,7 @@ import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; -import * as h3Framework from './h3'; +import * as h3Framework from "./h3"; declare const _default: { express: typeof expressFramework; fastify: typeof fastifyFramework; 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 6c26d1e1a..e7a5704e8 100644 --- a/lib/build/recipe/session/framework/koa.js +++ b/lib/build/recipe/session/framework/koa.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. * @@ -26,12 +48,13 @@ 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.js b/lib/build/recipe/session/framework/loopback.js index 0729815d2..14fa6c6c6 100644 --- a/lib/build/recipe/session/framework/loopback.js +++ b/lib/build/recipe/session/framework/loopback.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. * @@ -26,13 +48,14 @@ 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 294086f67..99faaec05 100644 --- a/lib/build/recipe/session/index.d.ts +++ b/lib/build/recipe/session/index.d.ts @@ -1,11 +1,29 @@ import SuperTokensError from "./error"; -import { VerifySessionOptions, RecipeInterface, SessionContainerInterface as SessionContainer, SessionInformation, APIInterface, APIOptions } from "./types"; +import { + VerifySessionOptions, + RecipeInterface, + SessionContainerInterface as SessionContainer, + SessionInformation, + APIInterface, + APIOptions, +} from "./types"; import Recipe from "./recipe"; export default class SessionWrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static createNewSession(res: any, userId: string, accessTokenPayload?: any, sessionData?: any, userContext?: any): Promise; - static getSession(req: any, res: any, options?: VerifySessionOptions, userContext?: any): Promise; + static createNewSession( + res: any, + userId: string, + accessTokenPayload?: any, + sessionData?: any, + userContext?: any + ): Promise; + static getSession( + req: any, + res: any, + options?: VerifySessionOptions, + 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; @@ -13,31 +31,52 @@ 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<{ + static regenerateAccessToken( + accessToken: string, + newAccessTokenPayload?: any, + userContext?: any + ): Promise<{ status: "OK"; session: { handle: string; userId: string; userDataInJWT: any; }; - accessToken?: { - token: string; - expiry: number; - createdTime: number; - } | undefined; + accessToken?: + | { + token: string; + expiry: number; + createdTime: number; + } + | undefined; }>; - static updateAccessTokenPayload(sessionHandle: string, newAccessTokenPayload: any, 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 updateAccessTokenPayload( + sessionHandle: string, + newAccessTokenPayload: any, + 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; diff --git a/lib/build/recipe/session/index.js b/lib/build/recipe/session/index.js index 26d6709ab..6dfc459b0 100644 --- a/lib/build/recipe/session/index.js +++ b/lib/build/recipe/session/index.js @@ -28,7 +28,9 @@ class SessionWrapper { }); } static getSession(req, res, options, userContext = {}) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getSession({ req, res, options, userContext }); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.getSession({ req, res, options, userContext }); } static getSessionInformation(sessionHandle, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getSessionInformation({ @@ -40,7 +42,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({ @@ -49,7 +53,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({ @@ -83,21 +89,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" + ); } } exports.default = SessionWrapper; diff --git a/lib/build/recipe/session/jwt.d.ts b/lib/build/recipe/session/jwt.d.ts index c72639760..656c61266 100644 --- a/lib/build/recipe/session/jwt.d.ts +++ b/lib/build/recipe/session/jwt.d.ts @@ -1,6 +1,11 @@ -export declare function verifyJWTAndGetPayload(jwt: string, jwtSigningPublicKey: string): { +export declare function verifyJWTAndGetPayload( + jwt: string, + jwtSigningPublicKey: string +): { [key: string]: any; }; -export declare function getPayloadWithoutVerifiying(jwt: string): { +export declare function getPayloadWithoutVerifiying( + jwt: string +): { [key: string]: any; }; diff --git a/lib/build/recipe/session/jwt.js b/lib/build/recipe/session/jwt.js index b51c4a45d..e544545ce 100644 --- a/lib/build/recipe/session/jwt.js +++ b/lib/build/recipe/session/jwt.js @@ -16,16 +16,20 @@ 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) { const splittedInput = jwt.split("."); @@ -40,7 +44,13 @@ function verifyJWTAndGetPayload(jwt, 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")) { + if ( + !verifier.verify( + "-----BEGIN PUBLIC KEY-----\n" + jwtSigningPublicKey + "\n-----END PUBLIC KEY-----", + splittedInput[2], + "base64" + ) + ) { throw new Error("JWT verification failed"); } // sending payload diff --git a/lib/build/recipe/session/recipe.d.ts b/lib/build/recipe/session/recipe.d.ts index c976a10de..e08cc0182 100644 --- a/lib/build/recipe/session/recipe.d.ts +++ b/lib/build/recipe/session/recipe.d.ts @@ -18,9 +18,19 @@ export default class SessionRecipe extends RecipeModule { 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; - 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 fdaddfa47..06e03914b 100644 --- a/lib/build/recipe/session/recipe.js +++ b/lib/build/recipe/session/recipe.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 recipeModule_1 = require("../../recipeModule"); const error_1 = require("./error"); @@ -63,53 +85,52 @@ 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"); - 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"); - return yield this.config.errorHandlers.onTokenTheftDetected(err.payload.sessionHandle, err.payload.userId, request, 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; } - else { + }); + 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"); + 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"); + return yield this.config.errorHandlers.onTokenTheftDetected( + err.payload.sessionHandle, + err.payload.userId, + request, + response + ); + } else { + throw err; + } + } 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) { @@ -118,30 +139,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: {}, + 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: {}, + }); }); - }); 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) { @@ -149,19 +175,25 @@ 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)); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipeId), this.config) + ); 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)); + 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(); } } @@ -181,8 +213,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 163856bf2..3f7980b4b 100644 --- a/lib/build/recipe/session/recipeImplementation.d.ts +++ b/lib/build/recipe/session/recipeImplementation.d.ts @@ -6,7 +6,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; diff --git a/lib/build/recipe/session/recipeImplementation.js b/lib/build/recipe/session/recipeImplementation.js index 1f9e90d6d..1d07bd735 100644 --- a/lib/build/recipe/session/recipeImplementation.js +++ b/lib/build/recipe/session/recipeImplementation.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 SessionFunctions = require("./sessionFunctions"); const cookieAndHeaders_1 = require("./cookieAndHeaders"); @@ -21,7 +43,13 @@ const supertokens_1 = require("../../supertokens"); const framework_1 = require("../../framework"); const logger_1 = require("../../logger"); class HandshakeInfo { - constructor(antiCsrf, accessTokenBlacklistingEnabled, accessTokenValidity, refreshTokenValidity, rawJwtSigningPublicKeyList) { + constructor( + antiCsrf, + accessTokenBlacklistingEnabled, + accessTokenValidity, + refreshTokenValidity, + rawJwtSigningPublicKeyList + ) { this.antiCsrf = antiCsrf; this.accessTokenBlacklistingEnabled = accessTokenBlacklistingEnabled; this.accessTokenValidity = accessTokenValidity; @@ -35,7 +63,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; @@ -43,12 +77,28 @@ function getRecipeInterface(querier, config) { 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; }); @@ -63,24 +113,42 @@ function getRecipeInterface(querier, config) { } } let obj = { - createNewSession: function ({ res, userId, accessTokenPayload = {}, sessionData = {}, }) { + createNewSession: function ({ res, userId, accessTokenPayload = {}, sessionData = {} }) { return __awaiter(this, void 0, void 0, function* () { if (!res.wrapperUsed) { - res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse(res); + res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse( + res + ); } - let response = yield SessionFunctions.createNewSession(helpers, userId, accessTokenPayload, sessionData); + let response = yield SessionFunctions.createNewSession( + helpers, + userId, + 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.userDataInJWT, res); + return new sessionClass_1.default( + helpers, + response.accessToken.token, + response.session.handle, + response.session.userId, + response.session.userDataInJWT, + res + ); }); }, - getSession: function ({ req, res, options, }) { + getSession: function ({ req, res, options }) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("getSession: Started"); if (!res.wrapperUsed) { - res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse(res); + res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse( + res + ); } if (!req.wrapperUsed) { - req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest(req); + req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest( + req + ); } logger_1.logDebugMessage("getSession: rid in header: " + utils_2.frontendHasInterceptor(req)); logger_1.logDebugMessage("getSession: request method: " + req.getMethod()); @@ -90,14 +158,19 @@ function getRecipeInterface(querier, config) { // 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"); + logger_1.logDebugMessage( + "getSession: returning undefined because idRefreshToken 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 idRefreshToken from cookies 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 as cookies?", type: error_1.default.UNAUTHORISED, }); } @@ -110,11 +183,15 @@ function getRecipeInterface(querier, config) { * options.sessionRequired === true || (frontendHasInterceptor or request method is get), * else we should return undefined */ - if (options === 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"); + 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, @@ -128,16 +205,38 @@ function getRecipeInterface(querier, config) { doAntiCsrfCheck = utils_2.normaliseHttpMethod(req.getMethod()) !== "get"; } 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, + cookieAndHeaders_1.getRidFromHeader(req) !== undefined + ); 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); + 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; } logger_1.logDebugMessage("getSession: Success!"); - return new sessionClass_1.default(helpers, accessToken, response.session.handle, response.session.userId, response.session.userDataInJWT, res); - } - catch (err) { + return new sessionClass_1.default( + helpers, + accessToken, + response.session.handle, + response.session.userId, + response.session.userDataInJWT, + res + ); + } catch (err) { if (err.type === error_1.default.UNAUTHORISED) { logger_1.logDebugMessage("getSession: Clearing cookies because of UNAUTHORISED response"); cookieAndHeaders_1.clearSessionFromCookie(config, res); @@ -146,7 +245,7 @@ function getRecipeInterface(querier, config) { } }); }, - getSessionInformation: function ({ sessionHandle, }) { + getSessionInformation: function ({ sessionHandle }) { return __awaiter(this, void 0, void 0, function* () { return SessionFunctions.getSessionInformation(helpers, sessionHandle); }); @@ -155,40 +254,65 @@ function getRecipeInterface(querier, config) { return __awaiter(this, void 0, void 0, function* () { logger_1.logDebugMessage("refreshSession: Started"); if (!res.wrapperUsed) { - res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse(res); + res = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapResponse( + res + ); } if (!req.wrapperUsed) { - req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest(req); + req = framework_1.default[supertokens_1.default.getInstanceOrThrowError().framework].wrapRequest( + req + ); } let inputIdRefreshToken = cookieAndHeaders_1.getIdRefreshTokenFromCookie(req); if (inputIdRefreshToken === undefined) { - logger_1.logDebugMessage("refreshSession: UNAUTHORISED because idRefreshToken from cookies is 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?", + message: + "Session does not exist. Are you sending the session tokens in the request as cookies?", type: error_1.default.UNAUTHORISED, }); } try { let inputRefreshToken = cookieAndHeaders_1.getRefreshTokenFromCookie(req); if (inputRefreshToken === undefined) { - logger_1.logDebugMessage("refreshSession: UNAUTHORISED because refresh token from cookies is undefined"); + logger_1.logDebugMessage( + "refreshSession: UNAUTHORISED because refresh token from cookies 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 as a cookie?", type: error_1.default.UNAUTHORISED, }); } let antiCsrfToken = cookieAndHeaders_1.getAntiCsrfTokenFromHeaders(req); - let response = yield SessionFunctions.refreshSession(helpers, inputRefreshToken, antiCsrfToken, cookieAndHeaders_1.getRidFromHeader(req) !== undefined); + 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.userDataInJWT, res); - } - catch (err) { - if ((err.type === error_1.default.UNAUTHORISED && err.payload.clearCookies) || - err.type === error_1.default.TOKEN_THEFT_DETECTED) { - logger_1.logDebugMessage("refreshSession: Clearing cookies because of UNAUTHORISED or TOKEN_THEFT_DETECTED response"); + return new sessionClass_1.default( + helpers, + response.accessToken.token, + response.session.handle, + response.session.userId, + response.session.userDataInJWT, + res + ); + } catch (err) { + if ( + (err.type === error_1.default.UNAUTHORISED && err.payload.clearCookies) || + err.type === error_1.default.TOKEN_THEFT_DETECTED + ) { + logger_1.logDebugMessage( + "refreshSession: Clearing cookies because of UNAUTHORISED or TOKEN_THEFT_DETECTED response" + ); cookieAndHeaders_1.clearSessionFromCookie(config, res); } throw err; @@ -197,13 +321,17 @@ function getRecipeInterface(querier, config) { }, 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") { throw new error_1.default({ message: response.message, @@ -225,10 +353,10 @@ function getRecipeInterface(querier, config) { 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); }, getAccessTokenLifeTimeMS: function () { diff --git a/lib/build/recipe/session/sessionClass.d.ts b/lib/build/recipe/session/sessionClass.d.ts index 468d45a46..f7704e9d0 100644 --- a/lib/build/recipe/session/sessionClass.d.ts +++ b/lib/build/recipe/session/sessionClass.d.ts @@ -8,7 +8,14 @@ export default class Session implements SessionContainerInterface { protected res: BaseResponse; protected accessToken: string; protected helpers: Helpers; - constructor(helpers: Helpers, accessToken: string, sessionHandle: string, userId: string, userDataInAccessToken: any, res: BaseResponse); + constructor( + helpers: Helpers, + accessToken: string, + sessionHandle: string, + userId: string, + userDataInAccessToken: any, + res: BaseResponse + ); revokeSession: (userContext?: any) => Promise; getSessionData: (userContext?: any) => Promise; updateSessionData: (newSessionData: any, userContext?: any) => Promise; diff --git a/lib/build/recipe/session/sessionClass.js b/lib/build/recipe/session/sessionClass.js index 3f91fec88..01605bf47 100644 --- a/lib/build/recipe/session/sessionClass.js +++ b/lib/build/recipe/session/sessionClass.js @@ -1,55 +1,80 @@ "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, userDataInAccessToken, res) { - this.revokeSession = (userContext) => __awaiter(this, void 0, void 0, function* () { - if (yield this.helpers.sessionRecipeImpl.revokeSession({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - })) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); - } - }); - this.getSessionData = (userContext) => __awaiter(this, void 0, void 0, function* () { - try { - return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - })).sessionData; - } - catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { + this.revokeSession = (userContext) => + __awaiter(this, void 0, void 0, function* () { + if ( + yield this.helpers.sessionRecipeImpl.revokeSession({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + }) + ) { cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); } - throw err; - } - }); - this.updateSessionData = (newSessionData, userContext) => __awaiter(this, void 0, void 0, function* () { - try { - yield this.helpers.sessionRecipeImpl.updateSessionData({ - sessionHandle: this.sessionHandle, - newSessionData, - userContext: userContext === undefined ? {} : userContext, - }); - } - catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + }); + this.getSessionData = (userContext) => + __awaiter(this, void 0, void 0, function* () { + try { + return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + })).sessionData; + } catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + } + throw err; } - throw err; - } - }); + }); + this.updateSessionData = (newSessionData, userContext) => + __awaiter(this, void 0, void 0, function* () { + try { + yield this.helpers.sessionRecipeImpl.updateSessionData({ + sessionHandle: this.sessionHandle, + newSessionData, + userContext: userContext === undefined ? {} : userContext, + }); + } catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + } + throw err; + } + }); this.getUserId = () => { return this.userId; }; @@ -62,55 +87,65 @@ class Session { this.getAccessToken = () => { return this.accessToken; }; - this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => __awaiter(this, void 0, void 0, function* () { - try { - let response = yield this.helpers.sessionRecipeImpl.regenerateAccessToken({ - accessToken: this.getAccessToken(), - newAccessTokenPayload, - userContext: userContext === undefined ? {} : userContext, - }); - 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); - } - } - catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => + __awaiter(this, void 0, void 0, function* () { + try { + let response = yield this.helpers.sessionRecipeImpl.regenerateAccessToken({ + accessToken: this.getAccessToken(), + newAccessTokenPayload, + userContext: userContext === undefined ? {} : userContext, + }); + 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 + ); + } + } catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + } + throw err; } - throw err; - } - }); - this.getTimeCreated = (userContext) => __awaiter(this, void 0, void 0, function* () { - try { - return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - })).timeCreated; - } - catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + }); + this.getTimeCreated = (userContext) => + __awaiter(this, void 0, void 0, function* () { + try { + return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + })).timeCreated; + } catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + } + throw err; } - throw err; - } - }); - this.getExpiry = (userContext) => __awaiter(this, void 0, void 0, function* () { - try { - return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ - sessionHandle: this.sessionHandle, - userContext: userContext === undefined ? {} : userContext, - })).expiry; - } - catch (err) { - if (err.type === error_1.default.UNAUTHORISED) { - cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + }); + this.getExpiry = (userContext) => + __awaiter(this, void 0, void 0, function* () { + try { + return (yield this.helpers.sessionRecipeImpl.getSessionInformation({ + sessionHandle: this.sessionHandle, + userContext: userContext === undefined ? {} : userContext, + })).expiry; + } catch (err) { + if (err.type === error_1.default.UNAUTHORISED) { + cookieAndHeaders_1.clearSessionFromCookie(this.helpers.config, this.res); + } + throw err; } - throw err; - } - }); + }); this.sessionHandle = sessionHandle; this.userId = userId; this.userDataInAccessToken = userDataInAccessToken; diff --git a/lib/build/recipe/session/sessionFunctions.d.ts b/lib/build/recipe/session/sessionFunctions.d.ts index 3e12ae77b..079e7864e 100644 --- a/lib/build/recipe/session/sessionFunctions.d.ts +++ b/lib/build/recipe/session/sessionFunctions.d.ts @@ -3,11 +3,22 @@ import { Helpers } from "./recipeImplementation"; /** * @description call this to "login" a user. */ -export declare function createNewSession(helpers: Helpers, userId: string, accessTokenPayload?: any, sessionData?: any): Promise; +export declare function createNewSession( + helpers: Helpers, + userId: 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, + accessToken: string, + antiCsrfToken: string | undefined, + doAntiCsrfCheck: boolean, + containsCustomHeader: boolean +): Promise<{ session: { handle: string; userId: string; @@ -28,7 +39,12 @@ export declare function getSessionInformation(helpers: Helpers, sessionHandle: s * @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 +): 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. @@ -57,4 +73,8 @@ export declare function updateSessionData(helpers: Helpers, sessionHandle: strin * @returns access token payload as provided by the user earlier */ export declare function getAccessTokenPayload(helpers: Helpers, sessionHandle: string): Promise; -export declare function updateAccessTokenPayload(helpers: Helpers, sessionHandle: string, newAccessTokenPayload: 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 e9ccd1023..9344ed5b5 100644 --- a/lib/build/recipe/session/sessionFunctions.js +++ b/lib/build/recipe/session/sessionFunctions.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. * @@ -44,8 +66,15 @@ function createNewSession(helpers, userId, accessTokenPayload = {}, 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); + 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; @@ -68,10 +97,13 @@ 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( + accessToken, + 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 @@ -100,8 +132,7 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai let payload; try { payload = jwt_1.getPayloadWithoutVerifiying(accessToken); - } - catch (_) { + } catch (_) { throw err; } if (payload === undefined) { @@ -142,14 +173,18 @@ 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, @@ -157,20 +192,24 @@ 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, @@ -186,29 +225,39 @@ function getSession(helpers, accessToken, antiCsrfToken, doAntiCsrfCheck, contai 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); } @@ -241,8 +290,7 @@ function getSessionInformation(helpers, sessionHandle) { delete response.userDataInJWT; delete response.userDataInJWT; return response; - } - else { + } else { throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, @@ -265,7 +313,9 @@ function refreshSession(helpers, refreshToken, antiCsrfToken, containsCustomHead }; if (handShakeInfo.antiCsrf === "VIA_CUSTOM_HEADER") { 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, @@ -275,19 +325,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", @@ -307,9 +358,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; }); } @@ -332,9 +386,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; }); } @@ -345,9 +402,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; }); } @@ -382,8 +442,7 @@ function getAccessTokenPayload(helpers, sessionHandle) { }); if (response.status === "OK") { return response.userDataInJWT; - } - else { + } else { throw new error_1.default({ message: response.message, type: error_1.default.UNAUTHORISED, diff --git a/lib/build/recipe/session/types.d.ts b/lib/build/recipe/session/types.d.ts index e1e77058e..96c4e7a54 100644 --- a/lib/build/recipe/session/types.d.ts +++ b/lib/build/recipe/session/types.d.ts @@ -14,13 +14,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; @@ -55,22 +58,39 @@ export declare type TypeInput = { cookieDomain?: string; 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; }; }; }; @@ -89,14 +109,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; }; }; }; @@ -133,41 +168,18 @@ export declare type RecipeInterface = { options?: VerifySessionOptions; userContext: any; }): Promise; - refreshSession(input: { - req: any; - res: any; - userContext: any; - }): Promise; + refreshSession(input: { req: any; res: any; userContext: any }): Promise; /** * Used to retrieve all session information for a given session handle. Can be used in place of: * - getSessionData * - getAccessTokenPayload */ - 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; updateAccessTokenPayload(input: { sessionHandle: string; newAccessTokenPayload: any; @@ -190,12 +202,8 @@ export declare type RecipeInterface = { createdTime: number; }; }>; - getAccessTokenLifeTimeMS(input: { - userContext: any; - }): Promise; - getRefreshTokenLifeTimeMS(input: { - userContext: any; - }): Promise; + getAccessTokenLifeTimeMS(input: { userContext: any }): Promise; + getRefreshTokenLifeTimeMS(input: { userContext: any }): Promise; }; export interface SessionContainerInterface { revokeSession(userContext?: any): Promise; @@ -218,16 +226,15 @@ export declare type APIOptions = { res: BaseResponse; }; export declare type APIInterface = { - refreshPOST: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise); - signOutPOST: undefined | ((input: { - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - }>); + refreshPOST: undefined | ((input: { options: APIOptions; userContext: any }) => Promise); + signOutPOST: + | undefined + | ((input: { + options: APIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + }>); verifySession(input: { verifySessionOptions: VerifySessionOptions | undefined; options: APIOptions; diff --git a/lib/build/recipe/session/utils.d.ts b/lib/build/recipe/session/utils.d.ts index 34d0d5032..ff00cc684 100644 --- a/lib/build/recipe/session/utils.d.ts +++ b/lib/build/recipe/session/utils.d.ts @@ -2,12 +2,36 @@ import { CreateOrRefreshAPIResponse, TypeInput, TypeNormalisedInput } from "./ty 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 sendTokenTheftDetectedResponse(recipeInstance: SessionRecipe, sessionHandle: 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 sendTokenTheftDetectedResponse( + recipeInstance: SessionRecipe, + sessionHandle: 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 attachCreateOrRefreshSessionResponseToExpressRes( + config: TypeNormalisedInput, + res: BaseResponse, + response: CreateOrRefreshAPIResponse +): void; diff --git a/lib/build/recipe/session/utils.js b/lib/build/recipe/session/utils.js index 8ae46e9aa..3dd8ee784 100644 --- a/lib/build/recipe/session/utils.js +++ b/lib/build/recipe/session/utils.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 cookieAndHeaders_1 = require("./cookieAndHeaders"); const url_1 = require("url"); @@ -68,8 +90,7 @@ function normaliseSessionScopeOrThrowError(sessionScope) { sessionScope = sessionScope.substr(1); } return sessionScope; - } - catch (err) { + } catch (err) { throw new Error("Please provide a valid sessionScope"); } } @@ -103,42 +124,50 @@ function getURLProtocol(url) { } exports.getURLProtocol = getURLProtocol; function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { - let cookieDomain = config === undefined || config.cookieDomain === undefined - ? undefined - : normaliseSessionScopeOrThrowError(config.cookieDomain); + let cookieDomain = + config === undefined || config.cookieDomain === undefined + ? 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 = topLevelAPIDomain !== topLevelWebsiteDomain || protocolOfAPIDomain !== protocolOfWebsiteDomain ? "none" : "lax"; + let cookieSameSite = + topLevelAPIDomain !== 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; + let cookieSecure = + config === undefined || config.cookieSecure === undefined + ? appInfo.apiDomain.getAsStringDangerous().startsWith("https") + : config.cookieSecure; + let sessionExpiredStatusCode = + config === undefined || config.sessionExpiredStatusCode === undefined ? 401 : config.sessionExpiredStatusCode; if (config !== undefined && config.antiCsrf !== undefined) { if (config.antiCsrf !== "NONE" && config.antiCsrf !== "VIA_CUSTOM_HEADER" && config.antiCsrf !== "VIA_TOKEN") { 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, request, response) => __awaiter(this, void 0, void 0, function* () { - return yield sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, userId, 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, request, response) => + __awaiter(this, void 0, void 0, function* () { + return yield sendTokenTheftDetectedResponse(recipeInstance, sessionHandle, userId, 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); + }), }; if (config !== undefined && config.errorHandlers !== undefined) { if (config.errorHandlers.onTokenTheftDetected !== undefined) { @@ -148,11 +177,15 @@ function validateAndNormaliseUserInput(recipeInstance, appInfo, config) { errorHandlers.onUnauthorised = config.errorHandlers.onUnauthorised; } } - if (cookieSameSite === "none" && + if ( + cookieSameSite === "none" && !cookieSecure && !(topLevelAPIDomain === "localhost" || utils_1.isAnIpAddress(topLevelAPIDomain)) && - !(topLevelWebsiteDomain === "localhost" || utils_1.isAnIpAddress(topLevelWebsiteDomain))) { - 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."); + !(topLevelWebsiteDomain === "localhost" || utils_1.isAnIpAddress(topLevelWebsiteDomain)) + ) { + 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"; @@ -168,7 +201,13 @@ 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)), cookieDomain, @@ -199,7 +238,12 @@ function attachCreateOrRefreshSessionResponseToExpressRes(config, res, response) 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.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); 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 d0ca100a8..5324e6382 100644 --- a/lib/build/recipe/session/with-jwt/recipeImplementation.js +++ b/lib/build/recipe/session/with-jwt/recipeImplementation.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. * @@ -42,11 +64,14 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { function getJWTExpiry(accessTokenExpiry) { return accessTokenExpiry + EXPIRY_OFFSET_SECONDS; } - return Object.assign(Object.assign({}, originalImplementation), { createNewSession: function ({ res, userId, accessTokenPayload, sessionData, userContext, }) { + return Object.assign(Object.assign({}, originalImplementation), { + createNewSession: function ({ res, userId, 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), @@ -64,7 +89,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) { @@ -72,9 +98,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(); @@ -89,13 +118,15 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { yield newSession.updateAccessTokenPayload(accessTokenPayload); return new sessionClass_1.default(newSession, openIdRecipeImplementation); }); - }, updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext, }) { + }, + updateAccessTokenPayload: function ({ sessionHandle, newAccessTokenPayload, userContext }) { return __awaiter(this, void 0, void 0, function* () { newAccessTokenPayload = newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; let sessionInformation = yield this.getSessionInformation({ sessionHandle, userContext }); let accessTokenPayload = sessionInformation.accessTokenPayload; - let existingJwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; + let existingJwtPropertyName = + accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; if (existingJwtPropertyName === undefined) { return yield originalImplementation.updateAccessTokenPayload({ sessionHandle, @@ -134,6 +165,7 @@ function default_1(originalImplementation, openIdRecipeImplementation, config) { userContext, }); }); - } }); + }, + }); } exports.default = default_1; diff --git a/lib/build/recipe/session/with-jwt/sessionClass.js b/lib/build/recipe/session/with-jwt/sessionClass.js index fa95bdf25..1e9c37986 100644 --- a/lib/build/recipe/session/with-jwt/sessionClass.js +++ b/lib/build/recipe/session/with-jwt/sessionClass.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. * @@ -56,40 +78,41 @@ class SessionClassWithJWT { this.getExpiry = (userContext) => { return this.originalSessionClass.getExpiry(userContext); }; - this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => __awaiter(this, void 0, void 0, function* () { - newAccessTokenPayload = - newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; - let accessTokenPayload = this.getAccessTokenPayload(userContext); - let jwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; - if (jwtPropertyName === undefined) { - return this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); - } - let existingJWT = accessTokenPayload[jwtPropertyName]; - assert.notStrictEqual(existingJWT, undefined); - let currentTimeInSeconds = Date.now() / 1000; - let decodedPayload = JsonWebToken.decode(existingJWT, { json: true }); - // JsonWebToken.decode possibly returns null - if (decodedPayload === null) { - throw new Error("Error reading JWT from session"); - } - let jwtExpiry = decodedPayload.exp - currentTimeInSeconds; - if (jwtExpiry <= 0) { - // it can come here if someone calls this function well after - // the access token and the jwt payload have expired (which can happen if an API takes a VERY long time). In this case, we still want the jwt payload to update, but the resulting JWT should - // not be alive for too long (since it's expired already). So we set it to - // 1 second lifetime. - jwtExpiry = 1; - } - newAccessTokenPayload = yield utils_1.addJWTToAccessTokenPayload({ - accessTokenPayload: newAccessTokenPayload, - jwtExpiry, - userId: this.getUserId(), - jwtPropertyName, - openIdRecipeImplementation: this.openIdRecipeImplementation, - userContext, + this.updateAccessTokenPayload = (newAccessTokenPayload, userContext) => + __awaiter(this, void 0, void 0, function* () { + newAccessTokenPayload = + newAccessTokenPayload === null || newAccessTokenPayload === undefined ? {} : newAccessTokenPayload; + let accessTokenPayload = this.getAccessTokenPayload(userContext); + let jwtPropertyName = accessTokenPayload[constants_1.ACCESS_TOKEN_PAYLOAD_JWT_PROPERTY_NAME_KEY]; + if (jwtPropertyName === undefined) { + return this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); + } + let existingJWT = accessTokenPayload[jwtPropertyName]; + assert.notStrictEqual(existingJWT, undefined); + let currentTimeInSeconds = Date.now() / 1000; + let decodedPayload = JsonWebToken.decode(existingJWT, { json: true }); + // JsonWebToken.decode possibly returns null + if (decodedPayload === null) { + throw new Error("Error reading JWT from session"); + } + let jwtExpiry = decodedPayload.exp - currentTimeInSeconds; + if (jwtExpiry <= 0) { + // it can come here if someone calls this function well after + // the access token and the jwt payload have expired (which can happen if an API takes a VERY long time). In this case, we still want the jwt payload to update, but the resulting JWT should + // not be alive for too long (since it's expired already). So we set it to + // 1 second lifetime. + jwtExpiry = 1; + } + newAccessTokenPayload = yield utils_1.addJWTToAccessTokenPayload({ + accessTokenPayload: newAccessTokenPayload, + jwtExpiry, + userId: this.getUserId(), + jwtPropertyName, + openIdRecipeImplementation: this.openIdRecipeImplementation, + userContext, + }); + return yield this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); }); - return yield this.originalSessionClass.updateAccessTokenPayload(newAccessTokenPayload, userContext); - }); this.openIdRecipeImplementation = openIdRecipeImplementation; this.originalSessionClass = originalSessionClass; } 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 9f4a72f43..49c1d7531 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 }); /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. * @@ -24,7 +46,14 @@ 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]; @@ -35,12 +64,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, }); @@ -49,7 +82,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) @@ -66,7 +99,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 f7a2bd08f..32d249bf4 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 }); function appleRedirectHandler(apiImplementation, options) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/build/recipe/thirdparty/api/authorisationUrl.js b/lib/build/recipe/thirdparty/api/authorisationUrl.js index 33c1d035e..08a72b0ef 100644 --- a/lib/build/recipe/thirdparty/api/authorisationUrl.js +++ b/lib/build/recipe/thirdparty/api/authorisationUrl.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 error_1 = require("../error"); diff --git a/lib/build/recipe/thirdparty/api/implementation.js b/lib/build/recipe/thirdparty/api/implementation.js index 8ad0191ed..c30026102 100644 --- a/lib/build/recipe/thirdparty/api/implementation.js +++ b/lib/build/recipe/thirdparty/api/implementation.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 session_1 = require("../../session"); const url_1 = require("url"); @@ -15,7 +37,7 @@ const axios = require("axios"); const qs = require("querystring"); function getAPIInterface() { return { - 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 = {}; @@ -25,8 +47,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 @@ -39,7 +63,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) + ); } }); } @@ -54,7 +80,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; @@ -62,8 +88,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); @@ -74,13 +99,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) + ); } }); } @@ -96,8 +122,7 @@ function getAPIInterface() { } try { userInfo = yield providerInfo.getProfileInfo(accessTokenAPIResponse.data, userContext); - } - catch (err) { + } catch (err) { if (err.message !== undefined) { return { status: "FIELD_ERROR", @@ -124,11 +149,13 @@ function getAPIInterface() { // we set the email as verified if already verified by the OAuth provider. // This block was added because of https://github.com/supertokens/supertokens-core/issues/295 if (emailInfo.isVerified) { - const tokenResponse = yield options.emailVerificationRecipeImplementation.createEmailVerificationToken({ - userId: response.user.id, - email: response.user.email, - userContext, - }); + const tokenResponse = yield options.emailVerificationRecipeImplementation.createEmailVerificationToken( + { + userId: response.user.id, + email: response.user.email, + userContext, + } + ); if (tokenResponse.status === "OK") { yield options.emailVerificationRecipeImplementation.verifyEmailUsingToken({ token: tokenResponse.token, @@ -136,7 +163,13 @@ function getAPIInterface() { }); } } - let session = yield session_1.default.createNewSession(options.res, response.user.id, {}, {}, userContext); + let session = yield session_1.default.createNewSession( + options.res, + response.user.id, + {}, + {}, + userContext + ); return { status: "OK", createdNewUser: response.createdNewUser, @@ -148,13 +181,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 a9d32fbba..62e05eb24 100644 --- a/lib/build/recipe/thirdparty/api/signinup.js +++ b/lib/build/recipe/thirdparty/api/signinup.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 error_1 = require("../error"); const utils_1 = require("../../../utils"); @@ -72,13 +94,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.`, }); @@ -99,13 +122,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, { status: "FIELD_ERROR", error: result.error, 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/index.d.ts b/lib/build/recipe/thirdparty/index.d.ts index 50797952b..60e47e5ee 100644 --- a/lib/build/recipe/thirdparty/index.d.ts +++ b/lib/build/recipe/thirdparty/index.d.ts @@ -4,34 +4,65 @@ 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: { - id: string; - isVerified: boolean; - }, userContext?: any): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "FIELD_ERROR"; - error: string; - }>; + static signInUp( + thirdPartyId: string, + thirdPartyUserId: string, + email: { + id: string; + isVerified: boolean; + }, + userContext?: any + ): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "FIELD_ERROR"; + error: string; + } + >; static getUserById(userId: string, userContext?: any): Promise; static getUsersByEmail(email: string, userContext?: any): Promise; - static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise; - static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - }>; - static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } | User | undefined>; + static getUserByThirdPartyInfo( + thirdPartyId: string, + thirdPartyUserId: string, + userContext?: any + ): Promise; + static createEmailVerificationToken( + userId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + } + >; + static verifyEmailUsingToken( + token: string, + userContext?: any + ): Promise< + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + | User + | undefined + >; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ + static revokeEmailVerificationTokens( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; - static unverifyEmail(userId: string, userContext?: any): Promise<{ + static unverifyEmail( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; static Google: typeof import("./providers/google").default; diff --git a/lib/build/recipe/thirdparty/index.js b/lib/build/recipe/thirdparty/index.js index 6fe0b81f6..8c10b0c58 100644 --- a/lib/build/recipe/thirdparty/index.js +++ b/lib/build/recipe/thirdparty/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); diff --git a/lib/build/recipe/thirdparty/providers/apple.js b/lib/build/recipe/thirdparty/providers/apple.js index ca66a32f4..7005957c1 100644 --- a/lib/build/recipe/thirdparty/providers/apple.js +++ b/lib/build/recipe/thirdparty/providers/apple.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 jsonwebtoken_1 = require("jsonwebtoken"); const error_1 = require("../error"); @@ -18,19 +40,27 @@ 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, @@ -38,7 +68,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, @@ -56,10 +91,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* () { /* @@ -92,9 +131,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 9d86a3a78..16fa3f8d0 100644 --- a/lib/build/recipe/thirdparty/providers/discord.js +++ b/lib/build/recipe/thirdparty/providers/discord.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 axios_1 = require("axios"); function Discord(config) { @@ -31,10 +53,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; @@ -49,12 +75,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 368119ea9..f54a7d4ba 100644 --- a/lib/build/recipe/thirdparty/providers/facebook.js +++ b/lib/build/recipe/thirdparty/providers/facebook.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 axios_1 = require("axios"); function Facebook(config) { diff --git a/lib/build/recipe/thirdparty/providers/github.js b/lib/build/recipe/thirdparty/providers/github.js index 3851c3edd..184960d58 100644 --- a/lib/build/recipe/thirdparty/providers/github.js +++ b/lib/build/recipe/thirdparty/providers/github.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 axios_1 = require("axios"); function Github(config) { @@ -30,10 +52,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; @@ -80,12 +106,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 93e0dd2f5..2587fd9ca 100644 --- a/lib/build/recipe/thirdparty/providers/google.js +++ b/lib/build/recipe/thirdparty/providers/google.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 axios_1 = require("axios"); function Google(config) { @@ -31,10 +53,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 3e5900f0d..1a808b91d 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/utils.d.ts b/lib/build/recipe/thirdparty/providers/utils.d.ts index 5c5e8d7c3..268e9b912 100644 --- a/lib/build/recipe/thirdparty/providers/utils.d.ts +++ b/lib/build/recipe/thirdparty/providers/utils.d.ts @@ -1,2 +1,6 @@ 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 8fce5a38e..542100115 100644 --- a/lib/build/recipe/thirdparty/providers/utils.js +++ b/lib/build/recipe/thirdparty/providers/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 }); const jwt = require("jsonwebtoken"); const jwksClient = require("jwks-rsa"); @@ -26,8 +48,7 @@ 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 bed75b2b5..f3f80c86f 100644 --- a/lib/build/recipe/thirdparty/recipe.d.ts +++ b/lib/build/recipe/thirdparty/recipe.d.ts @@ -14,14 +14,26 @@ export default class Recipe extends RecipeModule { recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; isInServerlessEnv: boolean; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + recipes: { + emailVerificationInstance: EmailVerificationRecipe | undefined; + } + ); 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 60cbe516b..3e7184571 100644 --- a/lib/build/recipe/thirdparty/recipe.js +++ b/lib/build/recipe/thirdparty/recipe.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 recipeModule_1 = require("../../recipeModule"); const utils_1 = require("./utils"); @@ -62,63 +84,71 @@ class Recipe extends recipeModule_1.default { ...this.emailVerificationRecipe.getAPIsHandled(), ]; }; - 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, - emailVerificationRecipeImplementation: this.emailVerificationRecipe.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); - } - else { - return yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); - } - }); - this.handleError = (err, request, response) => __awaiter(this, void 0, void 0, function* () { - if (err.fromRecipe === Recipe.RECIPE_ID) { - throw err; - } - else { - return yield this.emailVerificationRecipe.handleError(err, request, 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, + emailVerificationRecipeImplementation: this.emailVerificationRecipe.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); + } else { + return yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + } + }); + this.handleError = (err, request, response) => + __awaiter(this, void 0, void 0, function* () { + if (err.fromRecipe === Recipe.RECIPE_ID) { + throw err; + } else { + return yield this.emailVerificationRecipe.handleError(err, request, response); + } + }); this.getAllCORSHeaders = () => { return [...this.emailVerificationRecipe.getAllCORSHeaders()]; }; this.isErrorFromThisRecipe = (err) => { - return (error_1.default.isErrorFromSuperTokens(err) && - (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err))); + return ( + error_1.default.isErrorFromSuperTokens(err) && + (err.fromRecipe === Recipe.RECIPE_ID || this.emailVerificationRecipe.isErrorFromThisRecipe(err)) + ); }; // helper functions... - this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo === undefined) { - throw Error("Unknown User ID provided"); - } - return userInfo.email; - }); + this.getEmailForUserId = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw Error("Unknown User ID provided"); + } + return userInfo.email; + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); this.isInServerlessEnv = isInServerlessEnv; this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign({}, this.config.emailVerificationFeature)); + : new recipe_1.default( + recipeId, + appInfo, + isInServerlessEnv, + Object.assign({}, this.config.emailVerificationFeature) + ); 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(); } { @@ -133,8 +163,7 @@ class Recipe extends recipeModule_1.default { emailVerificationInstance: 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 dafb92577..7f0c83637 100644 --- a/lib/build/recipe/thirdparty/recipeImplementation.js +++ b/lib/build/recipe/thirdparty/recipeImplementation.js @@ -1,18 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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, @@ -33,21 +55,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, @@ -55,8 +79,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 7a364e921..b4d49680f 100644 --- a/lib/build/recipe/thirdparty/types.d.ts +++ b/lib/build/recipe/thirdparty/types.d.ts @@ -1,4 +1,7 @@ -import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; +import { + RecipeInterface as EmailVerificationRecipeInterface, + APIInterface as EmailVerificationAPIInterface, +} from "../emailverification"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; import { BaseRequest, BaseResponse } from "../../framework"; import { NormalisedAppinfo } from "../../types"; @@ -30,7 +33,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 = { @@ -56,11 +63,20 @@ export declare type TypeInput = { signInAndUpFeature: TypeInputSignInAndUp; emailVerificationFeature?: TypeInputEmailVerificationFeature; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; @@ -68,23 +84,26 @@ export declare type TypeNormalisedInput = { signInAndUpFeature: TypeNormalisedInputSignInAndUp; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; 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,14 +117,17 @@ export declare type RecipeInterface = { isVerified: boolean; }; userContext: any; - }): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "FIELD_ERROR"; - error: string; - }>; + }): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "FIELD_ERROR"; + error: string; + } + >; }; export declare type APIOptions = { recipeImplementation: RecipeInterface; @@ -119,38 +141,43 @@ export declare type APIOptions = { appInfo: NormalisedAppinfo; }; export declare type APIInterface = { - authorisationUrlGET: undefined | ((input: { - provider: TypeProvider; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - url: string; - }>); - signInUpPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: APIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - } | { - status: "FIELD_ERROR"; - error: string; - }>); - 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; + }>); + signInUpPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: APIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } + | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } + | { + status: "FIELD_ERROR"; + error: string; + } + >); + 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 b37ed4cf4..e628b8f72 100644 --- a/lib/build/recipe/thirdparty/utils.d.ts +++ b/lib/build/recipe/thirdparty/utils.d.ts @@ -2,5 +2,13 @@ import { NormalisedAppinfo } from "../../types"; import Recipe from "./recipe"; import { TypeProvider } from "./types"; import { TypeInput, TypeNormalisedInput } from "./types"; -export declare function validateAndNormaliseUserInput(recipeInstance: Recipe, appInfo: NormalisedAppinfo, config: TypeInput): TypeNormalisedInput; -export declare function findRightProvider(providers: TypeProvider[], thirdPartyId: string, clientId?: string): TypeProvider | undefined; +export declare function validateAndNormaliseUserInput( + recipeInstance: Recipe, + 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 4919096c8..2599914f9 100644 --- a/lib/build/recipe/thirdparty/utils.js +++ b/lib/build/recipe/thirdparty/utils.js @@ -13,20 +13,48 @@ * 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 validateAndNormaliseUserInput(recipeInstance, appInfo, config) { let emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, 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 { emailVerificationFeature, signInAndUpFeature, @@ -58,7 +86,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.. @@ -78,14 +108,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, @@ -95,34 +129,63 @@ function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserId, - override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, - createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); - }), - getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: + (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 + ? void 0 + : _a.emailVerificationFeature, + createAndSendCustomEmail: + ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _b === void 0 + ? void 0 + : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_d = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _d === void 0 + ? void 0 + : _d.createAndSendCustomEmail) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail( + userInfo, + link, + userContext + ); + }), + getEmailVerificationURL: + ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _c === void 0 + ? void 0 + : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_e = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _e === void 0 + ? void 0 + : _e.getEmailVerificationURL) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } diff --git a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js index 86a6a2bed..c8d9d033a 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.js @@ -3,11 +3,24 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e; 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), + 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), }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartyemailpassword/api/implementation.js b/lib/build/recipe/thirdpartyemailpassword/api/implementation.js index 4d90d420a..f9420149f 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/implementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/implementation.js @@ -9,14 +9,38 @@ 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)), - passwordResetPOST: (_f = emailPasswordImplementation.passwordResetPOST) === null || _f === void 0 ? void 0 : _f.bind(emailPasswordAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 ? void 0 : _h.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)), + passwordResetPOST: + (_f = emailPasswordImplementation.passwordResetPOST) === null || _f === void 0 + ? void 0 + : _f.bind(emailPasswordAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: + (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 + ? void 0 + : _g.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: + (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 + ? void 0 + : _h.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 ac7562f07..0023e4411 100644 --- a/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.js @@ -1,34 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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; - const signInUpPOSTFromThirdPartyEmailPassword = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyEmailPassword = + (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); return { - authorisationUrlGET: (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), - appleRedirectHandlerPOST: (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - 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: + (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), + appleRedirectHandlerPOST: + (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 + ? void 0 + : _c.bind(apiImplmentation), + 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/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/index.d.ts b/lib/build/recipe/thirdpartyemailpassword/index.d.ts index 73f881664..c9746be87 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/index.d.ts @@ -5,44 +5,83 @@ import { TypeProvider } from "../thirdparty/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: { - id: string; - isVerified: boolean; - }, userContext?: any): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "FIELD_ERROR"; - error: string; - }>; - 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 thirdPartySignInUp( + thirdPartyId: string, + thirdPartyUserId: string, + email: { + id: string; + isVerified: boolean; + }, + userContext?: any + ): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "FIELD_ERROR"; + error: string; + } + >; + 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, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "UNKNOWN_USER_ID_ERROR"; - }>; - static resetPasswordUsingToken(token: string, newPassword: string, userContext?: any): Promise<{ - status: "OK"; - userId?: string | undefined; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + static createResetPasswordToken( + userId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "UNKNOWN_USER_ID_ERROR"; + } + >; + static resetPasswordUsingToken( + token: string, + newPassword: string, + userContext?: any + ): Promise< + | { + status: "OK"; + userId?: string | undefined; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; static updateEmailOrPassword(input: { userId: string; email?: string; @@ -51,20 +90,39 @@ export default class Wrapper { }): Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; }>; - static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - }>; - static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } | User | undefined>; + static createEmailVerificationToken( + userId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + } + >; + static verifyEmailUsingToken( + token: string, + userContext?: any + ): Promise< + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + | User + | undefined + >; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ + static revokeEmailVerificationTokens( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; - static unverifyEmail(userId: string, userContext?: any): Promise<{ + static unverifyEmail( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; static Google: typeof import("../thirdparty/providers/google").default; diff --git a/lib/build/recipe/thirdpartyemailpassword/index.js b/lib/build/recipe/thirdpartyemailpassword/index.js index 1a8a52895..9bdbc5d65 100644 --- a/lib/build/recipe/thirdpartyemailpassword/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); @@ -63,7 +85,9 @@ class Wrapper { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.getUsersByEmail({ email, userContext }); } static createResetPasswordToken(userId, userContext = {}) { - return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.createResetPasswordToken({ userId, userContext }); + return recipe_1.default + .getInstanceOrThrowError() + .recipeInterfaceImpl.createResetPasswordToken({ userId, userContext }); } static resetPasswordUsingToken(token, newPassword, userContext = {}) { return recipe_1.default.getInstanceOrThrowError().recipeInterfaceImpl.resetPasswordUsingToken({ @@ -73,7 +97,9 @@ 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 createEmailVerificationToken(userId, userContext = {}) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts index b90b37d45..ff6f8d340 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.d.ts @@ -18,17 +18,33 @@ export default class Recipe extends RecipeModule { private thirdPartyRecipe; recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - thirdPartyInstance: ThirdPartyRecipe | undefined; - emailPasswordInstance: EmailPasswordRecipe | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + recipes: { + emailVerificationInstance: EmailVerificationRecipe | undefined; + thirdPartyInstance: ThirdPartyRecipe | undefined; + emailPasswordInstance: EmailPasswordRecipe | 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; getEmailForUserId: (userId: string, userContext: any) => Promise; diff --git a/lib/build/recipe/thirdpartyemailpassword/recipe.js b/lib/build/recipe/thirdpartyemailpassword/recipe.js index d6e82126b..44d068448 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipe.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipe.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. * @@ -50,30 +72,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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); - }); - 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); } - return yield this.emailVerificationRecipe.handleError(err, request, response); - } - }); + return yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + }); + 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); + } + return yield this.emailVerificationRecipe.handleError(err, request, response); + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [ ...this.emailVerificationRecipe.getAllCORSHeaders(), @@ -85,23 +112,31 @@ 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.emailVerificationRecipe.isErrorFromThisRecipe(err) || this.emailPasswordRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) + ); }; // helper functions... - this.getEmailForUserId = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo === undefined) { - throw new Error("Unknown User ID provided"); - } - return userInfo.email; - }); + this.getEmailForUserId = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw new Error("Unknown User ID provided"); + } + return userInfo.email; + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default( + querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), + querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID) + ) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -111,43 +146,60 @@ class Recipe extends recipeModule_1.default { this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign({}, this.config.emailVerificationFeature)); + : new recipe_1.default( + recipeId, + appInfo, + isInServerlessEnv, + Object.assign({}, this.config.emailVerificationFeature) + ); this.emailPasswordRecipe = recipes.emailPasswordInstance !== undefined ? recipes.emailPasswordInstance - : new recipe_2.default(recipeId, appInfo, isInServerlessEnv, { - override: { - functions: (_) => { - return emailPasswordRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return emailPasswordAPIImplementation_1.default(this.apiImpl); - }, - }, - signUpFeature: { - formFields: this.config.signUpFeature.formFields, - }, - resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, - }, { emailVerificationInstance: this.emailVerificationRecipe }); + : new recipe_2.default( + recipeId, + appInfo, + isInServerlessEnv, + { + override: { + functions: (_) => { + return emailPasswordRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return emailPasswordAPIImplementation_1.default(this.apiImpl); + }, + }, + signUpFeature: { + formFields: this.config.signUpFeature.formFields, + }, + resetPasswordUsingTokenFeature: this.config.resetPasswordUsingTokenFeature, + }, + { emailVerificationInstance: this.emailVerificationRecipe } + ); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_3.default(recipeId, appInfo, isInServerlessEnv, { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, { - emailVerificationInstance: this.emailVerificationRecipe, - }); + : new recipe_3.default( + recipeId, + appInfo, + isInServerlessEnv, + { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, + { + emailVerificationInstance: this.emailVerificationRecipe, + } + ); } } static init(config) { @@ -159,9 +211,10 @@ class Recipe extends recipeModule_1.default { thirdPartyInstance: 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 aa4e850e1..a0b965a09 100644 --- a/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartyemailpassword/recipeImplementation/index.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 recipeImplementation_1 = require("../../emailpassword/recipeImplementation"); const recipeImplementation_2 = require("../../thirdparty/recipeImplementation"); @@ -22,12 +44,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) { @@ -35,28 +61,38 @@ 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]; } @@ -68,17 +104,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) { @@ -88,11 +130,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 52907c9f1..481c0a3db 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 11ef357ce..c63f302eb 100644 --- a/lib/build/recipe/thirdpartyemailpassword/types.d.ts +++ b/lib/build/recipe/thirdpartyemailpassword/types.d.ts @@ -1,7 +1,16 @@ import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; -import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; -import { NormalisedFormField, TypeFormField, TypeInputFormField, TypeInputResetPasswordUsingTokenFeature, APIOptions as EmailPasswordAPIOptionsOriginal } from "../emailpassword/types"; +import { + RecipeInterface as EmailVerificationRecipeInterface, + APIInterface as EmailVerificationAPIInterface, +} from "../emailverification"; +import { + NormalisedFormField, + TypeFormField, + TypeInputFormField, + TypeInputResetPasswordUsingTokenFeature, + APIOptions as EmailPasswordAPIOptionsOriginal, +} from "../emailpassword/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/types"; export declare type User = { @@ -40,11 +49,20 @@ export declare type TypeInput = { resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; emailVerificationFeature?: TypeInputEmailVerificationFeature; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; @@ -54,23 +72,26 @@ export declare type TypeNormalisedInput = { resetPasswordUsingTokenFeature?: TypeInputResetPasswordUsingTokenFeature; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; 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; @@ -84,57 +105,72 @@ export declare type RecipeInterface = { isVerified: boolean; }; userContext: any; - }): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "FIELD_ERROR"; - error: string; - }>; + }): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "FIELD_ERROR"; + error: string; + } + >; emailPasswordSignUp(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"; + } + >; 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; 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"; - /** - * The id of the user whose password was reset. - * Defined for Core versions 3.9 or later - */ - userId?: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>; + }): Promise< + | { + status: "OK"; + /** + * The id of the user whose password was reset. + * Defined for Core versions 3.9 or later + */ + userId?: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >; updateEmailOrPassword(input: { userId: string; email?: string; @@ -147,98 +183,122 @@ export declare type RecipeInterface = { export declare type EmailPasswordAPIOptions = EmailPasswordAPIOptionsOriginal; export declare type ThirdPartyAPIOptions = ThirdPartyAPIOptionsOriginal; export declare type APIInterface = { - authorisationUrlGET: undefined | ((input: { - provider: TypeProvider; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - url: string; - }>); - emailPasswordEmailExistsGET: undefined | ((input: { - email: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); - generatePasswordResetTokenPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - }>); - passwordResetPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - token: string; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - userId?: string; - } | { - status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; - }>); - thirdPartySignInUpPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } | { - status: "FIELD_ERROR"; - error: string; - } | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - }>); - emailPasswordSignInPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - session: SessionContainerInterface; - } | { - status: "WRONG_CREDENTIALS_ERROR"; - }>); - emailPasswordSignUpPOST: undefined | ((input: { - formFields: { - id: string; - value: string; - }[]; - options: EmailPasswordAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - user: User; - session: SessionContainerInterface; - } | { - status: "EMAIL_ALREADY_EXISTS_ERROR"; - }>); - appleRedirectHandlerPOST: undefined | ((input: { - code: string; - state: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise); + authorisationUrlGET: + | undefined + | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + url: string; + }>); + emailPasswordEmailExistsGET: + | undefined + | ((input: { + email: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); + generatePasswordResetTokenPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + }>); + passwordResetPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + token: string; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + userId?: string; + } + | { + status: "RESET_PASSWORD_INVALID_TOKEN_ERROR"; + } + >); + thirdPartySignInUpPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } + | { + status: "FIELD_ERROR"; + error: string; + } + | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } + >); + emailPasswordSignInPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "WRONG_CREDENTIALS_ERROR"; + } + >); + emailPasswordSignUpPOST: + | undefined + | ((input: { + formFields: { + id: string; + value: string; + }[]; + options: EmailPasswordAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + user: User; + session: SessionContainerInterface; + } + | { + status: "EMAIL_ALREADY_EXISTS_ERROR"; + } + >); + appleRedirectHandlerPOST: + | undefined + | ((input: { code: string; state: string; options: ThirdPartyAPIOptions; userContext: any }) => Promise); }; 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 d8097494b..23c016a7a 100644 --- a/lib/build/recipe/thirdpartyemailpassword/utils.js +++ b/lib/build/recipe/thirdpartyemailpassword/utils.js @@ -13,23 +13,55 @@ * 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("../emailpassword/utils"); 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 emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, appInfo, 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, signUpFeature, @@ -49,34 +81,63 @@ function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserId, - override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, - createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); - }), - getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: + (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 + ? void 0 + : _a.emailVerificationFeature, + createAndSendCustomEmail: + ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _b === void 0 + ? void 0 + : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_d = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _d === void 0 + ? void 0 + : _d.createAndSendCustomEmail) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail( + userInfo, + link, + userContext + ); + }), + getEmailVerificationURL: + ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _c === void 0 + ? void 0 + : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_e = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _e === void 0 + ? void 0 + : _e.getEmailVerificationURL) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } diff --git a/lib/build/recipe/thirdpartypasswordless/api/implementation.js b/lib/build/recipe/thirdpartypasswordless/api/implementation.js index b08e28e0b..e97a96569 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/implementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/implementation.js @@ -9,14 +9,38 @@ 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)), - resendCodePOST: (_e = passwordlessImplementation.resendCodePOST) === null || _e === void 0 ? void 0 : _e.bind(passwordlessAPIImplementation_1.default(this)), - authorisationUrlGET: (_f = thirdPartyImplementation.authorisationUrlGET) === null || _f === void 0 ? void 0 : _f.bind(thirdPartyAPIImplementation_1.default(this)), - thirdPartySignInUpPOST: (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 ? void 0 : _g.bind(thirdPartyAPIImplementation_1.default(this)), - appleRedirectHandlerPOST: (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 ? void 0 : _h.bind(thirdPartyAPIImplementation_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)), + resendCodePOST: + (_e = passwordlessImplementation.resendCodePOST) === null || _e === void 0 + ? void 0 + : _e.bind(passwordlessAPIImplementation_1.default(this)), + authorisationUrlGET: + (_f = thirdPartyImplementation.authorisationUrlGET) === null || _f === void 0 + ? void 0 + : _f.bind(thirdPartyAPIImplementation_1.default(this)), + thirdPartySignInUpPOST: + (_g = thirdPartyImplementation.signInUpPOST) === null || _g === void 0 + ? void 0 + : _g.bind(thirdPartyAPIImplementation_1.default(this)), + appleRedirectHandlerPOST: + (_h = thirdPartyImplementation.appleRedirectHandlerPOST) === null || _h === void 0 + ? void 0 + : _h.bind(thirdPartyAPIImplementation_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 d47f4307c..25e56c8b2 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/passwordlessAPIImplementation.js @@ -3,11 +3,20 @@ Object.defineProperty(exports, "__esModule", { value: true }); function getIterfaceImpl(apiImplmentation) { var _a, _b, _c, _d, _e; 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), + 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), }; } exports.default = getIterfaceImpl; diff --git a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js index a26a501e8..e3d01c889 100644 --- a/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js +++ b/lib/build/recipe/thirdpartypasswordless/api/thirdPartyAPIImplementation.js @@ -1,34 +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 __awaiter = + (this && this.__awaiter) || + function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (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; - const signInUpPOSTFromThirdPartyPasswordless = (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); + const signInUpPOSTFromThirdPartyPasswordless = + (_a = apiImplmentation.thirdPartySignInUpPOST) === null || _a === void 0 ? void 0 : _a.bind(apiImplmentation); return { - authorisationUrlGET: (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), - appleRedirectHandlerPOST: (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 ? void 0 : _c.bind(apiImplmentation), - 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: + (_b = apiImplmentation.authorisationUrlGET) === null || _b === void 0 ? void 0 : _b.bind(apiImplmentation), + appleRedirectHandlerPOST: + (_c = apiImplmentation.appleRedirectHandlerPOST) === null || _c === void 0 + ? void 0 + : _c.bind(apiImplmentation), + 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/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/index.d.ts b/lib/build/recipe/thirdpartypasswordless/index.d.ts index e43f9f78a..02d55d83f 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/index.d.ts @@ -5,89 +5,137 @@ import { TypeProvider } from "../thirdparty/types"; export default class Wrapper { static init: typeof Recipe.init; static Error: typeof SuperTokensError; - static thirdPartySignInUp(thirdPartyId: string, thirdPartyUserId: string, email: { - id: string; - isVerified: boolean; - }, userContext?: any): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "FIELD_ERROR"; - error: string; - }>; - static getUserByThirdPartyInfo(thirdPartyId: string, thirdPartyUserId: string, userContext?: any): Promise<({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - timeJoined: number; - }) | ({ - email: string; - thirdParty: { + static thirdPartySignInUp( + thirdPartyId: string, + thirdPartyUserId: string, + email: { id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) | undefined>; - static getUserById(userId: string, userContext?: any): Promise<({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - timeJoined: number; - }) | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) | undefined>; + isVerified: boolean; + }, + userContext?: any + ): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "FIELD_ERROR"; + error: string; + } + >; + static getUserByThirdPartyInfo( + thirdPartyId: string, + thirdPartyUserId: string, + userContext?: any + ): Promise< + | ({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) + | ({ + email: string; + thirdParty: { + id: string; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) + | undefined + >; + static getUserById( + userId: string, + userContext?: any + ): Promise< + | ({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) + | ({ + email: string; + thirdParty: { + id: string; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) + | undefined + >; static getUsersByEmail(email: string, userContext?: any): Promise; - static createEmailVerificationToken(userId: string, userContext?: any): Promise<{ - status: "OK"; - token: string; - } | { - status: "EMAIL_ALREADY_VERIFIED_ERROR"; - }>; - static verifyEmailUsingToken(token: string, userContext?: any): Promise<{ - status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; - } | ({ - email?: string | undefined; - phoneNumber?: string | undefined; - } & { - id: string; - timeJoined: number; - }) | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) | undefined>; + static createEmailVerificationToken( + userId: string, + userContext?: any + ): Promise< + | { + status: "OK"; + token: string; + } + | { + status: "EMAIL_ALREADY_VERIFIED_ERROR"; + } + >; + static verifyEmailUsingToken( + token: string, + userContext?: any + ): Promise< + | { + status: "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"; + } + | ({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) + | ({ + email: string; + thirdParty: { + id: string; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) + | undefined + >; static isEmailVerified(userId: string, userContext?: any): Promise; - static revokeEmailVerificationTokens(userId: string, userContext?: any): Promise<{ + static revokeEmailVerificationTokens( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; - static unverifyEmail(userId: string, userContext?: any): Promise<{ + static unverifyEmail( + userId: string, + userContext?: any + ): Promise<{ status: "OK"; }>; - 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; @@ -101,57 +149,72 @@ 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; - timeJoined: number; - }) | ({ - email: string; - thirdParty: { - id: string; - userId: string; - }; - } & { - id: string; - timeJoined: number; - }) | undefined>; + }): Promise< + | ({ + email?: string | undefined; + phoneNumber?: string | undefined; + } & { + id: string; + timeJoined: number; + }) + | ({ + email: string; + thirdParty: { + id: string; + userId: string; + }; + } & { + id: string; + timeJoined: number; + }) + | undefined + >; static updatePasswordlessUser(input: { userId: string; email?: string | null; @@ -160,13 +223,17 @@ 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: { @@ -191,20 +258,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").User; diff --git a/lib/build/recipe/thirdpartypasswordless/index.js b/lib/build/recipe/thirdpartypasswordless/index.js index 86d524efc..80ab6a4ec 100644 --- a/lib/build/recipe/thirdpartypasswordless/index.js +++ b/lib/build/recipe/thirdpartypasswordless/index.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 recipe_1 = require("./recipe"); const error_1 = require("./error"); @@ -106,43 +128,69 @@ 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 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)); } } exports.default = Wrapper; diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts index ea6df8e59..a60588e9b 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/recipe.d.ts @@ -18,17 +18,33 @@ export default class Recipe extends RecipeModule { private thirdPartyRecipe; recipeInterfaceImpl: RecipeInterface; apiImpl: APIInterface; - constructor(recipeId: string, appInfo: NormalisedAppinfo, isInServerlessEnv: boolean, config: TypeInput, recipes: { - emailVerificationInstance: EmailVerificationRecipe | undefined; - thirdPartyInstance: ThirdPartyRecipe | undefined; - passwordlessInstance: PasswordlessRecipe | undefined; - }); + constructor( + recipeId: string, + appInfo: NormalisedAppinfo, + isInServerlessEnv: boolean, + config: TypeInput, + recipes: { + emailVerificationInstance: EmailVerificationRecipe | undefined; + thirdPartyInstance: ThirdPartyRecipe | undefined; + passwordlessInstance: PasswordlessRecipe | 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; getEmailForUserIdForEmailVerification: (userId: string, userContext: any) => Promise; diff --git a/lib/build/recipe/thirdpartypasswordless/recipe.js b/lib/build/recipe/thirdpartypasswordless/recipe.js index 0a12dd928..8e66a7682 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipe.js +++ b/lib/build/recipe/thirdpartypasswordless/recipe.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. * @@ -50,30 +72,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 yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); - }); - 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); } - return yield this.emailVerificationRecipe.handleError(err, request, response); - } - }); + return yield this.emailVerificationRecipe.handleAPIRequest(id, req, res, path, method); + }); + 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); + } + return yield this.emailVerificationRecipe.handleError(err, request, response); + } + }); this.getAllCORSHeaders = () => { let corsHeaders = [ ...this.emailVerificationRecipe.getAllCORSHeaders(), @@ -85,29 +112,36 @@ 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.emailVerificationRecipe.isErrorFromThisRecipe(err) || this.passwordlessRecipe.isErrorFromThisRecipe(err) || - (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err)))); + (this.thirdPartyRecipe !== undefined && this.thirdPartyRecipe.isErrorFromThisRecipe(err))) + ); }; // helper functions... - this.getEmailForUserIdForEmailVerification = (userId, userContext) => __awaiter(this, void 0, void 0, function* () { - let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); - if (userInfo === undefined) { - throw new Error("Unknown User ID provided"); - } - else if (!("thirdParty" in userInfo)) { - // this is a passwordless user.. so we always return some random email, - // and in the function for isEmailVerified, we will check if the user - // is a passwordless user, and if they are, we will return true in there - return "_____supertokens_passwordless_user@supertokens.com"; - } - return userInfo.email; - }); + this.getEmailForUserIdForEmailVerification = (userId, userContext) => + __awaiter(this, void 0, void 0, function* () { + let userInfo = yield this.recipeInterfaceImpl.getUserById({ userId, userContext }); + if (userInfo === undefined) { + throw new Error("Unknown User ID provided"); + } else if (!("thirdParty" in userInfo)) { + // this is a passwordless user.. so we always return some random email, + // and in the function for isEmailVerified, we will check if the user + // is a passwordless user, and if they are, we will return true in there + return "_____supertokens_passwordless_user@supertokens.com"; + } + return userInfo.email; + }); this.config = utils_1.validateAndNormaliseUserInput(this, appInfo, config); { - let builder = new supertokens_js_override_1.default(recipeImplementation_1.default(querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID))); + let builder = new supertokens_js_override_1.default( + recipeImplementation_1.default( + querier_1.Querier.getNewInstanceOrThrowError(recipe_2.default.RECIPE_ID), + querier_1.Querier.getNewInstanceOrThrowError(recipe_3.default.RECIPE_ID) + ) + ); this.recipeInterfaceImpl = builder.override(this.config.override.functions).build(); } { @@ -119,83 +153,110 @@ class Recipe extends recipeModule_1.default { this.emailVerificationRecipe = recipes.emailVerificationInstance !== undefined ? recipes.emailVerificationInstance - : new recipe_1.default(recipeId, appInfo, isInServerlessEnv, Object.assign(Object.assign({}, this.config.emailVerificationFeature), { override: Object.assign(Object.assign({}, this.config.emailVerificationFeature.override), { functions: (oI, builder) => { - var _a; - let passwordlessOverride = (oI) => { - return Object.assign(Object.assign({}, oI), { createEmailVerificationToken: function (input) { - return __awaiter(this, void 0, void 0, function* () { - let user = yield recipImplReference.getUserById({ - userId: input.userId, - userContext: input.userContext, - }); - if (user === undefined || "thirdParty" in user) { - return oI.createEmailVerificationToken(input); - } - else { - return { - status: "EMAIL_ALREADY_VERIFIED_ERROR", - }; - } - }); - }, isEmailVerified: function (input) { - return __awaiter(this, void 0, void 0, function* () { - let user = yield recipImplReference.getUserById({ - userId: input.userId, - userContext: input.userContext, - }); - if (user === undefined || "thirdParty" in user) { - return oI.isEmailVerified(input); - } - else { - // this is a passwordless user, so we always want - // to return that their info / email is verified - return true; - } - }); - } }); - }; - if (((_a = emailVerificationConfig.override) === null || _a === void 0 ? void 0 : _a.functions) !== undefined) { - // First we apply the override from what we have above, - // and then we apply their override. Notice that we don't - // pass in oI in here, but that is OK since that's how the - // override works! - return builder - .override(passwordlessOverride) - .override(emailVerificationConfig.override.functions) - .build(); - } - return passwordlessOverride(oI); - } }) })); + : new recipe_1.default( + recipeId, + appInfo, + isInServerlessEnv, + Object.assign(Object.assign({}, this.config.emailVerificationFeature), { + override: Object.assign(Object.assign({}, this.config.emailVerificationFeature.override), { + functions: (oI, builder) => { + var _a; + let passwordlessOverride = (oI) => { + return Object.assign(Object.assign({}, oI), { + createEmailVerificationToken: function (input) { + return __awaiter(this, void 0, void 0, function* () { + let user = yield recipImplReference.getUserById({ + userId: input.userId, + userContext: input.userContext, + }); + if (user === undefined || "thirdParty" in user) { + return oI.createEmailVerificationToken(input); + } else { + return { + status: "EMAIL_ALREADY_VERIFIED_ERROR", + }; + } + }); + }, + isEmailVerified: function (input) { + return __awaiter(this, void 0, void 0, function* () { + let user = yield recipImplReference.getUserById({ + userId: input.userId, + userContext: input.userContext, + }); + if (user === undefined || "thirdParty" in user) { + return oI.isEmailVerified(input); + } else { + // this is a passwordless user, so we always want + // to return that their info / email is verified + return true; + } + }); + }, + }); + }; + if ( + ((_a = emailVerificationConfig.override) === null || _a === void 0 + ? void 0 + : _a.functions) !== undefined + ) { + // First we apply the override from what we have above, + // and then we apply their override. Notice that we don't + // pass in oI in here, but that is OK since that's how the + // override works! + return builder + .override(passwordlessOverride) + .override(emailVerificationConfig.override.functions) + .build(); + } + return passwordlessOverride(oI); + }, + }), + }) + ); this.passwordlessRecipe = recipes.passwordlessInstance !== undefined ? recipes.passwordlessInstance - : new recipe_2.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); - }, - } })); + : new recipe_2.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); + }, + }, + }) + ); if (this.config.providers.length !== 0) { this.thirdPartyRecipe = recipes.thirdPartyInstance !== undefined ? recipes.thirdPartyInstance - : new recipe_3.default(recipeId, appInfo, isInServerlessEnv, { - override: { - functions: (_) => { - return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); - }, - apis: (_) => { - return thirdPartyAPIImplementation_1.default(this.apiImpl); - }, - }, - signInAndUpFeature: { - providers: this.config.providers, - }, - }, { - emailVerificationInstance: this.emailVerificationRecipe, - }); + : new recipe_3.default( + recipeId, + appInfo, + isInServerlessEnv, + { + override: { + functions: (_) => { + return thirdPartyRecipeImplementation_1.default(this.recipeInterfaceImpl); + }, + apis: (_) => { + return thirdPartyAPIImplementation_1.default(this.apiImpl); + }, + }, + signInAndUpFeature: { + providers: this.config.providers, + }, + }, + { + emailVerificationInstance: this.emailVerificationRecipe, + } + ); } } static init(config) { @@ -207,9 +268,10 @@ class Recipe extends recipeModule_1.default { thirdPartyInstance: 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 9781499b7..b1a29cf06 100644 --- a/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.js +++ b/lib/build/recipe/thirdpartypasswordless/recipeImplementation/index.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 recipeImplementation_1 = require("../../passwordless/recipeImplementation"); const recipeImplementation_2 = require("../../thirdparty/recipeImplementation"); @@ -22,52 +44,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) { @@ -77,11 +119,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) { @@ -89,28 +134,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]; } @@ -122,7 +177,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 7377bd5fe..d16ff3c59 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/types.d.ts b/lib/build/recipe/thirdpartypasswordless/types.d.ts index c5b93d6f3..26d7d970d 100644 --- a/lib/build/recipe/thirdpartypasswordless/types.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/types.d.ts @@ -1,20 +1,26 @@ import { TypeProvider, APIOptions as ThirdPartyAPIOptionsOriginal } from "../thirdparty/types"; import { TypeInput as TypeInputEmailVerification } from "../emailverification/types"; -import { RecipeInterface as EmailVerificationRecipeInterface, APIInterface as EmailVerificationAPIInterface } from "../emailverification"; +import { + RecipeInterface as EmailVerificationRecipeInterface, + APIInterface as EmailVerificationAPIInterface, +} from "../emailverification"; import { DeviceType as DeviceTypeOriginal, APIOptions as PasswordlessAPIOptionsOriginal } from "../passwordless/types"; import OverrideableBuilder from "supertokens-js-override"; import { SessionContainerInterface } from "../session/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; timeJoined: number; }; @@ -22,133 +28,184 @@ export declare type TypeInputEmailVerificationFeature = { getEmailVerificationURL?: (user: User, userContext: any) => Promise; createAndSendCustomEmail?: (user: User, emailVerificationURLWithToken: string, userContext: any) => Promise; }; -export declare type TypeInput = ({ - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - 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; + createAndSendCustomTextMessage: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + createAndSendCustomTextMessage: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } +) & { providers?: TypeProvider[]; emailVerificationFeature?: TypeInputEmailVerificationFeature; flowType: "USER_INPUT_CODE" | "MAGIC_LINK" | "USER_INPUT_CODE_AND_MAGIC_LINK"; - getLinkDomainAndPath?: (contactInfo: { - email: string; - } | { - phoneNumber: string; - }, userContext: any) => Promise | string; + getLinkDomainAndPath?: ( + contactInfo: + | { + email: string; + } + | { + phoneNumber: string; + }, + userContext: any + ) => Promise | string; getCustomUserInputCode?: (userContext: any) => Promise | string; override?: { - functions?: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions?: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis?: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; -export declare type TypeNormalisedInput = ({ - contactMethod: "PHONE"; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -} | { - contactMethod: "EMAIL"; - validateEmailAddress?: (email: string) => Promise | string | undefined; - 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; - createAndSendCustomEmail: (input: { - email: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; - validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; - createAndSendCustomTextMessage: (input: { - phoneNumber: string; - userInputCode?: string; - urlWithLinkCode?: string; - codeLifetime: number; - preAuthSessionId: string; - }, userContext: any) => Promise; -}) & { +export declare type TypeNormalisedInput = ( + | { + contactMethod: "PHONE"; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + createAndSendCustomTextMessage: ( + input: { + phoneNumber: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + } + | { + contactMethod: "EMAIL"; + validateEmailAddress?: (email: string) => Promise | string | undefined; + 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; + createAndSendCustomEmail: ( + input: { + email: string; + userInputCode?: string; + urlWithLinkCode?: string; + codeLifetime: number; + preAuthSessionId: string; + }, + userContext: any + ) => Promise; + validatePhoneNumber?: (phoneNumber: string) => Promise | string | undefined; + 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"; - getLinkDomainAndPath?: (contactInfo: { - email: string; - } | { - phoneNumber: string; - }, userContext: any) => Promise | string; + getLinkDomainAndPath?: ( + contactInfo: + | { + email: string; + } + | { + phoneNumber: string; + }, + userContext: any + ) => Promise | string; getCustomUserInputCode?: (userContext: any) => Promise | string; providers: TypeProvider[]; emailVerificationFeature: TypeInputEmailVerification; override: { - functions: (originalImplementation: RecipeInterface, builder?: OverrideableBuilder) => RecipeInterface; + functions: ( + originalImplementation: RecipeInterface, + builder?: OverrideableBuilder + ) => RecipeInterface; apis: (originalImplementation: APIInterface, builder?: OverrideableBuilder) => APIInterface; emailVerificationFeature?: { - functions?: (originalImplementation: EmailVerificationRecipeInterface, builder?: OverrideableBuilder) => EmailVerificationRecipeInterface; - apis?: (originalImplementation: EmailVerificationAPIInterface, builder?: OverrideableBuilder) => EmailVerificationAPIInterface; + functions?: ( + originalImplementation: EmailVerificationRecipeInterface, + builder?: OverrideableBuilder + ) => EmailVerificationRecipeInterface; + apis?: ( + originalImplementation: EmailVerificationAPIInterface, + builder?: OverrideableBuilder + ) => EmailVerificationAPIInterface; }; }; }; 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; @@ -162,22 +219,30 @@ export declare type RecipeInterface = { isVerified: boolean; }; userContext: any; - }): Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - } | { - status: "FIELD_ERROR"; - error: string; - }>; - createCode: (input: ({ - email: string; - } | { - phoneNumber: string; - }) & { - userInputCode?: string; - userContext: any; - }) => Promise<{ + }): Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + } + | { + status: "FIELD_ERROR"; + error: string; + } + >; + createCode: ( + input: ( + | { + email: string; + } + | { + phoneNumber: string; + } + ) & { + userInputCode?: string; + userContext: any; + } + ) => Promise<{ status: "OK"; preAuthSessionId: string; codeId: string; @@ -191,38 +256,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; @@ -231,13 +307,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: { @@ -246,18 +326,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; @@ -266,107 +337,145 @@ 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; - }>); - thirdPartySignInUpPOST: undefined | ((input: { - provider: TypeProvider; - code: string; - redirectURI: string; - authCodeResponse?: any; - clientId?: string; - options: ThirdPartyAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - createdNewUser: boolean; - user: User; - session: SessionContainerInterface; - authCodeResponse: any; - } | { - status: "FIELD_ERROR"; - error: string; - } | { - status: "NO_EMAIL_GIVEN_BY_PROVIDER"; - }>); - 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"; - } | { - status: "GENERAL_ERROR"; - message: string; - }>); - resendCodePOST: undefined | ((input: { - deviceId: string; - preAuthSessionId: string; - } & { - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "GENERAL_ERROR"; - message: string; - } | { - 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; - user: User; - session: SessionContainerInterface; - } | { - status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; - failedCodeInputAttemptCount: number; - maximumCodeInputAttempts: number; - } | { - status: "GENERAL_ERROR"; - message: string; - } | { - status: "RESTART_FLOW_ERROR"; - }>); - passwordlessUserEmailExistsGET: undefined | ((input: { - email: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); - passwordlessUserPhoneNumberExistsGET: undefined | ((input: { - phoneNumber: string; - options: PasswordlessAPIOptions; - userContext: any; - }) => Promise<{ - status: "OK"; - exists: boolean; - }>); + authorisationUrlGET: + | undefined + | ((input: { + provider: TypeProvider; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + url: string; + }>); + thirdPartySignInUpPOST: + | undefined + | ((input: { + provider: TypeProvider; + code: string; + redirectURI: string; + authCodeResponse?: any; + clientId?: string; + options: ThirdPartyAPIOptions; + userContext: any; + }) => Promise< + | { + status: "OK"; + createdNewUser: boolean; + user: User; + session: SessionContainerInterface; + authCodeResponse: any; + } + | { + status: "FIELD_ERROR"; + error: string; + } + | { + status: "NO_EMAIL_GIVEN_BY_PROVIDER"; + } + >); + 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"; + } + | { + status: "GENERAL_ERROR"; + message: string; + } + >); + resendCodePOST: + | undefined + | (( + input: { + deviceId: string; + preAuthSessionId: string; + } & { + options: PasswordlessAPIOptions; + userContext: any; + } + ) => Promise< + | { + status: "GENERAL_ERROR"; + message: string; + } + | { + 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; + user: User; + session: SessionContainerInterface; + } + | { + status: "INCORRECT_USER_INPUT_CODE_ERROR" | "EXPIRED_USER_INPUT_CODE_ERROR"; + failedCodeInputAttemptCount: number; + maximumCodeInputAttempts: number; + } + | { + status: "GENERAL_ERROR"; + message: string; + } + | { + status: "RESTART_FLOW_ERROR"; + } + >); + passwordlessUserEmailExistsGET: + | undefined + | ((input: { + email: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); + passwordlessUserPhoneNumberExistsGET: + | undefined + | ((input: { + phoneNumber: string; + options: PasswordlessAPIOptions; + userContext: any; + }) => Promise<{ + status: "OK"; + exists: boolean; + }>); }; diff --git a/lib/build/recipe/thirdpartypasswordless/utils.d.ts b/lib/build/recipe/thirdpartypasswordless/utils.d.ts index fa143e5f9..dc2cedfca 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.d.ts +++ b/lib/build/recipe/thirdpartypasswordless/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/thirdpartypasswordless/utils.js b/lib/build/recipe/thirdpartypasswordless/utils.js index 05be71037..b7641cf5b 100644 --- a/lib/build/recipe/thirdpartypasswordless/utils.js +++ b/lib/build/recipe/thirdpartypasswordless/utils.js @@ -13,57 +13,112 @@ * 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 validateAndNormaliseUserInput(recipeInstance, appInfo, config) { let providers = config.providers === undefined ? [] : config.providers; let emailVerificationFeature = validateAndNormaliseEmailVerificationConfig(recipeInstance, appInfo, config); - let override = Object.assign({ functions: (originalImplementation) => originalImplementation, apis: (originalImplementation) => originalImplementation }, config === null || config === void 0 ? void 0 : config.override); - return Object.assign(Object.assign({}, config), { providers, - emailVerificationFeature, - override }); + let override = Object.assign( + { + functions: (originalImplementation) => originalImplementation, + apis: (originalImplementation) => originalImplementation, + }, + config === null || config === void 0 ? void 0 : config.override + ); + return Object.assign(Object.assign({}, config), { providers, emailVerificationFeature, override }); } exports.validateAndNormaliseUserInput = validateAndNormaliseUserInput; function validateAndNormaliseEmailVerificationConfig(recipeInstance, _, config) { var _a, _b, _c; return { getEmailForUserId: recipeInstance.getEmailForUserIdForEmailVerification, - override: (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 ? void 0 : _a.emailVerificationFeature, - createAndSendCustomEmail: ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _b === void 0 ? void 0 : _b.createAndSendCustomEmail) === undefined - ? undefined - : (user, link, userContext) => __awaiter(this, void 0, void 0, function* () { - var _d; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_d = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _d === void 0 ? void 0 : _d.createAndSendCustomEmail) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.createAndSendCustomEmail(userInfo, link, userContext); - }), - getEmailVerificationURL: ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _c === void 0 ? void 0 : _c.getEmailVerificationURL) === undefined - ? undefined - : (user, userContext) => __awaiter(this, void 0, void 0, function* () { - var _e; - let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ - userId: user.id, - userContext, - }); - if (userInfo === undefined || - ((_e = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || _e === void 0 ? void 0 : _e.getEmailVerificationURL) === undefined) { - throw new Error("Unknown User ID provided"); - } - return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); - }), + override: + (_a = config === null || config === void 0 ? void 0 : config.override) === null || _a === void 0 + ? void 0 + : _a.emailVerificationFeature, + createAndSendCustomEmail: + ((_b = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _b === void 0 + ? void 0 + : _b.createAndSendCustomEmail) === undefined + ? undefined + : (user, link, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _d; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_d = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _d === void 0 + ? void 0 + : _d.createAndSendCustomEmail) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.createAndSendCustomEmail( + userInfo, + link, + userContext + ); + }), + getEmailVerificationURL: + ((_c = config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === null || + _c === void 0 + ? void 0 + : _c.getEmailVerificationURL) === undefined + ? undefined + : (user, userContext) => + __awaiter(this, void 0, void 0, function* () { + var _e; + let userInfo = yield recipeInstance.recipeInterfaceImpl.getUserById({ + userId: user.id, + userContext, + }); + if ( + userInfo === undefined || + ((_e = + config === null || config === void 0 ? void 0 : config.emailVerificationFeature) === + null || _e === void 0 + ? void 0 + : _e.getEmailVerificationURL) === undefined + ) { + throw new Error("Unknown User ID provided"); + } + return yield config.emailVerificationFeature.getEmailVerificationURL(userInfo, userContext); + }), }; } diff --git a/lib/build/recipe/usermetadata/index.d.ts b/lib/build/recipe/usermetadata/index.d.ts index ea604c3af..97f884631 100644 --- a/lib/build/recipe/usermetadata/index.d.ts +++ b/lib/build/recipe/usermetadata/index.d.ts @@ -2,15 +2,25 @@ import Recipe from "./recipe"; import { RecipeInterface, JSONObject } 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: JSONObject; }>; - 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 3a23e391a..9083e4e1f 100644 --- a/lib/build/recipe/usermetadata/index.js +++ b/lib/build/recipe/usermetadata/index.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 recipe_1 = require("./recipe"); class Wrapper { 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 db70af5b7..c03c030e6 100644 --- a/lib/build/recipe/usermetadata/recipe.js +++ b/lib/build/recipe/usermetadata/recipe.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 error_1 = require("../../error"); const querier_1 = require("../../querier"); @@ -33,13 +55,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(); } } @@ -55,8 +80,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("UserMetadata recipe has already been initialised. Please check your code for bugs."); } }; diff --git a/lib/build/recipe/usermetadata/types.d.ts b/lib/build/recipe/usermetadata/types.d.ts index be4a81dd3..4dfb70044 100644 --- a/lib/build/recipe/usermetadata/types.d.ts +++ b/lib/build/recipe/usermetadata/types.d.ts @@ -7,13 +7,19 @@ export interface JSONObject { } 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 b77b71bcd..5deab8250 100644 --- a/lib/build/recipe/usermetadata/utils.js +++ b/lib/build/recipe/usermetadata/utils.js @@ -15,7 +15,13 @@ */ Object.defineProperty(exports, "__esModule", { value: true }); 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/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 8f28fbfc1..7f6c05b84 100644 --- a/lib/build/supertokens.d.ts +++ b/lib/build/supertokens.d.ts @@ -14,7 +14,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; getUsers: (input: { diff --git a/lib/build/supertokens.js b/lib/build/supertokens.js index 971d6bc55..e41d8e7cd 100644 --- a/lib/build/supertokens.js +++ b/lib/build/supertokens.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 axios_1 = require("axios"); const utils_1 = require("./utils"); @@ -34,32 +56,33 @@ const logger_1 = require("./logger"); 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.io/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.io/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); @@ -72,158 +95,197 @@ 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.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, + 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 { - users: response.users, - 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, + 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 { - status: "OK", + users: response.users, + nextPaginationToken: response.nextPaginationToken, }; - } - else { - throw new global.Error("Please upgrade the SuperTokens core to >= 3.7.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 = 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; - } - 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; + }); + 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"); } - 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 + }); + 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: 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 = 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: 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.sendNon200Response(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.sendNon200Response(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); - 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"); } @@ -244,8 +306,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 16d9b8a9f..7bb320024 100644 --- a/lib/build/utils.js +++ b/lib/build/utils.js @@ -25,8 +25,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; } } @@ -49,19 +48,23 @@ 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(""); 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), + 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, }; } @@ -90,7 +93,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 frontendHasInterceptor(req) { diff --git a/lib/ts/framework/h3/framework.ts b/lib/ts/framework/h3/framework.ts index cce9a1c77..e6df8218b 100644 --- a/lib/ts/framework/h3/framework.ts +++ b/lib/ts/framework/h3/framework.ts @@ -1,13 +1,17 @@ -import { createError, H3Event, sendError } from 'h3'; -import type {IncomingMessage, ServerResponse} from 'http'; -import { SessionContainerInterface } from '../../recipe/session/types'; -import SuperTokens from '../../supertokens'; +import { createError, H3Event, sendError } from "h3"; +import type { IncomingMessage, ServerResponse } from "http"; +import { SessionContainerInterface } from "../../recipe/session/types"; +import SuperTokens from "../../supertokens"; import { normaliseHttpMethod } from "../../utils"; import { BaseRequest } from "../request"; -import { BaseResponse } from '../response'; -import { Framework } from '../types'; +import { BaseResponse } from "../response"; +import { Framework } from "../types"; import { - getCookieValueFromIncomingMessage, getHeaderValueFromIncomingMessage, useBody, useRawBody, setCookieForServerResponse + getCookieValueFromIncomingMessage, + getHeaderValueFromIncomingMessage, + useBody, + useRawBody, + setCookieForServerResponse, } from "../utils"; export class H3Request extends BaseRequest { @@ -16,7 +20,7 @@ export class H3Request extends BaseRequest { super(); this.original = request; this.request = request; - }; + } getCookieValue = (key: string) => { return getCookieValueFromIncomingMessage(this.request, key); }; @@ -24,30 +28,30 @@ export class H3Request extends BaseRequest { return useRawBody(this.request); }; getMethod = () => { - return normaliseHttpMethod(this.request.method!) + return normaliseHttpMethod(this.request.method!); }; getHeaderValue = (key: string) => { return getHeaderValueFromIncomingMessage(this.request, key); }; getOriginalURL = () => { - return this.request.url! + return this.request.url!; }; getKeyValueFromQuery = (key: string) => { - let path = this.request.url || "/" - const queryIndex = path.lastIndexOf('?') - if(queryIndex > -1) { - const queryArray = path.substring(queryIndex + 1, path.length).split('&'); - const index = queryArray.findIndex(el => el.includes(key)); - if(index === -1) return undefined; - const value = queryArray[index].split('=')[1] - if(value === undefined || typeof value !== 'string') { - return undefined + let path = this.request.url || "/"; + const queryIndex = path.lastIndexOf("?"); + if (queryIndex > -1) { + const queryArray = path.substring(queryIndex + 1, path.length).split("&"); + const index = queryArray.findIndex((el) => el.includes(key)); + if (index === -1) return undefined; + const value = queryArray[index].split("=")[1]; + if (value === undefined || typeof value !== "string") { + return undefined; } return value; } else { - return undefined; + return undefined; } - } + }; getJSONBody = async () => { return await useBody(this.request); }; @@ -60,18 +64,18 @@ export class H3ResponseTokens extends BaseResponse { super(); this.original = response; this.response = response; - this.statusCode = 200 + this.statusCode = 200; } sendHTMLResponse = (html: string) => { - if(this.response.writable) { - this.response.setHeader('Content-Type', 'text/html') + if (this.response.writable) { + this.response.setHeader("Content-Type", "text/html"); this.response.statusCode = this.statusCode; this.response.end(html); } }; setHeader = (key: string, value: string, allowDuplicateKey: boolean) => { - try { + try { const allheaders = this.response.getHeaders(); let existingValue = allheaders[key]; @@ -101,21 +105,21 @@ export class H3ResponseTokens extends BaseResponse { setCookieForServerResponse(this.response, key, value, domain, secure, httpOnly, expires, path, sameSite); }; setStatusCode = (statusCode: number) => { - if(this.response.writable) { + if (this.response.writable) { this.statusCode = statusCode; } }; sendJSONResponse = (content: any) => { - if(this.response.writable) { + if (this.response.writable) { content = JSON.stringify(content); - this.response.setHeader('Content-Type', 'application/json') + this.response.setHeader("Content-Type", "application/json"); this.response.statusCode = this.statusCode; - this.response.end(content, 'utf-8'); + this.response.end(content, "utf-8"); } }; } export interface SessionRequest extends IncomingMessage { - session?: SessionContainerInterface + session?: SessionContainerInterface; } export const middlware = () => { @@ -126,11 +130,11 @@ export const middlware = () => { try { supertokens = SuperTokens.getInstanceOrThrowError(); const result = await supertokens.middleware(request, response); - if(!result) { + if (!result) { return next(); } - } catch(err: any) { - if(supertokens) { + } catch (err) { + if (supertokens) { try { await supertokens.errorHandler(err, request, response); } catch { @@ -140,22 +144,20 @@ export const middlware = () => { next(err); } } - - } -} + }; +}; export const errorHandler = () => { return async (event: H3Event, errorPlain: Error, statusCode: number) => { const error = createError(errorPlain); error.statusCode = statusCode; - sendError(event, error) - } - -} + sendError(event, error); + }; +}; export interface H3Framework extends Framework { - middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise, - errorHandler: () => (event: H3Event, errorPlain: Error, statusCode: number) => Promise + middlware: () => (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => Promise; + errorHandler: () => (event: H3Event, errorPlain: Error, statusCode: number) => Promise; } export const H3Wrapper: H3Framework = { @@ -165,6 +167,6 @@ export const H3Wrapper: H3Framework = { return new H3Request(unwrapped.req); }, wrapResponse: (unwrapped) => { - return new H3ResponseTokens(unwrapped.res) - } -} \ No newline at end of file + return new H3ResponseTokens(unwrapped.res); + }, +}; diff --git a/lib/ts/framework/h3/index.ts b/lib/ts/framework/h3/index.ts index 6fcd57080..5dcc5a938 100644 --- a/lib/ts/framework/h3/index.ts +++ b/lib/ts/framework/h3/index.ts @@ -1,7 +1,7 @@ import { H3Wrapper } from "./framework"; -export type {SessionRequest} from './framework'; +export type { SessionRequest } from "./framework"; export const middleware = H3Wrapper.middlware; export const errorHandler = H3Wrapper.errorHandler; export const wrapRequest = H3Wrapper.wrapRequest; -export const wrapResponse = H3Wrapper.wrapResponse; \ No newline at end of file +export const wrapResponse = H3Wrapper.wrapResponse; diff --git a/lib/ts/framework/index.ts b/lib/ts/framework/index.ts index eef367e7c..e83df0391 100644 --- a/lib/ts/framework/index.ts +++ b/lib/ts/framework/index.ts @@ -21,7 +21,7 @@ import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; -import * as h3Framework from './h3' +import * as h3Framework from "./h3"; export default { express: expressFramework, @@ -30,7 +30,7 @@ export default { loopback: loopbackFramework, koa: koaFramework, awsLambda: awsLambdaFramework, - h3: h3Framework + h3: h3Framework, }; export let express = expressFramework; @@ -39,4 +39,4 @@ export let hapi = hapiFramework; export let loopback = loopbackFramework; export let koa = koaFramework; export let awsLambda = awsLambdaFramework; -export let h3 = h3Framework; \ No newline at end of file +export let h3 = h3Framework; diff --git a/lib/ts/framework/utils.ts b/lib/ts/framework/utils.ts index 694b42afd..ccb760525 100644 --- a/lib/ts/framework/utils.ts +++ b/lib/ts/framework/utils.ts @@ -22,7 +22,7 @@ import STError from "../error"; import type { HTTPMethod } from "../types"; import { NextApiRequest } from "next"; import { COOKIE_HEADER } from "./constants"; -import destr from 'destr'; +import destr from "destr"; export function getCookieValueFromHeaders(headers: any, key: string): string | undefined { if (headers === undefined || headers === null) { @@ -219,37 +219,40 @@ export function setHeaderForExpressLikeResponse(res: Response, key: string, valu } export function useRawBody(req: IncomingMessage): Promise { - const RawBodySymbol = Symbol('h3RawBody'); - if(RawBodySymbol in this.request) { - const promise = Promise.resolve((req as any)[RawBodySymbol]) - return promise.then(buff => buff.toString('utf-8')); + const RawBodySymbol = Symbol("h3RawBody"); + if (RawBodySymbol in this.request) { + const promise = Promise.resolve((req as any)[RawBodySymbol]); + return promise.then((buff) => buff.toString("utf-8")); } - if('body' in req) { + if ("body" in req) { return Promise.resolve((this.request as any).body); } - const promise = (req as any)[RawBodySymbol] = new Promise((resolve, reject) => { - const bodyData: any[] = [] - req - .on('error', (err) => reject(err)) - .on('data', (chunk) => {bodyData.push(chunk)}) - .on('end', () => {resolve(Buffer.concat(bodyData))}) - }) + const promise = ((req as any)[RawBodySymbol] = new Promise((resolve, reject) => { + const bodyData: any[] = []; + req.on("error", (err) => reject(err)) + .on("data", (chunk) => { + bodyData.push(chunk); + }) + .on("end", () => { + resolve(Buffer.concat(bodyData)); + }); + })); - return promise.then(buff => buff.toString('utf-8')); + return promise.then((buff) => buff.toString("utf-8")); } -export async function useBody(req: IncomingMessage): Promise { - const ParsedBodySymbol = Symbol('h3RawBody') - if(ParsedBodySymbol in req) { - return (req as any)[ParsedBodySymbol] +export async function useBody(req: IncomingMessage): Promise { + const ParsedBodySymbol = Symbol("h3RawBody"); + if (ParsedBodySymbol in req) { + return (req as any)[ParsedBodySymbol]; } - const body = await useRawBody(req) as string; + const body = (await useRawBody(req)) as string; const json = destr(body); (req as any)[ParsedBodySymbol] = json; - return json + return json; } /** * diff --git a/lib/ts/recipe/session/framework/h3.ts b/lib/ts/recipe/session/framework/h3.ts index a09d45a8a..9431f0015 100644 --- a/lib/ts/recipe/session/framework/h3.ts +++ b/lib/ts/recipe/session/framework/h3.ts @@ -1,9 +1,9 @@ -import Session from '../recipe'; -import type { VerifySessionOptions } from '../types'; -import { H3Request, H3ResponseTokens } from '../../../framework/h3/framework'; -import type { SessionRequest } from '../../../framework/h3'; -import SuperTokens from '../../../supertokens'; -import {ServerResponse} from 'http'; +import Session from "../recipe"; +import type { VerifySessionOptions } from "../types"; +import { H3Request, H3ResponseTokens } from "../../../framework/h3/framework"; +import type { SessionRequest } from "../../../framework/h3"; +import SuperTokens from "../../../supertokens"; +import { ServerResponse } from "http"; export function verifySession(options?: VerifySessionOptions) { return async (req: SessionRequest, res: ServerResponse, next: (err?: Error) => any) => { @@ -13,13 +13,13 @@ export function verifySession(options?: VerifySessionOptions) { const sessionRecipe = Session.getInstanceOrThrowError(); req.session = await sessionRecipe.verifySession(options, request, response); next(); - } catch (err: any) { + } catch (err) { try { const supertokens = SuperTokens.getInstanceOrThrowError(); await supertokens.errorHandler(err, request, response); - } catch(err: any) { + } catch (err) { next(err); } } - } -} \ No newline at end of file + }; +} diff --git a/lib/ts/recipe/session/framework/index.ts b/lib/ts/recipe/session/framework/index.ts index 42ea9d11a..5cd93c271 100644 --- a/lib/ts/recipe/session/framework/index.ts +++ b/lib/ts/recipe/session/framework/index.ts @@ -18,7 +18,7 @@ import * as hapiFramework from "./hapi"; import * as loopbackFramework from "./loopback"; import * as koaFramework from "./koa"; import * as awsLambdaFramework from "./awsLambda"; -import * as h3Framework from './h3'; +import * as h3Framework from "./h3"; export default { express: expressFramework, @@ -36,4 +36,4 @@ export let hapi = hapiFramework; export let loopback = loopbackFramework; export let koa = koaFramework; export let awsLambda = awsLambdaFramework; -export let h3 = h3Framework; \ No newline at end of file +export let h3 = h3Framework; diff --git a/package.json b/package.json index 32a5c67ae..9c9f0fbe4 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "NodeJS driver for SuperTokens core", "main": "index.js", "scripts": { - "test": "TEST_MODE=testing npx mocha --timeout 500000", + "test": "npx mocha --timeout 500000", "build-check": "cd lib && npx tsc -p tsconfig.json --noEmit && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit", "build": "cd lib && rm -rf build && npx tsc -p tsconfig.json && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit && cd ../.. && npm run post-build", "pretty": "npx pretty-quick .", diff --git a/test/framework/h3.test.js b/test/framework/h3.test.js deleted file mode 100644 index e3b57b180..000000000 --- a/test/framework/h3.test.js +++ /dev/null @@ -1,85 +0,0 @@ -const { ProcessState } = require("../../lib/build/processState"); -const {createServer, request} = require('http'); -const { default: SuperTokens } = require("../../lib/build/supertokens"); -const { killAllST, setupST, cleanST, startST, extractInfoFromResponse, printPath } = require("../utils") -const Session = require("../../recipe/session"); -const { createApp, createRouter } = require("h3"); -const { middleware } = require("../../lib/build/framework/h3"); -const { assert } = require("console"); -describe(`h3: ${printPath("[test/framework/h3.test.js]")}`, function () { - beforeEach(async function() { - await killAllST(); - await setupST(); - ProcessState.getInstance().reset(); - }) - - after(async function() { - await killAllST(); - await cleanST(); - }) - - it("test that if disabling api, the default refresh API does not work", async function() { - await startST(); - SuperTokens.init({ - supertokens: { - connectionURI: "http://localhost:8080", - }, - appInfo: { - apiDomain: "api.supertokens.io", - appName: "SuperTokens", - websiteDomain: "supertokens.io" - }, - recipeList: [ - Session.init({ - override: { - apis: (oI) => { - return { - ...oI, - refreshPOST: undefined, - }; - }, - }, - antiCsrf: "VIA_TOKEN", - }) - ] - }) - const app = createApp(); - const router = createRouter(); - router.post('/create', async (req, res) => { - await Session.createNewSession(res, "", {}, {}); - return ""; - }) - app.use(router); - app.use(middleware()); - const server = createServer(app); - let res = extractInfoFromResponse( - await new Promise((resolve) => { - request(server) - .post("/create") - .expect(200) - .end((err, res) => { - if(err) { - resolve(undefined) - } else { - resolve(res); - } - }) - }) - ) - - let res2 = await new Promise((resolve) => { - request(server) - .post("/auth/session/refresh") - .set("Cookie", ["sRefreshToken=" + res.refreshToken, "sIdRefreshToken=" + res.idRefreshTokenFromCookie]) - .set("anti-csrf", res.antiCsrf) - .end((err, res) => { - if (err) { - resolve(undefined); - } else { - resolve(res); - } - }) - }) - assert(res2.status === 404); - }) -}) \ No newline at end of file From 9054184456336af2ce782c861e04115d361bb600 Mon Sep 17 00:00:00 2001 From: Kenshi Date: Mon, 13 Jun 2022 12:13:38 +0200 Subject: [PATCH 13/13] fix(QF): Accidentall remove of part of command for tests --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9c9f0fbe4..32a5c67ae 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "NodeJS driver for SuperTokens core", "main": "index.js", "scripts": { - "test": "npx mocha --timeout 500000", + "test": "TEST_MODE=testing npx mocha --timeout 500000", "build-check": "cd lib && npx tsc -p tsconfig.json --noEmit && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit", "build": "cd lib && rm -rf build && npx tsc -p tsconfig.json && cd ../test/with-typescript && npx tsc -p tsconfig.json --noEmit && cd ../.. && npm run post-build", "pretty": "npx pretty-quick .",